File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1337: download - view: text, annotated - select for diffs
Wed Feb 12 16:25:48 2020 UTC (4 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Parameter setting via table mode for users with both student and non-student
  roles.
- Pop-up launched via "Select User" link shows appropriate table(s) of users.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1337 2020/02/12 16:25:48 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 HTTP::Request;
   76: use DateTime::TimeZone;
   77: use DateTime::Locale;
   78: use Encode();
   79: use Text::Aspell;
   80: use Authen::Captcha;
   81: use Captcha::reCAPTCHA;
   82: use JSON::DWIW;
   83: use LWP::UserAgent;
   84: use Crypt::DES;
   85: use DynaLoader; # for Crypt::DES version
   86: use MIME::Lite;
   87: use MIME::Types;
   88: use File::Copy();
   89: use File::Path();
   90: use String::CRC32();
   91: use Short::URL();
   92: 
   93: # ---------------------------------------------- Designs
   94: use vars qw(%defaultdesign);
   95: 
   96: my $readit;
   97: 
   98: 
   99: ##
  100: ## Global Variables
  101: ##
  102: 
  103: 
  104: # ----------------------------------------------- SSI with retries:
  105: #
  106: 
  107: =pod
  108: 
  109: =head1 Server Side include with retries:
  110: 
  111: =over 4
  112: 
  113: =item * &ssi_with_retries(resource,retries form)
  114: 
  115: Performs an ssi with some number of retries.  Retries continue either
  116: until the result is ok or until the retry count supplied by the
  117: caller is exhausted.  
  118: 
  119: Inputs:
  120: 
  121: =over 4
  122: 
  123: resource   - Identifies the resource to insert.
  124: 
  125: retries    - Count of the number of retries allowed.
  126: 
  127: form       - Hash that identifies the rendering options.
  128: 
  129: =back
  130: 
  131: Returns:
  132: 
  133: =over 4
  134: 
  135: content    - The content of the response.  If retries were exhausted this is empty.
  136: 
  137: response   - The response from the last attempt (which may or may not have been successful.
  138: 
  139: =back
  140: 
  141: =back
  142: 
  143: =cut
  144: 
  145: sub ssi_with_retries {
  146:     my ($resource, $retries, %form) = @_;
  147: 
  148: 
  149:     my $ok = 0;			# True if we got a good response.
  150:     my $content;
  151:     my $response;
  152: 
  153:     # Try to get the ssi done. within the retries count:
  154: 
  155:     do {
  156: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  157: 	$ok      = $response->is_success;
  158:         if (!$ok) {
  159:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  160:         }
  161: 	$retries--;
  162:     } while (!$ok && ($retries > 0));
  163: 
  164:     if (!$ok) {
  165: 	$content = '';		# On error return an empty content.
  166:     }
  167:     return ($content, $response);
  168: 
  169: }
  170: 
  171: 
  172: 
  173: # ----------------------------------------------- Filetypes/Languages/Copyright
  174: my %language;
  175: my %supported_language;
  176: my %supported_codes;
  177: my %latex_language;		# For choosing hyphenation in <transl..>
  178: my %latex_language_bykey;	# for choosing hyphenation from metadata
  179: my %cprtag;
  180: my %scprtag;
  181: my %fe; my %fd; my %fm;
  182: my %category_extensions;
  183: 
  184: # ---------------------------------------------- Thesaurus variables
  185: #
  186: # %Keywords:
  187: #      A hash used by &keyword to determine if a word is considered a keyword.
  188: # $thesaurus_db_file 
  189: #      Scalar containing the full path to the thesaurus database.
  190: 
  191: my %Keywords;
  192: my $thesaurus_db_file;
  193: 
  194: #
  195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  196: # thesaurus.tab, and filecategories.tab.
  197: #
  198: BEGIN {
  199:     # Variable initialization
  200:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  201:     #
  202:     unless ($readit) {
  203: # ------------------------------------------------------------------- languages
  204:     {
  205:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  206:                                    '/language.tab';
  207:         if ( open(my $fh,'<',$langtabfile) ) {
  208:             while (my $line = <$fh>) {
  209:                 next if ($line=~/^\#/);
  210:                 chomp($line);
  211:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  212:                 $language{$key}=$val.' - '.$enc;
  213:                 if ($sup) {
  214:                     $supported_language{$key}=$sup;
  215: 		    $supported_codes{$key}   = $code;
  216:                 }
  217: 		if ($latex) {
  218: 		    $latex_language_bykey{$key} = $latex;
  219: 		    $latex_language{$code} = $latex;
  220: 		}
  221:             }
  222:             close($fh);
  223:         }
  224:     }
  225: # ------------------------------------------------------------------ copyrights
  226:     {
  227:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  228:                                   '/copyright.tab';
  229:         if ( open (my $fh,'<',$copyrightfile) ) {
  230:             while (my $line = <$fh>) {
  231:                 next if ($line=~/^\#/);
  232:                 chomp($line);
  233:                 my ($key,$val)=(split(/\s+/,$line,2));
  234:                 $cprtag{$key}=$val;
  235:             }
  236:             close($fh);
  237:         }
  238:     }
  239: # ----------------------------------------------------------- source copyrights
  240:     {
  241:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  242:                                   '/source_copyright.tab';
  243:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  244:             while (my $line = <$fh>) {
  245:                 next if ($line =~ /^\#/);
  246:                 chomp($line);
  247:                 my ($key,$val)=(split(/\s+/,$line,2));
  248:                 $scprtag{$key}=$val;
  249:             }
  250:             close($fh);
  251:         }
  252:     }
  253: 
  254: # -------------------------------------------------------------- default domain designs
  255:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  256:     my $designfile = $designdir.'/default.tab';
  257:     if ( open (my $fh,'<',$designfile) ) {
  258:         while (my $line = <$fh>) {
  259:             next if ($line =~ /^\#/);
  260:             chomp($line);
  261:             my ($key,$val)=(split(/\=/,$line));
  262:             if ($val) { $defaultdesign{$key}=$val; }
  263:         }
  264:         close($fh);
  265:     }
  266: 
  267: # ------------------------------------------------------------- file categories
  268:     {
  269:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  270:                                   '/filecategories.tab';
  271:         if ( open (my $fh,'<',$categoryfile) ) {
  272: 	    while (my $line = <$fh>) {
  273: 		next if ($line =~ /^\#/);
  274: 		chomp($line);
  275:                 my ($extension,$category)=(split(/\s+/,$line,2));
  276:                 push(@{$category_extensions{lc($category)}},$extension);
  277:             }
  278:             close($fh);
  279:         }
  280: 
  281:     }
  282: # ------------------------------------------------------------------ file types
  283:     {
  284:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  285:                '/filetypes.tab';
  286:         if ( open (my $fh,'<',$typesfile) ) {
  287:             while (my $line = <$fh>) {
  288: 		next if ($line =~ /^\#/);
  289: 		chomp($line);
  290:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  291:                 if ($descr ne '') {
  292:                     $fe{$ending}=lc($emb);
  293:                     $fd{$ending}=$descr;
  294:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  295:                 }
  296:             }
  297:             close($fh);
  298:         }
  299:     }
  300:     &Apache::lonnet::logthis(
  301:              "<span style='color:yellow;'>INFO: Read file types</span>");
  302:     $readit=1;
  303:     }  # end of unless($readit) 
  304:     
  305: }
  306: 
  307: ###############################################################
  308: ##           HTML and Javascript Helper Functions            ##
  309: ###############################################################
  310: 
  311: =pod 
  312: 
  313: =head1 HTML and Javascript Functions
  314: 
  315: =over 4
  316: 
  317: =item * &browser_and_searcher_javascript()
  318: 
  319: X<browsing, javascript>X<searching, javascript>Returns a string
  320: containing javascript with two functions, C<openbrowser> and
  321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  322: tags.
  323: 
  324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  325: 
  326: inputs: formname, elementname, only, omit
  327: 
  328: formname and elementname indicate the name of the html form and name of
  329: the element that the results of the browsing selection are to be placed in. 
  330: 
  331: Specifying 'only' will restrict the browser to displaying only files
  332: with the given extension.  Can be a comma separated list.
  333: 
  334: Specifying 'omit' will restrict the browser to NOT displaying files
  335: with the given extension.  Can be a comma separated list.
  336: 
  337: =item * &opensearcher(formname,elementname) [javascript]
  338: 
  339: Inputs: formname, elementname
  340: 
  341: formname and elementname specify the name of the html form and the name
  342: of the element the selection from the search results will be placed in.
  343: 
  344: =cut
  345: 
  346: sub browser_and_searcher_javascript {
  347:     my ($mode)=@_;
  348:     if (!defined($mode)) { $mode='edit'; }
  349:     my $resurl=&escape_single(&lastresurl());
  350:     return <<END;
  351: // <!-- BEGIN LON-CAPA Internal
  352:     var editbrowser = null;
  353:     function openbrowser(formname,elementname,only,omit,titleelement) {
  354:         var url = '$resurl/?';
  355:         if (editbrowser == null) {
  356:             url += 'launch=1&';
  357:         }
  358:         url += 'catalogmode=interactive&';
  359:         url += 'mode=$mode&';
  360:         url += 'inhibitmenu=yes&';
  361:         url += 'form=' + formname + '&';
  362:         if (only != null) {
  363:             url += 'only=' + only + '&';
  364:         } else {
  365:             url += 'only=&';
  366: 	}
  367:         if (omit != null) {
  368:             url += 'omit=' + omit + '&';
  369:         } else {
  370:             url += 'omit=&';
  371: 	}
  372:         if (titleelement != null) {
  373:             url += 'titleelement=' + titleelement + '&';
  374:         } else {
  375: 	    url += 'titleelement=&';
  376: 	}
  377:         url += 'element=' + elementname + '';
  378:         var title = 'Browser';
  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  380:         options += ',width=700,height=600';
  381:         editbrowser = open(url,title,options,'1');
  382:         editbrowser.focus();
  383:     }
  384:     var editsearcher;
  385:     function opensearcher(formname,elementname,titleelement) {
  386:         var url = '/adm/searchcat?';
  387:         if (editsearcher == null) {
  388:             url += 'launch=1&';
  389:         }
  390:         url += 'catalogmode=interactive&';
  391:         url += 'mode=$mode&';
  392:         url += 'form=' + formname + '&';
  393:         if (titleelement != null) {
  394:             url += 'titleelement=' + titleelement + '&';
  395:         } else {
  396: 	    url += 'titleelement=&';
  397: 	}
  398:         url += 'element=' + elementname + '';
  399:         var title = 'Search';
  400:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  401:         options += ',width=700,height=600';
  402:         editsearcher = open(url,title,options,'1');
  403:         editsearcher.focus();
  404:     }
  405: // END LON-CAPA Internal -->
  406: END
  407: }
  408: 
  409: sub lastresurl {
  410:     if ($env{'environment.lastresurl'}) {
  411: 	return $env{'environment.lastresurl'}
  412:     } else {
  413: 	return '/res';
  414:     }
  415: }
  416: 
  417: sub storeresurl {
  418:     my $resurl=&Apache::lonnet::clutter(shift);
  419:     unless ($resurl=~/^\/res/) { return 0; }
  420:     $resurl=~s/\/$//;
  421:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  422:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  423:     return 1;
  424: }
  425: 
  426: sub studentbrowser_javascript {
  427:    unless (
  428:             (($env{'request.course.id'}) && 
  429:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  430: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  431: 					  '/'.$env{'request.course.sec'})
  432: 	      ))
  433:          || ($env{'request.role'}=~/^(au|dc|su)/)
  434:           ) { return ''; }  
  435:    return (<<'ENDSTDBRW');
  436: <script type="text/javascript" language="Javascript">
  437: // <![CDATA[
  438:     var stdeditbrowser;
  439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  440:         var url = '/adm/pickstudent?';
  441:         var filter;
  442: 	if (!ignorefilter) {
  443: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  444: 	}
  445:         if (filter != null) {
  446:            if (filter != '') {
  447:                url += 'filter='+filter+'&';
  448: 	   }
  449:         }
  450:         url += 'form=' + formname + '&unameelement='+uname+
  451:                                     '&udomelement='+udom+
  452:                                     '&clicker='+clicker;
  453: 	if (roleflag) { url+="&roles=1"; }
  454:         if (courseadv == 'condition') {
  455:             if (document.getElementById('courseadv')) {
  456:                 courseadv = document.getElementById('courseadv').value;
  457:             }
  458:         }
  459:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  460:         var title = 'Student_Browser';
  461:         var options = 'scrollbars=1,resizable=1,menubar=0';
  462:         options += ',width=700,height=600';
  463:         stdeditbrowser = open(url,title,options,'1');
  464:         stdeditbrowser.focus();
  465:     }
  466: // ]]>
  467: </script>
  468: ENDSTDBRW
  469: }
  470: 
  471: sub resourcebrowser_javascript {
  472:    unless ($env{'request.course.id'}) { return ''; }
  473:    return (<<'ENDRESBRW');
  474: <script type="text/javascript" language="Javascript">
  475: // <![CDATA[
  476:     var reseditbrowser;
  477:     function openresbrowser(formname,reslink) {
  478:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  479:         var title = 'Resource_Browser';
  480:         var options = 'scrollbars=1,resizable=1,menubar=0';
  481:         options += ',width=700,height=500';
  482:         reseditbrowser = open(url,title,options,'1');
  483:         reseditbrowser.focus();
  484:     }
  485: // ]]>
  486: </script>
  487: ENDRESBRW
  488: }
  489: 
  490: sub selectstudent_link {
  491:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  492:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  494:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  495:    if ($env{'request.course.id'}) {  
  496:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  497: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  498: 					'/'.$env{'request.course.sec'})) {
  499: 	   return '';
  500:        }
  501:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  502:        if ($courseadv eq 'only') {
  503:            $callargs .= ",'',1,'$courseadv'";
  504:        } elsif ($courseadv eq 'none') {
  505:            $callargs .= ",'','','$courseadv'";
  506:        } elsif ($courseadv eq 'condition') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        }
  509:        return '<span class="LC_nobreak">'.
  510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  511:               &mt('Select User').'</a></span>';
  512:    }
  513:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  514:        $callargs .= ",'',1"; 
  515:        return '<span class="LC_nobreak">'.
  516:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  517:               &mt('Select User').'</a></span>';
  518:    }
  519:    return '';
  520: }
  521: 
  522: sub selectresource_link {
  523:    my ($form,$reslink,$arg)=@_;
  524:    
  525:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  526:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  527:    unless ($env{'request.course.id'}) { return $arg; }
  528:    return '<span class="LC_nobreak">'.
  529:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  530:               $arg.'</a></span>';
  531: }
  532: 
  533: 
  534: 
  535: sub authorbrowser_javascript {
  536:     return <<"ENDAUTHORBRW";
  537: <script type="text/javascript" language="JavaScript">
  538: // <![CDATA[
  539: var stdeditbrowser;
  540: 
  541: function openauthorbrowser(formname,udom) {
  542:     var url = '/adm/pickauthor?';
  543:     url += 'form='+formname+'&roledom='+udom;
  544:     var title = 'Author_Browser';
  545:     var options = 'scrollbars=1,resizable=1,menubar=0';
  546:     options += ',width=700,height=600';
  547:     stdeditbrowser = open(url,title,options,'1');
  548:     stdeditbrowser.focus();
  549: }
  550: 
  551: // ]]>
  552: </script>
  553: ENDAUTHORBRW
  554: }
  555: 
  556: sub coursebrowser_javascript {
  557:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  558:         $credits_element,$instcode) = @_;
  559:     my $wintitle = 'Course_Browser';
  560:     if ($crstype eq 'Community') {
  561:         $wintitle = 'Community_Browser';
  562:     }
  563:     my $id_functions = &javascript_index_functions();
  564:     my $output = '
  565: <script type="text/javascript" language="JavaScript">
  566: // <![CDATA[
  567:     var stdeditbrowser;'."\n";
  568: 
  569:     $output .= <<"ENDSTDBRW";
  570:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  571:         var url = '/adm/pickcourse?';
  572:         var formid = getFormIdByName(formname);
  573:         var domainfilter = getDomainFromSelectbox(formname,udom);
  574:         if (domainfilter != null) {
  575:            if (domainfilter != '') {
  576:                url += 'domainfilter='+domainfilter+'&';
  577: 	   }
  578:         }
  579:         url += 'form=' + formname + '&cnumelement='+uname+
  580: 	                            '&cdomelement='+udom+
  581:                                     '&cnameelement='+desc;
  582:         if (extra_element !=null && extra_element != '') {
  583:             if (formname == 'rolechoice' || formname == 'studentform') {
  584:                 url += '&roleelement='+extra_element;
  585:                 if (domainfilter == null || domainfilter == '') {
  586:                     url += '&domainfilter='+extra_element;
  587:                 }
  588:             }
  589:             else {
  590:                 if (formname == 'portform') {
  591:                     url += '&setroles='+extra_element;
  592:                 } else {
  593:                     if (formname == 'rules') {
  594:                         url += '&fixeddom='+extra_element; 
  595:                     }
  596:                 }
  597:             }     
  598:         }
  599:         if (type != null && type != '') {
  600:             url += '&type='+type;
  601:         }
  602:         if (type_elem != null && type_elem != '') {
  603:             url += '&typeelement='+type_elem;
  604:         }
  605:         if (formname == 'ccrs') {
  606:             var ownername = document.forms[formid].ccuname.value;
  607:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  608:             url += '&cloner='+ownername+':'+ownerdom;
  609:             if (type == 'Course') {
  610:                 url += '&crscode='+document.forms[formid].crscode.value;
  611:             }
  612:         }
  613:         if (formname == 'requestcrs') {
  614:             url += '&crsdom=$domainfilter&crscode=$instcode';
  615:         }
  616:         if (multflag !=null && multflag != '') {
  617:             url += '&multiple='+multflag;
  618:         }
  619:         var title = '$wintitle';
  620:         var options = 'scrollbars=1,resizable=1,menubar=0';
  621:         options += ',width=700,height=600';
  622:         stdeditbrowser = open(url,title,options,'1');
  623:         stdeditbrowser.focus();
  624:     }
  625: $id_functions
  626: ENDSTDBRW
  627:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  628:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  629:                                       $credits_element);
  630:     }
  631:     $output .= '
  632: // ]]>
  633: </script>';
  634:     return $output;
  635: }
  636: 
  637: sub javascript_index_functions {
  638:     return <<"ENDJS";
  639: 
  640: function getFormIdByName(formname) {
  641:     for (var i=0;i<document.forms.length;i++) {
  642:         if (document.forms[i].name == formname) {
  643:             return i;
  644:         }
  645:     }
  646:     return -1;
  647: }
  648: 
  649: function getIndexByName(formid,item) {
  650:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  651:         if (document.forms[formid].elements[i].name == item) {
  652:             return i;
  653:         }
  654:     }
  655:     return -1;
  656: }
  657: 
  658: function getDomainFromSelectbox(formname,udom) {
  659:     var userdom;
  660:     var formid = getFormIdByName(formname);
  661:     if (formid > -1) {
  662:         var domid = getIndexByName(formid,udom);
  663:         if (domid > -1) {
  664:             if (document.forms[formid].elements[domid].type == 'select-one') {
  665:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  666:             }
  667:             if (document.forms[formid].elements[domid].type == 'hidden') {
  668:                 userdom=document.forms[formid].elements[domid].value;
  669:             }
  670:         }
  671:     }
  672:     return userdom;
  673: }
  674: 
  675: ENDJS
  676: 
  677: }
  678: 
  679: sub javascript_array_indexof {
  680:     return <<ENDJS;
  681: <script type="text/javascript" language="JavaScript">
  682: // <![CDATA[
  683: 
  684: if (!Array.prototype.indexOf) {
  685:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  686:         "use strict";
  687:         if (this === void 0 || this === null) {
  688:             throw new TypeError();
  689:         }
  690:         var t = Object(this);
  691:         var len = t.length >>> 0;
  692:         if (len === 0) {
  693:             return -1;
  694:         }
  695:         var n = 0;
  696:         if (arguments.length > 0) {
  697:             n = Number(arguments[1]);
  698:             if (n !== n) { // shortcut for verifying if it is NaN
  699:                 n = 0;
  700:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  701:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  702:             }
  703:         }
  704:         if (n >= len) {
  705:             return -1;
  706:         }
  707:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  708:         for (; k < len; k++) {
  709:             if (k in t && t[k] === searchElement) {
  710:                 return k;
  711:             }
  712:         }
  713:         return -1;
  714:     }
  715: }
  716: 
  717: // ]]>
  718: </script>
  719: 
  720: ENDJS
  721: 
  722: }
  723: 
  724: sub userbrowser_javascript {
  725:     my $id_functions = &javascript_index_functions();
  726:     return <<"ENDUSERBRW";
  727: 
  728: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  729:     var url = '/adm/pickuser?';
  730:     var userdom = getDomainFromSelectbox(formname,udom);
  731:     if (userdom != null) {
  732:        if (userdom != '') {
  733:            url += 'srchdom='+userdom+'&';
  734:        }
  735:     }
  736:     url += 'form=' + formname + '&unameelement='+uname+
  737:                                 '&udomelement='+udom+
  738:                                 '&ulastelement='+ulast+
  739:                                 '&ufirstelement='+ufirst+
  740:                                 '&uemailelement='+uemail+
  741:                                 '&hideudomelement='+hideudom+
  742:                                 '&coursedom='+crsdom;
  743:     if ((caller != null) && (caller != undefined)) {
  744:         url += '&caller='+caller;
  745:     }
  746:     var title = 'User_Browser';
  747:     var options = 'scrollbars=1,resizable=1,menubar=0';
  748:     options += ',width=700,height=600';
  749:     var stdeditbrowser = open(url,title,options,'1');
  750:     stdeditbrowser.focus();
  751: }
  752: 
  753: function fix_domain (formname,udom,origdom,uname) {
  754:     var formid = getFormIdByName(formname);
  755:     if (formid > -1) {
  756:         var unameid = getIndexByName(formid,uname);
  757:         var domid = getIndexByName(formid,udom);
  758:         var hidedomid = getIndexByName(formid,origdom);
  759:         if (hidedomid > -1) {
  760:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  761:             var unameval = document.forms[formid].elements[unameid].value;
  762:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  763:                 if (domid > -1) {
  764:                     var slct = document.forms[formid].elements[domid];
  765:                     if (slct.type == 'select-one') {
  766:                         var i;
  767:                         for (i=0;i<slct.length;i++) {
  768:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  769:                         }
  770:                     }
  771:                     if (slct.type == 'hidden') {
  772:                         slct.value = fixeddom;
  773:                     }
  774:                 }
  775:             }
  776:         }
  777:     }
  778:     return;
  779: }
  780: 
  781: $id_functions
  782: ENDUSERBRW
  783: }
  784: 
  785: sub setsec_javascript {
  786:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  787:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  788:         $communityrolestr);
  789:     if ($role_element ne '') {
  790:         my @allroles = ('st','ta','ep','in','ad');
  791:         foreach my $crstype ('Course','Community') {
  792:             if ($crstype eq 'Community') {
  793:                 foreach my $role (@allroles) {
  794:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  795:                 }
  796:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  797:             } else {
  798:                 foreach my $role (@allroles) {
  799:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  800:                 }
  801:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  802:             }
  803:         }
  804:         $rolestr = '"'.join('","',@allroles).'"';
  805:         $courserolestr = '"'.join('","',@courserolenames).'"';
  806:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  807:     }
  808:     my $setsections = qq|
  809: function setSect(sectionlist) {
  810:     var sectionsArray = new Array();
  811:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  812:         sectionsArray = sectionlist.split(",");
  813:     }
  814:     var numSections = sectionsArray.length;
  815:     document.$formname.$sec_element.length = 0;
  816:     if (numSections == 0) {
  817:         document.$formname.$sec_element.multiple=false;
  818:         document.$formname.$sec_element.size=1;
  819:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  820:     } else {
  821:         if (numSections == 1) {
  822:             document.$formname.$sec_element.multiple=false;
  823:             document.$formname.$sec_element.size=1;
  824:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  825:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  826:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  827:         } else {
  828:             for (var i=0; i<numSections; i++) {
  829:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  830:             }
  831:             document.$formname.$sec_element.multiple=true
  832:             if (numSections < 3) {
  833:                 document.$formname.$sec_element.size=numSections;
  834:             } else {
  835:                 document.$formname.$sec_element.size=3;
  836:             }
  837:             document.$formname.$sec_element.options[0].selected = false
  838:         }
  839:     }
  840: }
  841: 
  842: function setRole(crstype) {
  843: |;
  844:     if ($role_element eq '') {
  845:         $setsections .= '    return;
  846: }
  847: ';
  848:     } else {
  849:         $setsections .= qq|
  850:     var elementLength = document.$formname.$role_element.length;
  851:     var allroles = Array($rolestr);
  852:     var courserolenames = Array($courserolestr);
  853:     var communityrolenames = Array($communityrolestr);
  854:     if (elementLength != undefined) {
  855:         if (document.$formname.$role_element.options[5].value == 'cc') {
  856:             if (crstype == 'Course') {
  857:                 return;
  858:             } else {
  859:                 allroles[5] = 'co';
  860:                 for (var i=0; i<6; i++) {
  861:                     document.$formname.$role_element.options[i].value = allroles[i];
  862:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  863:                 }
  864:             }
  865:         } else {
  866:             if (crstype == 'Community') {
  867:                 return;
  868:             } else {
  869:                 allroles[5] = 'cc';
  870:                 for (var i=0; i<6; i++) {
  871:                     document.$formname.$role_element.options[i].value = allroles[i];
  872:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  873:                 }
  874:             }
  875:         }
  876:     }
  877:     return;
  878: }
  879: |;
  880:     }
  881:     if ($credits_element) {
  882:         $setsections .= qq|
  883: function setCredits(defaultcredits) {
  884:     document.$formname.$credits_element.value = defaultcredits;
  885:     return;
  886: }
  887: |;
  888:     }
  889:     return $setsections;
  890: }
  891: 
  892: sub selectcourse_link {
  893:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  894:        $typeelement) = @_;
  895:    my $type = $selecttype;
  896:    my $linktext = &mt('Select Course');
  897:    if ($selecttype eq 'Community') {
  898:        $linktext = &mt('Select Community');
  899:    } elsif ($selecttype eq 'Placement') {
  900:        $linktext = &mt('Select Placement Test'); 
  901:    } elsif ($selecttype eq 'Course/Community') {
  902:        $linktext = &mt('Select Course/Community');
  903:        $type = '';
  904:    } elsif ($selecttype eq 'Select') {
  905:        $linktext = &mt('Select');
  906:        $type = '';
  907:    }
  908:    return '<span class="LC_nobreak">'
  909:          ."<a href='"
  910:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  911:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  912:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  913:          ."'>".$linktext.'</a>'
  914:          .'</span>';
  915: }
  916: 
  917: sub selectauthor_link {
  918:    my ($form,$udom)=@_;
  919:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  920:           &mt('Select Author').'</a>';
  921: }
  922: 
  923: sub selectuser_link {
  924:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  925:         $coursedom,$linktext,$caller) = @_;
  926:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  927:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  928:            ');">'.$linktext.'</a>';
  929: }
  930: 
  931: sub check_uncheck_jscript {
  932:     my $jscript = <<"ENDSCRT";
  933: function checkAll(field) {
  934:     if (field.length > 0) {
  935:         for (i = 0; i < field.length; i++) {
  936:             if (!field[i].disabled) { 
  937:                 field[i].checked = true;
  938:             }
  939:         }
  940:     } else {
  941:         if (!field.disabled) { 
  942:             field.checked = true;
  943:         }
  944:     }
  945: }
  946:  
  947: function uncheckAll(field) {
  948:     if (field.length > 0) {
  949:         for (i = 0; i < field.length; i++) {
  950:             field[i].checked = false ;
  951:         }
  952:     } else {
  953:         field.checked = false ;
  954:     }
  955: }
  956: ENDSCRT
  957:     return $jscript;
  958: }
  959: 
  960: sub select_timezone {
  961:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  962:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  963:    if ($includeempty) {
  964:        $output .= '<option value=""';
  965:        if (($selected eq '') || ($selected eq 'local')) {
  966:            $output .= ' selected="selected" ';
  967:        }
  968:        $output .= '> </option>';
  969:    }
  970:    my @timezones = DateTime::TimeZone->all_names;
  971:    foreach my $tzone (@timezones) {
  972:        $output.= '<option value="'.$tzone.'"';
  973:        if ($tzone eq $selected) {
  974:            $output.=' selected="selected"';
  975:        }
  976:        $output.=">$tzone</option>\n";
  977:    }
  978:    $output.="</select>";
  979:    return $output;
  980: }
  981: 
  982: sub select_datelocale {
  983:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  984:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  985:     if ($includeempty) {
  986:         $output .= '<option value=""';
  987:         if ($selected eq '') {
  988:             $output .= ' selected="selected" ';
  989:         }
  990:         $output .= '> </option>';
  991:     }
  992:     my @languages = &Apache::lonlocal::preferred_languages();
  993:     my (@possibles,%locale_names);
  994:     my @locales = DateTime::Locale->ids();
  995:     foreach my $id (@locales) {
  996:         if ($id ne '') {
  997:             my ($en_terr,$native_terr);
  998:             my $loc = DateTime::Locale->load($id);
  999:             if (ref($loc)) {
 1000:                 $en_terr = $loc->name();
 1001:                 $native_terr = $loc->native_name();
 1002:                 if (grep(/^en$/,@languages) || !@languages) {
 1003:                     if ($en_terr ne '') {
 1004:                         $locale_names{$id} = '('.$en_terr.')';
 1005:                     } elsif ($native_terr ne '') {
 1006:                         $locale_names{$id} = $native_terr;
 1007:                     }
 1008:                 } else {
 1009:                     if ($native_terr ne '') {
 1010:                         $locale_names{$id} = $native_terr.' ';
 1011:                     } elsif ($en_terr ne '') {
 1012:                         $locale_names{$id} = '('.$en_terr.')';
 1013:                     }
 1014:                 }
 1015:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1016:                 push(@possibles,$id);
 1017:             } 
 1018:         }
 1019:     }
 1020:     foreach my $item (sort(@possibles)) {
 1021:         $output.= '<option value="'.$item.'"';
 1022:         if ($item eq $selected) {
 1023:             $output.=' selected="selected"';
 1024:         }
 1025:         $output.=">$item";
 1026:         if ($locale_names{$item} ne '') {
 1027:             $output.='  '.$locale_names{$item};
 1028:         }
 1029:         $output.="</option>\n";
 1030:     }
 1031:     $output.="</select>";
 1032:     return $output;
 1033: }
 1034: 
 1035: sub select_language {
 1036:     my ($name,$selected,$includeempty,$noedit) = @_;
 1037:     my %langchoices;
 1038:     if ($includeempty) {
 1039:         %langchoices = ('' => 'No language preference');
 1040:     }
 1041:     foreach my $id (&languageids()) {
 1042:         my $code = &supportedlanguagecode($id);
 1043:         if ($code) {
 1044:             $langchoices{$code} = &plainlanguagedescription($id);
 1045:         }
 1046:     }
 1047:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1048:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1049: }
 1050: 
 1051: =pod
 1052: 
 1053: 
 1054: =item * &list_languages()
 1055: 
 1056: Returns an array reference that is suitable for use in language prompters.
 1057: Each array element is itself a two element array.  The first element
 1058: is the language code.  The second element a descsriptiuon of the 
 1059: language itself.  This is suitable for use in e.g.
 1060: &Apache::edit::select_arg (once dereferenced that is).
 1061: 
 1062: =cut 
 1063: 
 1064: sub list_languages {
 1065:     my @lang_choices;
 1066: 
 1067:     foreach my $id (&languageids()) {
 1068: 	my $code = &supportedlanguagecode($id);
 1069: 	if ($code) {
 1070: 	    my $selector    = $supported_codes{$id};
 1071: 	    my $description = &plainlanguagedescription($id);
 1072: 	    push(@lang_choices, [$selector, $description]);
 1073: 	}
 1074:     }
 1075:     return \@lang_choices;
 1076: }
 1077: 
 1078: =pod
 1079: 
 1080: =item * &linked_select_forms(...)
 1081: 
 1082: linked_select_forms returns a string containing a <script></script> block
 1083: and html for two <select> menus.  The select menus will be linked in that
 1084: changing the value of the first menu will result in new values being placed
 1085: in the second menu.  The values in the select menu will appear in alphabetical
 1086: order unless a defined order is provided.
 1087: 
 1088: linked_select_forms takes the following ordered inputs:
 1089: 
 1090: =over 4
 1091: 
 1092: =item * $formname, the name of the <form> tag
 1093: 
 1094: =item * $middletext, the text which appears between the <select> tags
 1095: 
 1096: =item * $firstdefault, the default value for the first menu
 1097: 
 1098: =item * $firstselectname, the name of the first <select> tag
 1099: 
 1100: =item * $secondselectname, the name of the second <select> tag
 1101: 
 1102: =item * $hashref, a reference to a hash containing the data for the menus.
 1103: 
 1104: =item * $menuorder, the order of values in the first menu
 1105: 
 1106: =item * $onchangefirst, additional javascript call to execute for an onchange
 1107:         event for the first <select> tag
 1108: 
 1109: =item * $onchangesecond, additional javascript call to execute for an onchange
 1110:         event for the second <select> tag
 1111: 
 1112: =item * $suffix, to differentiate separate uses of select2data javascript
 1113:         objects in a page.
 1114: 
 1115: =back 
 1116: 
 1117: Below is an example of such a hash.  Only the 'text', 'default', and 
 1118: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1119: values for the first select menu.  The text that coincides with the 
 1120: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1121: and text for the second menu are given in the hash pointed to by 
 1122: $menu{$choice1}->{'select2'}.  
 1123: 
 1124:  my %menu = ( A1 => { text =>"Choice A1" ,
 1125:                        default => "B3",
 1126:                        select2 => { 
 1127:                            B1 => "Choice B1",
 1128:                            B2 => "Choice B2",
 1129:                            B3 => "Choice B3",
 1130:                            B4 => "Choice B4"
 1131:                            },
 1132:                        order => ['B4','B3','B1','B2'],
 1133:                    },
 1134:                A2 => { text =>"Choice A2" ,
 1135:                        default => "C2",
 1136:                        select2 => { 
 1137:                            C1 => "Choice C1",
 1138:                            C2 => "Choice C2",
 1139:                            C3 => "Choice C3"
 1140:                            },
 1141:                        order => ['C2','C1','C3'],
 1142:                    },
 1143:                A3 => { text =>"Choice A3" ,
 1144:                        default => "D6",
 1145:                        select2 => { 
 1146:                            D1 => "Choice D1",
 1147:                            D2 => "Choice D2",
 1148:                            D3 => "Choice D3",
 1149:                            D4 => "Choice D4",
 1150:                            D5 => "Choice D5",
 1151:                            D6 => "Choice D6",
 1152:                            D7 => "Choice D7"
 1153:                            },
 1154:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1155:                    }
 1156:                );
 1157: 
 1158: =cut
 1159: 
 1160: sub linked_select_forms {
 1161:     my ($formname,
 1162:         $middletext,
 1163:         $firstdefault,
 1164:         $firstselectname,
 1165:         $secondselectname, 
 1166:         $hashref,
 1167:         $menuorder,
 1168:         $onchangefirst,
 1169:         $onchangesecond,
 1170:         $suffix
 1171:         ) = @_;
 1172:     my $second = "document.$formname.$secondselectname";
 1173:     my $first = "document.$formname.$firstselectname";
 1174:     # output the javascript to do the changing
 1175:     my $result = '';
 1176:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1177:     $result.="// <![CDATA[\n";
 1178:     $result.="var select2data${suffix} = new Object();\n";
 1179:     $" = '","';
 1180:     my $debug = '';
 1181:     foreach my $s1 (sort(keys(%$hashref))) {
 1182:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1183:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1184:             $hashref->{$s1}->{'default'}."');\n";
 1185:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1186:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1187:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1188:             @s2values = @{$hashref->{$s1}->{'order'}};
 1189:         }
 1190:         $result.="\"@s2values\");\n";
 1191:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1192:         my @s2texts;
 1193:         foreach my $value (@s2values) {
 1194:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1195:         }
 1196:         $result.="\"@s2texts\");\n";
 1197:     }
 1198:     $"=' ';
 1199:     $result.= <<"END";
 1200: 
 1201: function select1${suffix}_changed() {
 1202:     // Determine new choice
 1203:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1204:     // update select2
 1205:     var values     = select2data${suffix}[newvalue].values;
 1206:     var texts      = select2data${suffix}[newvalue].texts;
 1207:     var select2def = select2data${suffix}[newvalue].def;
 1208:     var i;
 1209:     // out with the old
 1210:     $second.options.length = 0;
 1211:     // in with the new
 1212:     for (i=0;i<values.length; i++) {
 1213:         $second.options[i] = new Option(values[i]);
 1214:         $second.options[i].value = values[i];
 1215:         $second.options[i].text = texts[i];
 1216:         if (values[i] == select2def) {
 1217:             $second.options[i].selected = true;
 1218:         }
 1219:     }
 1220: }
 1221: // ]]>
 1222: </script>
 1223: END
 1224:     # output the initial values for the selection lists
 1225:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1226:     my @order = sort(keys(%{$hashref}));
 1227:     if (ref($menuorder) eq 'ARRAY') {
 1228:         @order = @{$menuorder};
 1229:     }
 1230:     foreach my $value (@order) {
 1231:         $result.="    <option value=\"$value\" ";
 1232:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1233:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1234:     }
 1235:     $result .= "</select>\n";
 1236:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1237:     $result .= $middletext;
 1238:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1239:     if ($onchangesecond) {
 1240:         $result .= ' onchange="'.$onchangesecond.'"';
 1241:     }
 1242:     $result .= ">\n";
 1243:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1244:     
 1245:     my @secondorder = sort(keys(%select2));
 1246:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1247:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1248:     }
 1249:     foreach my $value (@secondorder) {
 1250:         $result.="    <option value=\"$value\" ";        
 1251:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1252:         $result.=">".&mt($select2{$value})."</option>\n";
 1253:     }
 1254:     $result .= "</select>\n";
 1255:     #    return $debug;
 1256:     return $result;
 1257: }   #  end of sub linked_select_forms {
 1258: 
 1259: =pod
 1260: 
 1261: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1262: 
 1263: Returns a string corresponding to an HTML link to the given help
 1264: $topic, where $topic corresponds to the name of a .tex file in
 1265: /home/httpd/html/adm/help/tex, with underscores replaced by
 1266: spaces. 
 1267: 
 1268: $text will optionally be linked to the same topic, allowing you to
 1269: link text in addition to the graphic. If you do not want to link
 1270: text, but wish to specify one of the later parameters, pass an
 1271: empty string. 
 1272: 
 1273: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1274: the link will not open a new window. If false, the link will open
 1275: a new window using Javascript. (Default is false.) 
 1276: 
 1277: $width and $height are optional numerical parameters that will
 1278: override the width and height of the popped up window, which may
 1279: be useful for certain help topics with big pictures included.
 1280: 
 1281: $imgid is the id of the img tag used for the help icon. This may be
 1282: used in a javascript call to switch the image src.  See 
 1283: lonhtmlcommon::htmlareaselectactive() for an example.
 1284: 
 1285: =cut
 1286: 
 1287: sub help_open_topic {
 1288:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1289:     $text = "" if (not defined $text);
 1290:     $stayOnPage = 0 if (not defined $stayOnPage);
 1291:     $width = 500 if (not defined $width);
 1292:     $height = 400 if (not defined $height);
 1293:     my $filename = $topic;
 1294:     $filename =~ s/ /_/g;
 1295: 
 1296:     my $template = "";
 1297:     my $link;
 1298:     
 1299:     $topic=~s/\W/\_/g;
 1300: 
 1301:     if (!$stayOnPage) {
 1302: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1303:     } elsif ($stayOnPage eq 'popup') {
 1304:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1305:     } else {
 1306: 	$link = "/adm/help/${filename}.hlp";
 1307:     }
 1308: 
 1309:     # Add the text
 1310:     my $target = ' target="_top"';
 1311:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1312:         $target = '';
 1313:     }
 1314:     if ($text ne "") {	
 1315: 	$template.='<span class="LC_help_open_topic">'
 1316:                   .'<a'.$target.' href="'.$link.'">'
 1317:                   .$text.'</a>';
 1318:     }
 1319: 
 1320:     # (Always) Add the graphic
 1321:     my $title = &mt('Online Help');
 1322:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1323:     if ($imgid ne '') {
 1324:         $imgid = ' id="'.$imgid.'"';
 1325:     }
 1326:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1327:               .'<img src="'.$helpicon.'" border="0"'
 1328:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1329:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1330:               .' /></a>';
 1331:     if ($text ne "") {	
 1332:         $template.='</span>';
 1333:     }
 1334:     return $template;
 1335: 
 1336: }
 1337: 
 1338: # This is a quicky function for Latex cheatsheet editing, since it 
 1339: # appears in at least four places
 1340: sub helpLatexCheatsheet {
 1341:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1342:     my $out;
 1343:     my $addOther = '';
 1344:     if ($topic) {
 1345: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1346:     }
 1347:     $out = '<span>' # Start cheatsheet
 1348: 	  .$addOther
 1349:           .'<span>'
 1350: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1351: 	  .'</span> <span>'
 1352: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1353: 	  .'</span>';
 1354:     unless ($not_author) {
 1355:         $out .= '<span>'
 1356:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1357:                .'</span> <span>'
 1358:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1359: 	       .'</span>';
 1360:     }
 1361:     $out .= '</span>'; # End cheatsheet
 1362:     return $out;
 1363: }
 1364: 
 1365: sub general_help {
 1366:     my $helptopic='Student_Intro';
 1367:     if ($env{'request.role'}=~/^(ca|au)/) {
 1368: 	$helptopic='Authoring_Intro';
 1369:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1370: 	$helptopic='Course_Coordination_Intro';
 1371:     } elsif ($env{'request.role'}=~/^dc/) {
 1372:         $helptopic='Domain_Coordination_Intro';
 1373:     }
 1374:     return $helptopic;
 1375: }
 1376: 
 1377: sub update_help_link {
 1378:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1379:     my $origurl = $ENV{'REQUEST_URI'};
 1380:     $origurl=~s|^/~|/priv/|;
 1381:     my $timestamp = time;
 1382:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1383:         $$datum = &escape($$datum);
 1384:     }
 1385: 
 1386:     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";
 1387:     my $output .= <<"ENDOUTPUT";
 1388: <script type="text/javascript">
 1389: // <![CDATA[
 1390: banner_link = '$banner_link';
 1391: // ]]>
 1392: </script>
 1393: ENDOUTPUT
 1394:     return $output;
 1395: }
 1396: 
 1397: # now just updates the help link and generates a blue icon
 1398: sub help_open_menu {
 1399:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1400: 	= @_;    
 1401:     $stayOnPage = 1;
 1402:     my $output;
 1403:     if ($component_help) {
 1404: 	if (!$text) {
 1405: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1406: 				       $width,$height);
 1407: 	} else {
 1408: 	    my $help_text;
 1409: 	    $help_text=&unescape($topic);
 1410: 	    $output='<table><tr><td>'.
 1411: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1412: 				 $width,$height).'</td></tr></table>';
 1413: 	}
 1414:     }
 1415:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1416:     return $output.$banner_link;
 1417: }
 1418: 
 1419: sub top_nav_help {
 1420:     my ($text) = @_;
 1421:     $text = &mt($text);
 1422:     my $stay_on_page = 1;
 1423: 
 1424:     my ($link,$banner_link);
 1425:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1426:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1427: 	                         : "javascript:helpMenu('open')";
 1428:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1429:     }
 1430:     my $title = &mt('Get help');
 1431:     if ($link) {
 1432:         return <<"END";
 1433: $banner_link
 1434: <a href="$link" title="$title">$text</a>
 1435: END
 1436:     } else {
 1437:         return '&nbsp;'.$text.'&nbsp;';
 1438:     }
 1439: }
 1440: 
 1441: sub help_menu_js {
 1442:     my ($httphost) = @_;
 1443:     my $stayOnPage = 1;
 1444:     my $width = 620;
 1445:     my $height = 600;
 1446:     my $helptopic=&general_help();
 1447:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1448:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1449:     my $start_page =
 1450:         &Apache::loncommon::start_page('Help Menu', undef,
 1451: 				       {'frameset'    => 1,
 1452: 					'js_ready'    => 1,
 1453:                                         'use_absolute' => $httphost,
 1454: 					'add_entries' => {
 1455: 					    'border' => '0', 
 1456: 					    'rows'   => "110,*",},});
 1457:     my $end_page =
 1458:         &Apache::loncommon::end_page({'frameset' => 1,
 1459: 				      'js_ready' => 1,});
 1460: 
 1461:     my $template .= <<"ENDTEMPLATE";
 1462: <script type="text/javascript">
 1463: // <![CDATA[
 1464: // <!-- BEGIN LON-CAPA Internal
 1465: var banner_link = '';
 1466: function helpMenu(target) {
 1467:     var caller = this;
 1468:     if (target == 'open') {
 1469:         var newWindow = null;
 1470:         try {
 1471:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1472:         }
 1473:         catch(error) {
 1474:             writeHelp(caller);
 1475:             return;
 1476:         }
 1477:         if (newWindow) {
 1478:             caller = newWindow;
 1479:         }
 1480:     }
 1481:     writeHelp(caller);
 1482:     return;
 1483: }
 1484: function writeHelp(caller) {
 1485:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1486:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1487:     caller.document.close();
 1488:     caller.focus();
 1489: }
 1490: // END LON-CAPA Internal -->
 1491: // ]]>
 1492: </script>
 1493: ENDTEMPLATE
 1494:     return $template;
 1495: }
 1496: 
 1497: sub help_open_bug {
 1498:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1499:     unless ($env{'user.adv'}) { return ''; }
 1500:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1501:     $text = "" if (not defined $text);
 1502: 	$stayOnPage=1;
 1503:     $width = 600 if (not defined $width);
 1504:     $height = 600 if (not defined $height);
 1505: 
 1506:     $topic=~s/\W+/\+/g;
 1507:     my $link='';
 1508:     my $template='';
 1509:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1510: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1511:     if (!$stayOnPage)
 1512:     {
 1513: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1514:     }
 1515:     else
 1516:     {
 1517: 	$link = $url;
 1518:     }
 1519: 
 1520:     my $target = ' target="_top"';
 1521:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1522:         $target = '';
 1523:     }
 1524:     # Add the text
 1525:     if ($text ne "")
 1526:     {
 1527: 	$template .= 
 1528:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1529:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1530:     }
 1531: 
 1532:     # Add the graphic
 1533:     my $title = &mt('Report a Bug');
 1534:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1535:     $template .= <<"ENDTEMPLATE";
 1536:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1537: ENDTEMPLATE
 1538:     if ($text ne '') { $template.='</td></tr></table>' };
 1539:     return $template;
 1540: 
 1541: }
 1542: 
 1543: sub help_open_faq {
 1544:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1545:     unless ($env{'user.adv'}) { return ''; }
 1546:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1547:     $text = "" if (not defined $text);
 1548: 	$stayOnPage=1;
 1549:     $width = 350 if (not defined $width);
 1550:     $height = 400 if (not defined $height);
 1551: 
 1552:     $topic=~s/\W+/\+/g;
 1553:     my $link='';
 1554:     my $template='';
 1555:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1556:     if (!$stayOnPage)
 1557:     {
 1558: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1559:     }
 1560:     else
 1561:     {
 1562: 	$link = $url;
 1563:     }
 1564: 
 1565:     # Add the text
 1566:     if ($text ne "")
 1567:     {
 1568: 	$template .= 
 1569:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1570:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1571:     }
 1572: 
 1573:     # Add the graphic
 1574:     my $title = &mt('View the FAQ');
 1575:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1576:     $template .= <<"ENDTEMPLATE";
 1577:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1578: ENDTEMPLATE
 1579:     if ($text ne '') { $template.='</td></tr></table>' };
 1580:     return $template;
 1581: 
 1582: }
 1583: 
 1584: ###############################################################
 1585: ###############################################################
 1586: 
 1587: =pod
 1588: 
 1589: =item * &change_content_javascript():
 1590: 
 1591: This and the next function allow you to create small sections of an
 1592: otherwise static HTML page that you can update on the fly with
 1593: Javascript, even in Netscape 4.
 1594: 
 1595: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1596: must be written to the HTML page once. It will prove the Javascript
 1597: function "change(name, content)". Calling the change function with the
 1598: name of the section 
 1599: you want to update, matching the name passed to C<changable_area>, and
 1600: the new content you want to put in there, will put the content into
 1601: that area.
 1602: 
 1603: B<Note>: Netscape 4 only reserves enough space for the changable area
 1604: to contain room for the original contents. You need to "make space"
 1605: for whatever changes you wish to make, and be B<sure> to check your
 1606: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1607: it's adequate for updating a one-line status display, but little more.
 1608: This script will set the space to 100% width, so you only need to
 1609: worry about height in Netscape 4.
 1610: 
 1611: Modern browsers are much less limiting, and if you can commit to the
 1612: user not using Netscape 4, this feature may be used freely with
 1613: pretty much any HTML.
 1614: 
 1615: =cut
 1616: 
 1617: sub change_content_javascript {
 1618:     # If we're on Netscape 4, we need to use Layer-based code
 1619:     if ($env{'browser.type'} eq 'netscape' &&
 1620: 	$env{'browser.version'} =~ /^4\./) {
 1621: 	return (<<NETSCAPE4);
 1622: 	function change(name, content) {
 1623: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1624: 	    doc.open();
 1625: 	    doc.write(content);
 1626: 	    doc.close();
 1627: 	}
 1628: NETSCAPE4
 1629:     } else {
 1630: 	# Otherwise, we need to use semi-standards-compliant code
 1631: 	# (technically, "innerHTML" isn't standard but the equivalent
 1632: 	# is really scary, and every useful browser supports it
 1633: 	return (<<DOMBASED);
 1634: 	function change(name, content) {
 1635: 	    element = document.getElementById(name);
 1636: 	    element.innerHTML = content;
 1637: 	}
 1638: DOMBASED
 1639:     }
 1640: }
 1641: 
 1642: =pod
 1643: 
 1644: =item * &changable_area($name,$origContent):
 1645: 
 1646: This provides a "changable area" that can be modified on the fly via
 1647: the Javascript code provided in C<change_content_javascript>. $name is
 1648: the name you will use to reference the area later; do not repeat the
 1649: same name on a given HTML page more then once. $origContent is what
 1650: the area will originally contain, which can be left blank.
 1651: 
 1652: =cut
 1653: 
 1654: sub changable_area {
 1655:     my ($name, $origContent) = @_;
 1656: 
 1657:     if ($env{'browser.type'} eq 'netscape' &&
 1658: 	$env{'browser.version'} =~ /^4\./) {
 1659: 	# If this is netscape 4, we need to use the Layer tag
 1660: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1661:     } else {
 1662: 	return "<span id='$name'>$origContent</span>";
 1663:     }
 1664: }
 1665: 
 1666: =pod
 1667: 
 1668: =item * &viewport_geometry_js 
 1669: 
 1670: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1671: 
 1672: =cut
 1673: 
 1674: 
 1675: sub viewport_geometry_js { 
 1676:     return <<"GEOMETRY";
 1677: var Geometry = {};
 1678: function init_geometry() {
 1679:     if (Geometry.init) { return };
 1680:     Geometry.init=1;
 1681:     if (window.innerHeight) {
 1682:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1683:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1684:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1685:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1686:     }
 1687:     else if (document.documentElement && document.documentElement.clientHeight) {
 1688:         Geometry.getViewportHeight =
 1689:             function() { return document.documentElement.clientHeight; };
 1690:         Geometry.getViewportWidth =
 1691:             function() { return document.documentElement.clientWidth; };
 1692: 
 1693:         Geometry.getHorizontalScroll =
 1694:             function() { return document.documentElement.scrollLeft; };
 1695:         Geometry.getVerticalScroll =
 1696:             function() { return document.documentElement.scrollTop; };
 1697:     }
 1698:     else if (document.body.clientHeight) {
 1699:         Geometry.getViewportHeight =
 1700:             function() { return document.body.clientHeight; };
 1701:         Geometry.getViewportWidth =
 1702:             function() { return document.body.clientWidth; };
 1703:         Geometry.getHorizontalScroll =
 1704:             function() { return document.body.scrollLeft; };
 1705:         Geometry.getVerticalScroll =
 1706:             function() { return document.body.scrollTop; };
 1707:     }
 1708: }
 1709: 
 1710: GEOMETRY
 1711: }
 1712: 
 1713: =pod
 1714: 
 1715: =item * &viewport_size_js()
 1716: 
 1717: 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. 
 1718: 
 1719: =cut
 1720: 
 1721: sub viewport_size_js {
 1722:     my $geometry = &viewport_geometry_js();
 1723:     return <<"DIMS";
 1724: 
 1725: $geometry
 1726: 
 1727: function getViewportDims(width,height) {
 1728:     init_geometry();
 1729:     width.value = Geometry.getViewportWidth();
 1730:     height.value = Geometry.getViewportHeight();
 1731:     return;
 1732: }
 1733: 
 1734: DIMS
 1735: }
 1736: 
 1737: =pod
 1738: 
 1739: =item * &resize_textarea_js()
 1740: 
 1741: emits the needed javascript to resize a textarea to be as big as possible
 1742: 
 1743: creates a function resize_textrea that takes two IDs first should be
 1744: the id of the element to resize, second should be the id of a div that
 1745: surrounds everything that comes after the textarea, this routine needs
 1746: to be attached to the <body> for the onload and onresize events.
 1747: 
 1748: =back
 1749: 
 1750: =cut
 1751: 
 1752: sub resize_textarea_js {
 1753:     my $geometry = &viewport_geometry_js();
 1754:     return <<"RESIZE";
 1755:     <script type="text/javascript">
 1756: // <![CDATA[
 1757: $geometry
 1758: 
 1759: function getX(element) {
 1760:     var x = 0;
 1761:     while (element) {
 1762: 	x += element.offsetLeft;
 1763: 	element = element.offsetParent;
 1764:     }
 1765:     return x;
 1766: }
 1767: function getY(element) {
 1768:     var y = 0;
 1769:     while (element) {
 1770: 	y += element.offsetTop;
 1771: 	element = element.offsetParent;
 1772:     }
 1773:     return y;
 1774: }
 1775: 
 1776: 
 1777: function resize_textarea(textarea_id,bottom_id) {
 1778:     init_geometry();
 1779:     var textarea        = document.getElementById(textarea_id);
 1780:     //alert(textarea);
 1781: 
 1782:     var textarea_top    = getY(textarea);
 1783:     var textarea_height = textarea.offsetHeight;
 1784:     var bottom          = document.getElementById(bottom_id);
 1785:     var bottom_top      = getY(bottom);
 1786:     var bottom_height   = bottom.offsetHeight;
 1787:     var window_height   = Geometry.getViewportHeight();
 1788:     var fudge           = 23;
 1789:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1790:     if (new_height < 300) {
 1791: 	new_height = 300;
 1792:     }
 1793:     textarea.style.height=new_height+'px';
 1794: }
 1795: // ]]>
 1796: </script>
 1797: RESIZE
 1798: 
 1799: }
 1800: 
 1801: sub colorfuleditor_js {
 1802:     my $browse_or_search;
 1803:     my $respath;
 1804:     my ($cnum,$cdom) = &crsauthor_url();
 1805:     if ($cnum) {
 1806:         $respath = "/res/$cdom/$cnum/";
 1807:         my %js_lt = &Apache::lonlocal::texthash(
 1808:             sunm => 'Sub-directory name',
 1809:             save => 'Save page to make this permanent',
 1810:         );
 1811:         &js_escape(\%js_lt);
 1812:         $browse_or_search = <<"END";
 1813: 
 1814:     function toggleChooser(form,element,titleid,only,search) {
 1815:         var disp = 'none';
 1816:         if (document.getElementById('chooser_'+element)) {
 1817:             var curr = document.getElementById('chooser_'+element).style.display;
 1818:             if (curr == 'none') {
 1819:                 disp='inline';
 1820:                 if (form.elements['chooser_'+element].length) {
 1821:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1822:                         form.elements['chooser_'+element][i].checked = false;
 1823:                     }
 1824:                 }
 1825:                 toggleResImport(form,element);
 1826:             }
 1827:             document.getElementById('chooser_'+element).style.display = disp;
 1828:         }
 1829:     }
 1830: 
 1831:     function toggleCrsFile(form,element,numdirs) {
 1832:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1833:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1834:             if (curr == 'none') {
 1835:                 if (numdirs) {
 1836:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1837:                     if (numdirs > 1) {
 1838:                         window['select1'+element+'_changed']();
 1839:                     }
 1840:                 }
 1841:             } 
 1842:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1843:             
 1844:         }
 1845:         if (document.getElementById('chooser_'+element+'_upload')) {
 1846:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1847:             if (document.getElementById('uploadcrsres_'+element)) {
 1848:                 document.getElementById('uploadcrsres_'+element).value = '';
 1849:             }
 1850:         }
 1851:         return;
 1852:     }
 1853: 
 1854:     function toggleCrsUpload(form,element,numcrsdirs) {
 1855:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1856:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1857:         }
 1858:         if (document.getElementById('chooser_'+element+'_upload')) {
 1859:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1860:             if (curr == 'none') {
 1861:                 if (numcrsdirs) {
 1862:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1863:                    form.elements['newsubdir_'+element][0].checked = true;
 1864:                    toggleNewsubdir(form,element);
 1865:                 }
 1866:             }
 1867:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1868:         }
 1869:         return;
 1870:     }
 1871: 
 1872:     function toggleResImport(form,element) {
 1873:         var choices = new Array('crsres','upload');
 1874:         for (var i=0; i<choices.length; i++) {
 1875:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1876:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1877:             }
 1878:         }
 1879:     }
 1880: 
 1881:     function toggleNewsubdir(form,element) {
 1882:         var newsub = form.elements['newsubdir_'+element];
 1883:         if (newsub) {
 1884:             if (newsub.length) {
 1885:                 for (var j=0; j<newsub.length; j++) {
 1886:                     if (newsub[j].checked) {
 1887:                         if (document.getElementById('newsubdirname_'+element)) {
 1888:                             if (newsub[j].value == '1') {
 1889:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1890:                                 if (document.getElementById('newsubdir_'+element)) {
 1891:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1892:                                 }
 1893:                             } else {
 1894:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1895:                                 document.getElementById('newsubdirname_'+element).value = "";
 1896:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1897:                             }
 1898:                         }
 1899:                         break; 
 1900:                     }
 1901:                 }
 1902:             }
 1903:         }
 1904:     }
 1905: 
 1906:     function updateCrsFile(form,element) {
 1907:         var directory = form.elements['coursepath_'+element];
 1908:         var filename = form.elements['coursefile_'+element];
 1909:         var path = directory.options[directory.selectedIndex].value;
 1910:         var file = filename.options[filename.selectedIndex].value;
 1911:         form.elements[element].value = '$respath';
 1912:         if (path == '/') {
 1913:             form.elements[element].value += file;
 1914:         } else {
 1915:             form.elements[element].value += path+'/'+file;
 1916:         }
 1917:         unClean();
 1918:         if (document.getElementById('previewimg_'+element)) {
 1919:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1920:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1921:         }
 1922:         if (document.getElementById('showimg_'+element)) {
 1923:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1924:         }
 1925:         toggleChooser(form,element);
 1926:         return;
 1927:     }
 1928: 
 1929:     function uploadDone(suffix,name) {
 1930:         if (name) {
 1931: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1932:             unClean();
 1933:             toggleChooser(document.forms["lonhomework"],suffix);
 1934:         }
 1935:     }
 1936: 
 1937: \$(document).ready(function(){
 1938: 
 1939:     \$(document).delegate('form :submit', 'click', function( event ) {
 1940:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1941:             var buttonId = this.id;
 1942:             var suffix = buttonId.toString();
 1943:             suffix = suffix.replace(/^crsupload_/,'');
 1944:             event.preventDefault();
 1945:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1946:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1947:             \$(this.form).submit();
 1948:             document.lonhomework.target = '';
 1949:             if (document.getElementById('crsuploadto_'+suffix)) {
 1950:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1951:             }
 1952:             return false;
 1953:         }
 1954:     });
 1955: });
 1956: END
 1957:     }
 1958:     return <<"COLORFULEDIT"
 1959: <script type="text/javascript">
 1960: // <![CDATA[>
 1961:     function fold_box(curDepth, lastresource){
 1962: 
 1963:     // we need a list because there can be several blocks you need to fold in one tag
 1964:         var block = document.getElementsByName('foldblock_'+curDepth);
 1965:     // but there is only one folding button per tag
 1966:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1967: 
 1968:         if(block.item(0).style.display == 'none'){
 1969: 
 1970:             foldbutton.value = '@{[&mt("Hide")]}';
 1971:             for (i = 0; i < block.length; i++){
 1972:                 block.item(i).style.display = '';
 1973:             }
 1974:         }else{
 1975: 
 1976:             foldbutton.value = '@{[&mt("Show")]}';
 1977:             for (i = 0; i < block.length; i++){
 1978:                 // block.item(i).style.visibility = 'collapse';
 1979:                 block.item(i).style.display = 'none';
 1980:             }
 1981:         };
 1982:         saveState(lastresource);
 1983:     }
 1984: 
 1985:     function saveState (lastresource) {
 1986: 
 1987:         var tag_list = getTagList();
 1988:         if(tag_list != null){
 1989:             var timestamp = new Date().getTime();
 1990:             var key = lastresource;
 1991: 
 1992:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1993:             // starting with timestamp
 1994:             var value = timestamp+';';
 1995: 
 1996:             // building the list of key-value pairs
 1997:             for(var i = 0; i < tag_list.length; i++){
 1998:                 value += tag_list[i]+',';
 1999:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2000:             }
 2001: 
 2002:             // only iterate whole storage if nothing to override
 2003:             if(localStorage.getItem(key) == null){        
 2004: 
 2005:                 // prevent storage from growing large
 2006:                 if(localStorage.length > 50){
 2007:                     var regex_getTimestamp = /^(?:\d)+;/;
 2008:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2009:                     var oldest_key;
 2010:                     
 2011:                     for(var i = 1; i < localStorage.length; i++){
 2012:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2013:                             oldest_key = localStorage.key(i);
 2014:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2015:                         }
 2016:                     }
 2017:                     localStorage.removeItem(oldest_key);
 2018:                 }
 2019:             }
 2020:             localStorage.setItem(key,value);
 2021:         }
 2022:     }
 2023: 
 2024:     // restore folding status of blocks (on page load)
 2025:     function restoreState (lastresource) {
 2026:         if(localStorage.getItem(lastresource) != null){
 2027:             var key = lastresource;
 2028:             var value = localStorage.getItem(key);
 2029:             var regex_delTimestamp = /^\d+;/;
 2030: 
 2031:             value.replace(regex_delTimestamp, '');
 2032: 
 2033:             var valueArr = value.split(';');
 2034:             var pairs;
 2035:             var elements;
 2036:             for (var i = 0; i < valueArr.length; i++){
 2037:                 pairs = valueArr[i].split(',');
 2038:                 elements = document.getElementsByName(pairs[0]);
 2039: 
 2040:                 for (var j = 0; j < elements.length; j++){  
 2041:                     elements[j].style.display = pairs[1];
 2042:                     if (pairs[1] == "none"){
 2043:                         var regex_id = /([_\\d]+)\$/;
 2044:                         regex_id.exec(pairs[0]);
 2045:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2046:                     }
 2047:                 }
 2048:             }
 2049:         }
 2050:     }
 2051: 
 2052:     function getTagList () {
 2053:         
 2054:         var stringToSearch = document.lonhomework.innerHTML;
 2055: 
 2056:         var ret = new Array();
 2057:         var regex_findBlock = /(foldblock_.*?)"/g;
 2058:         var tag_list = stringToSearch.match(regex_findBlock);
 2059: 
 2060:         if(tag_list != null){
 2061:             for(var i = 0; i < tag_list.length; i++){            
 2062:                 ret.push(tag_list[i].replace(/"/, ''));
 2063:             }
 2064:         }
 2065:         return ret;
 2066:     }
 2067: 
 2068:     function saveScrollPosition (resource) {
 2069:         var tag_list = getTagList();
 2070: 
 2071:         // we dont always want to jump to the first block
 2072:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2073:         if(\$(window).scrollTop() > 170){
 2074:             if(tag_list != null){
 2075:                 var result;
 2076:                 for(var i = 0; i < tag_list.length; i++){
 2077:                     if(isElementInViewport(tag_list[i])){
 2078:                         result += tag_list[i]+';';
 2079:                     }
 2080:                 }
 2081:                 sessionStorage.setItem('anchor_'+resource, result);
 2082:             }
 2083:         } else {
 2084:             // we dont need to save zero, just delete the item to leave everything tidy
 2085:             sessionStorage.removeItem('anchor_'+resource);
 2086:         }
 2087:     }
 2088: 
 2089:     function restoreScrollPosition(resource){
 2090: 
 2091:         var elem = sessionStorage.getItem('anchor_'+resource);
 2092:         if(elem != null){
 2093:             var tag_list = elem.split(';');
 2094:             var elem_list;
 2095: 
 2096:             for(var i = 0; i < tag_list.length; i++){
 2097:                 elem_list = document.getElementsByName(tag_list[i]);
 2098:                 
 2099:                 if(elem_list.length > 0){
 2100:                     elem = elem_list[0];
 2101:                     break;
 2102:                 }
 2103:             }
 2104:             elem.scrollIntoView();
 2105:         }
 2106:     }
 2107: 
 2108:     function isElementInViewport(el) {
 2109: 
 2110:         // change to last element instead of first
 2111:         var elem = document.getElementsByName(el);
 2112:         var rect = elem[0].getBoundingClientRect();
 2113: 
 2114:         return (
 2115:             rect.top >= 0 &&
 2116:             rect.left >= 0 &&
 2117:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2118:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2119:         );
 2120:     }
 2121:     
 2122:     function autosize(depth){
 2123:         var cmInst = window['cm'+depth];
 2124:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2125: 
 2126:         // is fixed size, switching to dynamic
 2127:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2128:             cmInst.setSize("","auto");
 2129:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2130:             sessionStorage.setItem("autosized_"+depth, "yes");
 2131: 
 2132:         // is dynamic size, switching to fixed
 2133:         } else {
 2134:             cmInst.setSize("","300px");
 2135:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2136:             sessionStorage.removeItem("autosized_"+depth);
 2137:         }
 2138:     }
 2139: 
 2140: $browse_or_search
 2141: 
 2142: // ]]>
 2143: </script>
 2144: COLORFULEDIT
 2145: }
 2146: 
 2147: sub xmleditor_js {
 2148:     return <<XMLEDIT
 2149: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2150: <script type="text/javascript">
 2151: // <![CDATA[>
 2152: 
 2153:     function saveScrollPosition (resource) {
 2154: 
 2155:         var scrollPos = \$(window).scrollTop();
 2156:         sessionStorage.setItem(resource,scrollPos);
 2157:     }
 2158: 
 2159:     function restoreScrollPosition(resource){
 2160: 
 2161:         var scrollPos = sessionStorage.getItem(resource);
 2162:         \$(window).scrollTop(scrollPos);
 2163:     }
 2164: 
 2165:     // unless internet explorer
 2166:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2167: 
 2168:         \$(document).ready(function() {
 2169:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2170:         });
 2171:     }
 2172: 
 2173:     // inserts text at cursor position into codemirror (xml editor only)
 2174:     function insertText(text){
 2175:         cm.focus();
 2176:         var curPos = cm.getCursor();
 2177:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2178:     }
 2179: // ]]>
 2180: </script>
 2181: XMLEDIT
 2182: }
 2183: 
 2184: sub insert_folding_button {
 2185:     my $curDepth = $Apache::lonxml::curdepth;
 2186:     my $lastresource = $env{'request.ambiguous'};
 2187: 
 2188:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2189:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2190: }
 2191: 
 2192: sub crsauthor_url {
 2193:     my ($url) = @_;
 2194:     if ($url eq '') {
 2195:         $url = $ENV{'REQUEST_URI'};
 2196:     }
 2197:     my ($cnum,$cdom);
 2198:     if ($env{'request.course.id'}) {
 2199:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2200:         if ($audom ne '' && $auname ne '') {
 2201:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2202:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2203:                 $cnum = $auname;
 2204:                 $cdom = $audom;
 2205:             }
 2206:         }
 2207:     }
 2208:     return ($cnum,$cdom);
 2209: }
 2210: 
 2211: sub import_crsauthor_form {
 2212:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2213:     return (0) unless ($env{'request.course.id'});
 2214:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2215:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2216:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2217:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2218:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2219:     my @ids=&Apache::lonnet::current_machine_ids();
 2220:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2221:     
 2222:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2223:         $is_home = 1;
 2224:     }
 2225:     $relpath = "/priv/$cdom/$cnum";
 2226:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2227:     my %lt = &Apache::lonlocal::texthash (
 2228:         fnam => 'Filename',
 2229:         dire => 'Directory',
 2230:     );
 2231:     my $numdirs = scalar(keys(%files));
 2232:     my (%possexts,$singledir,@singledirfiles);
 2233:     if ($only) {
 2234:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2235:     }
 2236:     my (%nonemptydirs,$possdirs);
 2237:     if ($numdirs > 1) {
 2238:         my @order;
 2239:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2240:             if (ref($files{$key}) eq 'HASH') {
 2241:                 my $shown = $key;
 2242:                 if ($key eq '') {
 2243:                     $shown = '/';
 2244:                 }
 2245:                 my @ordered = ();
 2246:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2247:                     next if ($file =~ /\.rights$/);
 2248:                     if ($only) {
 2249:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2250:                         unless ($possexts{lc($ext)}) {
 2251:                             next;
 2252:                         }
 2253:                     }
 2254:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2255:                     push(@ordered,$file);
 2256:                 }
 2257:                 if (@ordered) {
 2258:                     push(@order,$key);
 2259:                     $nonemptydirs{$key} = 1;
 2260:                     $selimport_menus{$key}->{'text'} = $shown;
 2261:                     $selimport_menus{$key}->{'default'} = '';
 2262:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2263:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2264:                 }
 2265:             }
 2266:         }
 2267:         $possdirs = scalar(keys(%nonemptydirs));
 2268:         if ($possdirs > 1) {
 2269:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2270:             $output = $lt{'dire'}.
 2271:                       &linked_select_forms($form,'<br />'.
 2272:                                            $lt{'fnam'},'',
 2273:                                            $firstselectname,$secondselectname,
 2274:                                            \%selimport_menus,\@order,
 2275:                                            $onchangefirst,'',$suffix).'<br />';
 2276:         } elsif ($possdirs == 1) {
 2277:             $singledir = (keys(%nonemptydirs))[0];
 2278:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2279:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2280:             }
 2281:             delete($selimport_menus{$singledir});
 2282:         }
 2283:     } elsif ($numdirs == 1) {
 2284:         $singledir = (keys(%files))[0];
 2285:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2286:             if ($only) {
 2287:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2288:                 unless ($possexts{lc($ext)}) {
 2289:                     next;
 2290:                 }
 2291:             } else {
 2292:                 next if ($file =~ /\.rights$/);
 2293:             }
 2294:             push(@singledirfiles,$file);
 2295:         }
 2296:         if (@singledirfiles) {
 2297:             $possdirs = 1;
 2298:         }
 2299:     }
 2300:     if (($possdirs == 1) && (@singledirfiles)) {
 2301:         my $showdir = $singledir;
 2302:         if ($singledir eq '') {
 2303:             $showdir = '/';
 2304:         }
 2305:         $output = $lt{'dire'}.
 2306:                   '<select name="'.$firstselectname.'">'.
 2307:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2308:                   '</select><br />'.
 2309:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2310:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2311:         foreach my $file (@singledirfiles) {
 2312:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2313:         }
 2314:         $output .= '</select><br />'."\n";
 2315:     }
 2316:     return ($possdirs,$output);
 2317: }
 2318: 
 2319: =pod
 2320: 
 2321: =head1 Excel and CSV file utility routines
 2322: 
 2323: =cut
 2324: 
 2325: ###############################################################
 2326: ###############################################################
 2327: 
 2328: =pod
 2329: 
 2330: =over 4
 2331: 
 2332: =item * &csv_translate($text) 
 2333: 
 2334: Translate $text to allow it to be output as a 'comma separated values' 
 2335: format.
 2336: 
 2337: =cut
 2338: 
 2339: ###############################################################
 2340: ###############################################################
 2341: sub csv_translate {
 2342:     my $text = shift;
 2343:     $text =~ s/\"/\"\"/g;
 2344:     $text =~ s/\n/ /g;
 2345:     return $text;
 2346: }
 2347: 
 2348: ###############################################################
 2349: ###############################################################
 2350: 
 2351: =pod
 2352: 
 2353: =item * &define_excel_formats()
 2354: 
 2355: Define some commonly used Excel cell formats.
 2356: 
 2357: Currently supported formats:
 2358: 
 2359: =over 4
 2360: 
 2361: =item header
 2362: 
 2363: =item bold
 2364: 
 2365: =item h1
 2366: 
 2367: =item h2
 2368: 
 2369: =item h3
 2370: 
 2371: =item h4
 2372: 
 2373: =item i
 2374: 
 2375: =item date
 2376: 
 2377: =back
 2378: 
 2379: Inputs: $workbook
 2380: 
 2381: Returns: $format, a hash reference.
 2382: 
 2383: 
 2384: =cut
 2385: 
 2386: ###############################################################
 2387: ###############################################################
 2388: sub define_excel_formats {
 2389:     my ($workbook) = @_;
 2390:     my $format;
 2391:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2392:                                                 bottom    => 1,
 2393:                                                 align     => 'center');
 2394:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2395:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2396:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2397:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2398:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2399:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2400:     $format->{'date'} = $workbook->add_format(num_format=>
 2401:                                             'mm/dd/yyyy hh:mm:ss');
 2402:     return $format;
 2403: }
 2404: 
 2405: ###############################################################
 2406: ###############################################################
 2407: 
 2408: =pod
 2409: 
 2410: =item * &create_workbook()
 2411: 
 2412: Create an Excel worksheet.  If it fails, output message on the
 2413: request object and return undefs.
 2414: 
 2415: Inputs: Apache request object
 2416: 
 2417: Returns (undef) on failure, 
 2418:     Excel worksheet object, scalar with filename, and formats 
 2419:     from &Apache::loncommon::define_excel_formats on success
 2420: 
 2421: =cut
 2422: 
 2423: ###############################################################
 2424: ###############################################################
 2425: sub create_workbook {
 2426:     my ($r) = @_;
 2427:         #
 2428:     # Create the excel spreadsheet
 2429:     my $filename = '/prtspool/'.
 2430:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2431:         time.'_'.rand(1000000000).'.xls';
 2432:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2433:     if (! defined($workbook)) {
 2434:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2435:         $r->print(
 2436:             '<p class="LC_error">'
 2437:            .&mt('Problems occurred in creating the new Excel file.')
 2438:            .' '.&mt('This error has been logged.')
 2439:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2440:            .'</p>'
 2441:         );
 2442:         return (undef);
 2443:     }
 2444:     #
 2445:     $workbook->set_tempdir(LONCAPA::tempdir());
 2446:     #
 2447:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2448:     return ($workbook,$filename,$format);
 2449: }
 2450: 
 2451: ###############################################################
 2452: ###############################################################
 2453: 
 2454: =pod
 2455: 
 2456: =item * &create_text_file()
 2457: 
 2458: Create a file to write to and eventually make available to the user.
 2459: If file creation fails, outputs an error message on the request object and 
 2460: return undefs.
 2461: 
 2462: Inputs: Apache request object, and file suffix
 2463: 
 2464: Returns (undef) on failure, 
 2465:     Filehandle and filename on success.
 2466: 
 2467: =cut
 2468: 
 2469: ###############################################################
 2470: ###############################################################
 2471: sub create_text_file {
 2472:     my ($r,$suffix) = @_;
 2473:     if (! defined($suffix)) { $suffix = 'txt'; };
 2474:     my $fh;
 2475:     my $filename = '/prtspool/'.
 2476:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2477:         time.'_'.rand(1000000000).'.'.$suffix;
 2478:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2479:     if (! defined($fh)) {
 2480:         $r->log_error("Couldn't open $filename for output $!");
 2481:         $r->print(
 2482:             '<p class="LC_error">'
 2483:            .&mt('Problems occurred in creating the output file.')
 2484:            .' '.&mt('This error has been logged.')
 2485:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2486:            .'</p>'
 2487:         );
 2488:     }
 2489:     return ($fh,$filename)
 2490: }
 2491: 
 2492: 
 2493: =pod 
 2494: 
 2495: =back
 2496: 
 2497: =cut
 2498: 
 2499: ###############################################################
 2500: ##        Home server <option> list generating code          ##
 2501: ###############################################################
 2502: 
 2503: # ------------------------------------------
 2504: 
 2505: sub domain_select {
 2506:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2507:     my @possdoms;
 2508:     if (ref($incdoms) eq 'ARRAY') {
 2509:         @possdoms = @{$incdoms};
 2510:     } else {
 2511:         @possdoms = &Apache::lonnet::all_domains();
 2512:     }
 2513: 
 2514:     my %domains=map { 
 2515: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2516:     } @possdoms;
 2517: 
 2518:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2519:         foreach my $dom (@{$excdoms}) {
 2520:             delete($domains{$dom});
 2521:         }
 2522:     }
 2523: 
 2524:     if ($multiple) {
 2525: 	$domains{''}=&mt('Any domain');
 2526: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2527: 	return &multiple_select_form($name,$value,4,\%domains);
 2528:     } else {
 2529: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2530: 	return &select_form($name,$value,\%domains);
 2531:     }
 2532: }
 2533: 
 2534: #-------------------------------------------
 2535: 
 2536: =pod
 2537: 
 2538: =head1 Routines for form select boxes
 2539: 
 2540: =over 4
 2541: 
 2542: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2543: 
 2544: Returns a string containing a <select> element int multiple mode
 2545: 
 2546: 
 2547: Args:
 2548:   $name - name of the <select> element
 2549:   $value - scalar or array ref of values that should already be selected
 2550:   $size - number of rows long the select element is
 2551:   $hash - the elements should be 'option' => 'shown text'
 2552:           (shown text should already have been &mt())
 2553:   $order - (optional) array ref of the order to show the elements in
 2554: 
 2555: =cut
 2556: 
 2557: #-------------------------------------------
 2558: sub multiple_select_form {
 2559:     my ($name,$value,$size,$hash,$order)=@_;
 2560:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2561:     my $output='';
 2562:     if (! defined($size)) {
 2563:         $size = 4;
 2564:         if (scalar(keys(%$hash))<4) {
 2565:             $size = scalar(keys(%$hash));
 2566:         }
 2567:     }
 2568:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2569:     my @order;
 2570:     if (ref($order) eq 'ARRAY')  {
 2571:         @order = @{$order};
 2572:     } else {
 2573:         @order = sort(keys(%$hash));
 2574:     }
 2575:     if (exists($$hash{'select_form_order'})) {
 2576:         @order = @{$$hash{'select_form_order'}};
 2577:     }
 2578:         
 2579:     foreach my $key (@order) {
 2580:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2581:         $output.='selected="selected" ' if ($selected{$key});
 2582:         $output.='>'.$hash->{$key}."</option>\n";
 2583:     }
 2584:     $output.="</select>\n";
 2585:     return $output;
 2586: }
 2587: 
 2588: #-------------------------------------------
 2589: 
 2590: =pod
 2591: 
 2592: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2593: 
 2594: Returns a string containing a <select name='$name' size='1'> form to 
 2595: allow a user to select options from a ref to a hash containing:
 2596: option_name => displayed text. An optional $onchange can include
 2597: a javascript onchange item, e.g., onchange="this.form.submit();".
 2598: An optional arg -- $readonly -- if true will cause the select form
 2599: to be disabled, e.g., for the case where an instructor has a section-
 2600: specific role, and is viewing/modifying parameters. 
 2601: 
 2602: See lonrights.pm for an example invocation and use.
 2603: 
 2604: =cut
 2605: 
 2606: #-------------------------------------------
 2607: sub select_form {
 2608:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2609:     return unless (ref($hashref) eq 'HASH');
 2610:     if ($onchange) {
 2611:         $onchange = ' onchange="'.$onchange.'"';
 2612:     }
 2613:     my $disabled;
 2614:     if ($readonly) {
 2615:         $disabled = ' disabled="disabled"';
 2616:     }
 2617:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2618:     my @keys;
 2619:     if (exists($hashref->{'select_form_order'})) {
 2620: 	@keys=@{$hashref->{'select_form_order'}};
 2621:     } else {
 2622: 	@keys=sort(keys(%{$hashref}));
 2623:     }
 2624:     foreach my $key (@keys) {
 2625:         $selectform.=
 2626: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2627:             ($key eq $def ? 'selected="selected" ' : '').
 2628:                 ">".$hashref->{$key}."</option>\n";
 2629:     }
 2630:     $selectform.="</select>";
 2631:     return $selectform;
 2632: }
 2633: 
 2634: # For display filters
 2635: 
 2636: sub display_filter {
 2637:     my ($context) = @_;
 2638:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2639:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2640:     my $phraseinput = 'hidden';
 2641:     my $includeinput = 'hidden';
 2642:     my ($checked,$includetypestext);
 2643:     if ($env{'form.displayfilter'} eq 'containing') {
 2644:         $phraseinput = 'text'; 
 2645:         if ($context eq 'parmslog') {
 2646:             $includeinput = 'checkbox';
 2647:             if ($env{'form.includetypes'}) {
 2648:                 $checked = ' checked="checked"';
 2649:             }
 2650:             $includetypestext = &mt('Include parameter types');
 2651:         }
 2652:     } else {
 2653:         $includetypestext = '&nbsp;';
 2654:     }
 2655:     my ($additional,$secondid,$thirdid);
 2656:     if ($context eq 'parmslog') {
 2657:         $additional = 
 2658:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2659:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2660:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2661:             '</label>';
 2662:         $secondid = 'includetypes';
 2663:         $thirdid = 'includetypestext';
 2664:     }
 2665:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2666:                                                     '$secondid','$thirdid')";
 2667:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2668: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2669: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2670: 	   '</label></span> <span class="LC_nobreak">'.
 2671:            &mt('Filter: [_1]',
 2672: 	   &select_form($env{'form.displayfilter'},
 2673: 			'displayfilter',
 2674: 			{'currentfolder' => 'Current folder/page',
 2675: 			 'containing' => 'Containing phrase',
 2676: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2677: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2678:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2679:                          '" />'.$additional;
 2680: }
 2681: 
 2682: sub display_filter_js {
 2683:     my $includetext = &mt('Include parameter types');
 2684:     return <<"ENDJS";
 2685:   
 2686: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2687:     var firstType = 'hidden';
 2688:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2689:         firstType = 'text';
 2690:     }
 2691:     firstObject = document.getElementById(firstid);
 2692:     if (typeof(firstObject) == 'object') {
 2693:         if (firstObject.type != firstType) {
 2694:             changeInputType(firstObject,firstType);
 2695:         }
 2696:     }
 2697:     if (context == 'parmslog') {
 2698:         var secondType = 'hidden';
 2699:         if (firstType == 'text') {
 2700:             secondType = 'checkbox';
 2701:         }
 2702:         secondObject = document.getElementById(secondid);  
 2703:         if (typeof(secondObject) == 'object') {
 2704:             if (secondObject.type != secondType) {
 2705:                 changeInputType(secondObject,secondType);
 2706:             }
 2707:         }
 2708:         var textItem = document.getElementById(thirdid);
 2709:         var currtext = textItem.innerHTML;
 2710:         var newtext;
 2711:         if (firstType == 'text') {
 2712:             newtext = '$includetext';
 2713:         } else {
 2714:             newtext = '&nbsp;';
 2715:         }
 2716:         if (currtext != newtext) {
 2717:             textItem.innerHTML = newtext;
 2718:         }
 2719:     }
 2720:     return;
 2721: }
 2722: 
 2723: function changeInputType(oldObject,newType) {
 2724:     var newObject = document.createElement('input');
 2725:     newObject.type = newType;
 2726:     if (oldObject.size) {
 2727:         newObject.size = oldObject.size;
 2728:     }
 2729:     if (oldObject.value) {
 2730:         newObject.value = oldObject.value;
 2731:     }
 2732:     if (oldObject.name) {
 2733:         newObject.name = oldObject.name;
 2734:     }
 2735:     if (oldObject.id) {
 2736:         newObject.id = oldObject.id;
 2737:     }
 2738:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2739:     return;
 2740: }
 2741: 
 2742: ENDJS
 2743: }
 2744: 
 2745: sub gradeleveldescription {
 2746:     my $gradelevel=shift;
 2747:     my %gradelevels=(0 => 'Not specified',
 2748: 		     1 => 'Grade 1',
 2749: 		     2 => 'Grade 2',
 2750: 		     3 => 'Grade 3',
 2751: 		     4 => 'Grade 4',
 2752: 		     5 => 'Grade 5',
 2753: 		     6 => 'Grade 6',
 2754: 		     7 => 'Grade 7',
 2755: 		     8 => 'Grade 8',
 2756: 		     9 => 'Grade 9',
 2757: 		     10 => 'Grade 10',
 2758: 		     11 => 'Grade 11',
 2759: 		     12 => 'Grade 12',
 2760: 		     13 => 'Grade 13',
 2761: 		     14 => '100 Level',
 2762: 		     15 => '200 Level',
 2763: 		     16 => '300 Level',
 2764: 		     17 => '400 Level',
 2765: 		     18 => 'Graduate Level');
 2766:     return &mt($gradelevels{$gradelevel});
 2767: }
 2768: 
 2769: sub select_level_form {
 2770:     my ($deflevel,$name)=@_;
 2771:     unless ($deflevel) { $deflevel=0; }
 2772:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2773:     for (my $i=0; $i<=18; $i++) {
 2774:         $selectform.="<option value=\"$i\" ".
 2775:             ($i==$deflevel ? 'selected="selected" ' : '').
 2776:                 ">".&gradeleveldescription($i)."</option>\n";
 2777:     }
 2778:     $selectform.="</select>";
 2779:     return $selectform;
 2780: }
 2781: 
 2782: #-------------------------------------------
 2783: 
 2784: =pod
 2785: 
 2786: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2787: 
 2788: Returns a string containing a <select name='$name' size='1'> form to 
 2789: allow a user to select the domain to preform an operation in.  
 2790: See loncreateuser.pm for an example invocation and use.
 2791: 
 2792: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2793: selected");
 2794: 
 2795: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2796: 
 2797: 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.
 2798: 
 2799: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2800: 
 2801: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2802: 
 2803: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2804: 
 2805: =cut
 2806: 
 2807: #-------------------------------------------
 2808: sub select_dom_form {
 2809:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2810:     if ($onchange) {
 2811:         $onchange = ' onchange="'.$onchange.'"';
 2812:     }
 2813:     if ($disabled) {
 2814:         $disabled = ' disabled="disabled"';
 2815:     }
 2816:     my (@domains,%exclude);
 2817:     if (ref($incdoms) eq 'ARRAY') {
 2818:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2819:     } else {
 2820:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2821:     }
 2822:     if ($includeempty) { @domains=('',@domains); }
 2823:     if (ref($excdoms) eq 'ARRAY') {
 2824:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2825:     }
 2826:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2827:     foreach my $dom (@domains) {
 2828:         next if ($exclude{$dom});
 2829:         $selectdomain.="<option value=\"$dom\" ".
 2830:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2831:         if ($showdomdesc) {
 2832:             if ($dom ne '') {
 2833:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2834:                 if ($domdesc ne '') {
 2835:                     $selectdomain .= ' ('.$domdesc.')';
 2836:                 }
 2837:             } 
 2838:         }
 2839:         $selectdomain .= "</option>\n";
 2840:     }
 2841:     $selectdomain.="</select>";
 2842:     return $selectdomain;
 2843: }
 2844: 
 2845: #-------------------------------------------
 2846: 
 2847: =pod
 2848: 
 2849: =item * &home_server_form_item($domain,$name,$defaultflag)
 2850: 
 2851: input: 4 arguments (two required, two optional) - 
 2852:     $domain - domain of new user
 2853:     $name - name of form element
 2854:     $default - Value of 'default' causes a default item to be first 
 2855:                             option, and selected by default. 
 2856:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2857:                             if 1 server found, or default, if 0 found.
 2858: output: returns 2 items: 
 2859: (a) form element which contains either:
 2860:    (i) <select name="$name">
 2861:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2862:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2863:        </select>
 2864:        form item if there are multiple library servers in $domain, or
 2865:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2866:        if there is only one library server in $domain.
 2867: 
 2868: (b) number of library servers found.
 2869: 
 2870: See loncreateuser.pm for example of use.
 2871: 
 2872: =cut
 2873: 
 2874: #-------------------------------------------
 2875: sub home_server_form_item {
 2876:     my ($domain,$name,$default,$hide) = @_;
 2877:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2878:     my $result;
 2879:     my $numlib = keys(%servers);
 2880:     if ($numlib > 1) {
 2881:         $result .= '<select name="'.$name.'" />'."\n";
 2882:         if ($default) {
 2883:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2884:                        '</option>'."\n";
 2885:         }
 2886:         foreach my $hostid (sort(keys(%servers))) {
 2887:             $result.= '<option value="'.$hostid.'">'.
 2888: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2889:         }
 2890:         $result .= '</select>'."\n";
 2891:     } elsif ($numlib == 1) {
 2892:         my $hostid;
 2893:         foreach my $item (keys(%servers)) {
 2894:             $hostid = $item;
 2895:         }
 2896:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2897:                    $hostid.'" />';
 2898:                    if (!$hide) {
 2899:                        $result .= $hostid.' '.$servers{$hostid};
 2900:                    }
 2901:                    $result .= "\n";
 2902:     } elsif ($default) {
 2903:         $result .= '<input type="hidden" name="'.$name.
 2904:                    '" value="default" />';
 2905:                    if (!$hide) {
 2906:                        $result .= &mt('default');
 2907:                    }
 2908:                    $result .= "\n";
 2909:     }
 2910:     return ($result,$numlib);
 2911: }
 2912: 
 2913: =pod
 2914: 
 2915: =back 
 2916: 
 2917: =cut
 2918: 
 2919: ###############################################################
 2920: ##                  Decoding User Agent                      ##
 2921: ###############################################################
 2922: 
 2923: =pod
 2924: 
 2925: =head1 Decoding the User Agent
 2926: 
 2927: =over 4
 2928: 
 2929: =item * &decode_user_agent()
 2930: 
 2931: Inputs: $r
 2932: 
 2933: Outputs:
 2934: 
 2935: =over 4
 2936: 
 2937: =item * $httpbrowser
 2938: 
 2939: =item * $clientbrowser
 2940: 
 2941: =item * $clientversion
 2942: 
 2943: =item * $clientmathml
 2944: 
 2945: =item * $clientunicode
 2946: 
 2947: =item * $clientos
 2948: 
 2949: =item * $clientmobile
 2950: 
 2951: =item * $clientinfo
 2952: 
 2953: =item * $clientosversion
 2954: 
 2955: =back
 2956: 
 2957: =back 
 2958: 
 2959: =cut
 2960: 
 2961: ###############################################################
 2962: ###############################################################
 2963: sub decode_user_agent {
 2964:     my ($r)=@_;
 2965:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2966:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2967:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2968:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2969:     my $clientbrowser='unknown';
 2970:     my $clientversion='0';
 2971:     my $clientmathml='';
 2972:     my $clientunicode='0';
 2973:     my $clientmobile=0;
 2974:     my $clientosversion='';
 2975:     for (my $i=0;$i<=$#browsertype;$i++) {
 2976:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2977: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2978: 	    $clientbrowser=$bname;
 2979:             $httpbrowser=~/$vreg/i;
 2980: 	    $clientversion=$1;
 2981:             $clientmathml=($clientversion>=$minv);
 2982:             $clientunicode=($clientversion>=$univ);
 2983: 	}
 2984:     }
 2985:     my $clientos='unknown';
 2986:     my $clientinfo;
 2987:     if (($httpbrowser=~/linux/i) ||
 2988:         ($httpbrowser=~/unix/i) ||
 2989:         ($httpbrowser=~/ux/i) ||
 2990:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2991:     if (($httpbrowser=~/vax/i) ||
 2992:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2993:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2994:     if (($httpbrowser=~/mac/i) ||
 2995:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2996:     if ($httpbrowser=~/win/i) {
 2997:         $clientos='win';
 2998:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2999:             $clientosversion = $1;
 3000:         }
 3001:     }
 3002:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3003:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3004:         $clientmobile=lc($1);
 3005:     }
 3006:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3007:         $clientinfo = 'firefox-'.$1;
 3008:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3009:         $clientinfo = 'chromeframe-'.$1;
 3010:     }
 3011:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3012:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3013:             $clientosversion);
 3014: }
 3015: 
 3016: ###############################################################
 3017: ##    Authentication changing form generation subroutines    ##
 3018: ###############################################################
 3019: ##
 3020: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3021: ## hash, and have reasonable default values.
 3022: ##
 3023: ##    formname = the name given in the <form> tag.
 3024: #-------------------------------------------
 3025: 
 3026: =pod
 3027: 
 3028: =head1 Authentication Routines
 3029: 
 3030: =over 4
 3031: 
 3032: =item * &authform_xxxxxx()
 3033: 
 3034: The authform_xxxxxx subroutines provide javascript and html forms which 
 3035: handle some of the conveniences required for authentication forms.  
 3036: This is not an optimal method, but it works.  
 3037: 
 3038: =over 4
 3039: 
 3040: =item * authform_header
 3041: 
 3042: =item * authform_authorwarning
 3043: 
 3044: =item * authform_nochange
 3045: 
 3046: =item * authform_kerberos
 3047: 
 3048: =item * authform_internal
 3049: 
 3050: =item * authform_filesystem
 3051: 
 3052: =item * authform_lti
 3053: 
 3054: =back
 3055: 
 3056: See loncreateuser.pm for invocation and use examples.
 3057: 
 3058: =cut
 3059: 
 3060: #-------------------------------------------
 3061: sub authform_header{  
 3062:     my %in = (
 3063:         formname => 'cu',
 3064:         kerb_def_dom => '',
 3065:         @_,
 3066:     );
 3067:     $in{'formname'} = 'document.' . $in{'formname'};
 3068:     my $result='';
 3069: 
 3070: #---------------------------------------------- Code for upper case translation
 3071:     my $Javascript_toUpperCase;
 3072:     unless ($in{kerb_def_dom}) {
 3073:         $Javascript_toUpperCase =<<"END";
 3074:         switch (choice) {
 3075:            case 'krb': currentform.elements[choicearg].value =
 3076:                currentform.elements[choicearg].value.toUpperCase();
 3077:                break;
 3078:            default:
 3079:         }
 3080: END
 3081:     } else {
 3082:         $Javascript_toUpperCase = "";
 3083:     }
 3084: 
 3085:     my $radioval = "'nochange'";
 3086:     if (defined($in{'curr_authtype'})) {
 3087:         if ($in{'curr_authtype'} ne '') {
 3088:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3089:         }
 3090:     }
 3091:     my $argfield = 'null';
 3092:     if (defined($in{'mode'})) {
 3093:         if ($in{'mode'} eq 'modifycourse')  {
 3094:             if (defined($in{'curr_autharg'})) {
 3095:                 if ($in{'curr_autharg'} ne '') {
 3096:                     $argfield = "'$in{'curr_autharg'}'";
 3097:                 }
 3098:             }
 3099:         }
 3100:     }
 3101: 
 3102:     $result.=<<"END";
 3103: var current = new Object();
 3104: current.radiovalue = $radioval;
 3105: current.argfield = $argfield;
 3106: 
 3107: function changed_radio(choice,currentform) {
 3108:     var choicearg = choice + 'arg';
 3109:     // If a radio button in changed, we need to change the argfield
 3110:     if (current.radiovalue != choice) {
 3111:         current.radiovalue = choice;
 3112:         if (current.argfield != null) {
 3113:             currentform.elements[current.argfield].value = '';
 3114:         }
 3115:         if (choice == 'nochange') {
 3116:             current.argfield = null;
 3117:         } else {
 3118:             current.argfield = choicearg;
 3119:             switch(choice) {
 3120:                 case 'krb': 
 3121:                     currentform.elements[current.argfield].value = 
 3122:                         "$in{'kerb_def_dom'}";
 3123:                 break;
 3124:               default:
 3125:                 break;
 3126:             }
 3127:         }
 3128:     }
 3129:     return;
 3130: }
 3131: 
 3132: function changed_text(choice,currentform) {
 3133:     var choicearg = choice + 'arg';
 3134:     if (currentform.elements[choicearg].value !='') {
 3135:         $Javascript_toUpperCase
 3136:         // clear old field
 3137:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3138:             currentform.elements[current.argfield].value = '';
 3139:         }
 3140:         current.argfield = choicearg;
 3141:     }
 3142:     set_auth_radio_buttons(choice,currentform);
 3143:     return;
 3144: }
 3145: 
 3146: function set_auth_radio_buttons(newvalue,currentform) {
 3147:     var numauthchoices = currentform.login.length;
 3148:     if (typeof numauthchoices  == "undefined") {
 3149:         return;
 3150:     } 
 3151:     var i=0;
 3152:     while (i < numauthchoices) {
 3153:         if (currentform.login[i].value == newvalue) { break; }
 3154:         i++;
 3155:     }
 3156:     if (i == numauthchoices) {
 3157:         return;
 3158:     }
 3159:     current.radiovalue = newvalue;
 3160:     currentform.login[i].checked = true;
 3161:     return;
 3162: }
 3163: END
 3164:     return $result;
 3165: }
 3166: 
 3167: sub authform_authorwarning {
 3168:     my $result='';
 3169:     $result='<i>'.
 3170:         &mt('As a general rule, only authors or co-authors should be '.
 3171:             'filesystem authenticated '.
 3172:             '(which allows access to the server filesystem).')."</i>\n";
 3173:     return $result;
 3174: }
 3175: 
 3176: sub authform_nochange {
 3177:     my %in = (
 3178:               formname => 'document.cu',
 3179:               kerb_def_dom => 'MSU.EDU',
 3180:               @_,
 3181:           );
 3182:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3183:     my $result;
 3184:     if (!$authnum) {
 3185:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3186:     } else {
 3187:         $result = '<label>'.&mt('[_1] Do not change login data',
 3188:                   '<input type="radio" name="login" value="nochange" '.
 3189:                   'checked="checked" onclick="'.
 3190:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3191: 	    '</label>';
 3192:     }
 3193:     return $result;
 3194: }
 3195: 
 3196: sub authform_kerberos {
 3197:     my %in = (
 3198:               formname => 'document.cu',
 3199:               kerb_def_dom => 'MSU.EDU',
 3200:               kerb_def_auth => 'krb4',
 3201:               @_,
 3202:               );
 3203:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3204:         $autharg,$jscall,$disabled);
 3205:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3206:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3207:        $check5 = ' checked="checked"';
 3208:     } else {
 3209:        $check4 = ' checked="checked"';
 3210:     }
 3211:     if ($in{'readonly'}) {
 3212:         $disabled = ' disabled="disabled"';
 3213:     }
 3214:     $krbarg = $in{'kerb_def_dom'};
 3215:     if (defined($in{'curr_authtype'})) {
 3216:         if ($in{'curr_authtype'} eq 'krb') {
 3217:             $krbcheck = ' checked="checked"';
 3218:             if (defined($in{'mode'})) {
 3219:                 if ($in{'mode'} eq 'modifyuser') {
 3220:                     $krbcheck = '';
 3221:                 }
 3222:             }
 3223:             if (defined($in{'curr_kerb_ver'})) {
 3224:                 if ($in{'curr_krb_ver'} eq '5') {
 3225:                     $check5 = ' checked="checked"';
 3226:                     $check4 = '';
 3227:                 } else {
 3228:                     $check4 = ' checked="checked"';
 3229:                     $check5 = '';
 3230:                 }
 3231:             }
 3232:             if (defined($in{'curr_autharg'})) {
 3233:                 $krbarg = $in{'curr_autharg'};
 3234:             }
 3235:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3236:                 if (defined($in{'curr_autharg'})) {
 3237:                     $result = 
 3238:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3239:         $in{'curr_autharg'},$krbver);
 3240:                 } else {
 3241:                     $result =
 3242:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3243:                 }
 3244:                 return $result; 
 3245:             }
 3246:         }
 3247:     } else {
 3248:         if ($authnum == 1) {
 3249:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3250:         }
 3251:     }
 3252:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3253:         return;
 3254:     } elsif ($authtype eq '') {
 3255:         if (defined($in{'mode'})) {
 3256:             if ($in{'mode'} eq 'modifycourse') {
 3257:                 if ($authnum == 1) {
 3258:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3259:                 }
 3260:             }
 3261:         }
 3262:     }
 3263:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3264:     if ($authtype eq '') {
 3265:         $authtype = '<input type="radio" name="login" value="krb" '.
 3266:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3267:                     $krbcheck.$disabled.' />';
 3268:     }
 3269:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3270:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3271:          $in{'curr_authtype'} eq 'krb5') ||
 3272:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3273:          $in{'curr_authtype'} eq 'krb4')) {
 3274:         $result .= &mt
 3275:         ('[_1] Kerberos authenticated with domain [_2] '.
 3276:          '[_3] Version 4 [_4] Version 5 [_5]',
 3277:          '<label>'.$authtype,
 3278:          '</label><input type="text" size="10" name="krbarg" '.
 3279:              'value="'.$krbarg.'" '.
 3280:              'onchange="'.$jscall.'"'.$disabled.' />',
 3281:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3282:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3283: 	 '</label>');
 3284:     } elsif ($can_assign{'krb4'}) {
 3285:         $result .= &mt
 3286:         ('[_1] Kerberos authenticated with domain [_2] '.
 3287:          '[_3] Version 4 [_4]',
 3288:          '<label>'.$authtype,
 3289:          '</label><input type="text" size="10" name="krbarg" '.
 3290:              'value="'.$krbarg.'" '.
 3291:              'onchange="'.$jscall.'"'.$disabled.' />',
 3292:          '<label><input type="hidden" name="krbver" value="4" />',
 3293:          '</label>');
 3294:     } elsif ($can_assign{'krb5'}) {
 3295:         $result .= &mt
 3296:         ('[_1] Kerberos authenticated with domain [_2] '.
 3297:          '[_3] Version 5 [_4]',
 3298:          '<label>'.$authtype,
 3299:          '</label><input type="text" size="10" name="krbarg" '.
 3300:              'value="'.$krbarg.'" '.
 3301:              'onchange="'.$jscall.'"'.$disabled.' />',
 3302:          '<label><input type="hidden" name="krbver" value="5" />',
 3303:          '</label>');
 3304:     }
 3305:     return $result;
 3306: }
 3307: 
 3308: sub authform_internal {
 3309:     my %in = (
 3310:                 formname => 'document.cu',
 3311:                 kerb_def_dom => 'MSU.EDU',
 3312:                 @_,
 3313:                 );
 3314:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3315:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3316:     if ($in{'readonly'}) {
 3317:         $disabled = ' disabled="disabled"';
 3318:     }
 3319:     if (defined($in{'curr_authtype'})) {
 3320:         if ($in{'curr_authtype'} eq 'int') {
 3321:             if ($can_assign{'int'}) {
 3322:                 $intcheck = 'checked="checked" ';
 3323:                 if (defined($in{'mode'})) {
 3324:                     if ($in{'mode'} eq 'modifyuser') {
 3325:                         $intcheck = '';
 3326:                     }
 3327:                 }
 3328:                 if (defined($in{'curr_autharg'})) {
 3329:                     $intarg = $in{'curr_autharg'};
 3330:                 }
 3331:             } else {
 3332:                 $result = &mt('Currently internally authenticated.');
 3333:                 return $result;
 3334:             }
 3335:         }
 3336:     } else {
 3337:         if ($authnum == 1) {
 3338:             $authtype = '<input type="hidden" name="login" value="int" />';
 3339:         }
 3340:     }
 3341:     if (!$can_assign{'int'}) {
 3342:         return;
 3343:     } elsif ($authtype eq '') {
 3344:         if (defined($in{'mode'})) {
 3345:             if ($in{'mode'} eq 'modifycourse') {
 3346:                 if ($authnum == 1) {
 3347:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3348:                 }
 3349:             }
 3350:         }
 3351:     }
 3352:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3353:     if ($authtype eq '') {
 3354:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3355:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3356:     }
 3357:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3358:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3359:     $result = &mt
 3360:         ('[_1] Internally authenticated (with initial password [_2])',
 3361:          '<label>'.$authtype,'</label>'.$autharg);
 3362:     $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>';
 3363:     return $result;
 3364: }
 3365: 
 3366: sub authform_local {
 3367:     my %in = (
 3368:               formname => 'document.cu',
 3369:               kerb_def_dom => 'MSU.EDU',
 3370:               @_,
 3371:               );
 3372:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3373:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3374:     if ($in{'readonly'}) {
 3375:         $disabled = ' disabled="disabled"';
 3376:     } 
 3377:     if (defined($in{'curr_authtype'})) {
 3378:         if ($in{'curr_authtype'} eq 'loc') {
 3379:             if ($can_assign{'loc'}) {
 3380:                 $loccheck = 'checked="checked" ';
 3381:                 if (defined($in{'mode'})) {
 3382:                     if ($in{'mode'} eq 'modifyuser') {
 3383:                         $loccheck = '';
 3384:                     }
 3385:                 }
 3386:                 if (defined($in{'curr_autharg'})) {
 3387:                     $locarg = $in{'curr_autharg'};
 3388:                 }
 3389:             } else {
 3390:                 $result = &mt('Currently using local (institutional) authentication.');
 3391:                 return $result;
 3392:             }
 3393:         }
 3394:     } else {
 3395:         if ($authnum == 1) {
 3396:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3397:         }
 3398:     }
 3399:     if (!$can_assign{'loc'}) {
 3400:         return;
 3401:     } elsif ($authtype eq '') {
 3402:         if (defined($in{'mode'})) {
 3403:             if ($in{'mode'} eq 'modifycourse') {
 3404:                 if ($authnum == 1) {
 3405:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3406:                 }
 3407:             }
 3408:         }
 3409:     }
 3410:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3411:     if ($authtype eq '') {
 3412:         $authtype = '<input type="radio" name="login" value="loc" '.
 3413:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3414:                     $jscall.'"'.$disabled.' />';
 3415:     }
 3416:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3417:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3418:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3419:                   '<label>'.$authtype,'</label>'.$autharg);
 3420:     return $result;
 3421: }
 3422: 
 3423: sub authform_filesystem {
 3424:     my %in = (
 3425:               formname => 'document.cu',
 3426:               kerb_def_dom => 'MSU.EDU',
 3427:               @_,
 3428:               );
 3429:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3430:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3431:     if ($in{'readonly'}) {
 3432:         $disabled = ' disabled="disabled"';
 3433:     }
 3434:     if (defined($in{'curr_authtype'})) {
 3435:         if ($in{'curr_authtype'} eq 'fsys') {
 3436:             if ($can_assign{'fsys'}) {
 3437:                 $fsyscheck = 'checked="checked" ';
 3438:                 if (defined($in{'mode'})) {
 3439:                     if ($in{'mode'} eq 'modifyuser') {
 3440:                         $fsyscheck = '';
 3441:                     }
 3442:                 }
 3443:             } else {
 3444:                 $result = &mt('Currently Filesystem Authenticated.');
 3445:                 return $result;
 3446:             }
 3447:         }
 3448:     } else {
 3449:         if ($authnum == 1) {
 3450:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3451:         }
 3452:     }
 3453:     if (!$can_assign{'fsys'}) {
 3454:         return;
 3455:     } elsif ($authtype eq '') {
 3456:         if (defined($in{'mode'})) {
 3457:             if ($in{'mode'} eq 'modifycourse') {
 3458:                 if ($authnum == 1) {
 3459:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3460:                 }
 3461:             }
 3462:         }
 3463:     }
 3464:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3465:     if ($authtype eq '') {
 3466:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3467:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3468:                     $jscall.'"'.$disabled.' />';
 3469:     }
 3470:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3471:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3472:     $result = &mt
 3473:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3474:          '<label>'.$authtype,'</label>'.$autharg);
 3475:     return $result;
 3476: }
 3477: 
 3478: sub authform_lti {
 3479:     my %in = (
 3480:               formname => 'document.cu',
 3481:               kerb_def_dom => 'MSU.EDU',
 3482:               @_,
 3483:               );
 3484:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3485:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3486:     if ($in{'readonly'}) {
 3487:         $disabled = ' disabled="disabled"';
 3488:     }
 3489:     if (defined($in{'curr_authtype'})) {
 3490:         if ($in{'curr_authtype'} eq 'lti') {
 3491:             if ($can_assign{'lti'}) {
 3492:                 $lticheck = 'checked="checked" ';
 3493:                 if (defined($in{'mode'})) {
 3494:                     if ($in{'mode'} eq 'modifyuser') {
 3495:                         $lticheck = '';
 3496:                     }
 3497:                 }
 3498:             } else {
 3499:                 $result = &mt('Currently LTI Authenticated.');
 3500:                 return $result;
 3501:             }
 3502:         }
 3503:     } else {
 3504:         if ($authnum == 1) {
 3505:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3506:         }
 3507:     }
 3508:     if (!$can_assign{'lti'}) {
 3509:         return;
 3510:     } elsif ($authtype eq '') {
 3511:         if (defined($in{'mode'})) {
 3512:             if ($in{'mode'} eq 'modifycourse') {
 3513:                 if ($authnum == 1) {
 3514:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3515:                 }
 3516:             }
 3517:         }
 3518:     }
 3519:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3520:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3521:         $authtype = '<input type="radio" name="login" value="lti" '.
 3522:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3523:                     $jscall.'"'.$disabled.' />';
 3524:     }
 3525:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3526:     if ($authtype) {
 3527:         $result = &mt('[_1] LTI Authenticated',
 3528:                       '<label>'.$authtype.'</label>'.$autharg);
 3529:     } else {
 3530:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3531:                   $autharg;
 3532:     }
 3533:     return $result;
 3534: }
 3535: 
 3536: sub get_assignable_auth {
 3537:     my ($dom) = @_;
 3538:     if ($dom eq '') {
 3539:         $dom = $env{'request.role.domain'};
 3540:     }
 3541:     my %can_assign = (
 3542:                           krb4 => 1,
 3543:                           krb5 => 1,
 3544:                           int  => 1,
 3545:                           loc  => 1,
 3546:                           lti  => 1,
 3547:                      );
 3548:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3549:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3550:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3551:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3552:             my $context;
 3553:             if ($env{'request.role'} =~ /^au/) {
 3554:                 $context = 'author';
 3555:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3556:                 $context = 'domain';
 3557:             } elsif ($env{'request.course.id'}) {
 3558:                 $context = 'course';
 3559:             }
 3560:             if ($context) {
 3561:                 if (ref($authhash->{$context}) eq 'HASH') {
 3562:                    %can_assign = %{$authhash->{$context}}; 
 3563:                 }
 3564:             }
 3565:         }
 3566:     }
 3567:     my $authnum = 0;
 3568:     foreach my $key (keys(%can_assign)) {
 3569:         if ($can_assign{$key}) {
 3570:             $authnum ++;
 3571:         }
 3572:     }
 3573:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3574:         $authnum --;
 3575:     }
 3576:     return ($authnum,%can_assign);
 3577: }
 3578: 
 3579: sub check_passwd_rules {
 3580:     my ($domain,$plainpass) = @_;
 3581:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3582:     my ($min,$max,@chars,@brokerule,$warning);
 3583:     $min = $Apache::lonnet::passwdmin;
 3584:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3585:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3586:             if ($passwdconf{'min'} > $min) {
 3587:                 $min = $passwdconf{'min'};
 3588:             }
 3589:         }
 3590:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3591:             $max = $passwdconf{'max'};
 3592:         }
 3593:         @chars = @{$passwdconf{'chars'}};
 3594:     }
 3595:     if (($min) && (length($plainpass) < $min)) {
 3596:         push(@brokerule,'min');
 3597:     }
 3598:     if (($max) && (length($plainpass) > $max)) {
 3599:         push(@brokerule,'max');
 3600:     }
 3601:     if (@chars) {
 3602:         my %rules;
 3603:         map { $rules{$_} = 1; } @chars;
 3604:         if ($rules{'uc'}) {
 3605:             unless ($plainpass =~ /[A-Z]/) {
 3606:                 push(@brokerule,'uc');
 3607:             }
 3608:         }
 3609:         if ($rules{'lc'}) {
 3610:             unless ($plainpass =~ /[a-z]/) {
 3611:                 push(@brokerule,'lc');
 3612:             }
 3613:         }
 3614:         if ($rules{'num'}) {
 3615:             unless ($plainpass =~ /\d/) {
 3616:                 push(@brokerule,'num');
 3617:             }
 3618:         }
 3619:         if ($rules{'spec'}) {
 3620:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3621:                 push(@brokerule,'spec');
 3622:             }
 3623:         }
 3624:     }
 3625:     if (@brokerule) {
 3626:         my %rulenames = &Apache::lonlocal::texthash(
 3627:             uc   => 'At least one upper case letter',
 3628:             lc   => 'At least one lower case letter',
 3629:             num  => 'At least one number',
 3630:             spec => 'At least one non-alphanumeric',
 3631:         );
 3632:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3633:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3634:         $rulenames{'num'} .= ': 0123456789';
 3635:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3636:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3637:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3638:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3639:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3640:             if (grep(/^$rule$/,@brokerule)) {
 3641:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3642:             }
 3643:         }
 3644:         $warning .= '</ul>';
 3645:     }
 3646:     if (wantarray) {
 3647:         return @brokerule;
 3648:     }
 3649:     return $warning;
 3650: }
 3651: 
 3652: ###############################################################
 3653: ##    Get Kerberos Defaults for Domain                 ##
 3654: ###############################################################
 3655: ##
 3656: ## Returns default kerberos version and an associated argument
 3657: ## as listed in file domain.tab. If not listed, provides
 3658: ## appropriate default domain and kerberos version.
 3659: ##
 3660: #-------------------------------------------
 3661: 
 3662: =pod
 3663: 
 3664: =item * &get_kerberos_defaults()
 3665: 
 3666: get_kerberos_defaults($target_domain) returns the default kerberos
 3667: version and domain. If not found, it defaults to version 4 and the 
 3668: domain of the server.
 3669: 
 3670: =over 4
 3671: 
 3672: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3673: 
 3674: =back
 3675: 
 3676: =back
 3677: 
 3678: =cut
 3679: 
 3680: #-------------------------------------------
 3681: sub get_kerberos_defaults {
 3682:     my $domain=shift;
 3683:     my ($krbdef,$krbdefdom);
 3684:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3685:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3686:         $krbdef = $domdefaults{'auth_def'};
 3687:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3688:     } else {
 3689:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3690:         my $krbdefdom=$1;
 3691:         $krbdefdom=~tr/a-z/A-Z/;
 3692:         $krbdef = "krb4";
 3693:     }
 3694:     return ($krbdef,$krbdefdom);
 3695: }
 3696: 
 3697: 
 3698: ###############################################################
 3699: ##                Thesaurus Functions                        ##
 3700: ###############################################################
 3701: 
 3702: =pod
 3703: 
 3704: =head1 Thesaurus Functions
 3705: 
 3706: =over 4
 3707: 
 3708: =item * &initialize_keywords()
 3709: 
 3710: Initializes the package variable %Keywords if it is empty.  Uses the
 3711: package variable $thesaurus_db_file.
 3712: 
 3713: =cut
 3714: 
 3715: ###################################################
 3716: 
 3717: sub initialize_keywords {
 3718:     return 1 if (scalar keys(%Keywords));
 3719:     # If we are here, %Keywords is empty, so fill it up
 3720:     #   Make sure the file we need exists...
 3721:     if (! -e $thesaurus_db_file) {
 3722:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3723:                                  " failed because it does not exist");
 3724:         return 0;
 3725:     }
 3726:     #   Set up the hash as a database
 3727:     my %thesaurus_db;
 3728:     if (! tie(%thesaurus_db,'GDBM_File',
 3729:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3730:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3731:                                  $thesaurus_db_file);
 3732:         return 0;
 3733:     } 
 3734:     #  Get the average number of appearances of a word.
 3735:     my $avecount = $thesaurus_db{'average.count'};
 3736:     #  Put keywords (those that appear > average) into %Keywords
 3737:     while (my ($word,$data)=each (%thesaurus_db)) {
 3738:         my ($count,undef) = split /:/,$data;
 3739:         $Keywords{$word}++ if ($count > $avecount);
 3740:     }
 3741:     untie %thesaurus_db;
 3742:     # Remove special values from %Keywords.
 3743:     foreach my $value ('total.count','average.count') {
 3744:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3745:   }
 3746:     return 1;
 3747: }
 3748: 
 3749: ###################################################
 3750: 
 3751: =pod
 3752: 
 3753: =item * &keyword($word)
 3754: 
 3755: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3756: than the average number of times in the thesaurus database.  Calls 
 3757: &initialize_keywords
 3758: 
 3759: =cut
 3760: 
 3761: ###################################################
 3762: 
 3763: sub keyword {
 3764:     return if (!&initialize_keywords());
 3765:     my $word=lc(shift());
 3766:     $word=~s/\W//g;
 3767:     return exists($Keywords{$word});
 3768: }
 3769: 
 3770: ###############################################################
 3771: 
 3772: =pod 
 3773: 
 3774: =item * &get_related_words()
 3775: 
 3776: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3777: an array of words.  If the keyword is not in the thesaurus, an empty array
 3778: will be returned.  The order of the words returned is determined by the
 3779: database which holds them.
 3780: 
 3781: Uses global $thesaurus_db_file.
 3782: 
 3783: 
 3784: =cut
 3785: 
 3786: ###############################################################
 3787: sub get_related_words {
 3788:     my $keyword = shift;
 3789:     my %thesaurus_db;
 3790:     if (! -e $thesaurus_db_file) {
 3791:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3792:                                  "failed because the file does not exist");
 3793:         return ();
 3794:     }
 3795:     if (! tie(%thesaurus_db,'GDBM_File',
 3796:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3797:         return ();
 3798:     } 
 3799:     my @Words=();
 3800:     my $count=0;
 3801:     if (exists($thesaurus_db{$keyword})) {
 3802: 	# The first element is the number of times
 3803: 	# the word appears.  We do not need it now.
 3804: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3805: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3806: 	my $threshold=$mostfrequentcount/10;
 3807:         foreach my $possibleword (@RelatedWords) {
 3808:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3809:             if ($wordcount>$threshold) {
 3810: 		push(@Words,$word);
 3811:                 $count++;
 3812:                 if ($count>10) { last; }
 3813: 	    }
 3814:         }
 3815:     }
 3816:     untie %thesaurus_db;
 3817:     return @Words;
 3818: }
 3819: ###############################################################
 3820: #
 3821: #  Spell checking
 3822: #
 3823: 
 3824: =pod
 3825: 
 3826: =back
 3827: 
 3828: =head1 Spell checking
 3829: 
 3830: =over 4
 3831: 
 3832: =item * &check_spelling($wordlist $language)
 3833: 
 3834: Takes a string containing words and feeds it to an external
 3835: spellcheck program via a pipeline. Returns a string containing
 3836: them mis-spelled words.
 3837: 
 3838: Parameters:
 3839: 
 3840: =over 4
 3841: 
 3842: =item - $wordlist
 3843: 
 3844: String that will be fed into the spellcheck program.
 3845: 
 3846: =item - $language
 3847: 
 3848: Language string that specifies the language for which the spell
 3849: check will be performed.
 3850: 
 3851: =back
 3852: 
 3853: =back
 3854: 
 3855: Note: This sub assumes that aspell is installed.
 3856: 
 3857: 
 3858: =cut
 3859: 
 3860: 
 3861: sub check_spelling {
 3862:     my ($wordlist, $language) = @_;
 3863:     my @misspellings;
 3864:     
 3865:     # Generate the speller and set the langauge.
 3866:     # if explicitly selected:
 3867: 
 3868:     my $speller = Text::Aspell->new;
 3869:     if ($language) {
 3870: 	$speller->set_option('lang', $language);
 3871:     }
 3872: 
 3873:     # Turn the word list into an array of words by splittingon whitespace
 3874: 
 3875:     my @words = split(/\s+/, $wordlist);
 3876: 
 3877:     foreach my $word (@words) {
 3878: 	if(! $speller->check($word)) {
 3879: 	    push(@misspellings, $word);
 3880: 	}
 3881:     }
 3882:     return join(' ', @misspellings);
 3883:     
 3884: }
 3885: 
 3886: # -------------------------------------------------------------- Plaintext name
 3887: =pod
 3888: 
 3889: =head1 User Name Functions
 3890: 
 3891: =over 4
 3892: 
 3893: =item * &plainname($uname,$udom,$first)
 3894: 
 3895: Takes a users logon name and returns it as a string in
 3896: "first middle last generation" form 
 3897: if $first is set to 'lastname' then it returns it as
 3898: 'lastname generation, firstname middlename' if their is a lastname
 3899: 
 3900: =cut
 3901: 
 3902: 
 3903: ###############################################################
 3904: sub plainname {
 3905:     my ($uname,$udom,$first)=@_;
 3906:     return if (!defined($uname) || !defined($udom));
 3907:     my %names=&getnames($uname,$udom);
 3908:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3909: 					  $names{'middlename'},
 3910: 					  $names{'lastname'},
 3911: 					  $names{'generation'},$first);
 3912:     $name=~s/^\s+//;
 3913:     $name=~s/\s+$//;
 3914:     $name=~s/\s+/ /g;
 3915:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3916:     return $name;
 3917: }
 3918: 
 3919: # -------------------------------------------------------------------- Nickname
 3920: =pod
 3921: 
 3922: =item * &nickname($uname,$udom)
 3923: 
 3924: Gets a users name and returns it as a string as
 3925: 
 3926: "&quot;nickname&quot;"
 3927: 
 3928: if the user has a nickname or
 3929: 
 3930: "first middle last generation"
 3931: 
 3932: if the user does not
 3933: 
 3934: =cut
 3935: 
 3936: sub nickname {
 3937:     my ($uname,$udom)=@_;
 3938:     return if (!defined($uname) || !defined($udom));
 3939:     my %names=&getnames($uname,$udom);
 3940:     my $name=$names{'nickname'};
 3941:     if ($name) {
 3942:        $name='&quot;'.$name.'&quot;'; 
 3943:     } else {
 3944:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3945: 	     $names{'lastname'}.' '.$names{'generation'};
 3946:        $name=~s/\s+$//;
 3947:        $name=~s/\s+/ /g;
 3948:     }
 3949:     return $name;
 3950: }
 3951: 
 3952: sub getnames {
 3953:     my ($uname,$udom)=@_;
 3954:     return if (!defined($uname) || !defined($udom));
 3955:     if ($udom eq 'public' && $uname eq 'public') {
 3956: 	return ('lastname' => &mt('Public'));
 3957:     }
 3958:     my $id=$uname.':'.$udom;
 3959:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3960:     if ($cached) {
 3961: 	return %{$names};
 3962:     } else {
 3963: 	my %loadnames=&Apache::lonnet::get('environment',
 3964:                     ['firstname','middlename','lastname','generation','nickname'],
 3965: 					 $udom,$uname);
 3966: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3967: 	return %loadnames;
 3968:     }
 3969: }
 3970: 
 3971: # -------------------------------------------------------------------- getemails
 3972: 
 3973: =pod
 3974: 
 3975: =item * &getemails($uname,$udom)
 3976: 
 3977: Gets a user's email information and returns it as a hash with keys:
 3978: notification, critnotification, permanentemail
 3979: 
 3980: For notification and critnotification, values are comma-separated lists 
 3981: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3982:  
 3983: 
 3984: =cut
 3985: 
 3986: 
 3987: sub getemails {
 3988:     my ($uname,$udom)=@_;
 3989:     if ($udom eq 'public' && $uname eq 'public') {
 3990: 	return;
 3991:     }
 3992:     if (!$udom) { $udom=$env{'user.domain'}; }
 3993:     if (!$uname) { $uname=$env{'user.name'}; }
 3994:     my $id=$uname.':'.$udom;
 3995:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3996:     if ($cached) {
 3997: 	return %{$names};
 3998:     } else {
 3999: 	my %loadnames=&Apache::lonnet::get('environment',
 4000:                     			   ['notification','critnotification',
 4001: 					    'permanentemail'],
 4002: 					   $udom,$uname);
 4003: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4004: 	return %loadnames;
 4005:     }
 4006: }
 4007: 
 4008: sub flush_email_cache {
 4009:     my ($uname,$udom)=@_;
 4010:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4011:     if (!$uname) { $uname=$env{'user.name'};   }
 4012:     return if ($udom eq 'public' && $uname eq 'public');
 4013:     my $id=$uname.':'.$udom;
 4014:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4015: }
 4016: 
 4017: # -------------------------------------------------------------------- getlangs
 4018: 
 4019: =pod
 4020: 
 4021: =item * &getlangs($uname,$udom)
 4022: 
 4023: Gets a user's language preference and returns it as a hash with key:
 4024: language.
 4025: 
 4026: =cut
 4027: 
 4028: 
 4029: sub getlangs {
 4030:     my ($uname,$udom) = @_;
 4031:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4032:     if (!$uname) { $uname=$env{'user.name'};   }
 4033:     my $id=$uname.':'.$udom;
 4034:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4035:     if ($cached) {
 4036:         return %{$langs};
 4037:     } else {
 4038:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4039:                                            $udom,$uname);
 4040:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4041:         return %loadlangs;
 4042:     }
 4043: }
 4044: 
 4045: sub flush_langs_cache {
 4046:     my ($uname,$udom)=@_;
 4047:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4048:     if (!$uname) { $uname=$env{'user.name'};   }
 4049:     return if ($udom eq 'public' && $uname eq 'public');
 4050:     my $id=$uname.':'.$udom;
 4051:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4052: }
 4053: 
 4054: # ------------------------------------------------------------------ Screenname
 4055: 
 4056: =pod
 4057: 
 4058: =item * &screenname($uname,$udom)
 4059: 
 4060: Gets a users screenname and returns it as a string
 4061: 
 4062: =cut
 4063: 
 4064: sub screenname {
 4065:     my ($uname,$udom)=@_;
 4066:     if ($uname eq $env{'user.name'} &&
 4067: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4068:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4069:     return $names{'screenname'};
 4070: }
 4071: 
 4072: 
 4073: # ------------------------------------------------------------- Confirm Wrapper
 4074: =pod
 4075: 
 4076: =item * &confirmwrapper($message)
 4077: 
 4078: Wrap messages about completion of operation in box
 4079: 
 4080: =cut
 4081: 
 4082: sub confirmwrapper {
 4083:     my ($message)=@_;
 4084:     if ($message) {
 4085:         return "\n".'<div class="LC_confirm_box">'."\n"
 4086:                .$message."\n"
 4087:                .'</div>'."\n";
 4088:     } else {
 4089:         return $message;
 4090:     }
 4091: }
 4092: 
 4093: # ------------------------------------------------------------- Message Wrapper
 4094: 
 4095: sub messagewrapper {
 4096:     my ($link,$username,$domain,$subject,$text)=@_;
 4097:     return 
 4098:         '<a href="/adm/email?compose=individual&amp;'.
 4099:         'recname='.$username.'&amp;recdom='.$domain.
 4100: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4101:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4102: }
 4103: 
 4104: # --------------------------------------------------------------- Notes Wrapper
 4105: 
 4106: sub noteswrapper {
 4107:     my ($link,$un,$do)=@_;
 4108:     return 
 4109: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4110: }
 4111: 
 4112: # ------------------------------------------------------------- Aboutme Wrapper
 4113: 
 4114: sub aboutmewrapper {
 4115:     my ($link,$username,$domain,$target,$class)=@_;
 4116:     if (!defined($username)  && !defined($domain)) {
 4117:         return;
 4118:     }
 4119:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4120: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4121: }
 4122: 
 4123: # ------------------------------------------------------------ Syllabus Wrapper
 4124: 
 4125: sub syllabuswrapper {
 4126:     my ($linktext,$coursedir,$domain)=@_;
 4127:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4128: }
 4129: 
 4130: # -----------------------------------------------------------------------------
 4131: 
 4132: sub track_student_link {
 4133:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4134:     my $link ="/adm/trackstudent?";
 4135:     my $title = 'View recent activity';
 4136:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4137:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4138:         $link .= "selected_student=$sname:$sdom";
 4139:         $title .= ' of this student';
 4140:     } 
 4141:     if (defined($target) && $target !~ /^\s*$/) {
 4142:         $target = qq{target="$target"};
 4143:     } else {
 4144:         $target = '';
 4145:     }
 4146:     if ($start) { $link.='&amp;start='.$start; }
 4147:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4148:     $title = &mt($title);
 4149:     $linktext = &mt($linktext);
 4150:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4151: 	&help_open_topic('View_recent_activity');
 4152: }
 4153: 
 4154: sub slot_reservations_link {
 4155:     my ($linktext,$sname,$sdom,$target) = @_;
 4156:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4157:     my $title = 'View slot reservation history';
 4158:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4159:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4160:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4161:         $title .= ' of this student';
 4162:     }
 4163:     if (defined($target) && $target !~ /^\s*$/) {
 4164:         $target = qq{target="$target"};
 4165:     } else {
 4166:         $target = '';
 4167:     }
 4168:     $title = &mt($title);
 4169:     $linktext = &mt($linktext);
 4170:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4171: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4172: 
 4173: }
 4174: 
 4175: # ===================================================== Display a student photo
 4176: 
 4177: 
 4178: sub student_image_tag {
 4179:     my ($domain,$user)=@_;
 4180:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4181:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4182: 	return '<img src="'.$imgsrc.'" align="right" />';
 4183:     } else {
 4184: 	return '';
 4185:     }
 4186: }
 4187: 
 4188: =pod
 4189: 
 4190: =back
 4191: 
 4192: =head1 Access .tab File Data
 4193: 
 4194: =over 4
 4195: 
 4196: =item * &languageids() 
 4197: 
 4198: returns list of all language ids
 4199: 
 4200: =cut
 4201: 
 4202: sub languageids {
 4203:     return sort(keys(%language));
 4204: }
 4205: 
 4206: =pod
 4207: 
 4208: =item * &languagedescription() 
 4209: 
 4210: returns description of a specified language id
 4211: 
 4212: =cut
 4213: 
 4214: sub languagedescription {
 4215:     my $code=shift;
 4216:     return  ($supported_language{$code}?'* ':'').
 4217:             $language{$code}.
 4218: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4219: }
 4220: 
 4221: =pod
 4222: 
 4223: =item * &plainlanguagedescription
 4224: 
 4225: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4226: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4227: 
 4228: =cut
 4229: 
 4230: sub plainlanguagedescription {
 4231:     my $code=shift;
 4232:     return $language{$code};
 4233: }
 4234: 
 4235: =pod
 4236: 
 4237: =item * &supportedlanguagecode
 4238: 
 4239: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4240: code.
 4241: 
 4242: =cut
 4243: 
 4244: sub supportedlanguagecode {
 4245:     my $code=shift;
 4246:     return $supported_language{$code};
 4247: }
 4248: 
 4249: =pod
 4250: 
 4251: =item * &latexlanguage()
 4252: 
 4253: Given a language key code returns the correspondnig language to use
 4254: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4255: is no supported hyphenation for the language code.
 4256: 
 4257: =cut
 4258: 
 4259: sub latexlanguage {
 4260:     my $code = shift;
 4261:     return $latex_language{$code};
 4262: }
 4263: 
 4264: =pod
 4265: 
 4266: =item * &latexhyphenation()
 4267: 
 4268: Same as above but what's supplied is the language as it might be stored
 4269: in the metadata.
 4270: 
 4271: =cut
 4272: 
 4273: sub latexhyphenation {
 4274:     my $key = shift;
 4275:     return $latex_language_bykey{$key};
 4276: }
 4277: 
 4278: =pod
 4279: 
 4280: =item * &copyrightids() 
 4281: 
 4282: returns list of all copyrights
 4283: 
 4284: =cut
 4285: 
 4286: sub copyrightids {
 4287:     return sort(keys(%cprtag));
 4288: }
 4289: 
 4290: =pod
 4291: 
 4292: =item * &copyrightdescription() 
 4293: 
 4294: returns description of a specified copyright id
 4295: 
 4296: =cut
 4297: 
 4298: sub copyrightdescription {
 4299:     return &mt($cprtag{shift(@_)});
 4300: }
 4301: 
 4302: =pod
 4303: 
 4304: =item * &source_copyrightids() 
 4305: 
 4306: returns list of all source copyrights
 4307: 
 4308: =cut
 4309: 
 4310: sub source_copyrightids {
 4311:     return sort(keys(%scprtag));
 4312: }
 4313: 
 4314: =pod
 4315: 
 4316: =item * &source_copyrightdescription() 
 4317: 
 4318: returns description of a specified source copyright id
 4319: 
 4320: =cut
 4321: 
 4322: sub source_copyrightdescription {
 4323:     return &mt($scprtag{shift(@_)});
 4324: }
 4325: 
 4326: =pod
 4327: 
 4328: =item * &filecategories() 
 4329: 
 4330: returns list of all file categories
 4331: 
 4332: =cut
 4333: 
 4334: sub filecategories {
 4335:     return sort(keys(%category_extensions));
 4336: }
 4337: 
 4338: =pod
 4339: 
 4340: =item * &filecategorytypes() 
 4341: 
 4342: returns list of file types belonging to a given file
 4343: category
 4344: 
 4345: =cut
 4346: 
 4347: sub filecategorytypes {
 4348:     my ($cat) = @_;
 4349:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4350:         return @{$category_extensions{lc($cat)}};
 4351:     } else {
 4352:         return ();
 4353:     }
 4354: }
 4355: 
 4356: =pod
 4357: 
 4358: =item * &fileembstyle() 
 4359: 
 4360: returns embedding style for a specified file type
 4361: 
 4362: =cut
 4363: 
 4364: sub fileembstyle {
 4365:     return $fe{lc(shift(@_))};
 4366: }
 4367: 
 4368: sub filemimetype {
 4369:     return $fm{lc(shift(@_))};
 4370: }
 4371: 
 4372: 
 4373: sub filecategoryselect {
 4374:     my ($name,$value)=@_;
 4375:     return &select_form($value,$name,
 4376:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4377: }
 4378: 
 4379: =pod
 4380: 
 4381: =item * &filedescription() 
 4382: 
 4383: returns description for a specified file type
 4384: 
 4385: =cut
 4386: 
 4387: sub filedescription {
 4388:     my $file_description = $fd{lc(shift())};
 4389:     $file_description =~ s:([\[\]]):~$1:g;
 4390:     return &mt($file_description);
 4391: }
 4392: 
 4393: =pod
 4394: 
 4395: =item * &filedescriptionex() 
 4396: 
 4397: returns description for a specified file type with
 4398: extra formatting
 4399: 
 4400: =cut
 4401: 
 4402: sub filedescriptionex {
 4403:     my $ex=shift;
 4404:     my $file_description = $fd{lc($ex)};
 4405:     $file_description =~ s:([\[\]]):~$1:g;
 4406:     return '.'.$ex.' '.&mt($file_description);
 4407: }
 4408: 
 4409: # End of .tab access
 4410: =pod
 4411: 
 4412: =back
 4413: 
 4414: =cut
 4415: 
 4416: # ------------------------------------------------------------------ File Types
 4417: sub fileextensions {
 4418:     return sort(keys(%fe));
 4419: }
 4420: 
 4421: # ----------------------------------------------------------- Display Languages
 4422: # returns a hash with all desired display languages
 4423: #
 4424: 
 4425: sub display_languages {
 4426:     my %languages=();
 4427:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4428: 	$languages{$lang}=1;
 4429:     }
 4430:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4431:     if ($env{'form.displaylanguage'}) {
 4432: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4433: 	    $languages{$lang}=1;
 4434:         }
 4435:     }
 4436:     return %languages;
 4437: }
 4438: 
 4439: sub languages {
 4440:     my ($possible_langs) = @_;
 4441:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4442:     if (!ref($possible_langs)) {
 4443: 	if( wantarray ) {
 4444: 	    return @preferred_langs;
 4445: 	} else {
 4446: 	    return $preferred_langs[0];
 4447: 	}
 4448:     }
 4449:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4450:     my @preferred_possibilities;
 4451:     foreach my $preferred_lang (@preferred_langs) {
 4452: 	if (exists($possibilities{$preferred_lang})) {
 4453: 	    push(@preferred_possibilities, $preferred_lang);
 4454: 	}
 4455:     }
 4456:     if( wantarray ) {
 4457: 	return @preferred_possibilities;
 4458:     }
 4459:     return $preferred_possibilities[0];
 4460: }
 4461: 
 4462: sub user_lang {
 4463:     my ($touname,$toudom,$fromcid) = @_;
 4464:     my @userlangs;
 4465:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4466:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4467:                     $env{'course.'.$fromcid.'.languages'}));
 4468:     } else {
 4469:         my %langhash = &getlangs($touname,$toudom);
 4470:         if ($langhash{'languages'} ne '') {
 4471:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4472:         } else {
 4473:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4474:             if ($domdefs{'lang_def'} ne '') {
 4475:                 @userlangs = ($domdefs{'lang_def'});
 4476:             }
 4477:         }
 4478:     }
 4479:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4480:     my $user_lh = Apache::localize->get_handle(@languages);
 4481:     return $user_lh;
 4482: }
 4483: 
 4484: 
 4485: ###############################################################
 4486: ##               Student Answer Attempts                     ##
 4487: ###############################################################
 4488: 
 4489: =pod
 4490: 
 4491: =head1 Alternate Problem Views
 4492: 
 4493: =over 4
 4494: 
 4495: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4496:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4497: 
 4498: Return string with previous attempt on problem. Arguments:
 4499: 
 4500: =over 4
 4501: 
 4502: =item * $symb: Problem, including path
 4503: 
 4504: =item * $username: username of the desired student
 4505: 
 4506: =item * $domain: domain of the desired student
 4507: 
 4508: =item * $course: Course ID
 4509: 
 4510: =item * $getattempt: Leave blank for all attempts, otherwise put
 4511:     something
 4512: 
 4513: =item * $regexp: if string matches this regexp, the string will be
 4514:     sent to $gradesub
 4515: 
 4516: =item * $gradesub: routine that processes the string if it matches $regexp
 4517: 
 4518: =item * $usec: section of the desired student
 4519: 
 4520: =item * $identifier: counter for student (multiple students one problem) or 
 4521:     problem (one student; whole sequence).
 4522: 
 4523: =back
 4524: 
 4525: The output string is a table containing all desired attempts, if any.
 4526: 
 4527: =cut
 4528: 
 4529: sub get_previous_attempt {
 4530:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4531:   my $prevattempts='';
 4532:   no strict 'refs';
 4533:   if ($symb) {
 4534:     my (%returnhash)=
 4535:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4536:     if ($returnhash{'version'}) {
 4537:       my %lasthash=();
 4538:       my $version;
 4539:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4540:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4541:             if ($key =~ /\.rawrndseed$/) {
 4542:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4543:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4544:             } else {
 4545:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4546:             }
 4547:         }
 4548:       }
 4549:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4550:       $prevattempts.='<th>'.&mt('History').'</th>';
 4551:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4552:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4553:       foreach my $key (sort(keys(%lasthash))) {
 4554: 	my ($ign,@parts) = split(/\./,$key);
 4555: 	if ($#parts > 0) {
 4556: 	  my $data=$parts[-1];
 4557:           next if ($data eq 'foilorder');
 4558: 	  pop(@parts);
 4559:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4560:           if ($data eq 'type') {
 4561:               unless ($showsurv) {
 4562:                   my $id = join(',',@parts);
 4563:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4564:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4565:                       $lasthidden{$ign.'.'.$id} = 1;
 4566:                   }
 4567:               }
 4568:               if ($identifier ne '') {
 4569:                   my $id = join(',',@parts);
 4570:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4571:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4572:                       $hidestatus{$ign.'.'.$id} = 1;
 4573:                   }
 4574:               }
 4575:           } elsif ($data eq 'regrader') {
 4576:               if (($identifier ne '') && (@parts)) {
 4577:                   my $id = join(',',@parts);
 4578:                   $regraded{$ign.'.'.$id} = 1;
 4579:               }
 4580:           } 
 4581: 	} else {
 4582: 	  if ($#parts == 0) {
 4583: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4584: 	  } else {
 4585: 	    $prevattempts.='<th>'.$ign.'</th>';
 4586: 	  }
 4587: 	}
 4588:       }
 4589:       $prevattempts.=&end_data_table_header_row();
 4590:       if ($getattempt eq '') {
 4591:         my (%solved,%resets,%probstatus);
 4592:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4593:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4594:                 foreach my $id (keys(%regraded)) {
 4595:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4596:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4597:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4598:                         push(@{$resets{$id}},$version);
 4599:                     }
 4600:                 }
 4601:             }
 4602:         }
 4603: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4604:             my (@hidden,@unsolved);
 4605:             if (%typeparts) {
 4606:                 foreach my $id (keys(%typeparts)) {
 4607:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4608:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4609:                         push(@hidden,$id);
 4610:                     } elsif ($identifier ne '') {
 4611:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4612:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4613:                                 ($hidestatus{$id})) {
 4614:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4615:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4616:                                 push(@{$solved{$id}},$version);
 4617:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4618:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4619:                                 my $skip;
 4620:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4621:                                     foreach my $reset (@{$resets{$id}}) {
 4622:                                         if ($reset > $solved{$id}[-1]) {
 4623:                                             $skip=1;
 4624:                                             last;
 4625:                                         }
 4626:                                     }
 4627:                                 }
 4628:                                 unless ($skip) {
 4629:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4630:                                     push(@unsolved,$partslist);
 4631:                                 }
 4632:                             }
 4633:                         }
 4634:                     }
 4635:                 }
 4636:             }
 4637:             $prevattempts.=&start_data_table_row().
 4638:                            '<td>'.&mt('Transaction [_1]',$version);
 4639:             if (@unsolved) {
 4640:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4641:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4642:                                  &mt('Hide').'</label></span>';
 4643:             }
 4644:             $prevattempts .= '</td>';
 4645:             if (@hidden) {
 4646:                 foreach my $key (sort(keys(%lasthash))) {
 4647:                     next if ($key =~ /\.foilorder$/);
 4648:                     my $hide;
 4649:                     foreach my $id (@hidden) {
 4650:                         if ($key =~ /^\Q$id\E/) {
 4651:                             $hide = 1;
 4652:                             last;
 4653:                         }
 4654:                     }
 4655:                     if ($hide) {
 4656:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4657:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4658:                             my $value = &format_previous_attempt_value($key,
 4659:                                              $returnhash{$version.':'.$key});
 4660:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4661:                         } else {
 4662:                             $prevattempts.='<td>&nbsp;</td>';
 4663:                         }
 4664:                     } else {
 4665:                         if ($key =~ /\./) {
 4666:                             my $value = $returnhash{$version.':'.$key};
 4667:                             if ($key =~ /\.rndseed$/) {
 4668:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4669:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4670:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4671:                                 }
 4672:                             }
 4673:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4674:                                            '&nbsp;</td>';
 4675:                         } else {
 4676:                             $prevattempts.='<td>&nbsp;</td>';
 4677:                         }
 4678:                     }
 4679:                 }
 4680:             } else {
 4681: 	        foreach my $key (sort(keys(%lasthash))) {
 4682:                     next if ($key =~ /\.foilorder$/);
 4683:                     my $value = $returnhash{$version.':'.$key};
 4684:                     if ($key =~ /\.rndseed$/) {
 4685:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4686:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4687:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4688:                         }
 4689:                     }
 4690:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4691:                                    '&nbsp;</td>';
 4692: 	        }
 4693:             }
 4694: 	    $prevattempts.=&end_data_table_row();
 4695: 	 }
 4696:       }
 4697:       my @currhidden = keys(%lasthidden);
 4698:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4699:       foreach my $key (sort(keys(%lasthash))) {
 4700:           next if ($key =~ /\.foilorder$/);
 4701:           if (%typeparts) {
 4702:               my $hidden;
 4703:               foreach my $id (@currhidden) {
 4704:                   if ($key =~ /^\Q$id\E/) {
 4705:                       $hidden = 1;
 4706:                       last;
 4707:                   }
 4708:               }
 4709:               if ($hidden) {
 4710:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4711:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4712:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4713:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4714:                           $value = &$gradesub($value);
 4715:                       }
 4716:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4717:                   } else {
 4718:                       $prevattempts.='<td>&nbsp;</td>';
 4719:                   }
 4720:               } else {
 4721:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4722:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4723:                       $value = &$gradesub($value);
 4724:                   }
 4725:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4726:               }
 4727:           } else {
 4728: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4729: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4730:                   $value = &$gradesub($value);
 4731:               }
 4732: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4733:           }
 4734:       }
 4735:       $prevattempts.= &end_data_table_row().&end_data_table();
 4736:     } else {
 4737:       my $msg;
 4738:       if ($symb =~ /ext\.tool$/) {
 4739:           $msg = &mt('No grade passed back.');
 4740:       } else {
 4741:           $msg = &mt('Nothing submitted - no attempts.');
 4742:       }
 4743:       $prevattempts=
 4744: 	  &start_data_table().&start_data_table_row().
 4745: 	  '<td>'.$msg.'</td>'.
 4746: 	  &end_data_table_row().&end_data_table();
 4747:     }
 4748:   } else {
 4749:     $prevattempts=
 4750: 	  &start_data_table().&start_data_table_row().
 4751: 	  '<td>'.&mt('No data.').'</td>'.
 4752: 	  &end_data_table_row().&end_data_table();
 4753:   }
 4754: }
 4755: 
 4756: sub format_previous_attempt_value {
 4757:     my ($key,$value) = @_;
 4758:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4759:         $value = &Apache::lonlocal::locallocaltime($value);
 4760:     } elsif (ref($value) eq 'ARRAY') {
 4761:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4762:     } elsif ($key =~ /answerstring$/) {
 4763:         my %answers = &Apache::lonnet::str2hash($value);
 4764:         my @answer = %answers;
 4765:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4766:         my @anskeys = sort(keys(%answers));
 4767:         if (@anskeys == 1) {
 4768:             my $answer = $answers{$anskeys[0]};
 4769:             if ($answer =~ m{\0}) {
 4770:                 $answer =~ s{\0}{,}g;
 4771:             }
 4772:             my $tag_internal_answer_name = 'INTERNAL';
 4773:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4774:                 $value = $answer; 
 4775:             } else {
 4776:                 $value = $anskeys[0].'='.$answer;
 4777:             }
 4778:         } else {
 4779:             foreach my $ans (@anskeys) {
 4780:                 my $answer = $answers{$ans};
 4781:                 if ($answer =~ m{\0}) {
 4782:                     $answer =~ s{\0}{,}g;
 4783:                 }
 4784:                 $value .=  $ans.'='.$answer.'<br />';;
 4785:             } 
 4786:         }
 4787:     } else {
 4788:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4789:     }
 4790:     return $value;
 4791: }
 4792: 
 4793: 
 4794: sub relative_to_absolute {
 4795:     my ($url,$output)=@_;
 4796:     my $parser=HTML::TokeParser->new(\$output);
 4797:     my $token;
 4798:     my $thisdir=$url;
 4799:     my @rlinks=();
 4800:     while ($token=$parser->get_token) {
 4801: 	if ($token->[0] eq 'S') {
 4802: 	    if ($token->[1] eq 'a') {
 4803: 		if ($token->[2]->{'href'}) {
 4804: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4805: 		}
 4806: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4807: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4808: 	    } elsif ($token->[1] eq 'base') {
 4809: 		$thisdir=$token->[2]->{'href'};
 4810: 	    }
 4811: 	}
 4812:     }
 4813:     $thisdir=~s-/[^/]*$--;
 4814:     foreach my $link (@rlinks) {
 4815: 	unless (($link=~/^https?\:\/\//i) ||
 4816: 		($link=~/^\//) ||
 4817: 		($link=~/^javascript:/i) ||
 4818: 		($link=~/^mailto:/i) ||
 4819: 		($link=~/^\#/)) {
 4820: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4821: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4822: 	}
 4823:     }
 4824: # -------------------------------------------------- Deal with Applet codebases
 4825:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4826:     return $output;
 4827: }
 4828: 
 4829: =pod
 4830: 
 4831: =item * &get_student_view()
 4832: 
 4833: show a snapshot of what student was looking at
 4834: 
 4835: =cut
 4836: 
 4837: sub get_student_view {
 4838:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4839:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4840:   my (%form);
 4841:   my @elements=('symb','courseid','domain','username');
 4842:   foreach my $element (@elements) {
 4843:       $form{'grade_'.$element}=eval '$'.$element #'
 4844:   }
 4845:   if (defined($moreenv)) {
 4846:       %form=(%form,%{$moreenv});
 4847:   }
 4848:   if (defined($target)) { $form{'grade_target'} = $target; }
 4849:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4850:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 4851:       $feedurl =~ s{^/adm/wrapper}{};
 4852:   }
 4853:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4854:   $userview=~s/\<body[^\>]*\>//gi;
 4855:   $userview=~s/\<\/body\>//gi;
 4856:   $userview=~s/\<html\>//gi;
 4857:   $userview=~s/\<\/html\>//gi;
 4858:   $userview=~s/\<head\>//gi;
 4859:   $userview=~s/\<\/head\>//gi;
 4860:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4861:   $userview=&relative_to_absolute($feedurl,$userview);
 4862:   if (wantarray) {
 4863:      return ($userview,$response);
 4864:   } else {
 4865:      return $userview;
 4866:   }
 4867: }
 4868: 
 4869: sub get_student_view_with_retries {
 4870:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4871: 
 4872:     my $ok = 0;                 # True if we got a good response.
 4873:     my $content;
 4874:     my $response;
 4875: 
 4876:     # Try to get the student_view done. within the retries count:
 4877:     
 4878:     do {
 4879:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4880:          $ok      = $response->is_success;
 4881:          if (!$ok) {
 4882:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4883:          }
 4884:          $retries--;
 4885:     } while (!$ok && ($retries > 0));
 4886:     
 4887:     if (!$ok) {
 4888:        $content = '';          # On error return an empty content.
 4889:     }
 4890:     if (wantarray) {
 4891:        return ($content, $response);
 4892:     } else {
 4893:        return $content;
 4894:     }
 4895: }
 4896: 
 4897: =pod
 4898: 
 4899: =item * &get_student_answers() 
 4900: 
 4901: show a snapshot of how student was answering problem
 4902: 
 4903: =cut
 4904: 
 4905: sub get_student_answers {
 4906:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4907:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4908:   my (%moreenv);
 4909:   my @elements=('symb','courseid','domain','username');
 4910:   foreach my $element (@elements) {
 4911:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4912:   }
 4913:   $moreenv{'grade_target'}='answer';
 4914:   %moreenv=(%form,%moreenv);
 4915:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4916:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4917:   return $userview;
 4918: }
 4919: 
 4920: =pod
 4921: 
 4922: =item * &submlink()
 4923: 
 4924: Inputs: $text $uname $udom $symb $target
 4925: 
 4926: Returns: A link to grades.pm such as to see the SUBM view of a student
 4927: 
 4928: =cut
 4929: 
 4930: ###############################################
 4931: sub submlink {
 4932:     my ($text,$uname,$udom,$symb,$target)=@_;
 4933:     if (!($uname && $udom)) {
 4934: 	(my $cursymb, my $courseid,$udom,$uname)=
 4935: 	    &Apache::lonnet::whichuser($symb);
 4936: 	if (!$symb) { $symb=$cursymb; }
 4937:     }
 4938:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4939:     $symb=&escape($symb);
 4940:     if ($target) { $target=" target=\"$target\""; }
 4941:     return
 4942:         '<a href="/adm/grades?command=submission'.
 4943:         '&amp;symb='.$symb.
 4944:         '&amp;student='.$uname.
 4945:         '&amp;userdom='.$udom.'"'.
 4946:         $target.'>'.$text.'</a>';
 4947: }
 4948: ##############################################
 4949: 
 4950: =pod
 4951: 
 4952: =item * &pgrdlink()
 4953: 
 4954: Inputs: $text $uname $udom $symb $target
 4955: 
 4956: Returns: A link to grades.pm such as to see the PGRD view of a student
 4957: 
 4958: =cut
 4959: 
 4960: ###############################################
 4961: sub pgrdlink {
 4962:     my $link=&submlink(@_);
 4963:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4964:     return $link;
 4965: }
 4966: ##############################################
 4967: 
 4968: =pod
 4969: 
 4970: =item * &pprmlink()
 4971: 
 4972: Inputs: $text $uname $udom $symb $target
 4973: 
 4974: Returns: A link to parmset.pm such as to see the PPRM view of a
 4975: student and a specific resource
 4976: 
 4977: =cut
 4978: 
 4979: ###############################################
 4980: sub pprmlink {
 4981:     my ($text,$uname,$udom,$symb,$target)=@_;
 4982:     if (!($uname && $udom)) {
 4983: 	(my $cursymb, my $courseid,$udom,$uname)=
 4984: 	    &Apache::lonnet::whichuser($symb);
 4985: 	if (!$symb) { $symb=$cursymb; }
 4986:     }
 4987:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4988:     $symb=&escape($symb);
 4989:     if ($target) { $target="target=\"$target\""; }
 4990:     return '<a href="/adm/parmset?command=set&amp;'.
 4991: 	'symb='.$symb.'&amp;uname='.$uname.
 4992: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4993: }
 4994: ##############################################
 4995: 
 4996: =pod
 4997: 
 4998: =back
 4999: 
 5000: =cut
 5001: 
 5002: ###############################################
 5003: 
 5004: 
 5005: sub timehash {
 5006:     my ($thistime) = @_;
 5007:     my $timezone = &Apache::lonlocal::gettimezone();
 5008:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5009:                      ->set_time_zone($timezone);
 5010:     my $wday = $dt->day_of_week();
 5011:     if ($wday == 7) { $wday = 0; }
 5012:     return ( 'second' => $dt->second(),
 5013:              'minute' => $dt->minute(),
 5014:              'hour'   => $dt->hour(),
 5015:              'day'     => $dt->day_of_month(),
 5016:              'month'   => $dt->month(),
 5017:              'year'    => $dt->year(),
 5018:              'weekday' => $wday,
 5019:              'dayyear' => $dt->day_of_year(),
 5020:              'dlsav'   => $dt->is_dst() );
 5021: }
 5022: 
 5023: sub utc_string {
 5024:     my ($date)=@_;
 5025:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5026: }
 5027: 
 5028: sub maketime {
 5029:     my %th=@_;
 5030:     my ($epoch_time,$timezone,$dt);
 5031:     $timezone = &Apache::lonlocal::gettimezone();
 5032:     eval {
 5033:         $dt = DateTime->new( year   => $th{'year'},
 5034:                              month  => $th{'month'},
 5035:                              day    => $th{'day'},
 5036:                              hour   => $th{'hour'},
 5037:                              minute => $th{'minute'},
 5038:                              second => $th{'second'},
 5039:                              time_zone => $timezone,
 5040:                          );
 5041:     };
 5042:     if (!$@) {
 5043:         $epoch_time = $dt->epoch;
 5044:         if ($epoch_time) {
 5045:             return $epoch_time;
 5046:         }
 5047:     }
 5048:     return POSIX::mktime(
 5049:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5050:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5051: }
 5052: 
 5053: #########################################
 5054: 
 5055: sub findallcourses {
 5056:     my ($roles,$uname,$udom) = @_;
 5057:     my %roles;
 5058:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5059:     my %courses;
 5060:     my $now=time;
 5061:     if (!defined($uname)) {
 5062:         $uname = $env{'user.name'};
 5063:     }
 5064:     if (!defined($udom)) {
 5065:         $udom = $env{'user.domain'};
 5066:     }
 5067:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5068:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5069:         if (!%roles) {
 5070:             %roles = (
 5071:                        cc => 1,
 5072:                        co => 1,
 5073:                        in => 1,
 5074:                        ep => 1,
 5075:                        ta => 1,
 5076:                        cr => 1,
 5077:                        st => 1,
 5078:              );
 5079:         }
 5080:         foreach my $entry (keys(%roleshash)) {
 5081:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5082:             if ($trole =~ /^cr/) { 
 5083:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5084:             } else {
 5085:                 next if (!exists($roles{$trole}));
 5086:             }
 5087:             if ($tend) {
 5088:                 next if ($tend < $now);
 5089:             }
 5090:             if ($tstart) {
 5091:                 next if ($tstart > $now);
 5092:             }
 5093:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5094:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5095:             my $value = $trole.'/'.$cdom.'/';
 5096:             if ($secpart eq '') {
 5097:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5098:                 $sec = 'none';
 5099:                 $value .= $cnum.'/';
 5100:             } else {
 5101:                 $cnum = $cnumpart;
 5102:                 ($sec,$role) = split(/_/,$secpart);
 5103:                 $value .= $cnum.'/'.$sec;
 5104:             }
 5105:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5106:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5107:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5108:                 }
 5109:             } else {
 5110:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5111:             }
 5112:         }
 5113:     } else {
 5114:         foreach my $key (keys(%env)) {
 5115: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5116:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5117: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5118: 	        next if ($role eq 'ca' || $role eq 'aa');
 5119: 	        next if (%roles && !exists($roles{$role}));
 5120: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5121:                 my $active=1;
 5122:                 if ($starttime) {
 5123: 		    if ($now<$starttime) { $active=0; }
 5124:                 }
 5125:                 if ($endtime) {
 5126:                     if ($now>$endtime) { $active=0; }
 5127:                 }
 5128:                 if ($active) {
 5129:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5130:                     if ($sec eq '') {
 5131:                         $sec = 'none';
 5132:                     } else {
 5133:                         $value .= $sec;
 5134:                     }
 5135:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5136:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5137:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5138:                         }
 5139:                     } else {
 5140:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5141:                     }
 5142:                 }
 5143:             }
 5144:         }
 5145:     }
 5146:     return %courses;
 5147: }
 5148: 
 5149: ###############################################
 5150: 
 5151: sub blockcheck {
 5152:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 5153: 
 5154:     if (defined($udom) && defined($uname)) {
 5155:         # If uname and udom are for a course, check for blocks in the course.
 5156:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5157:             my ($startblock,$endblock,$triggerblock) =
 5158:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 5159:             return ($startblock,$endblock,$triggerblock);
 5160:         }
 5161:     } else {
 5162:         $udom = $env{'user.domain'};
 5163:         $uname = $env{'user.name'};
 5164:     }
 5165: 
 5166:     my $startblock = 0;
 5167:     my $endblock = 0;
 5168:     my $triggerblock = '';
 5169:     my %live_courses = &findallcourses(undef,$uname,$udom);
 5170: 
 5171:     # If uname is for a user, and activity is course-specific, i.e.,
 5172:     # boards, chat or groups, check for blocking in current course only.
 5173: 
 5174:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5175:          $activity eq 'groups' || $activity eq 'printout' ||
 5176:          $activity eq 'reinit' || $activity eq 'alert') &&
 5177:         ($env{'request.course.id'})) {
 5178:         foreach my $key (keys(%live_courses)) {
 5179:             if ($key ne $env{'request.course.id'}) {
 5180:                 delete($live_courses{$key});
 5181:             }
 5182:         }
 5183:     }
 5184: 
 5185:     my $otheruser = 0;
 5186:     my %own_courses;
 5187:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5188:         # Resource belongs to user other than current user.
 5189:         $otheruser = 1;
 5190:         # Gather courses for current user
 5191:         %own_courses = 
 5192:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5193:     }
 5194: 
 5195:     # Gather active course roles - course coordinator, instructor, 
 5196:     # exam proctor, ta, student, or custom role.
 5197: 
 5198:     foreach my $course (keys(%live_courses)) {
 5199:         my ($cdom,$cnum);
 5200:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5201:             $cdom = $env{'course.'.$course.'.domain'};
 5202:             $cnum = $env{'course.'.$course.'.num'};
 5203:         } else {
 5204:             ($cdom,$cnum) = split(/_/,$course); 
 5205:         }
 5206:         my $no_ownblock = 0;
 5207:         my $no_userblock = 0;
 5208:         if ($otheruser && $activity ne 'com') {
 5209:             # Check if current user has 'evb' priv for this
 5210:             if (defined($own_courses{$course})) {
 5211:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5212:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5213:                     if ($sec ne 'none') {
 5214:                         $checkrole .= '/'.$sec;
 5215:                     }
 5216:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5217:                         $no_ownblock = 1;
 5218:                         last;
 5219:                     }
 5220:                 }
 5221:             }
 5222:             # if they have 'evb' priv and are currently not playing student
 5223:             next if (($no_ownblock) &&
 5224:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5225:         }
 5226:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5227:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5228:             if ($sec ne 'none') {
 5229:                 $checkrole .= '/'.$sec;
 5230:             }
 5231:             if ($otheruser) {
 5232:                 # Resource belongs to user other than current user.
 5233:                 # Assemble privs for that user, and check for 'evb' priv.
 5234:                 my (%allroles,%userroles);
 5235:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5236:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5237:                         my ($trole,$tdom,$tnum,$tsec);
 5238:                         if ($entry =~ /^cr/) {
 5239:                             ($trole,$tdom,$tnum,$tsec) = 
 5240:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5241:                         } else {
 5242:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5243:                         }
 5244:                         my ($spec,$area,$trest);
 5245:                         $area = '/'.$tdom.'/'.$tnum;
 5246:                         $trest = $tnum;
 5247:                         if ($tsec ne '') {
 5248:                             $area .= '/'.$tsec;
 5249:                             $trest .= '/'.$tsec;
 5250:                         }
 5251:                         $spec = $trole.'.'.$area;
 5252:                         if ($trole =~ /^cr/) {
 5253:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5254:                                                               $tdom,$spec,$trest,$area);
 5255:                         } else {
 5256:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5257:                                                                 $tdom,$spec,$trest,$area);
 5258:                         }
 5259:                     }
 5260:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5261:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5262:                         if ($1) {
 5263:                             $no_userblock = 1;
 5264:                             last;
 5265:                         }
 5266:                     }
 5267:                 }
 5268:             } else {
 5269:                 # Resource belongs to current user
 5270:                 # Check for 'evb' priv via lonnet::allowed().
 5271:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5272:                     $no_ownblock = 1;
 5273:                     last;
 5274:                 }
 5275:             }
 5276:         }
 5277:         # if they have the evb priv and are currently not playing student
 5278:         next if (($no_ownblock) &&
 5279:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5280:         next if ($no_userblock);
 5281: 
 5282:         # Retrieve blocking times and identity of blocker for course
 5283:         # of specified user, unless user has 'evb' privilege.
 5284: 
 5285:         my ($start,$end,$trigger) = 
 5286:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5287:         if (($start != 0) && 
 5288:             (($startblock == 0) || ($startblock > $start))) {
 5289:             $startblock = $start;
 5290:             if ($trigger ne '') {
 5291:                 $triggerblock = $trigger;
 5292:             }
 5293:         }
 5294:         if (($end != 0)  &&
 5295:             (($endblock == 0) || ($endblock < $end))) {
 5296:             $endblock = $end;
 5297:             if ($trigger ne '') {
 5298:                 $triggerblock = $trigger;
 5299:             }
 5300:         }
 5301:     }
 5302:     return ($startblock,$endblock,$triggerblock);
 5303: }
 5304: 
 5305: sub get_blocks {
 5306:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5307:     my $startblock = 0;
 5308:     my $endblock = 0;
 5309:     my $triggerblock = '';
 5310:     my $course = $cdom.'_'.$cnum;
 5311:     $setters->{$course} = {};
 5312:     $setters->{$course}{'staff'} = [];
 5313:     $setters->{$course}{'times'} = [];
 5314:     $setters->{$course}{'triggers'} = [];
 5315:     my (@blockers,%triggered);
 5316:     my $now = time;
 5317:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5318:     if ($activity eq 'docs') {
 5319:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5320:         foreach my $block (@blockers) {
 5321:             if ($block =~ /^firstaccess____(.+)$/) {
 5322:                 my $item = $1;
 5323:                 my $type = 'map';
 5324:                 my $timersymb = $item;
 5325:                 if ($item eq 'course') {
 5326:                     $type = 'course';
 5327:                 } elsif ($item =~ /___\d+___/) {
 5328:                     $type = 'resource';
 5329:                 } else {
 5330:                     $timersymb = &Apache::lonnet::symbread($item);
 5331:                 }
 5332:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5333:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5334:                 $triggered{$block} = {
 5335:                                        start => $start,
 5336:                                        end   => $end,
 5337:                                        type  => $type,
 5338:                                      };
 5339:             }
 5340:         }
 5341:     } else {
 5342:         foreach my $block (keys(%commblocks)) {
 5343:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5344:                 my ($start,$end) = ($1,$2);
 5345:                 if ($start <= time && $end >= time) {
 5346:                     if (ref($commblocks{$block}) eq 'HASH') {
 5347:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5348:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5349:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5350:                                     push(@blockers,$block);
 5351:                                 }
 5352:                             }
 5353:                         }
 5354:                     }
 5355:                 }
 5356:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5357:                 my $item = $1;
 5358:                 my $timersymb = $item; 
 5359:                 my $type = 'map';
 5360:                 if ($item eq 'course') {
 5361:                     $type = 'course';
 5362:                 } elsif ($item =~ /___\d+___/) {
 5363:                     $type = 'resource';
 5364:                 } else {
 5365:                     $timersymb = &Apache::lonnet::symbread($item);
 5366:                 }
 5367:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5368:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5369:                 if ($start && $end) {
 5370:                     if (($start <= time) && ($end >= time)) {
 5371:                         if (ref($commblocks{$block}) eq 'HASH') {
 5372:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5373:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5374:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5375:                                         push(@blockers,$block);
 5376:                                         $triggered{$block} = {
 5377:                                                                start => $start,
 5378:                                                                end   => $end,
 5379:                                                                type  => $type,
 5380:                                                              };
 5381:                                     }
 5382:                                 }
 5383:                             }
 5384:                         }
 5385:                     }
 5386:                 }
 5387:             }
 5388:         }
 5389:     }
 5390:     foreach my $blocker (@blockers) {
 5391:         my ($staff_name,$staff_dom,$title,$blocks) =
 5392:             &parse_block_record($commblocks{$blocker});
 5393:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5394:         my ($start,$end,$triggertype);
 5395:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5396:             ($start,$end) = ($1,$2);
 5397:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5398:             $start = $triggered{$blocker}{'start'};
 5399:             $end = $triggered{$blocker}{'end'};
 5400:             $triggertype = $triggered{$blocker}{'type'};
 5401:         }
 5402:         if ($start) {
 5403:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5404:             if ($triggertype) {
 5405:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5406:             } else {
 5407:                 push(@{$$setters{$course}{'triggers'}},0);
 5408:             }
 5409:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5410:                 $startblock = $start;
 5411:                 if ($triggertype) {
 5412:                     $triggerblock = $blocker;
 5413:                 }
 5414:             }
 5415:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5416:                $endblock = $end;
 5417:                if ($triggertype) {
 5418:                    $triggerblock = $blocker;
 5419:                }
 5420:             }
 5421:         }
 5422:     }
 5423:     return ($startblock,$endblock,$triggerblock);
 5424: }
 5425: 
 5426: sub parse_block_record {
 5427:     my ($record) = @_;
 5428:     my ($setuname,$setudom,$title,$blocks);
 5429:     if (ref($record) eq 'HASH') {
 5430:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5431:         $title = &unescape($record->{'event'});
 5432:         $blocks = $record->{'blocks'};
 5433:     } else {
 5434:         my @data = split(/:/,$record,3);
 5435:         if (scalar(@data) eq 2) {
 5436:             $title = $data[1];
 5437:             ($setuname,$setudom) = split(/@/,$data[0]);
 5438:         } else {
 5439:             ($setuname,$setudom,$title) = @data;
 5440:         }
 5441:         $blocks = { 'com' => 'on' };
 5442:     }
 5443:     return ($setuname,$setudom,$title,$blocks);
 5444: }
 5445: 
 5446: sub blocking_status {
 5447:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5448:     my %setters;
 5449: 
 5450: # check for active blocking
 5451:     my ($startblock,$endblock,$triggerblock) = 
 5452:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5453:     my $blocked = 0;
 5454:     if ($startblock && $endblock) {
 5455:         $blocked = 1;
 5456:     }
 5457: 
 5458: # caller just wants to know whether a block is active
 5459:     if (!wantarray) { return $blocked; }
 5460: 
 5461: # build a link to a popup window containing the details
 5462:     my $querystring  = "?activity=$activity";
 5463: # $uname and $udom decide whose portfolio the user is trying to look at
 5464:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5465:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5466:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5467:     } elsif ($activity eq 'docs') {
 5468:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5469:     }
 5470: 
 5471:     my $output .= <<'END_MYBLOCK';
 5472: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5473:     var options = "width=" + w + ",height=" + h + ",";
 5474:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5475:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5476:     var newWin = window.open(url, wdwName, options);
 5477:     newWin.focus();
 5478: }
 5479: END_MYBLOCK
 5480: 
 5481:     $output = Apache::lonhtmlcommon::scripttag($output);
 5482:   
 5483:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5484:     my $text = &mt('Communication Blocked');
 5485:     my $class = 'LC_comblock';
 5486:     if ($activity eq 'docs') {
 5487:         $text = &mt('Content Access Blocked');
 5488:         $class = '';
 5489:     } elsif ($activity eq 'printout') {
 5490:         $text = &mt('Printing Blocked');
 5491:     } elsif ($activity eq 'passwd') {
 5492:         $text = &mt('Password Changing Blocked');
 5493:     } elsif ($activity eq 'alert') {
 5494:         $text = &mt('Checking Critical Messages Blocked');
 5495:     } elsif ($activity eq 'reinit') {
 5496:         $text = &mt('Checking Course Update Blocked');
 5497:     }
 5498:     $output .= <<"END_BLOCK";
 5499: <div class='$class'>
 5500:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5501:   title='$text'>
 5502:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5503:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5504:   title='$text'>$text</a>
 5505: </div>
 5506: 
 5507: END_BLOCK
 5508: 
 5509:     return ($blocked, $output);
 5510: }
 5511: 
 5512: ###############################################
 5513: 
 5514: sub check_ip_acc {
 5515:     my ($acc,$clientip)=@_;
 5516:     &Apache::lonxml::debug("acc is $acc");
 5517:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5518:         return 1;
 5519:     }
 5520:     my $allowed;
 5521:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5522: 
 5523:     my $name;
 5524:     my %access = (
 5525:                      allowfrom => 1,
 5526:                      denyfrom  => 0,
 5527:                  );
 5528:     my @allows;
 5529:     my @denies;
 5530:     foreach my $item (split(',',$acc)) {
 5531:         $item =~ s/^\s*//;
 5532:         $item =~ s/\s*$//;
 5533:         my $pattern;
 5534:         if ($item =~ /^\!(.+)$/) {
 5535:             push(@denies,$1);
 5536:         } else {
 5537:             push(@allows,$item);
 5538:         }
 5539:    }
 5540:    my $numdenies = scalar(@denies);
 5541:    my $numallows = scalar(@allows);
 5542:    my $count = 0;
 5543:    foreach my $pattern (@denies,@allows) {
 5544:         $count ++; 
 5545:         my $acctype = 'allowfrom';
 5546:         if ($count <= $numdenies) {
 5547:             $acctype = 'denyfrom';
 5548:         }
 5549:         if ($pattern =~ /\*$/) {
 5550:             #35.8.*
 5551:             $pattern=~s/\*//;
 5552:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5553:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5554:             #35.8.3.[34-56]
 5555:             my $low=$2;
 5556:             my $high=$3;
 5557:             $pattern=$1;
 5558:             if ($ip =~ /^\Q$pattern\E/) {
 5559:                 my $last=(split(/\./,$ip))[3];
 5560:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5561:             }
 5562:         } elsif ($pattern =~ /^\*/) {
 5563:             #*.msu.edu
 5564:             $pattern=~s/\*//;
 5565:             if (!defined($name)) {
 5566:                 use Socket;
 5567:                 my $netaddr=inet_aton($ip);
 5568:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5569:             }
 5570:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5571:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5572:             #127.0.0.1
 5573:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5574:         } else {
 5575:             #some.name.com
 5576:             if (!defined($name)) {
 5577:                 use Socket;
 5578:                 my $netaddr=inet_aton($ip);
 5579:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5580:             }
 5581:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5582:         }
 5583:         if ($allowed =~ /^(0|1)$/) { last; }
 5584:     }
 5585:     if ($allowed eq '') {
 5586:         if ($numdenies && !$numallows) {
 5587:             $allowed = 1;
 5588:         } else {
 5589:             $allowed = 0;
 5590:         }
 5591:     }
 5592:     return $allowed;
 5593: }
 5594: 
 5595: ###############################################
 5596: 
 5597: =pod
 5598: 
 5599: =head1 Domain Template Functions
 5600: 
 5601: =over 4
 5602: 
 5603: =item * &determinedomain()
 5604: 
 5605: Inputs: $domain (usually will be undef)
 5606: 
 5607: Returns: Determines which domain should be used for designs
 5608: 
 5609: =cut
 5610: 
 5611: ###############################################
 5612: sub determinedomain {
 5613:     my $domain=shift;
 5614:     if (! $domain) {
 5615:         # Determine domain if we have not been given one
 5616:         $domain = &Apache::lonnet::default_login_domain();
 5617:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5618:         if ($env{'request.role.domain'}) { 
 5619:             $domain=$env{'request.role.domain'}; 
 5620:         }
 5621:     }
 5622:     return $domain;
 5623: }
 5624: ###############################################
 5625: 
 5626: sub devalidate_domconfig_cache {
 5627:     my ($udom)=@_;
 5628:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5629: }
 5630: 
 5631: # ---------------------- Get domain configuration for a domain
 5632: sub get_domainconf {
 5633:     my ($udom) = @_;
 5634:     my $cachetime=1800;
 5635:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5636:     if (defined($cached)) { return %{$result}; }
 5637: 
 5638:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5639: 					     ['login','rolecolors','autoenroll'],$udom);
 5640:     my (%designhash,%legacy);
 5641:     if (keys(%domconfig) > 0) {
 5642:         if (ref($domconfig{'login'}) eq 'HASH') {
 5643:             if (keys(%{$domconfig{'login'}})) {
 5644:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5645:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5646:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5647:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5648:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5649:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5650:                                         if ($key eq 'loginvia') {
 5651:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5652:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5653:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5654:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5655: 
 5656:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5657:                                                 } else {
 5658:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5659:                                                 }
 5660:                                             }
 5661:                                         } elsif ($key eq 'headtag') {
 5662:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5663:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5664:                                             }
 5665:                                         }
 5666:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5667:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5668:                                         }
 5669:                                     }
 5670:                                 }
 5671:                             }
 5672:                         } else {
 5673:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5674:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5675:                                     $domconfig{'login'}{$key}{$img};
 5676:                             }
 5677:                         }
 5678:                     } else {
 5679:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5680:                     }
 5681:                 }
 5682:             } else {
 5683:                 $legacy{'login'} = 1;
 5684:             }
 5685:         } else {
 5686:             $legacy{'login'} = 1;
 5687:         }
 5688:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5689:             if (keys(%{$domconfig{'rolecolors'}})) {
 5690:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5691:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5692:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5693:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5694:                         }
 5695:                     }
 5696:                 }
 5697:             } else {
 5698:                 $legacy{'rolecolors'} = 1;
 5699:             }
 5700:         } else {
 5701:             $legacy{'rolecolors'} = 1;
 5702:         }
 5703:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5704:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5705:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5706:             }
 5707:         }
 5708:         if (keys(%legacy) > 0) {
 5709:             my %legacyhash = &get_legacy_domconf($udom);
 5710:             foreach my $item (keys(%legacyhash)) {
 5711:                 if ($item =~ /^\Q$udom\E\.login/) {
 5712:                     if ($legacy{'login'}) { 
 5713:                         $designhash{$item} = $legacyhash{$item};
 5714:                     }
 5715:                 } else {
 5716:                     if ($legacy{'rolecolors'}) {
 5717:                         $designhash{$item} = $legacyhash{$item};
 5718:                     }
 5719:                 }
 5720:             }
 5721:         }
 5722:     } else {
 5723:         %designhash = &get_legacy_domconf($udom); 
 5724:     }
 5725:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5726: 				  $cachetime);
 5727:     return %designhash;
 5728: }
 5729: 
 5730: sub get_legacy_domconf {
 5731:     my ($udom) = @_;
 5732:     my %legacyhash;
 5733:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5734:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5735:     if (-e $designfile) {
 5736:         if ( open (my $fh,'<',$designfile) ) {
 5737:             while (my $line = <$fh>) {
 5738:                 next if ($line =~ /^\#/);
 5739:                 chomp($line);
 5740:                 my ($key,$val)=(split(/\=/,$line));
 5741:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5742:             }
 5743:             close($fh);
 5744:         }
 5745:     }
 5746:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5747:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5748:     }
 5749:     return %legacyhash;
 5750: }
 5751: 
 5752: =pod
 5753: 
 5754: =item * &domainlogo()
 5755: 
 5756: Inputs: $domain (usually will be undef)
 5757: 
 5758: Returns: A link to a domain logo, if the domain logo exists.
 5759: If the domain logo does not exist, a description of the domain.
 5760: 
 5761: =cut
 5762: 
 5763: ###############################################
 5764: sub domainlogo {
 5765:     my $domain = &determinedomain(shift);
 5766:     my %designhash = &get_domainconf($domain);    
 5767:     # See if there is a logo
 5768:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5769:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5770:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5771: 	    if ($imgsrc =~ m{^/res/}) {
 5772: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5773: 		&Apache::lonnet::repcopy($local_name);
 5774: 	    }
 5775: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5776:         } 
 5777:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5778:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5779:         return &Apache::lonnet::domain($domain,'description');
 5780:     } else {
 5781:         return '';
 5782:     }
 5783: }
 5784: ##############################################
 5785: 
 5786: =pod
 5787: 
 5788: =item * &designparm()
 5789: 
 5790: Inputs: $which parameter; $domain (usually will be undef)
 5791: 
 5792: Returns: value of designparamter $which
 5793: 
 5794: =cut
 5795: 
 5796: 
 5797: ##############################################
 5798: sub designparm {
 5799:     my ($which,$domain)=@_;
 5800:     if (exists($env{'environment.color.'.$which})) {
 5801:         return $env{'environment.color.'.$which};
 5802:     }
 5803:     $domain=&determinedomain($domain);
 5804:     my %domdesign;
 5805:     unless ($domain eq 'public') {
 5806:         %domdesign = &get_domainconf($domain);
 5807:     }
 5808:     my $output;
 5809:     if ($domdesign{$domain.'.'.$which} ne '') {
 5810:         $output = $domdesign{$domain.'.'.$which};
 5811:     } else {
 5812:         $output = $defaultdesign{$which};
 5813:     }
 5814:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5815:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5816:         if ($output =~ m{^/(adm|res)/}) {
 5817:             if ($output =~ m{^/res/}) {
 5818:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5819:                 &Apache::lonnet::repcopy($local_name);
 5820:             }
 5821:             $output = &lonhttpdurl($output);
 5822:         }
 5823:     }
 5824:     return $output;
 5825: }
 5826: 
 5827: ##############################################
 5828: =pod
 5829: 
 5830: =item * &authorspace()
 5831: 
 5832: Inputs: $url (usually will be undef).
 5833: 
 5834: Returns: Path to Authoring Space containing the resource or 
 5835:          directory being viewed (or for which action is being taken). 
 5836:          If $url is provided, and begins /priv/<domain>/<uname>
 5837:          the path will be that portion of the $context argument.
 5838:          Otherwise the path will be for the author space of the current
 5839:          user when the current role is author, or for that of the 
 5840:          co-author/assistant co-author space when the current role 
 5841:          is co-author or assistant co-author.
 5842: 
 5843: =cut
 5844: 
 5845: sub authorspace {
 5846:     my ($url) = @_;
 5847:     if ($url ne '') {
 5848:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5849:            return $1;
 5850:         }
 5851:     }
 5852:     my $caname = '';
 5853:     my $cadom = '';
 5854:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5855:         ($cadom,$caname) =
 5856:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5857:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5858:         $caname = $env{'user.name'};
 5859:         $cadom = $env{'user.domain'};
 5860:     }
 5861:     if (($caname ne '') && ($cadom ne '')) {
 5862:         return "/priv/$cadom/$caname/";
 5863:     }
 5864:     return;
 5865: }
 5866: 
 5867: ##############################################
 5868: =pod
 5869: 
 5870: =item * &head_subbox()
 5871: 
 5872: Inputs: $content (contains HTML code with page functions, etc.)
 5873: 
 5874: Returns: HTML div with $content
 5875:          To be included in page header
 5876: 
 5877: =cut
 5878: 
 5879: sub head_subbox {
 5880:     my ($content)=@_;
 5881:     my $output =
 5882:         '<div class="LC_head_subbox">'
 5883:        .$content
 5884:        .'</div>'
 5885: }
 5886: 
 5887: ##############################################
 5888: =pod
 5889: 
 5890: =item * &CSTR_pageheader()
 5891: 
 5892: Input: (optional) filename from which breadcrumb trail is built.
 5893:        In most cases no input as needed, as $env{'request.filename'}
 5894:        is appropriate for use in building the breadcrumb trail.
 5895: 
 5896: Returns: HTML div with CSTR path and recent box
 5897:          To be included on Authoring Space pages
 5898: 
 5899: =cut
 5900: 
 5901: sub CSTR_pageheader {
 5902:     my ($trailfile) = @_;
 5903:     if ($trailfile eq '') {
 5904:         $trailfile = $env{'request.filename'};
 5905:     }
 5906: 
 5907: # this is for resources; directories have customtitle, and crumbs
 5908: # and select recent are created in lonpubdir.pm
 5909: 
 5910:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5911:     my ($udom,$uname,$thisdisfn)=
 5912:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5913:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5914:     $formaction =~ s{/+}{/}g;
 5915: 
 5916:     my $parentpath = '';
 5917:     my $lastitem = '';
 5918:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5919:         $parentpath = $1;
 5920:         $lastitem = $2;
 5921:     } else {
 5922:         $lastitem = $thisdisfn;
 5923:     }
 5924: 
 5925:     my ($crsauthor,$title);
 5926:     if (($env{'request.course.id'}) &&
 5927:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5928:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5929:         $crsauthor = 1;
 5930:         $title = &mt('Course Authoring Space');
 5931:     } else {
 5932:         $title = &mt('Authoring Space');
 5933:     }
 5934: 
 5935:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
 5936:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 5937:         $target = '';
 5938:         $crumbtarget = '';
 5939:     }
 5940: 
 5941:     my $output =
 5942:          '<div>'
 5943:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5944:         .'<b>'.$title.'</b> '
 5945:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5946:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5947: 
 5948:     if ($lastitem) {
 5949:         $output .=
 5950:              '<span class="LC_filename">'
 5951:             .$lastitem
 5952:             .'</span>';
 5953:     }
 5954: 
 5955:     if ($crsauthor) {
 5956:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5957:     } else {
 5958:         $output .=
 5959:              '<br />'
 5960:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5961:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5962:             .'</form>'
 5963:             .&Apache::lonmenu::constspaceform();
 5964:     }
 5965:     $output .= '</div>';
 5966: 
 5967:     return $output;
 5968: }
 5969: 
 5970: ###############################################
 5971: ###############################################
 5972: 
 5973: =pod
 5974: 
 5975: =back
 5976: 
 5977: =head1 HTML Helpers
 5978: 
 5979: =over 4
 5980: 
 5981: =item * &bodytag()
 5982: 
 5983: Returns a uniform header for LON-CAPA web pages.
 5984: 
 5985: Inputs: 
 5986: 
 5987: =over 4
 5988: 
 5989: =item * $title, A title to be displayed on the page.
 5990: 
 5991: =item * $function, the current role (can be undef).
 5992: 
 5993: =item * $addentries, extra parameters for the <body> tag.
 5994: 
 5995: =item * $bodyonly, if defined, only return the <body> tag.
 5996: 
 5997: =item * $domain, if defined, force a given domain.
 5998: 
 5999: =item * $forcereg, if page should register as content page (relevant for 
 6000:             text interface only)
 6001: 
 6002: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6003:                      navigational links
 6004: 
 6005: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6006: 
 6007: =item * $args, optional argument valid values are
 6008:             no_auto_mt_title -> prevents &mt()ing the title arg
 6009:             use_absolute     -> for external resource or syllabus, this will
 6010:                                 contain https://<hostname> if server uses
 6011:                                 https (as per hosts.tab), but request is for http
 6012:             hostname         -> hostname, from $r->hostname().
 6013: 
 6014: =item * $advtoolsref, optional argument, ref to an array containing
 6015:             inlineremote items to be added in "Functions" menu below
 6016:             breadcrumbs.
 6017: 
 6018: =item * $ltiscope, optional argument, will be one of: resource, map or
 6019:             course, if LON-CAPA is in LTI Provider context. Value is
 6020:             the scope of use, i.e., launch was for access to a single, a map
 6021:             or the entire course.
 6022: 
 6023: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6024:             context, this will contain the URL for the landing item in
 6025:             the course, after launch from an LTI Consumer
 6026: 
 6027: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6028:             context, this will contain a reference to hash of items
 6029:             to be included in the page header and/or inline menu.
 6030: 
 6031: =back
 6032: 
 6033: Returns: A uniform header for LON-CAPA web pages.  
 6034: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6035: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6036: other decorations will be returned.
 6037: 
 6038: =cut
 6039: 
 6040: sub bodytag {
 6041:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6042:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
 6043: 
 6044:     my $public;
 6045:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6046:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6047:         $public = 1;
 6048:     }
 6049:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6050:     my $httphost = $args->{'use_absolute'};
 6051:     my $hostname = $args->{'hostname'};
 6052: 
 6053:     $function = &get_users_function() if (!$function);
 6054:     my $img =    &designparm($function.'.img',$domain);
 6055:     my $font =   &designparm($function.'.font',$domain);
 6056:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6057: 
 6058:     my %design = ( 'style'   => 'margin-top: 0',
 6059: 		   'bgcolor' => $pgbg,
 6060: 		   'text'    => $font,
 6061:                    'alink'   => &designparm($function.'.alink',$domain),
 6062: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6063: 		   'link'    => &designparm($function.'.link',$domain),);
 6064:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6065: 
 6066:  # role and realm
 6067:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6068:     if ($realm) {
 6069:         $realm = '/'.$realm;
 6070:     }
 6071:     if ($role  eq 'ca') {
 6072:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6073:         $realm = &plainname($rname,$rdom);
 6074:     } 
 6075: # realm
 6076:     if ($env{'request.course.id'}) {
 6077:         if ($env{'request.role'} !~ /^cr/) {
 6078:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6079:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6080:             if ($env{'request.role.desc'}) {
 6081:                 $role = $env{'request.role.desc'};
 6082:             } else {
 6083:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6084:             }
 6085:         } else {
 6086:             $role = (split(/\//,$role,4))[-1]; 
 6087:         }
 6088:         if ($env{'request.course.sec'}) {
 6089:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 6090:         }   
 6091: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 6092:     } else {
 6093:         $role = &Apache::lonnet::plaintext($role);
 6094:     }
 6095: 
 6096:     if (!$realm) { $realm='&nbsp;'; }
 6097: 
 6098:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6099: 
 6100: # construct main body tag
 6101:     my $bodytag = "<body $extra_body_attr>".
 6102: 	&Apache::lontexconvert::init_math_support();
 6103: 
 6104:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6105: 
 6106:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6107:         return $bodytag;
 6108:     }
 6109: 
 6110:     if ($public) {
 6111: 	undef($role);
 6112:     }
 6113: 
 6114:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 6115:         if (ref($ltimenu) eq 'HASH') {
 6116:             unless ($ltimenu->{'role'}) {
 6117:                 undef($role);
 6118:             }
 6119:             unless ($ltimenu->{'coursetitle'}) {
 6120:                 $realm='&nbsp;';
 6121:             }
 6122:         }
 6123:     }
 6124: 
 6125:     my $titleinfo = '<h1>'.$title.'</h1>';
 6126:     #
 6127:     # Extra info if you are the DC
 6128:     my $dc_info = '';
 6129:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 6130:                         $env{'course.'.$env{'request.course.id'}.
 6131:                                  '.domain'}.'/'})) {
 6132:         my $cid = $env{'request.course.id'};
 6133:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6134:         $dc_info =~ s/\s+$//;
 6135:     }
 6136: 
 6137:     my $crstype;
 6138:     if ($env{'request.course.id'}) {
 6139:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 6140:     } elsif ($args->{'crstype'}) {
 6141:         $crstype = $args->{'crstype'};
 6142:     }
 6143:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6144:         undef($role);
 6145:     } else {
 6146:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6147:     }
 6148: 
 6149:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6150: 
 6151:         #    if ($env{'request.state'} eq 'construct') {
 6152:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6153:         #    }
 6154: 
 6155:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6156:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6157: 
 6158:         unless ($args->{'no_primary_menu'}) {
 6159:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
 6160: 
 6161:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6162:                 if ($dc_info) {
 6163:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6164:                 }
 6165:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6166:                                <em>$realm</em> $dc_info</div>|;
 6167:                 return $bodytag;
 6168:             }
 6169: 
 6170:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6171:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6172:             }
 6173: 
 6174:             $bodytag .= $right;
 6175: 
 6176:             if ($dc_info) {
 6177:                 $dc_info = &dc_courseid_toggle($dc_info);
 6178:             }
 6179:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6180:         }
 6181: 
 6182:         #if directed to not display the secondary menu, don't.  
 6183:         if ($args->{'no_secondary_menu'}) {
 6184:             return $bodytag;
 6185:         }
 6186:         #don't show menus for public users
 6187:         if (!$public){
 6188:             unless ($args->{'no_inline_menu'}) {
 6189:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6190:                                                             $args->{'no_primary_menu'});
 6191:             }
 6192:             $bodytag .= Apache::lonmenu::serverform();
 6193:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6194:             if ($env{'request.state'} eq 'construct') {
 6195:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6196:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
 6197:             } elsif ($forcereg) {
 6198:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6199:                                                             $args->{'group'},
 6200:                                                             $args->{'hide_buttons'},
 6201:                                                             $hostname,$ltiscope,$ltiuri);
 6202:             } else {
 6203:                 $bodytag .= 
 6204:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6205:                                                         $forcereg,$args->{'group'},
 6206:                                                         $args->{'bread_crumbs'},
 6207:                                                         $advtoolsref,'',$hostname);
 6208:             }
 6209:         }else{
 6210:             # this is to seperate menu from content when there's no secondary
 6211:             # menu. Especially needed for public accessible ressources.
 6212:             $bodytag .= '<hr style="clear:both" />';
 6213:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6214:         }
 6215: 
 6216:         return $bodytag;
 6217: }
 6218: 
 6219: sub dc_courseid_toggle {
 6220:     my ($dc_info) = @_;
 6221:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6222:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6223:            &mt('(More ...)').'</a></span>'.
 6224:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6225: }
 6226: 
 6227: sub make_attr_string {
 6228:     my ($register,$attr_ref) = @_;
 6229: 
 6230:     if ($attr_ref && !ref($attr_ref)) {
 6231: 	die("addentries Must be a hash ref ".
 6232: 	    join(':',caller(1))." ".
 6233: 	    join(':',caller(0))." ");
 6234:     }
 6235: 
 6236:     if ($register) {
 6237: 	my ($on_load,$on_unload);
 6238: 	foreach my $key (keys(%{$attr_ref})) {
 6239: 	    if      (lc($key) eq 'onload') {
 6240: 		$on_load.=$attr_ref->{$key}.';';
 6241: 		delete($attr_ref->{$key});
 6242: 
 6243: 	    } elsif (lc($key) eq 'onunload') {
 6244: 		$on_unload.=$attr_ref->{$key}.';';
 6245: 		delete($attr_ref->{$key});
 6246: 	    }
 6247: 	}
 6248: 	$attr_ref->{'onload'}  = $on_load;
 6249: 	$attr_ref->{'onunload'}= $on_unload;
 6250:     }
 6251: 
 6252:     my $attr_string;
 6253:     foreach my $attr (sort(keys(%$attr_ref))) {
 6254: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6255:     }
 6256:     return $attr_string;
 6257: }
 6258: 
 6259: 
 6260: ###############################################
 6261: ###############################################
 6262: 
 6263: =pod
 6264: 
 6265: =item * &endbodytag()
 6266: 
 6267: Returns a uniform footer for LON-CAPA web pages.
 6268: 
 6269: Inputs: 1 - optional reference to an args hash
 6270: If in the hash, key for noredirectlink has a value which evaluates to true,
 6271: a 'Continue' link is not displayed if the page contains an
 6272: internal redirect in the <head></head> section,
 6273: i.e., $env{'internal.head.redirect'} exists   
 6274: 
 6275: =cut
 6276: 
 6277: sub endbodytag {
 6278:     my ($args) = @_;
 6279:     my $endbodytag;
 6280:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6281:         $endbodytag='</body>';
 6282:     }
 6283:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6284:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6285: 	    $endbodytag=
 6286: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6287: 	        &mt('Continue').'</a>'.
 6288: 	        $endbodytag;
 6289:         }
 6290:     }
 6291:     return $endbodytag;
 6292: }
 6293: 
 6294: =pod
 6295: 
 6296: =item * &standard_css()
 6297: 
 6298: Returns a style sheet
 6299: 
 6300: Inputs: (all optional)
 6301:             domain         -> force to color decorate a page for a specific
 6302:                                domain
 6303:             function       -> force usage of a specific rolish color scheme
 6304:             bgcolor        -> override the default page bgcolor
 6305: 
 6306: =cut
 6307: 
 6308: sub standard_css {
 6309:     my ($function,$domain,$bgcolor) = @_;
 6310:     $function  = &get_users_function() if (!$function);
 6311:     my $img    = &designparm($function.'.img',   $domain);
 6312:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6313:     my $font   = &designparm($function.'.font',  $domain);
 6314:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6315: #second colour for later usage
 6316:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6317:     my $pgbg_or_bgcolor =
 6318: 	         $bgcolor ||
 6319: 	         &designparm($function.'.pgbg',  $domain);
 6320:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6321:     my $alink  = &designparm($function.'.alink', $domain);
 6322:     my $vlink  = &designparm($function.'.vlink', $domain);
 6323:     my $link   = &designparm($function.'.link',  $domain);
 6324: 
 6325:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6326:     my $mono                 = 'monospace';
 6327:     my $data_table_head      = $sidebg;
 6328:     my $data_table_light     = '#FAFAFA';
 6329:     my $data_table_dark      = '#E0E0E0';
 6330:     my $data_table_darker    = '#CCCCCC';
 6331:     my $data_table_highlight = '#FFFF00';
 6332:     my $mail_new             = '#FFBB77';
 6333:     my $mail_new_hover       = '#DD9955';
 6334:     my $mail_read            = '#BBBB77';
 6335:     my $mail_read_hover      = '#999944';
 6336:     my $mail_replied         = '#AAAA88';
 6337:     my $mail_replied_hover   = '#888855';
 6338:     my $mail_other           = '#99BBBB';
 6339:     my $mail_other_hover     = '#669999';
 6340:     my $table_header         = '#DDDDDD';
 6341:     my $feedback_link_bg     = '#BBBBBB';
 6342:     my $lg_border_color      = '#C8C8C8';
 6343:     my $button_hover         = '#BF2317';
 6344: 
 6345:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6346:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6347:                                              : '0 3px 0 4px';
 6348: 
 6349: 
 6350:     return <<END;
 6351: 
 6352: /* needed for iframe to allow 100% height in FF */
 6353: body, html { 
 6354:     margin: 0;
 6355:     padding: 0 0.5%;
 6356:     height: 99%; /* to avoid scrollbars */
 6357: }
 6358: 
 6359: body {
 6360:   font-family: $sans;
 6361:   line-height:130%;
 6362:   font-size:0.83em;
 6363:   color:$font;
 6364: }
 6365: 
 6366: a:focus,
 6367: a:focus img {
 6368:   color: red;
 6369: }
 6370: 
 6371: form, .inline {
 6372:   display: inline;
 6373: }
 6374: 
 6375: .LC_right {
 6376:   text-align:right;
 6377: }
 6378: 
 6379: .LC_middle {
 6380:   vertical-align:middle;
 6381: }
 6382: 
 6383: .LC_floatleft {
 6384:   float: left;
 6385: }
 6386: 
 6387: .LC_floatright {
 6388:   float: right;
 6389: }
 6390: 
 6391: .LC_400Box {
 6392:   width:400px;
 6393: }
 6394: 
 6395: .LC_iframecontainer {
 6396:     width: 98%;
 6397:     margin: 0;
 6398:     position: fixed;
 6399:     top: 8.5em;
 6400:     bottom: 0;
 6401: }
 6402: 
 6403: .LC_iframecontainer iframe{
 6404:     border: none;
 6405:     width: 100%;
 6406:     height: 100%;
 6407: }
 6408: 
 6409: .LC_filename {
 6410:   font-family: $mono;
 6411:   white-space:pre;
 6412:   font-size: 120%;
 6413: }
 6414: 
 6415: .LC_fileicon {
 6416:   border: none;
 6417:   height: 1.3em;
 6418:   vertical-align: text-bottom;
 6419:   margin-right: 0.3em;
 6420:   text-decoration:none;
 6421: }
 6422: 
 6423: .LC_setting {
 6424:   text-decoration:underline;
 6425: }
 6426: 
 6427: .LC_error {
 6428:   color: red;
 6429: }
 6430: 
 6431: .LC_warning {
 6432:   color: darkorange;
 6433: }
 6434: 
 6435: .LC_diff_removed {
 6436:   color: red;
 6437: }
 6438: 
 6439: .LC_info,
 6440: .LC_success,
 6441: .LC_diff_added {
 6442:   color: green;
 6443: }
 6444: 
 6445: div.LC_confirm_box {
 6446:   background-color: #FAFAFA;
 6447:   border: 1px solid $lg_border_color;
 6448:   margin-right: 0;
 6449:   padding: 5px;
 6450: }
 6451: 
 6452: div.LC_confirm_box .LC_error img,
 6453: div.LC_confirm_box .LC_success img {
 6454:   vertical-align: middle;
 6455: }
 6456: 
 6457: .LC_maxwidth {
 6458:   max-width: 100%;
 6459:   height: auto;
 6460: }
 6461: 
 6462: .LC_textsize_mobile {
 6463:   \@media only screen and (max-device-width: 480px) {
 6464:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6465:   }
 6466: }
 6467: 
 6468: .LC_icon {
 6469:   border: none;
 6470:   vertical-align: middle;
 6471: }
 6472: 
 6473: .LC_docs_spacer {
 6474:   width: 25px;
 6475:   height: 1px;
 6476:   border: none;
 6477: }
 6478: 
 6479: .LC_internal_info {
 6480:   color: #999999;
 6481: }
 6482: 
 6483: .LC_discussion {
 6484:   background: $data_table_dark;
 6485:   border: 1px solid black;
 6486:   margin: 2px;
 6487: }
 6488: 
 6489: .LC_disc_action_left {
 6490:   background: $sidebg;
 6491:   text-align: left;
 6492:   padding: 4px;
 6493:   margin: 2px;
 6494: }
 6495: 
 6496: .LC_disc_action_right {
 6497:   background: $sidebg;
 6498:   text-align: right;
 6499:   padding: 4px;
 6500:   margin: 2px;
 6501: }
 6502: 
 6503: .LC_disc_new_item {
 6504:   background: white;
 6505:   border: 2px solid red;
 6506:   margin: 4px;
 6507:   padding: 4px;
 6508: }
 6509: 
 6510: .LC_disc_old_item {
 6511:   background: white;
 6512:   margin: 4px;
 6513:   padding: 4px;
 6514: }
 6515: 
 6516: table.LC_pastsubmission {
 6517:   border: 1px solid black;
 6518:   margin: 2px;
 6519: }
 6520: 
 6521: table#LC_menubuttons {
 6522:   width: 100%;
 6523:   background: $pgbg;
 6524:   border: 2px;
 6525:   border-collapse: separate;
 6526:   padding: 0;
 6527: }
 6528: 
 6529: table#LC_title_bar a {
 6530:   color: $fontmenu;
 6531: }
 6532: 
 6533: table#LC_title_bar {
 6534:   clear: both;
 6535:   display: none;
 6536: }
 6537: 
 6538: table#LC_title_bar,
 6539: table.LC_breadcrumbs, /* obsolete? */
 6540: table#LC_title_bar.LC_with_remote {
 6541:   width: 100%;
 6542:   border-color: $pgbg;
 6543:   border-style: solid;
 6544:   border-width: $border;
 6545:   background: $pgbg;
 6546:   color: $fontmenu;
 6547:   border-collapse: collapse;
 6548:   padding: 0;
 6549:   margin: 0;
 6550: }
 6551: 
 6552: ul.LC_breadcrumb_tools_outerlist {
 6553:     margin: 0;
 6554:     padding: 0;
 6555:     position: relative;
 6556:     list-style: none;
 6557: }
 6558: ul.LC_breadcrumb_tools_outerlist li {
 6559:     display: inline;
 6560: }
 6561: 
 6562: .LC_breadcrumb_tools_navigation {
 6563:     padding: 0;
 6564:     margin: 0;
 6565:     float: left;
 6566: }
 6567: .LC_breadcrumb_tools_tools {
 6568:     padding: 0;
 6569:     margin: 0;
 6570:     float: right;
 6571: }
 6572: 
 6573: .LC_placement_prog {
 6574:     padding-right: 20px;
 6575:     font-weight: bold;
 6576:     font-size: 90%;
 6577: }
 6578: 
 6579: table#LC_title_bar td {
 6580:   background: $tabbg;
 6581: }
 6582: 
 6583: table#LC_menubuttons img {
 6584:   border: none;
 6585: }
 6586: 
 6587: .LC_breadcrumbs_component {
 6588:   float: right;
 6589:   margin: 0 1em;
 6590: }
 6591: .LC_breadcrumbs_component img {
 6592:   vertical-align: middle;
 6593: }
 6594: 
 6595: .LC_breadcrumbs_hoverable {
 6596:   background: $sidebg;
 6597: }
 6598: 
 6599: td.LC_table_cell_checkbox {
 6600:   text-align: center;
 6601: }
 6602: 
 6603: .LC_fontsize_small {
 6604:   font-size: 70%;
 6605: }
 6606: 
 6607: #LC_breadcrumbs {
 6608:   clear:both;
 6609:   background: $sidebg;
 6610:   border-bottom: 1px solid $lg_border_color;
 6611:   line-height: 2.5em;
 6612:   overflow: hidden;
 6613:   margin: 0;
 6614:   padding: 0;
 6615:   text-align: left;
 6616: }
 6617: 
 6618: .LC_head_subbox, .LC_actionbox {
 6619:   clear:both;
 6620:   background: #F8F8F8; /* $sidebg; */
 6621:   border: 1px solid $sidebg;
 6622:   margin: 0 0 10px 0;
 6623:   padding: 3px;
 6624:   text-align: left;
 6625: }
 6626: 
 6627: .LC_fontsize_medium {
 6628:   font-size: 85%;
 6629: }
 6630: 
 6631: .LC_fontsize_large {
 6632:   font-size: 120%;
 6633: }
 6634: 
 6635: .LC_menubuttons_inline_text {
 6636:   color: $font;
 6637:   font-size: 90%;
 6638:   padding-left:3px;
 6639: }
 6640: 
 6641: .LC_menubuttons_inline_text img{
 6642:   vertical-align: middle;
 6643: }
 6644: 
 6645: li.LC_menubuttons_inline_text img {
 6646:   cursor:pointer;
 6647:   text-decoration: none;
 6648: }
 6649: 
 6650: .LC_menubuttons_link {
 6651:   text-decoration: none;
 6652: }
 6653: 
 6654: .LC_menubuttons_category {
 6655:   color: $font;
 6656:   background: $pgbg;
 6657:   font-size: larger;
 6658:   font-weight: bold;
 6659: }
 6660: 
 6661: td.LC_menubuttons_text {
 6662:   color: $font;
 6663: }
 6664: 
 6665: .LC_current_location {
 6666:   background: $tabbg;
 6667: }
 6668: 
 6669: td.LC_zero_height {
 6670:   line-height: 0; 
 6671:   cellpadding: 0;
 6672: }
 6673: 
 6674: table.LC_data_table {
 6675:   border: 1px solid #000000;
 6676:   border-collapse: separate;
 6677:   border-spacing: 1px;
 6678:   background: $pgbg;
 6679: }
 6680: 
 6681: .LC_data_table_dense {
 6682:   font-size: small;
 6683: }
 6684: 
 6685: table.LC_nested_outer {
 6686:   border: 1px solid #000000;
 6687:   border-collapse: collapse;
 6688:   border-spacing: 0;
 6689:   width: 100%;
 6690: }
 6691: 
 6692: table.LC_innerpickbox,
 6693: table.LC_nested {
 6694:   border: none;
 6695:   border-collapse: collapse;
 6696:   border-spacing: 0;
 6697:   width: 100%;
 6698: }
 6699: 
 6700: table.LC_data_table tr th,
 6701: table.LC_calendar tr th,
 6702: table.LC_prior_tries tr th,
 6703: table.LC_innerpickbox tr th {
 6704:   font-weight: bold;
 6705:   background-color: $data_table_head;
 6706:   color:$fontmenu;
 6707:   font-size:90%;
 6708: }
 6709: 
 6710: table.LC_innerpickbox tr th,
 6711: table.LC_innerpickbox tr td {
 6712:   vertical-align: top;
 6713: }
 6714: 
 6715: table.LC_data_table tr.LC_info_row > td {
 6716:   background-color: #CCCCCC;
 6717:   font-weight: bold;
 6718:   text-align: left;
 6719: }
 6720: 
 6721: table.LC_data_table tr.LC_odd_row > td {
 6722:   background-color: $data_table_light;
 6723:   padding: 2px;
 6724:   vertical-align: top;
 6725: }
 6726: 
 6727: table.LC_pick_box tr > td.LC_odd_row {
 6728:   background-color: $data_table_light;
 6729:   vertical-align: top;
 6730: }
 6731: 
 6732: table.LC_data_table tr.LC_even_row > td {
 6733:   background-color: $data_table_dark;
 6734:   padding: 2px;
 6735:   vertical-align: top;
 6736: }
 6737: 
 6738: table.LC_pick_box tr > td.LC_even_row {
 6739:   background-color: $data_table_dark;
 6740:   vertical-align: top;
 6741: }
 6742: 
 6743: table.LC_data_table tr.LC_data_table_highlight td {
 6744:   background-color: $data_table_darker;
 6745: }
 6746: 
 6747: table.LC_data_table tr td.LC_leftcol_header {
 6748:   background-color: $data_table_head;
 6749:   font-weight: bold;
 6750: }
 6751: 
 6752: table.LC_data_table tr.LC_empty_row td,
 6753: table.LC_nested tr.LC_empty_row td {
 6754:   font-weight: bold;
 6755:   font-style: italic;
 6756:   text-align: center;
 6757:   padding: 8px;
 6758: }
 6759: 
 6760: table.LC_data_table tr.LC_empty_row td,
 6761: table.LC_data_table tr.LC_footer_row td {
 6762:   background-color: $sidebg;
 6763: }
 6764: 
 6765: table.LC_nested tr.LC_empty_row td {
 6766:   background-color: #FFFFFF;
 6767: }
 6768: 
 6769: table.LC_caption {
 6770: }
 6771: 
 6772: table.LC_nested tr.LC_empty_row td {
 6773:   padding: 4ex
 6774: }
 6775: 
 6776: table.LC_nested_outer tr th {
 6777:   font-weight: bold;
 6778:   color:$fontmenu;
 6779:   background-color: $data_table_head;
 6780:   font-size: small;
 6781:   border-bottom: 1px solid #000000;
 6782: }
 6783: 
 6784: table.LC_nested_outer tr td.LC_subheader {
 6785:   background-color: $data_table_head;
 6786:   font-weight: bold;
 6787:   font-size: small;
 6788:   border-bottom: 1px solid #000000;
 6789:   text-align: right;
 6790: }
 6791: 
 6792: table.LC_nested tr.LC_info_row td {
 6793:   background-color: #CCCCCC;
 6794:   font-weight: bold;
 6795:   font-size: small;
 6796:   text-align: center;
 6797: }
 6798: 
 6799: table.LC_nested tr.LC_info_row td.LC_left_item,
 6800: table.LC_nested_outer tr th.LC_left_item {
 6801:   text-align: left;
 6802: }
 6803: 
 6804: table.LC_nested td {
 6805:   background-color: #FFFFFF;
 6806:   font-size: small;
 6807: }
 6808: 
 6809: table.LC_nested_outer tr th.LC_right_item,
 6810: table.LC_nested tr.LC_info_row td.LC_right_item,
 6811: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6812: table.LC_nested tr td.LC_right_item {
 6813:   text-align: right;
 6814: }
 6815: 
 6816: table.LC_nested tr.LC_odd_row td {
 6817:   background-color: #EEEEEE;
 6818: }
 6819: 
 6820: table.LC_createuser {
 6821: }
 6822: 
 6823: table.LC_createuser tr.LC_section_row td {
 6824:   font-size: small;
 6825: }
 6826: 
 6827: table.LC_createuser tr.LC_info_row td  {
 6828:   background-color: #CCCCCC;
 6829:   font-weight: bold;
 6830:   text-align: center;
 6831: }
 6832: 
 6833: table.LC_calendar {
 6834:   border: 1px solid #000000;
 6835:   border-collapse: collapse;
 6836:   width: 98%;
 6837: }
 6838: 
 6839: table.LC_calendar_pickdate {
 6840:   font-size: xx-small;
 6841: }
 6842: 
 6843: table.LC_calendar tr td {
 6844:   border: 1px solid #000000;
 6845:   vertical-align: top;
 6846:   width: 14%;
 6847: }
 6848: 
 6849: table.LC_calendar tr td.LC_calendar_day_empty {
 6850:   background-color: $data_table_dark;
 6851: }
 6852: 
 6853: table.LC_calendar tr td.LC_calendar_day_current {
 6854:   background-color: $data_table_highlight;
 6855: }
 6856: 
 6857: table.LC_data_table tr td.LC_mail_new {
 6858:   background-color: $mail_new;
 6859: }
 6860: 
 6861: table.LC_data_table tr.LC_mail_new:hover {
 6862:   background-color: $mail_new_hover;
 6863: }
 6864: 
 6865: table.LC_data_table tr td.LC_mail_read {
 6866:   background-color: $mail_read;
 6867: }
 6868: 
 6869: /*
 6870: table.LC_data_table tr.LC_mail_read:hover {
 6871:   background-color: $mail_read_hover;
 6872: }
 6873: */
 6874: 
 6875: table.LC_data_table tr td.LC_mail_replied {
 6876:   background-color: $mail_replied;
 6877: }
 6878: 
 6879: /*
 6880: table.LC_data_table tr.LC_mail_replied:hover {
 6881:   background-color: $mail_replied_hover;
 6882: }
 6883: */
 6884: 
 6885: table.LC_data_table tr td.LC_mail_other {
 6886:   background-color: $mail_other;
 6887: }
 6888: 
 6889: /*
 6890: table.LC_data_table tr.LC_mail_other:hover {
 6891:   background-color: $mail_other_hover;
 6892: }
 6893: */
 6894: 
 6895: table.LC_data_table tr > td.LC_browser_file,
 6896: table.LC_data_table tr > td.LC_browser_file_published {
 6897:   background: #AAEE77;
 6898: }
 6899: 
 6900: table.LC_data_table tr > td.LC_browser_file_locked,
 6901: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6902:   background: #FFAA99;
 6903: }
 6904: 
 6905: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6906:   background: #888888;
 6907: }
 6908: 
 6909: table.LC_data_table tr > td.LC_browser_file_modified,
 6910: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6911:   background: #F8F866;
 6912: }
 6913: 
 6914: table.LC_data_table tr.LC_browser_folder > td {
 6915:   background: #E0E8FF;
 6916: }
 6917: 
 6918: table.LC_data_table tr > td.LC_roles_is {
 6919:   /* background: #77FF77; */
 6920: }
 6921: 
 6922: table.LC_data_table tr > td.LC_roles_future {
 6923:   border-right: 8px solid #FFFF77;
 6924: }
 6925: 
 6926: table.LC_data_table tr > td.LC_roles_will {
 6927:   border-right: 8px solid #FFAA77;
 6928: }
 6929: 
 6930: table.LC_data_table tr > td.LC_roles_expired {
 6931:   border-right: 8px solid #FF7777;
 6932: }
 6933: 
 6934: table.LC_data_table tr > td.LC_roles_will_not {
 6935:   border-right: 8px solid #AAFF77;
 6936: }
 6937: 
 6938: table.LC_data_table tr > td.LC_roles_selected {
 6939:   border-right: 8px solid #11CC55;
 6940: }
 6941: 
 6942: span.LC_current_location {
 6943:   font-size:larger;
 6944:   background: $pgbg;
 6945: }
 6946: 
 6947: span.LC_current_nav_location {
 6948:   font-weight:bold;
 6949:   background: $sidebg;
 6950: }
 6951: 
 6952: span.LC_parm_menu_item {
 6953:   font-size: larger;
 6954: }
 6955: 
 6956: span.LC_parm_scope_all {
 6957:   color: red;
 6958: }
 6959: 
 6960: span.LC_parm_scope_folder {
 6961:   color: green;
 6962: }
 6963: 
 6964: span.LC_parm_scope_resource {
 6965:   color: orange;
 6966: }
 6967: 
 6968: span.LC_parm_part {
 6969:   color: blue;
 6970: }
 6971: 
 6972: span.LC_parm_folder,
 6973: span.LC_parm_symb {
 6974:   font-size: x-small;
 6975:   font-family: $mono;
 6976:   color: #AAAAAA;
 6977: }
 6978: 
 6979: ul.LC_parm_parmlist li {
 6980:   display: inline-block;
 6981:   padding: 0.3em 0.8em;
 6982:   vertical-align: top;
 6983:   width: 150px;
 6984:   border-top:1px solid $lg_border_color;
 6985: }
 6986: 
 6987: td.LC_parm_overview_level_menu,
 6988: td.LC_parm_overview_map_menu,
 6989: td.LC_parm_overview_parm_selectors,
 6990: td.LC_parm_overview_restrictions  {
 6991:   border: 1px solid black;
 6992:   border-collapse: collapse;
 6993: }
 6994: 
 6995: span.LC_parm_recursive,
 6996: td.LC_parm_recursive {
 6997:   font-weight: bold;
 6998:   font-size: smaller;
 6999: }
 7000: 
 7001: table.LC_parm_overview_restrictions td {
 7002:   border-width: 1px 4px 1px 4px;
 7003:   border-style: solid;
 7004:   border-color: $pgbg;
 7005:   text-align: center;
 7006: }
 7007: 
 7008: table.LC_parm_overview_restrictions th {
 7009:   background: $tabbg;
 7010:   border-width: 1px 4px 1px 4px;
 7011:   border-style: solid;
 7012:   border-color: $pgbg;
 7013: }
 7014: 
 7015: table#LC_helpmenu {
 7016:   border: none;
 7017:   height: 55px;
 7018:   border-spacing: 0;
 7019: }
 7020: 
 7021: table#LC_helpmenu fieldset legend {
 7022:   font-size: larger;
 7023: }
 7024: 
 7025: table#LC_helpmenu_links {
 7026:   width: 100%;
 7027:   border: 1px solid black;
 7028:   background: $pgbg;
 7029:   padding: 0;
 7030:   border-spacing: 1px;
 7031: }
 7032: 
 7033: table#LC_helpmenu_links tr td {
 7034:   padding: 1px;
 7035:   background: $tabbg;
 7036:   text-align: center;
 7037:   font-weight: bold;
 7038: }
 7039: 
 7040: table#LC_helpmenu_links a:link,
 7041: table#LC_helpmenu_links a:visited,
 7042: table#LC_helpmenu_links a:active {
 7043:   text-decoration: none;
 7044:   color: $font;
 7045: }
 7046: 
 7047: table#LC_helpmenu_links a:hover {
 7048:   text-decoration: underline;
 7049:   color: $vlink;
 7050: }
 7051: 
 7052: .LC_chrt_popup_exists {
 7053:   border: 1px solid #339933;
 7054:   margin: -1px;
 7055: }
 7056: 
 7057: .LC_chrt_popup_up {
 7058:   border: 1px solid yellow;
 7059:   margin: -1px;
 7060: }
 7061: 
 7062: .LC_chrt_popup {
 7063:   border: 1px solid #8888FF;
 7064:   background: #CCCCFF;
 7065: }
 7066: 
 7067: table.LC_pick_box {
 7068:   border-collapse: separate;
 7069:   background: white;
 7070:   border: 1px solid black;
 7071:   border-spacing: 1px;
 7072: }
 7073: 
 7074: table.LC_pick_box td.LC_pick_box_title {
 7075:   background: $sidebg;
 7076:   font-weight: bold;
 7077:   text-align: left;
 7078:   vertical-align: top;
 7079:   width: 184px;
 7080:   padding: 8px;
 7081: }
 7082: 
 7083: table.LC_pick_box td.LC_pick_box_value {
 7084:   text-align: left;
 7085:   padding: 8px;
 7086: }
 7087: 
 7088: table.LC_pick_box td.LC_pick_box_select {
 7089:   text-align: left;
 7090:   padding: 8px;
 7091: }
 7092: 
 7093: table.LC_pick_box td.LC_pick_box_separator {
 7094:   padding: 0;
 7095:   height: 1px;
 7096:   background: black;
 7097: }
 7098: 
 7099: table.LC_pick_box td.LC_pick_box_submit {
 7100:   text-align: right;
 7101: }
 7102: 
 7103: table.LC_pick_box td.LC_evenrow_value {
 7104:   text-align: left;
 7105:   padding: 8px;
 7106:   background-color: $data_table_light;
 7107: }
 7108: 
 7109: table.LC_pick_box td.LC_oddrow_value {
 7110:   text-align: left;
 7111:   padding: 8px;
 7112:   background-color: $data_table_light;
 7113: }
 7114: 
 7115: span.LC_helpform_receipt_cat {
 7116:   font-weight: bold;
 7117: }
 7118: 
 7119: table.LC_group_priv_box {
 7120:   background: white;
 7121:   border: 1px solid black;
 7122:   border-spacing: 1px;
 7123: }
 7124: 
 7125: table.LC_group_priv_box td.LC_pick_box_title {
 7126:   background: $tabbg;
 7127:   font-weight: bold;
 7128:   text-align: right;
 7129:   width: 184px;
 7130: }
 7131: 
 7132: table.LC_group_priv_box td.LC_groups_fixed {
 7133:   background: $data_table_light;
 7134:   text-align: center;
 7135: }
 7136: 
 7137: table.LC_group_priv_box td.LC_groups_optional {
 7138:   background: $data_table_dark;
 7139:   text-align: center;
 7140: }
 7141: 
 7142: table.LC_group_priv_box td.LC_groups_functionality {
 7143:   background: $data_table_darker;
 7144:   text-align: center;
 7145:   font-weight: bold;
 7146: }
 7147: 
 7148: table.LC_group_priv td {
 7149:   text-align: left;
 7150:   padding: 0;
 7151: }
 7152: 
 7153: .LC_navbuttons {
 7154:   margin: 2ex 0ex 2ex 0ex;
 7155: }
 7156: 
 7157: .LC_topic_bar {
 7158:   font-weight: bold;
 7159:   background: $tabbg;
 7160:   margin: 1em 0em 1em 2em;
 7161:   padding: 3px;
 7162:   font-size: 1.2em;
 7163: }
 7164: 
 7165: .LC_topic_bar span {
 7166:   left: 0.5em;
 7167:   position: absolute;
 7168:   vertical-align: middle;
 7169:   font-size: 1.2em;
 7170: }
 7171: 
 7172: table.LC_course_group_status {
 7173:   margin: 20px;
 7174: }
 7175: 
 7176: table.LC_status_selector td {
 7177:   vertical-align: top;
 7178:   text-align: center;
 7179:   padding: 4px;
 7180: }
 7181: 
 7182: div.LC_feedback_link {
 7183:   clear: both;
 7184:   background: $sidebg;
 7185:   width: 100%;
 7186:   padding-bottom: 10px;
 7187:   border: 1px $tabbg solid;
 7188:   height: 22px;
 7189:   line-height: 22px;
 7190:   padding-top: 5px;
 7191: }
 7192: 
 7193: div.LC_feedback_link img {
 7194:   height: 22px;
 7195:   vertical-align:middle;
 7196: }
 7197: 
 7198: div.LC_feedback_link a {
 7199:   text-decoration: none;
 7200: }
 7201: 
 7202: div.LC_comblock {
 7203:   display:inline;
 7204:   color:$font;
 7205:   font-size:90%;
 7206: }
 7207: 
 7208: div.LC_feedback_link div.LC_comblock {
 7209:   padding-left:5px;
 7210: }
 7211: 
 7212: div.LC_feedback_link div.LC_comblock a {
 7213:   color:$font;
 7214: }
 7215: 
 7216: span.LC_feedback_link {
 7217:   /* background: $feedback_link_bg; */
 7218:   font-size: larger;
 7219: }
 7220: 
 7221: span.LC_message_link {
 7222:   /* background: $feedback_link_bg; */
 7223:   font-size: larger;
 7224:   position: absolute;
 7225:   right: 1em;
 7226: }
 7227: 
 7228: table.LC_prior_tries {
 7229:   border: 1px solid #000000;
 7230:   border-collapse: separate;
 7231:   border-spacing: 1px;
 7232: }
 7233: 
 7234: table.LC_prior_tries td {
 7235:   padding: 2px;
 7236: }
 7237: 
 7238: .LC_answer_correct {
 7239:   background: lightgreen;
 7240:   color: darkgreen;
 7241:   padding: 6px;
 7242: }
 7243: 
 7244: .LC_answer_charged_try {
 7245:   background: #FFAAAA;
 7246:   color: darkred;
 7247:   padding: 6px;
 7248: }
 7249: 
 7250: .LC_answer_not_charged_try,
 7251: .LC_answer_no_grade,
 7252: .LC_answer_late {
 7253:   background: lightyellow;
 7254:   color: black;
 7255:   padding: 6px;
 7256: }
 7257: 
 7258: .LC_answer_previous {
 7259:   background: lightblue;
 7260:   color: darkblue;
 7261:   padding: 6px;
 7262: }
 7263: 
 7264: .LC_answer_no_message {
 7265:   background: #FFFFFF;
 7266:   color: black;
 7267:   padding: 6px;
 7268: }
 7269: 
 7270: .LC_answer_unknown,
 7271: .LC_answer_warning {
 7272:   background: orange;
 7273:   color: black;
 7274:   padding: 6px;
 7275: }
 7276: 
 7277: span.LC_prior_numerical,
 7278: span.LC_prior_string,
 7279: span.LC_prior_custom,
 7280: span.LC_prior_reaction,
 7281: span.LC_prior_math {
 7282:   font-family: $mono;
 7283:   white-space: pre;
 7284: }
 7285: 
 7286: span.LC_prior_string {
 7287:   font-family: $mono;
 7288:   white-space: pre;
 7289: }
 7290: 
 7291: table.LC_prior_option {
 7292:   width: 100%;
 7293:   border-collapse: collapse;
 7294: }
 7295: 
 7296: table.LC_prior_rank,
 7297: table.LC_prior_match {
 7298:   border-collapse: collapse;
 7299: }
 7300: 
 7301: table.LC_prior_option tr td,
 7302: table.LC_prior_rank tr td,
 7303: table.LC_prior_match tr td {
 7304:   border: 1px solid #000000;
 7305: }
 7306: 
 7307: .LC_nobreak {
 7308:   white-space: nowrap;
 7309: }
 7310: 
 7311: span.LC_cusr_emph {
 7312:   font-style: italic;
 7313: }
 7314: 
 7315: span.LC_cusr_subheading {
 7316:   font-weight: normal;
 7317:   font-size: 85%;
 7318: }
 7319: 
 7320: div.LC_docs_entry_move {
 7321:   border: 1px solid #BBBBBB;
 7322:   background: #DDDDDD;
 7323:   width: 22px;
 7324:   padding: 1px;
 7325:   margin: 0;
 7326: }
 7327: 
 7328: table.LC_data_table tr > td.LC_docs_entry_commands,
 7329: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7330:   font-size: x-small;
 7331: }
 7332: 
 7333: .LC_docs_entry_parameter {
 7334:   white-space: nowrap;
 7335: }
 7336: 
 7337: .LC_docs_copy {
 7338:   color: #000099;
 7339: }
 7340: 
 7341: .LC_docs_cut {
 7342:   color: #550044;
 7343: }
 7344: 
 7345: .LC_docs_rename {
 7346:   color: #009900;
 7347: }
 7348: 
 7349: .LC_docs_remove {
 7350:   color: #990000;
 7351: }
 7352: 
 7353: .LC_docs_alias {
 7354:   color: #440055;  
 7355: }
 7356: 
 7357: .LC_domprefs_email,
 7358: .LC_docs_alias_name,
 7359: .LC_docs_reinit_warn,
 7360: .LC_docs_ext_edit {
 7361:   font-size: x-small;
 7362: }
 7363: 
 7364: table.LC_docs_adddocs td,
 7365: table.LC_docs_adddocs th {
 7366:   border: 1px solid #BBBBBB;
 7367:   padding: 4px;
 7368:   background: #DDDDDD;
 7369: }
 7370: 
 7371: table.LC_sty_begin {
 7372:   background: #BBFFBB;
 7373: }
 7374: 
 7375: table.LC_sty_end {
 7376:   background: #FFBBBB;
 7377: }
 7378: 
 7379: table.LC_double_column {
 7380:   border-width: 0;
 7381:   border-collapse: collapse;
 7382:   width: 100%;
 7383:   padding: 2px;
 7384: }
 7385: 
 7386: table.LC_double_column tr td.LC_left_col {
 7387:   top: 2px;
 7388:   left: 2px;
 7389:   width: 47%;
 7390:   vertical-align: top;
 7391: }
 7392: 
 7393: table.LC_double_column tr td.LC_right_col {
 7394:   top: 2px;
 7395:   right: 2px;
 7396:   width: 47%;
 7397:   vertical-align: top;
 7398: }
 7399: 
 7400: div.LC_left_float {
 7401:   float: left;
 7402:   padding-right: 5%;
 7403:   padding-bottom: 4px;
 7404: }
 7405: 
 7406: div.LC_clear_float_header {
 7407:   padding-bottom: 2px;
 7408: }
 7409: 
 7410: div.LC_clear_float_footer {
 7411:   padding-top: 10px;
 7412:   clear: both;
 7413: }
 7414: 
 7415: div.LC_grade_show_user {
 7416: /*  border-left: 5px solid $sidebg; */
 7417:   border-top: 5px solid #000000;
 7418:   margin: 50px 0 0 0;
 7419:   padding: 15px 0 5px 10px;
 7420: }
 7421: 
 7422: div.LC_grade_show_user_odd_row {
 7423: /*  border-left: 5px solid #000000; */
 7424: }
 7425: 
 7426: div.LC_grade_show_user div.LC_Box {
 7427:   margin-right: 50px;
 7428: }
 7429: 
 7430: div.LC_grade_submissions,
 7431: div.LC_grade_message_center,
 7432: div.LC_grade_info_links {
 7433:   margin: 5px;
 7434:   width: 99%;
 7435:   background: #FFFFFF;
 7436: }
 7437: 
 7438: div.LC_grade_submissions_header,
 7439: div.LC_grade_message_center_header {
 7440:   font-weight: bold;
 7441:   font-size: large;
 7442: }
 7443: 
 7444: div.LC_grade_submissions_body,
 7445: div.LC_grade_message_center_body {
 7446:   border: 1px solid black;
 7447:   width: 99%;
 7448:   background: #FFFFFF;
 7449: }
 7450: 
 7451: table.LC_scantron_action {
 7452:   width: 100%;
 7453: }
 7454: 
 7455: table.LC_scantron_action tr th {
 7456:   font-weight:bold;
 7457:   font-style:normal;
 7458: }
 7459: 
 7460: .LC_edit_problem_header,
 7461: div.LC_edit_problem_footer {
 7462:   font-weight: normal;
 7463:   font-size:  medium;
 7464:   margin: 2px;
 7465:   background-color: $sidebg;
 7466: }
 7467: 
 7468: div.LC_edit_problem_header,
 7469: div.LC_edit_problem_header div,
 7470: div.LC_edit_problem_footer,
 7471: div.LC_edit_problem_footer div,
 7472: div.LC_edit_problem_editxml_header,
 7473: div.LC_edit_problem_editxml_header div {
 7474:   z-index: 100;
 7475: }
 7476: 
 7477: div.LC_edit_problem_header_title {
 7478:   font-weight: bold;
 7479:   font-size: larger;
 7480:   background: $tabbg;
 7481:   padding: 3px;
 7482:   margin: 0 0 5px 0;
 7483: }
 7484: 
 7485: table.LC_edit_problem_header_title {
 7486:   width: 100%;
 7487:   background: $tabbg;
 7488: }
 7489: 
 7490: div.LC_edit_actionbar {
 7491:     background-color: $sidebg;
 7492:     margin: 0;
 7493:     padding: 0;
 7494:     line-height: 200%;
 7495: }
 7496: 
 7497: div.LC_edit_actionbar div{
 7498:     padding: 0;
 7499:     margin: 0;
 7500:     display: inline-block;
 7501: }
 7502: 
 7503: .LC_edit_opt {
 7504:   padding-left: 1em;
 7505:   white-space: nowrap;
 7506: }
 7507: 
 7508: .LC_edit_problem_latexhelper{
 7509:     text-align: right;
 7510: }
 7511: 
 7512: #LC_edit_problem_colorful div{
 7513:     margin-left: 40px;
 7514: }
 7515: 
 7516: #LC_edit_problem_codemirror div{
 7517:     margin-left: 0px;
 7518: }
 7519: 
 7520: img.stift {
 7521:   border-width: 0;
 7522:   vertical-align: middle;
 7523: }
 7524: 
 7525: table td.LC_mainmenu_col_fieldset {
 7526:   vertical-align: top;
 7527: }
 7528: 
 7529: div.LC_createcourse {
 7530:   margin: 10px 10px 10px 10px;
 7531: }
 7532: 
 7533: .LC_dccid {
 7534:   float: right;
 7535:   margin: 0.2em 0 0 0;
 7536:   padding: 0;
 7537:   font-size: 90%;
 7538:   display:none;
 7539: }
 7540: 
 7541: ol.LC_primary_menu a:hover,
 7542: ol#LC_MenuBreadcrumbs a:hover,
 7543: ol#LC_PathBreadcrumbs a:hover,
 7544: ul#LC_secondary_menu a:hover,
 7545: .LC_FormSectionClearButton input:hover
 7546: ul.LC_TabContent   li:hover a {
 7547:   color:$button_hover;
 7548:   text-decoration:none;
 7549: }
 7550: 
 7551: h1 {
 7552:   padding: 0;
 7553:   line-height:130%;
 7554: }
 7555: 
 7556: h2,
 7557: h3,
 7558: h4,
 7559: h5,
 7560: h6 {
 7561:   margin: 5px 0 5px 0;
 7562:   padding: 0;
 7563:   line-height:130%;
 7564: }
 7565: 
 7566: .LC_hcell {
 7567:   padding:3px 15px 3px 15px;
 7568:   margin: 0;
 7569:   background-color:$tabbg;
 7570:   color:$fontmenu;
 7571:   border-bottom:solid 1px $lg_border_color;
 7572: }
 7573: 
 7574: .LC_Box > .LC_hcell {
 7575:   margin: 0 -10px 10px -10px;
 7576: }
 7577: 
 7578: .LC_noBorder {
 7579:   border: 0;
 7580: }
 7581: 
 7582: .LC_FormSectionClearButton input {
 7583:   background-color:transparent;
 7584:   border: none;
 7585:   cursor:pointer;
 7586:   text-decoration:underline;
 7587: }
 7588: 
 7589: .LC_help_open_topic {
 7590:   color: #FFFFFF;
 7591:   background-color: #EEEEFF;
 7592:   margin: 1px;
 7593:   padding: 4px;
 7594:   border: 1px solid #000033;
 7595:   white-space: nowrap;
 7596:   /* vertical-align: middle; */
 7597: }
 7598: 
 7599: dl,
 7600: ul,
 7601: div,
 7602: fieldset {
 7603:   margin: 10px 10px 10px 0;
 7604:   /* overflow: hidden; */
 7605: }
 7606: 
 7607: article.geogebraweb div {
 7608:     margin: 0;
 7609: }
 7610: 
 7611: fieldset > legend {
 7612:   font-weight: bold;
 7613:   padding: 0 5px 0 5px;
 7614: }
 7615: 
 7616: #LC_nav_bar {
 7617:   float: left;
 7618:   background-color: $pgbg_or_bgcolor;
 7619:   margin: 0 0 2px 0;
 7620: }
 7621: 
 7622: #LC_realm {
 7623:   margin: 0.2em 0 0 0;
 7624:   padding: 0;
 7625:   font-weight: bold;
 7626:   text-align: center;
 7627:   background-color: $pgbg_or_bgcolor;
 7628: }
 7629: 
 7630: #LC_nav_bar em {
 7631:   font-weight: bold;
 7632:   font-style: normal;
 7633: }
 7634: 
 7635: ol.LC_primary_menu {
 7636:   margin: 0;
 7637:   padding: 0;
 7638: }
 7639: 
 7640: ol#LC_PathBreadcrumbs {
 7641:   margin: 0;
 7642: }
 7643: 
 7644: ol.LC_primary_menu li {
 7645:   color: RGB(80, 80, 80);
 7646:   vertical-align: middle;
 7647:   text-align: left;
 7648:   list-style: none;
 7649:   position: relative;
 7650:   float: left;
 7651:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7652:   line-height: 1.5em;
 7653: }
 7654: 
 7655: ol.LC_primary_menu li a,
 7656: ol.LC_primary_menu li p {
 7657:   display: block;
 7658:   margin: 0;
 7659:   padding: 0 5px 0 10px;
 7660:   text-decoration: none;
 7661: }
 7662: 
 7663: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7664:   display: inline-block;
 7665:   width: 95%;
 7666:   text-align: left;
 7667: }
 7668: 
 7669: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7670:   display: inline-block;	
 7671:   width: 5%;
 7672:   float: right;
 7673:   text-align: right;
 7674:   font-size: 70%;
 7675: }
 7676: 
 7677: ol.LC_primary_menu ul {
 7678:   display: none;
 7679:   width: 15em;
 7680:   background-color: $data_table_light;
 7681:   position: absolute;
 7682:   top: 100%;
 7683: }
 7684: 
 7685: ol.LC_primary_menu ul ul {
 7686:   left: 100%;
 7687:   top: 0;
 7688: }
 7689: 
 7690: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7691:   display: block;
 7692:   position: absolute;
 7693:   margin: 0;
 7694:   padding: 0;
 7695:   z-index: 2;
 7696: }
 7697: 
 7698: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7699: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7700:   font-size: 90%;
 7701:   vertical-align: top;
 7702:   float: none;
 7703:   border-left: 1px solid black;
 7704:   border-right: 1px solid black;
 7705: /* A dark bottom border to visualize different menu options; 
 7706: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7707:   border-bottom: 1px solid $data_table_dark; 
 7708: }
 7709: 
 7710: ol.LC_primary_menu li li p:hover {
 7711:   color:$button_hover;
 7712:   text-decoration:none;
 7713:   background-color:$data_table_dark;
 7714: }
 7715: 
 7716: ol.LC_primary_menu li li a:hover {
 7717:    color:$button_hover;
 7718:    background-color:$data_table_dark;
 7719: }
 7720: 
 7721: /* Font-size equal to the size of the predecessors*/
 7722: ol.LC_primary_menu li:hover li li {
 7723:   font-size: 100%;
 7724: }
 7725: 
 7726: ol.LC_primary_menu li img {
 7727:   vertical-align: bottom;
 7728:   height: 1.1em;
 7729:   margin: 0.2em 0 0 0;
 7730: }
 7731: 
 7732: ol.LC_primary_menu a {
 7733:   color: RGB(80, 80, 80);
 7734:   text-decoration: none;
 7735: }
 7736: 
 7737: ol.LC_primary_menu a.LC_new_message {
 7738:   font-weight:bold;
 7739:   color: darkred;
 7740: }
 7741: 
 7742: ol.LC_docs_parameters {
 7743:   margin-left: 0;
 7744:   padding: 0;
 7745:   list-style: none;
 7746: }
 7747: 
 7748: ol.LC_docs_parameters li {
 7749:   margin: 0;
 7750:   padding-right: 20px;
 7751:   display: inline;
 7752: }
 7753: 
 7754: ol.LC_docs_parameters li:before {
 7755:   content: "\\002022 \\0020";
 7756: }
 7757: 
 7758: li.LC_docs_parameters_title {
 7759:   font-weight: bold;
 7760: }
 7761: 
 7762: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7763:   content: "";
 7764: }
 7765: 
 7766: ul#LC_secondary_menu {
 7767:   clear: right;
 7768:   color: $fontmenu;
 7769:   background: $tabbg;
 7770:   list-style: none;
 7771:   padding: 0;
 7772:   margin: 0;
 7773:   width: 100%;
 7774:   text-align: left;
 7775:   float: left;
 7776: }
 7777: 
 7778: ul#LC_secondary_menu li {
 7779:   font-weight: bold;
 7780:   line-height: 1.8em;
 7781:   border-right: 1px solid black;
 7782:   float: left;
 7783: }
 7784: 
 7785: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7786:   background-color: $data_table_light;
 7787: }
 7788: 
 7789: ul#LC_secondary_menu li a {
 7790:   padding: 0 0.8em;
 7791: }
 7792: 
 7793: ul#LC_secondary_menu li ul {
 7794:   display: none;
 7795: }
 7796: 
 7797: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7798:   display: block;
 7799:   position: absolute;
 7800:   margin: 0;
 7801:   padding: 0;
 7802:   list-style:none;
 7803:   float: none;
 7804:   background-color: $data_table_light;
 7805:   z-index: 2;
 7806:   margin-left: -1px;
 7807: }
 7808: 
 7809: ul#LC_secondary_menu li ul li {
 7810:   font-size: 90%;
 7811:   vertical-align: top;
 7812:   border-left: 1px solid black;
 7813:   border-right: 1px solid black;
 7814:   background-color: $data_table_light;
 7815:   list-style:none;
 7816:   float: none;
 7817: }
 7818: 
 7819: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7820:   background-color: $data_table_dark;
 7821: }
 7822: 
 7823: ul.LC_TabContent {
 7824:   display:block;
 7825:   background: $sidebg;
 7826:   border-bottom: solid 1px $lg_border_color;
 7827:   list-style:none;
 7828:   margin: -1px -10px 0 -10px;
 7829:   padding: 0;
 7830: }
 7831: 
 7832: ul.LC_TabContent li,
 7833: ul.LC_TabContentBigger li {
 7834:   float:left;
 7835: }
 7836: 
 7837: ul#LC_secondary_menu li a {
 7838:   color: $fontmenu;
 7839:   text-decoration: none;
 7840: }
 7841: 
 7842: ul.LC_TabContent {
 7843:   min-height:20px;
 7844: }
 7845: 
 7846: ul.LC_TabContent li {
 7847:   vertical-align:middle;
 7848:   padding: 0 16px 0 10px;
 7849:   background-color:$tabbg;
 7850:   border-bottom:solid 1px $lg_border_color;
 7851:   border-left: solid 1px $font;
 7852: }
 7853: 
 7854: ul.LC_TabContent .right {
 7855:   float:right;
 7856: }
 7857: 
 7858: ul.LC_TabContent li a,
 7859: ul.LC_TabContent li {
 7860:   color:rgb(47,47,47);
 7861:   text-decoration:none;
 7862:   font-size:95%;
 7863:   font-weight:bold;
 7864:   min-height:20px;
 7865: }
 7866: 
 7867: ul.LC_TabContent li a:hover,
 7868: ul.LC_TabContent li a:focus {
 7869:   color: $button_hover;
 7870:   background:none;
 7871:   outline:none;
 7872: }
 7873: 
 7874: ul.LC_TabContent li:hover {
 7875:   color: $button_hover;
 7876:   cursor:pointer;
 7877: }
 7878: 
 7879: ul.LC_TabContent li.active {
 7880:   color: $font;
 7881:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7882:   border-bottom:solid 1px #FFFFFF;
 7883:   cursor: default;
 7884: }
 7885: 
 7886: ul.LC_TabContent li.active a {
 7887:   color:$font;
 7888:   background:#FFFFFF;
 7889:   outline: none;
 7890: }
 7891: 
 7892: ul.LC_TabContent li.goback {
 7893:   float: left;
 7894:   border-left: none;
 7895: }
 7896: 
 7897: #maincoursedoc {
 7898:   clear:both;
 7899: }
 7900: 
 7901: ul.LC_TabContentBigger {
 7902:   display:block;
 7903:   list-style:none;
 7904:   padding: 0;
 7905: }
 7906: 
 7907: ul.LC_TabContentBigger li {
 7908:   vertical-align:bottom;
 7909:   height: 30px;
 7910:   font-size:110%;
 7911:   font-weight:bold;
 7912:   color: #737373;
 7913: }
 7914: 
 7915: ul.LC_TabContentBigger li.active {
 7916:   position: relative;
 7917:   top: 1px;
 7918: }
 7919: 
 7920: ul.LC_TabContentBigger li a {
 7921:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7922:   height: 30px;
 7923:   line-height: 30px;
 7924:   text-align: center;
 7925:   display: block;
 7926:   text-decoration: none;
 7927:   outline: none;  
 7928: }
 7929: 
 7930: ul.LC_TabContentBigger li.active a {
 7931:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7932:   color:$font;
 7933: }
 7934: 
 7935: ul.LC_TabContentBigger li b {
 7936:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7937:   display: block;
 7938:   float: left;
 7939:   padding: 0 30px;
 7940:   border-bottom: 1px solid $lg_border_color;
 7941: }
 7942: 
 7943: ul.LC_TabContentBigger li:hover b {
 7944:   color:$button_hover;
 7945: }
 7946: 
 7947: ul.LC_TabContentBigger li.active b {
 7948:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7949:   color:$font;
 7950:   border: 0;
 7951: }
 7952: 
 7953: 
 7954: ul.LC_CourseBreadcrumbs {
 7955:   background: $sidebg;
 7956:   height: 2em;
 7957:   padding-left: 10px;
 7958:   margin: 0;
 7959:   list-style-position: inside;
 7960: }
 7961: 
 7962: ol#LC_MenuBreadcrumbs,
 7963: ol#LC_PathBreadcrumbs {
 7964:   padding-left: 10px;
 7965:   margin: 0;
 7966:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7967: }
 7968: 
 7969: ol#LC_MenuBreadcrumbs li,
 7970: ol#LC_PathBreadcrumbs li,
 7971: ul.LC_CourseBreadcrumbs li {
 7972:   display: inline;
 7973:   white-space: normal;  
 7974: }
 7975: 
 7976: ol#LC_MenuBreadcrumbs li a,
 7977: ul.LC_CourseBreadcrumbs li a {
 7978:   text-decoration: none;
 7979:   font-size:90%;
 7980: }
 7981: 
 7982: ol#LC_MenuBreadcrumbs h1 {
 7983:   display: inline;
 7984:   font-size: 90%;
 7985:   line-height: 2.5em;
 7986:   margin: 0;
 7987:   padding: 0;
 7988: }
 7989: 
 7990: ol#LC_PathBreadcrumbs li a {
 7991:   text-decoration:none;
 7992:   font-size:100%;
 7993:   font-weight:bold;
 7994: }
 7995: 
 7996: .LC_Box {
 7997:   border: solid 1px $lg_border_color;
 7998:   padding: 0 10px 10px 10px;
 7999: }
 8000: 
 8001: .LC_DocsBox {
 8002:   border: solid 1px $lg_border_color;
 8003:   padding: 0 0 10px 10px;
 8004: }
 8005: 
 8006: .LC_AboutMe_Image {
 8007:   float:left;
 8008:   margin-right:10px;
 8009: }
 8010: 
 8011: .LC_Clear_AboutMe_Image {
 8012:   clear:left;
 8013: }
 8014: 
 8015: dl.LC_ListStyleClean dt {
 8016:   padding-right: 5px;
 8017:   display: table-header-group;
 8018: }
 8019: 
 8020: dl.LC_ListStyleClean dd {
 8021:   display: table-row;
 8022: }
 8023: 
 8024: .LC_ListStyleClean,
 8025: .LC_ListStyleSimple,
 8026: .LC_ListStyleNormal,
 8027: .LC_ListStyleSpecial {
 8028:   /* display:block; */
 8029:   list-style-position: inside;
 8030:   list-style-type: none;
 8031:   overflow: hidden;
 8032:   padding: 0;
 8033: }
 8034: 
 8035: .LC_ListStyleSimple li,
 8036: .LC_ListStyleSimple dd,
 8037: .LC_ListStyleNormal li,
 8038: .LC_ListStyleNormal dd,
 8039: .LC_ListStyleSpecial li,
 8040: .LC_ListStyleSpecial dd {
 8041:   margin: 0;
 8042:   padding: 5px 5px 5px 10px;
 8043:   clear: both;
 8044: }
 8045: 
 8046: .LC_ListStyleClean li,
 8047: .LC_ListStyleClean dd {
 8048:   padding-top: 0;
 8049:   padding-bottom: 0;
 8050: }
 8051: 
 8052: .LC_ListStyleSimple dd,
 8053: .LC_ListStyleSimple li {
 8054:   border-bottom: solid 1px $lg_border_color;
 8055: }
 8056: 
 8057: .LC_ListStyleSpecial li,
 8058: .LC_ListStyleSpecial dd {
 8059:   list-style-type: none;
 8060:   background-color: RGB(220, 220, 220);
 8061:   margin-bottom: 4px;
 8062: }
 8063: 
 8064: table.LC_SimpleTable {
 8065:   margin:5px;
 8066:   border:solid 1px $lg_border_color;
 8067: }
 8068: 
 8069: table.LC_SimpleTable tr {
 8070:   padding: 0;
 8071:   border:solid 1px $lg_border_color;
 8072: }
 8073: 
 8074: table.LC_SimpleTable thead {
 8075:   background:rgb(220,220,220);
 8076: }
 8077: 
 8078: div.LC_columnSection {
 8079:   display: block;
 8080:   clear: both;
 8081:   overflow: hidden;
 8082:   margin: 0;
 8083: }
 8084: 
 8085: div.LC_columnSection>* {
 8086:   float: left;
 8087:   margin: 10px 20px 10px 0;
 8088:   overflow:hidden;
 8089: }
 8090: 
 8091: table em {
 8092:   font-weight: bold;
 8093:   font-style: normal;
 8094: }
 8095: 
 8096: table.LC_tableBrowseRes,
 8097: table.LC_tableOfContent {
 8098:   border:none;
 8099:   border-spacing: 1px;
 8100:   padding: 3px;
 8101:   background-color: #FFFFFF;
 8102:   font-size: 90%;
 8103: }
 8104: 
 8105: table.LC_tableOfContent {
 8106:   border-collapse: collapse;
 8107: }
 8108: 
 8109: table.LC_tableBrowseRes a,
 8110: table.LC_tableOfContent a {
 8111:   background-color: transparent;
 8112:   text-decoration: none;
 8113: }
 8114: 
 8115: table.LC_tableOfContent img {
 8116:   border: none;
 8117:   height: 1.3em;
 8118:   vertical-align: text-bottom;
 8119:   margin-right: 0.3em;
 8120: }
 8121: 
 8122: a#LC_content_toolbar_firsthomework {
 8123:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8124: }
 8125: 
 8126: a#LC_content_toolbar_everything {
 8127:   background-image:url(/res/adm/pages/show-all.gif);
 8128: }
 8129: 
 8130: a#LC_content_toolbar_uncompleted {
 8131:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8132: }
 8133: 
 8134: #LC_content_toolbar_clearbubbles {
 8135:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8136: }
 8137: 
 8138: a#LC_content_toolbar_changefolder {
 8139:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8140: }
 8141: 
 8142: a#LC_content_toolbar_changefolder_toggled {
 8143:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8144: }
 8145: 
 8146: a#LC_content_toolbar_edittoplevel {
 8147:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8148: }
 8149: 
 8150: ul#LC_toolbar li a:hover {
 8151:   background-position: bottom center;
 8152: }
 8153: 
 8154: ul#LC_toolbar {
 8155:   padding: 0;
 8156:   margin: 2px;
 8157:   list-style:none;
 8158:   position:relative;
 8159:   background-color:white;
 8160:   overflow: auto;
 8161: }
 8162: 
 8163: ul#LC_toolbar li {
 8164:   border:1px solid white;
 8165:   padding: 0;
 8166:   margin: 0;
 8167:   float: left;
 8168:   display:inline;
 8169:   vertical-align:middle;
 8170:   white-space: nowrap;
 8171: }
 8172: 
 8173: 
 8174: a.LC_toolbarItem {
 8175:   display:block;
 8176:   padding: 0;
 8177:   margin: 0;
 8178:   height: 32px;
 8179:   width: 32px;
 8180:   color:white;
 8181:   border: none;
 8182:   background-repeat:no-repeat;
 8183:   background-color:transparent;
 8184: }
 8185: 
 8186: ul.LC_funclist {
 8187:     margin: 0;
 8188:     padding: 0.5em 1em 0.5em 0;
 8189: }
 8190: 
 8191: ul.LC_funclist > li:first-child {
 8192:     font-weight:bold; 
 8193:     margin-left:0.8em;
 8194: }
 8195: 
 8196: ul.LC_funclist + ul.LC_funclist {
 8197:     /* 
 8198:        left border as a seperator if we have more than
 8199:        one list 
 8200:     */
 8201:     border-left: 1px solid $sidebg;
 8202:     /* 
 8203:        this hides the left border behind the border of the 
 8204:        outer box if element is wrapped to the next 'line' 
 8205:     */
 8206:     margin-left: -1px;
 8207: }
 8208: 
 8209: ul.LC_funclist li {
 8210:   display: inline;
 8211:   white-space: nowrap;
 8212:   margin: 0 0 0 25px;
 8213:   line-height: 150%;
 8214: }
 8215: 
 8216: .LC_hidden {
 8217:   display: none;
 8218: }
 8219: 
 8220: .LCmodal-overlay {
 8221: 		position:fixed;
 8222: 		top:0;
 8223: 		right:0;
 8224: 		bottom:0;
 8225: 		left:0;
 8226: 		height:100%;
 8227: 		width:100%;
 8228: 		margin:0;
 8229: 		padding:0;
 8230: 		background:#999;
 8231: 		opacity:.75;
 8232: 		filter: alpha(opacity=75);
 8233: 		-moz-opacity: 0.75;
 8234: 		z-index:101;
 8235: }
 8236: 
 8237: * html .LCmodal-overlay {   
 8238: 		position: absolute;
 8239: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8240: }
 8241: 
 8242: .LCmodal-window {
 8243: 		position:fixed;
 8244: 		top:50%;
 8245: 		left:50%;
 8246: 		margin:0;
 8247: 		padding:0;
 8248: 		z-index:102;
 8249: 	}
 8250: 
 8251: * html .LCmodal-window {
 8252: 		position:absolute;
 8253: }
 8254: 
 8255: .LCclose-window {
 8256: 		position:absolute;
 8257: 		width:32px;
 8258: 		height:32px;
 8259: 		right:8px;
 8260: 		top:8px;
 8261: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8262: 		text-indent:-99999px;
 8263: 		overflow:hidden;
 8264: 		cursor:pointer;
 8265: }
 8266: 
 8267: pre.LC_wordwrap {
 8268:   white-space: pre-wrap;
 8269:   white-space: -moz-pre-wrap;
 8270:   white-space: -pre-wrap;
 8271:   white-space: -o-pre-wrap;
 8272:   word-wrap: break-word;
 8273: }
 8274: 
 8275: /*
 8276:   styles used for response display
 8277: */
 8278: div.LC_radiofoil, div.LC_rankfoil {
 8279:   margin: .5em 0em .5em 0em;
 8280: }
 8281: table.LC_itemgroup {
 8282:   margin-top: 1em;
 8283: }
 8284: 
 8285: /*
 8286:   styles used by TTH when "Default set of options to pass to tth/m
 8287:   when converting TeX" in course settings has been set
 8288: 
 8289:   option passed: -t
 8290: 
 8291: */
 8292: 
 8293: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8294: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8295: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8296: td div.norm {line-height:normal;}
 8297: 
 8298: /*
 8299:   option passed -y3
 8300: */
 8301: 
 8302: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8303: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8304: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8305: 
 8306: /*
 8307:   sections with roles, for content only
 8308: */
 8309: section[class^="role-"] {
 8310:   padding-left: 10px;
 8311:   padding-right: 5px;
 8312:   margin-top: 8px;
 8313:   margin-bottom: 8px;
 8314:   border: 1px solid #2A4;
 8315:   border-radius: 5px;
 8316:   box-shadow: 0px 1px 1px #BBB;
 8317: }
 8318: section[class^="role-"]>h1 {
 8319:   position: relative;
 8320:   margin: 0px;
 8321:   padding-top: 10px;
 8322:   padding-left: 40px;
 8323: }
 8324: section[class^="role-"]>h1:before {
 8325:   position: absolute;
 8326:   left: -5px;
 8327:   top: 5px;
 8328: }
 8329: section.role-activity>h1:before {
 8330:   content:url('/adm/daxe/images/section_icons/activity.png');
 8331: }
 8332: section.role-advice>h1:before {
 8333:   content:url('/adm/daxe/images/section_icons/advice.png');
 8334: }
 8335: section.role-bibliography>h1:before {
 8336:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8337: }
 8338: section.role-citation>h1:before {
 8339:   content:url('/adm/daxe/images/section_icons/citation.png');
 8340: }
 8341: section.role-conclusion>h1:before {
 8342:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8343: }
 8344: section.role-definition>h1:before {
 8345:   content:url('/adm/daxe/images/section_icons/definition.png');
 8346: }
 8347: section.role-demonstration>h1:before {
 8348:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8349: }
 8350: section.role-example>h1:before {
 8351:   content:url('/adm/daxe/images/section_icons/example.png');
 8352: }
 8353: section.role-explanation>h1:before {
 8354:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8355: }
 8356: section.role-introduction>h1:before {
 8357:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8358: }
 8359: section.role-method>h1:before {
 8360:   content:url('/adm/daxe/images/section_icons/method.png');
 8361: }
 8362: section.role-more_information>h1:before {
 8363:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8364: }
 8365: section.role-objectives>h1:before {
 8366:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8367: }
 8368: section.role-prerequisites>h1:before {
 8369:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8370: }
 8371: section.role-remark>h1:before {
 8372:   content:url('/adm/daxe/images/section_icons/remark.png');
 8373: }
 8374: section.role-reminder>h1:before {
 8375:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8376: }
 8377: section.role-summary>h1:before {
 8378:   content:url('/adm/daxe/images/section_icons/summary.png');
 8379: }
 8380: section.role-syntax>h1:before {
 8381:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8382: }
 8383: section.role-warning>h1:before {
 8384:   content:url('/adm/daxe/images/section_icons/warning.png');
 8385: }
 8386: 
 8387: #LC_minitab_header {
 8388:   float:left;
 8389:   width:100%;
 8390:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8391:   font-size:93%;
 8392:   line-height:normal;
 8393:   margin: 0.5em 0 0.5em 0;
 8394: }
 8395: #LC_minitab_header ul {
 8396:   margin:0;
 8397:   padding:10px 10px 0;
 8398:   list-style:none;
 8399: }
 8400: #LC_minitab_header li {
 8401:   float:left;
 8402:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8403:   margin:0;
 8404:   padding:0 0 0 9px;
 8405: }
 8406: #LC_minitab_header a {
 8407:   display:block;
 8408:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8409:   padding:5px 15px 4px 6px;
 8410: }
 8411: #LC_minitab_header #LC_current_minitab {
 8412:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8413: }
 8414: #LC_minitab_header #LC_current_minitab a {
 8415:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8416:   padding-bottom:5px;
 8417: }
 8418: 
 8419: 
 8420: END
 8421: }
 8422: 
 8423: =pod
 8424: 
 8425: =item * &headtag()
 8426: 
 8427: Returns a uniform footer for LON-CAPA web pages.
 8428: 
 8429: Inputs: $title - optional title for the head
 8430:         $head_extra - optional extra HTML to put inside the <head>
 8431:         $args - optional arguments
 8432:             force_register - if is true call registerurl so the remote is 
 8433:                              informed
 8434:             redirect       -> array ref of
 8435:                                    1- seconds before redirect occurs
 8436:                                    2- url to redirect to
 8437:                                    3- whether the side effect should occur
 8438:                            (side effect of setting 
 8439:                                $env{'internal.head.redirect'} to the url 
 8440:                                redirected too)
 8441:             domain         -> force to color decorate a page for a specific
 8442:                                domain
 8443:             function       -> force usage of a specific rolish color scheme
 8444:             bgcolor        -> override the default page bgcolor
 8445:             no_auto_mt_title
 8446:                            -> prevent &mt()ing the title arg
 8447: 
 8448: =cut
 8449: 
 8450: sub headtag {
 8451:     my ($title,$head_extra,$args) = @_;
 8452:     
 8453:     my $function = $args->{'function'} || &get_users_function();
 8454:     my $domain   = $args->{'domain'}   || &determinedomain();
 8455:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8456:     my $httphost = $args->{'use_absolute'};
 8457:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8458: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8459: 		   #time(),
 8460: 		   $env{'environment.color.timestamp'},
 8461: 		   $function,$domain,$bgcolor);
 8462: 
 8463:     $url = '/adm/css/'.&escape($url).'.css';
 8464: 
 8465:     my $result =
 8466: 	'<head>'.
 8467: 	&font_settings($args);
 8468: 
 8469:     my $inhibitprint;
 8470:     if ($args->{'print_suppress'}) {
 8471:         $inhibitprint = &print_suppression();
 8472:     }
 8473: 
 8474:     if (!$args->{'frameset'}) {
 8475: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8476:     }
 8477:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8478:         $result .= Apache::lonxml::display_title();
 8479:     }
 8480:     if (!$args->{'no_nav_bar'} 
 8481: 	&& !$args->{'only_body'}
 8482: 	&& !$args->{'frameset'}) {
 8483: 	$result .= &help_menu_js($httphost);
 8484:         $result.=&modal_window();
 8485:         $result.=&togglebox_script();
 8486:         $result.=&wishlist_window();
 8487:         $result.=&LCprogressbarUpdate_script();
 8488:     } else {
 8489:         if ($args->{'add_modal'}) {
 8490:            $result.=&modal_window();
 8491:         }
 8492:         if ($args->{'add_wishlist'}) {
 8493:            $result.=&wishlist_window();
 8494:         }
 8495:         if ($args->{'add_togglebox'}) {
 8496:            $result.=&togglebox_script();
 8497:         }
 8498:         if ($args->{'add_progressbar'}) {
 8499:            $result.=&LCprogressbarUpdate_script();
 8500:         }
 8501:     }
 8502:     if (ref($args->{'redirect'})) {
 8503: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8504: 	$url = &Apache::lonenc::check_encrypt($url);
 8505: 	if (!$inhibit_continue) {
 8506: 	    $env{'internal.head.redirect'} = $url;
 8507: 	}
 8508: 	$result.=<<ADDMETA
 8509: <meta http-equiv="pragma" content="no-cache" />
 8510: <meta http-equiv="Refresh" content="$time; url=$url" />
 8511: ADDMETA
 8512:     } else {
 8513:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8514:             my $requrl = $env{'request.uri'};
 8515:             if ($requrl eq '') {
 8516:                 $requrl = $ENV{'REQUEST_URI'};
 8517:                 $requrl =~ s/\?.+$//;
 8518:             }
 8519:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8520:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8521:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8522:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8523:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8524:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8525:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8526:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8527:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8528:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8529:                             if (($newserver) && ($newserver ne $lonhost)) {
 8530:                                 my $numsec = 5;
 8531:                                 my $timeout = $numsec * 1000;
 8532:                                 my ($newurl,$locknum,%locks,$msg);
 8533:                                 if ($env{'request.role.adv'}) {
 8534:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8535:                                 }
 8536:                                 my $disable_submit = 0;
 8537:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8538:                                     $disable_submit = 1;
 8539:                                 }
 8540:                                 if ($locknum) {
 8541:                                     my @lockinfo = sort(values(%locks));
 8542:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8543:                                            join(", ",sort(values(%locks)))."\\n".
 8544:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8545:                                 } else {
 8546:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8547:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8548:                                     }
 8549:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8550:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8551:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8552:                                         $newurl .= '&role='.$env{'request.role'};
 8553:                                     }
 8554:                                     if ($env{'request.symb'}) {
 8555:                                         $newurl .= '&symb='.$env{'request.symb'};
 8556:                                     } else {
 8557:                                         $newurl .= '&origurl='.$requrl;
 8558:                                     }
 8559:                                 }
 8560:                                 &js_escape(\$msg);
 8561:                                 $result.=<<OFFLOAD
 8562: <meta http-equiv="pragma" content="no-cache" />
 8563: <script type="text/javascript">
 8564: // <![CDATA[
 8565: function LC_Offload_Now() {
 8566:     var dest = "$newurl";
 8567:     if (dest != '') {
 8568:         window.location.href="$newurl";
 8569:     }
 8570: }
 8571: \$(document).ready(function () {
 8572:     window.alert('$msg');
 8573:     if ($disable_submit) {
 8574:         \$(".LC_hwk_submit").prop("disabled", true);
 8575:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8576:     }
 8577:     setTimeout('LC_Offload_Now()', $timeout);
 8578: });
 8579: // ]]>
 8580: </script>
 8581: OFFLOAD
 8582:                             }
 8583:                         }
 8584:                     }
 8585:                 }
 8586:             }
 8587:         }
 8588:     }
 8589:     if (!defined($title)) {
 8590: 	$title = 'The LearningOnline Network with CAPA';
 8591:     }
 8592:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8593:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8594: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8595:     if (!$args->{'frameset'}) {
 8596:         $result .= ' /';
 8597:     }
 8598:     $result .= '>' 
 8599:         .$inhibitprint
 8600: 	.$head_extra;
 8601:     my $clientmobile;
 8602:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8603:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8604:     } else {
 8605:         $clientmobile = $env{'browser.mobile'};
 8606:     }
 8607:     if ($clientmobile) {
 8608:         $result .= '
 8609: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8610: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8611:     }
 8612:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8613:     return $result.'</head>';
 8614: }
 8615: 
 8616: =pod
 8617: 
 8618: =item * &font_settings()
 8619: 
 8620: Returns neccessary <meta> to set the proper encoding
 8621: 
 8622: Inputs: optional reference to HASH -- $args passed to &headtag()
 8623: 
 8624: =cut
 8625: 
 8626: sub font_settings {
 8627:     my ($args) = @_;
 8628:     my $headerstring='';
 8629:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8630:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8631:         $headerstring.=
 8632:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8633:         if (!$args->{'frameset'}) {
 8634: 	    $headerstring.= ' /';
 8635:         }
 8636: 	$headerstring .= '>'."\n";
 8637:     }
 8638:     return $headerstring;
 8639: }
 8640: 
 8641: =pod
 8642: 
 8643: =item * &print_suppression()
 8644: 
 8645: In course context returns css which causes the body to be blank when media="print",
 8646: if printout generation is unavailable for the current resource.
 8647: 
 8648: This could be because:
 8649: 
 8650: (a) printstartdate is in the future
 8651: 
 8652: (b) printenddate is in the past
 8653: 
 8654: (c) there is an active exam block with "printout"
 8655: functionality blocked
 8656: 
 8657: Users with pav, pfo or evb privileges are exempt.
 8658: 
 8659: Inputs: none
 8660: 
 8661: =cut
 8662: 
 8663: 
 8664: sub print_suppression {
 8665:     my $noprint;
 8666:     if ($env{'request.course.id'}) {
 8667:         my $scope = $env{'request.course.id'};
 8668:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8669:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8670:             return;
 8671:         }
 8672:         if ($env{'request.course.sec'} ne '') {
 8673:             $scope .= "/$env{'request.course.sec'}";
 8674:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8675:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8676:                 return;
 8677:             }
 8678:         }
 8679:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8680:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8681:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8682:         if ($blocked) {
 8683:             my $checkrole = "cm./$cdom/$cnum";
 8684:             if ($env{'request.course.sec'} ne '') {
 8685:                 $checkrole .= "/$env{'request.course.sec'}";
 8686:             }
 8687:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8688:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8689:                 $noprint = 1;
 8690:             }
 8691:         }
 8692:         unless ($noprint) {
 8693:             my $symb = &Apache::lonnet::symbread();
 8694:             if ($symb ne '') {
 8695:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8696:                 if (ref($navmap)) {
 8697:                     my $res = $navmap->getBySymb($symb);
 8698:                     if (ref($res)) {
 8699:                         if (!$res->resprintable()) {
 8700:                             $noprint = 1;
 8701:                         }
 8702:                     }
 8703:                 }
 8704:             }
 8705:         }
 8706:         if ($noprint) {
 8707:             return <<"ENDSTYLE";
 8708: <style type="text/css" media="print">
 8709:     body { display:none }
 8710: </style>
 8711: ENDSTYLE
 8712:         }
 8713:     }
 8714:     return;
 8715: }
 8716: 
 8717: =pod
 8718: 
 8719: =item * &xml_begin()
 8720: 
 8721: Returns the needed doctype and <html>
 8722: 
 8723: Inputs: none
 8724: 
 8725: =cut
 8726: 
 8727: sub xml_begin {
 8728:     my ($is_frameset) = @_;
 8729:     my $output='';
 8730: 
 8731:     if ($env{'browser.mathml'}) {
 8732: 	$output='<?xml version="1.0"?>'
 8733:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8734: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8735:             
 8736: #	    .'<!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">] >'
 8737: 	    .'<!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">'
 8738:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8739: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8740:     } elsif ($is_frameset) {
 8741:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8742:                 '<html>'."\n";
 8743:     } else {
 8744: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8745:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8746:     }
 8747:     return $output;
 8748: }
 8749: 
 8750: =pod
 8751: 
 8752: =item * &start_page()
 8753: 
 8754: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8755: 
 8756: Inputs:
 8757: 
 8758: =over 4
 8759: 
 8760: $title - optional title for the page
 8761: 
 8762: $head_extra - optional extra HTML to incude inside the <head>
 8763: 
 8764: $args - additional optional args supported are:
 8765: 
 8766: =over 8
 8767: 
 8768:              only_body      -> is true will set &bodytag() onlybodytag
 8769:                                     arg on
 8770:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8771:              add_entries    -> additional attributes to add to the  <body>
 8772:              domain         -> force to color decorate a page for a 
 8773:                                     specific domain
 8774:              function       -> force usage of a specific rolish color
 8775:                                     scheme
 8776:              redirect       -> see &headtag()
 8777:              bgcolor        -> override the default page bg color
 8778:              js_ready       -> return a string ready for being used in 
 8779:                                     a javascript writeln
 8780:              html_encode    -> return a string ready for being used in 
 8781:                                     a html attribute
 8782:              force_register -> if is true will turn on the &bodytag()
 8783:                                     $forcereg arg
 8784:              frameset       -> if true will start with a <frameset>
 8785:                                     rather than <body>
 8786:              skip_phases    -> hash ref of 
 8787:                                     head -> skip the <html><head> generation
 8788:                                     body -> skip all <body> generation
 8789:              no_auto_mt_title -> prevent &mt()ing the title arg
 8790:              bread_crumbs ->             Array containing breadcrumbs
 8791:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8792:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8793:                                     to lonhtmlcommon::breadcrumbs
 8794:              group          -> includes the current group, if page is for a 
 8795:                                specific group
 8796:              use_absolute   -> for request for external resource or syllabus, this
 8797:                                will contain https://<hostname> if server uses
 8798:                                https (as per hosts.tab), but request is for http
 8799:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8800: 
 8801: =back
 8802: 
 8803: =back
 8804: 
 8805: =cut
 8806: 
 8807: sub start_page {
 8808:     my ($title,$head_extra,$args) = @_;
 8809:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8810: 
 8811:     $env{'internal.start_page'}++;
 8812:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
 8813: 
 8814:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8815:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8816:     }
 8817: 
 8818:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8819:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8820:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8821:                 $args->{'no_primary_menu'} = 1;
 8822:             }
 8823:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8824:                 $args->{'no_inline_menu'} = 1;
 8825:             }
 8826:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8827:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8828:             }
 8829:         } else {
 8830:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8831:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8832:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8833:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8834:                     $args->{'no_primary_menu'} = 1;
 8835:                 }
 8836:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8837:                     $args->{'no_inline_menu'} = 1;
 8838:                 }
 8839:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8840:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8841:                 }
 8842:             }
 8843:         }
 8844:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8845:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8846:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8847:     }
 8848:     
 8849:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8850: 	if ($args->{'frameset'}) {
 8851: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8852: 						$args->{'add_entries'});
 8853: 	    $result .= "\n<frameset $attr_string>\n";
 8854:         } else {
 8855:             $result .=
 8856:                 &bodytag($title, 
 8857:                          $args->{'function'},       $args->{'add_entries'},
 8858:                          $args->{'only_body'},      $args->{'domain'},
 8859:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8860:                          $args->{'bgcolor'},        $args,
 8861:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
 8862:         }
 8863:     }
 8864: 
 8865:     if ($args->{'js_ready'}) {
 8866: 		$result = &js_ready($result);
 8867:     }
 8868:     if ($args->{'html_encode'}) {
 8869: 		$result = &html_encode($result);
 8870:     }
 8871: 
 8872:     # Preparation for new and consistent functionlist at top of screen
 8873:     # if ($args->{'functionlist'}) {
 8874:     #            $result .= &build_functionlist();
 8875:     #}
 8876: 
 8877:     # Don't add anything more if only_body wanted or in const space
 8878:     return $result if    $args->{'only_body'} 
 8879:                       || $env{'request.state'} eq 'construct';
 8880: 
 8881:     #Breadcrumbs
 8882:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8883: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8884: 		#if any br links exists, add them to the breadcrumbs
 8885: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8886: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8887: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8888: 			}
 8889: 		}
 8890:                 # if @advtools array contains items add then to the breadcrumbs
 8891:                 if (@advtools > 0) {
 8892:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8893:                 }
 8894:                 my $menulink;
 8895:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8896:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8897:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 8898:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 8899:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 8900:                      (!$env{'request.role.adv'}))) {
 8901:                     $menulink = 0;
 8902:                 } else {
 8903:                     undef($menulink);
 8904:                 }
 8905: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8906: 		if(exists($args->{'bread_crumbs_component'})){
 8907: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8908:                 } else {
 8909: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8910: 		}
 8911:     }
 8912:     return $result;
 8913: }
 8914: 
 8915: sub end_page {
 8916:     my ($args) = @_;
 8917:     $env{'internal.end_page'}++;
 8918:     my $result;
 8919:     if ($args->{'discussion'}) {
 8920: 	my ($target,$parser);
 8921: 	if (ref($args->{'discussion'})) {
 8922: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8923: 				$args->{'discussion'}{'parser'});
 8924: 	}
 8925: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8926:     }
 8927:     if ($args->{'frameset'}) {
 8928: 	$result .= '</frameset>';
 8929:     } else {
 8930: 	$result .= &endbodytag($args);
 8931:     }
 8932:     unless ($args->{'notbody'}) {
 8933:         $result .= "\n</html>";
 8934:     }
 8935: 
 8936:     if ($args->{'js_ready'}) {
 8937: 	$result = &js_ready($result);
 8938:     }
 8939: 
 8940:     if ($args->{'html_encode'}) {
 8941: 	$result = &html_encode($result);
 8942:     }
 8943: 
 8944:     return $result;
 8945: }
 8946: 
 8947: sub wishlist_window {
 8948:     return(<<'ENDWISHLIST');
 8949: <script type="text/javascript">
 8950: // <![CDATA[
 8951: // <!-- BEGIN LON-CAPA Internal
 8952: function set_wishlistlink(title, path) {
 8953:     if (!title) {
 8954:         title = document.title;
 8955:         title = title.replace(/^LON-CAPA /,'');
 8956:     }
 8957:     title = encodeURIComponent(title);
 8958:     title = title.replace("'","\\\'");
 8959:     if (!path) {
 8960:         path = location.pathname;
 8961:     }
 8962:     path = encodeURIComponent(path);
 8963:     path = path.replace("'","\\\'");
 8964:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8965:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8966: }
 8967: // END LON-CAPA Internal -->
 8968: // ]]>
 8969: </script>
 8970: ENDWISHLIST
 8971: }
 8972: 
 8973: sub modal_window {
 8974:     return(<<'ENDMODAL');
 8975: <script type="text/javascript">
 8976: // <![CDATA[
 8977: // <!-- BEGIN LON-CAPA Internal
 8978: var modalWindow = {
 8979: 	parent:"body",
 8980: 	windowId:null,
 8981: 	content:null,
 8982: 	width:null,
 8983: 	height:null,
 8984: 	close:function()
 8985: 	{
 8986: 	        $(".LCmodal-window").remove();
 8987: 	        $(".LCmodal-overlay").remove();
 8988: 	},
 8989: 	open:function()
 8990: 	{
 8991: 		var modal = "";
 8992: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8993: 		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;\">";
 8994: 		modal += this.content;
 8995: 		modal += "</div>";	
 8996: 
 8997: 		$(this.parent).append(modal);
 8998: 
 8999: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9000: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9001: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9002: 	}
 9003: };
 9004: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9005: 	{
 9006:                 source = source.replace(/'/g,"&#39;");
 9007: 		modalWindow.windowId = "myModal";
 9008: 		modalWindow.width = width;
 9009: 		modalWindow.height = height;
 9010: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9011: 		modalWindow.open();
 9012: 	};
 9013: // END LON-CAPA Internal -->
 9014: // ]]>
 9015: </script>
 9016: ENDMODAL
 9017: }
 9018: 
 9019: sub modal_link {
 9020:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9021:     unless ($width) { $width=480; }
 9022:     unless ($height) { $height=400; }
 9023:     unless ($scrolling) { $scrolling='yes'; }
 9024:     unless ($transparency) { $transparency='true'; }
 9025: 
 9026:     my $target_attr;
 9027:     if (defined($target)) {
 9028:         $target_attr = 'target="'.$target.'"';
 9029:     }
 9030:     return <<"ENDLINK";
 9031: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9032: ENDLINK
 9033: }
 9034: 
 9035: sub modal_adhoc_script {
 9036:     my ($funcname,$width,$height,$content)=@_;
 9037:     return (<<ENDADHOC);
 9038: <script type="text/javascript">
 9039: // <![CDATA[
 9040:         var $funcname = function()
 9041:         {
 9042:                 modalWindow.windowId = "myModal";
 9043:                 modalWindow.width = $width;
 9044:                 modalWindow.height = $height;
 9045:                 modalWindow.content = '$content';
 9046:                 modalWindow.open();
 9047:         };  
 9048: // ]]>
 9049: </script>
 9050: ENDADHOC
 9051: }
 9052: 
 9053: sub modal_adhoc_inner {
 9054:     my ($funcname,$width,$height,$content)=@_;
 9055:     my $innerwidth=$width-20;
 9056:     $content=&js_ready(
 9057:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9058:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9059:                  $content.
 9060:                  &end_scrollbox().
 9061:                  &end_page()
 9062:              );
 9063:     return &modal_adhoc_script($funcname,$width,$height,$content);
 9064: }
 9065: 
 9066: sub modal_adhoc_window {
 9067:     my ($funcname,$width,$height,$content,$linktext)=@_;
 9068:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 9069:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9070: }
 9071: 
 9072: sub modal_adhoc_launch {
 9073:     my ($funcname,$width,$height,$content)=@_;
 9074:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9075: <script type="text/javascript">
 9076: // <![CDATA[
 9077: $funcname();
 9078: // ]]>
 9079: </script>
 9080: ENDLAUNCH
 9081: }
 9082: 
 9083: sub modal_adhoc_close {
 9084:     return (<<ENDCLOSE);
 9085: <script type="text/javascript">
 9086: // <![CDATA[
 9087: modalWindow.close();
 9088: // ]]>
 9089: </script>
 9090: ENDCLOSE
 9091: }
 9092: 
 9093: sub togglebox_script {
 9094:    return(<<ENDTOGGLE);
 9095: <script type="text/javascript"> 
 9096: // <![CDATA[
 9097: function LCtoggleDisplay(id,hidetext,showtext) {
 9098:    link = document.getElementById(id + "link").childNodes[0];
 9099:    with (document.getElementById(id).style) {
 9100:       if (display == "none" ) {
 9101:           display = "inline";
 9102:           link.nodeValue = hidetext;
 9103:         } else {
 9104:           display = "none";
 9105:           link.nodeValue = showtext;
 9106:        }
 9107:    }
 9108: }
 9109: // ]]>
 9110: </script>
 9111: ENDTOGGLE
 9112: }
 9113: 
 9114: sub start_togglebox {
 9115:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9116:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9117:     unless ($showtext) { $showtext=&mt('show'); }
 9118:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9119:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9120:     return &start_data_table().
 9121:            &start_data_table_header_row().
 9122:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9123:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9124:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9125:            &end_data_table_header_row().
 9126:            '<tr id="'.$id.'" style="display:none""><td>';
 9127: }
 9128: 
 9129: sub end_togglebox {
 9130:     return '</td></tr>'.&end_data_table();
 9131: }
 9132: 
 9133: sub LCprogressbar_script {
 9134:    my ($id,$number_to_do)=@_;
 9135:    if ($number_to_do) {
 9136:        return(<<ENDPROGRESS);
 9137: <script type="text/javascript">
 9138: // <![CDATA[
 9139: \$('#progressbar$id').progressbar({
 9140:   value: 0,
 9141:   change: function(event, ui) {
 9142:     var newVal = \$(this).progressbar('option', 'value');
 9143:     \$('.pblabel', this).text(LCprogressTxt);
 9144:   }
 9145: });
 9146: // ]]>
 9147: </script>
 9148: ENDPROGRESS
 9149:    } else {
 9150:        return(<<ENDPROGRESS);
 9151: <script type="text/javascript">
 9152: // <![CDATA[
 9153: \$('#progressbar$id').progressbar({
 9154:   value: false,
 9155:   create: function(event, ui) {
 9156:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9157:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9158:   }
 9159: });
 9160: // ]]>
 9161: </script>
 9162: ENDPROGRESS
 9163:    }
 9164: }
 9165: 
 9166: sub LCprogressbarUpdate_script {
 9167:    return(<<ENDPROGRESSUPDATE);
 9168: <style type="text/css">
 9169: .ui-progressbar { position:relative; }
 9170: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
 9171: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9172: </style>
 9173: <script type="text/javascript">
 9174: // <![CDATA[
 9175: var LCprogressTxt='---';
 9176: 
 9177: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9178:    LCprogressTxt=progresstext;
 9179:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9180:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9181:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9182:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9183:    } else {
 9184:        \$('#progressbar'+id).progressbar('value',percent);
 9185:    }
 9186: }
 9187: // ]]>
 9188: </script>
 9189: ENDPROGRESSUPDATE
 9190: }
 9191: 
 9192: my $LClastpercent;
 9193: my $LCidcnt;
 9194: my $LCcurrentid;
 9195: 
 9196: sub LCprogressbar {
 9197:     my ($r,$number_to_do,$preamble)=@_;
 9198:     $LClastpercent=0;
 9199:     $LCidcnt++;
 9200:     $LCcurrentid=$$.'_'.$LCidcnt;
 9201:     my ($starting,$content);
 9202:     if ($number_to_do) {
 9203:         $starting=&mt('Starting');
 9204:         $content=(<<ENDPROGBAR);
 9205: $preamble
 9206:   <div id="progressbar$LCcurrentid">
 9207:     <span class="pblabel">$starting</span>
 9208:   </div>
 9209: ENDPROGBAR
 9210:     } else {
 9211:         $starting=&mt('Loading...');
 9212:         $LClastpercent='false';
 9213:         $content=(<<ENDPROGBAR);
 9214: $preamble
 9215:   <div id="progressbar$LCcurrentid">
 9216:       <div class="progress-label">$starting</div>
 9217:   </div>
 9218: ENDPROGBAR
 9219:     }
 9220:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9221: }
 9222: 
 9223: sub LCprogressbarUpdate {
 9224:     my ($r,$val,$text,$number_to_do)=@_;
 9225:     if ($number_to_do) {
 9226:         unless ($val) { 
 9227:             if ($LClastpercent) {
 9228:                 $val=$LClastpercent;
 9229:             } else {
 9230:                 $val=0;
 9231:             }
 9232:         }
 9233:         if ($val<0) { $val=0; }
 9234:         if ($val>100) { $val=0; }
 9235:         $LClastpercent=$val;
 9236:         unless ($text) { $text=$val.'%'; }
 9237:     } else {
 9238:         $val = 'false';
 9239:     }
 9240:     $text=&js_ready($text);
 9241:     &r_print($r,<<ENDUPDATE);
 9242: <script type="text/javascript">
 9243: // <![CDATA[
 9244: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9245: // ]]>
 9246: </script>
 9247: ENDUPDATE
 9248: }
 9249: 
 9250: sub LCprogressbarClose {
 9251:     my ($r)=@_;
 9252:     $LClastpercent=0;
 9253:     &r_print($r,<<ENDCLOSE);
 9254: <script type="text/javascript">
 9255: // <![CDATA[
 9256: \$("#progressbar$LCcurrentid").hide('slow'); 
 9257: // ]]>
 9258: </script>
 9259: ENDCLOSE
 9260: }
 9261: 
 9262: sub r_print {
 9263:     my ($r,$to_print)=@_;
 9264:     if ($r) {
 9265:       $r->print($to_print);
 9266:       $r->rflush();
 9267:     } else {
 9268:       print($to_print);
 9269:     }
 9270: }
 9271: 
 9272: sub html_encode {
 9273:     my ($result) = @_;
 9274: 
 9275:     $result = &HTML::Entities::encode($result,'<>&"');
 9276:     
 9277:     return $result;
 9278: }
 9279: 
 9280: sub js_ready {
 9281:     my ($result) = @_;
 9282: 
 9283:     $result =~ s/[\n\r]/ /xmsg;
 9284:     $result =~ s/\\/\\\\/xmsg;
 9285:     $result =~ s/'/\\'/xmsg;
 9286:     $result =~ s{</}{<\\/}xmsg;
 9287:     
 9288:     return $result;
 9289: }
 9290: 
 9291: sub validate_page {
 9292:     if (  exists($env{'internal.start_page'})
 9293: 	  &&     $env{'internal.start_page'} > 1) {
 9294: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9295: 				 $env{'internal.start_page'}.' '.
 9296: 				 $ENV{'request.filename'});
 9297:     }
 9298:     if (  exists($env{'internal.end_page'})
 9299: 	  &&     $env{'internal.end_page'} > 1) {
 9300: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9301: 				 $env{'internal.end_page'}.' '.
 9302: 				 $env{'request.filename'});
 9303:     }
 9304:     if (     exists($env{'internal.start_page'})
 9305: 	&& ! exists($env{'internal.end_page'})) {
 9306: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9307: 				 $env{'request.filename'});
 9308:     }
 9309:     if (   ! exists($env{'internal.start_page'})
 9310: 	&&   exists($env{'internal.end_page'})) {
 9311: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9312: 				 $env{'request.filename'});
 9313:     }
 9314: }
 9315: 
 9316: 
 9317: sub start_scrollbox {
 9318:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9319:     unless ($outerwidth) { $outerwidth='520px'; }
 9320:     unless ($width) { $width='500px'; }
 9321:     unless ($height) { $height='200px'; }
 9322:     my ($table_id,$div_id,$tdcol);
 9323:     if ($id ne '') {
 9324:         $table_id = ' id="table_'.$id.'"';
 9325:         $div_id = ' id="div_'.$id.'"';
 9326:     }
 9327:     if ($bgcolor ne '') {
 9328:         $tdcol = "background-color: $bgcolor;";
 9329:     }
 9330:     my $nicescroll_js;
 9331:     if ($env{'browser.mobile'}) {
 9332:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9333:     }
 9334:     return <<"END";
 9335: $nicescroll_js
 9336: 
 9337: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9338: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9339: END
 9340: }
 9341: 
 9342: sub end_scrollbox {
 9343:     return '</div></td></tr></table>';
 9344: }
 9345: 
 9346: sub nicescroll_javascript {
 9347:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9348:     my %options;
 9349:     if (ref($cursor) eq 'HASH') {
 9350:         %options = %{$cursor};
 9351:     }
 9352:     unless ($options{'railalign'} =~ /^left|right$/) {
 9353:         $options{'railalign'} = 'left';
 9354:     }
 9355:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9356:         my $function  = &get_users_function();
 9357:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9358:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9359:             $options{'cursorcolor'} = '#00F';
 9360:         }
 9361:     }
 9362:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9363:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9364:             $options{'cursoropacity'}='1.0';
 9365:         }
 9366:     } else {
 9367:         $options{'cursoropacity'}='1.0';
 9368:     }
 9369:     if ($options{'cursorfixedheight'} eq 'none') {
 9370:         delete($options{'cursorfixedheight'});
 9371:     } else {
 9372:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9373:     }
 9374:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9375:         delete($options{'railoffset'});
 9376:     }
 9377:     my @niceoptions;
 9378:     while (my($key,$value) = each(%options)) {
 9379:         if ($value =~ /^\{.+\}$/) {
 9380:             push(@niceoptions,$key.':'.$value);
 9381:         } else {
 9382:             push(@niceoptions,$key.':"'.$value.'"');
 9383:         }
 9384:     }
 9385:     my $nicescroll_js = '
 9386: $(document).ready(
 9387:       function() {
 9388:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9389:       }
 9390: );
 9391: ';
 9392:     if ($framecheck) {
 9393:         $nicescroll_js .= '
 9394: function expand_div(caller) {
 9395:     if (top === self) {
 9396:         document.getElementById("'.$id.'").style.width = "auto";
 9397:         document.getElementById("'.$id.'").style.height = "auto";
 9398:     } else {
 9399:         try {
 9400:             if (parent.frames) {
 9401:                 if (parent.frames.length > 1) {
 9402:                     var framesrc = parent.frames[1].location.href;
 9403:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9404:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9405:                         document.getElementById("'.$id.'").style.width = "auto";
 9406:                         document.getElementById("'.$id.'").style.height = "auto";
 9407:                     }
 9408:                 }
 9409:             }
 9410:         } catch (e) {
 9411:             return;
 9412:         }
 9413:     }
 9414:     return;
 9415: }
 9416: ';
 9417:     }
 9418:     if ($needjsready) {
 9419:         $nicescroll_js = '
 9420: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9421:     } else {
 9422:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9423:     }
 9424:     return $nicescroll_js;
 9425: }
 9426: 
 9427: sub simple_error_page {
 9428:     my ($r,$title,$msg,$args) = @_;
 9429:     my %displayargs;
 9430:     if (ref($args) eq 'HASH') {
 9431:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9432:         if ($args->{'only_body'}) {
 9433:             $displayargs{'only_body'} = 1;
 9434:         }
 9435:         if ($args->{'no_nav_bar'}) {
 9436:             $displayargs{'no_nav_bar'} = 1;
 9437:         }
 9438:     } else {
 9439:         $msg = &mt($msg);
 9440:     }
 9441: 
 9442:     my $page =
 9443: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9444: 	'<p class="LC_error">'.$msg.'</p>'.
 9445: 	&Apache::loncommon::end_page();
 9446:     if (ref($r)) {
 9447: 	$r->print($page);
 9448: 	return;
 9449:     }
 9450:     return $page;
 9451: }
 9452: 
 9453: {
 9454:     my @row_count;
 9455: 
 9456:     sub start_data_table_count {
 9457:         unshift(@row_count, 0);
 9458:         return;
 9459:     }
 9460: 
 9461:     sub end_data_table_count {
 9462:         shift(@row_count);
 9463:         return;
 9464:     }
 9465: 
 9466:     sub start_data_table {
 9467: 	my ($add_class,$id) = @_;
 9468: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9469:         my $table_id;
 9470:         if (defined($id)) {
 9471:             $table_id = ' id="'.$id.'"';
 9472:         }
 9473: 	&start_data_table_count();
 9474: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9475:     }
 9476: 
 9477:     sub end_data_table {
 9478: 	&end_data_table_count();
 9479: 	return '</table>'."\n";;
 9480:     }
 9481: 
 9482:     sub start_data_table_row {
 9483: 	my ($add_class, $id) = @_;
 9484: 	$row_count[0]++;
 9485: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9486: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9487:         $id = (' id="'.$id.'"') unless ($id eq '');
 9488:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9489:     }
 9490:     
 9491:     sub continue_data_table_row {
 9492: 	my ($add_class, $id) = @_;
 9493: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9494: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9495:         $id = (' id="'.$id.'"') unless ($id eq '');
 9496:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9497:     }
 9498: 
 9499:     sub end_data_table_row {
 9500: 	return '</tr>'."\n";;
 9501:     }
 9502: 
 9503:     sub start_data_table_empty_row {
 9504: #	$row_count[0]++;
 9505: 	return  '<tr class="LC_empty_row" >'."\n";;
 9506:     }
 9507: 
 9508:     sub end_data_table_empty_row {
 9509: 	return '</tr>'."\n";;
 9510:     }
 9511: 
 9512:     sub start_data_table_header_row {
 9513: 	return  '<tr class="LC_header_row">'."\n";;
 9514:     }
 9515: 
 9516:     sub end_data_table_header_row {
 9517: 	return '</tr>'."\n";;
 9518:     }
 9519: 
 9520:     sub data_table_caption {
 9521:         my $caption = shift;
 9522:         return "<caption class=\"LC_caption\">$caption</caption>";
 9523:     }
 9524: }
 9525: 
 9526: =pod
 9527: 
 9528: =item * &inhibit_menu_check($arg)
 9529: 
 9530: Checks for a inhibitmenu state and generates output to preserve it
 9531: 
 9532: Inputs:         $arg - can be any of
 9533:                      - undef - in which case the return value is a string 
 9534:                                to add  into arguments list of a uri
 9535:                      - 'input' - in which case the return value is a HTML
 9536:                                  <form> <input> field of type hidden to
 9537:                                  preserve the value
 9538:                      - a url - in which case the return value is the url with
 9539:                                the neccesary cgi args added to preserve the
 9540:                                inhibitmenu state
 9541:                      - a ref to a url - no return value, but the string is
 9542:                                         updated to include the neccessary cgi
 9543:                                         args to preserve the inhibitmenu state
 9544: 
 9545: =cut
 9546: 
 9547: sub inhibit_menu_check {
 9548:     my ($arg) = @_;
 9549:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9550:     if ($arg eq 'input') {
 9551: 	if ($env{'form.inhibitmenu'}) {
 9552: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9553: 	} else {
 9554: 	    return
 9555: 	}
 9556:     }
 9557:     if ($env{'form.inhibitmenu'}) {
 9558: 	if (ref($arg)) {
 9559: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9560: 	} elsif ($arg eq '') {
 9561: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9562: 	} else {
 9563: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9564: 	}
 9565:     }
 9566:     if (!ref($arg)) {
 9567: 	return $arg;
 9568:     }
 9569: }
 9570: 
 9571: ###############################################
 9572: 
 9573: =pod
 9574: 
 9575: =back
 9576: 
 9577: =head1 User Information Routines
 9578: 
 9579: =over 4
 9580: 
 9581: =item * &get_users_function()
 9582: 
 9583: Used by &bodytag to determine the current users primary role.
 9584: Returns either 'student','coordinator','admin', or 'author'.
 9585: 
 9586: =cut
 9587: 
 9588: ###############################################
 9589: sub get_users_function {
 9590:     my $function = 'norole';
 9591:     if ($env{'request.role'}=~/^(st)/) {
 9592:         $function='student';
 9593:     }
 9594:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9595:         $function='coordinator';
 9596:     }
 9597:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9598:         $function='admin';
 9599:     }
 9600:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9601:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9602:         $function='author';
 9603:     }
 9604:     return $function;
 9605: }
 9606: 
 9607: ###############################################
 9608: 
 9609: =pod
 9610: 
 9611: =item * &show_course()
 9612: 
 9613: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9614: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9615: 
 9616: Inputs:
 9617: None
 9618: 
 9619: Outputs:
 9620: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9621: 
 9622: =cut
 9623: 
 9624: ###############################################
 9625: sub show_course {
 9626:     my $course = !$env{'user.adv'};
 9627:     if (!$env{'user.adv'}) {
 9628:         foreach my $env (keys(%env)) {
 9629:             next if ($env !~ m/^user\.priv\./);
 9630:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9631:                 $course = 0;
 9632:                 last;
 9633:             }
 9634:         }
 9635:     }
 9636:     return $course;
 9637: }
 9638: 
 9639: ###############################################
 9640: 
 9641: =pod
 9642: 
 9643: =item * &check_user_status()
 9644: 
 9645: Determines current status of supplied role for a
 9646: specific user. Roles can be active, previous or future.
 9647: 
 9648: Inputs: 
 9649: user's domain, user's username, course's domain,
 9650: course's number, optional section ID.
 9651: 
 9652: Outputs:
 9653: role status: active, previous or future. 
 9654: 
 9655: =cut
 9656: 
 9657: sub check_user_status {
 9658:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9659:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9660:     my @uroles = keys(%userinfo);
 9661:     my $srchstr;
 9662:     my $active_chk = 'none';
 9663:     my $now = time;
 9664:     if (@uroles > 0) {
 9665:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9666:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9667:         } else {
 9668:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9669:         }
 9670:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9671:             my $role_end = 0;
 9672:             my $role_start = 0;
 9673:             $active_chk = 'active';
 9674:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9675:                 $role_end = $1;
 9676:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9677:                     $role_start = $1;
 9678:                 }
 9679:             }
 9680:             if ($role_start > 0) {
 9681:                 if ($now < $role_start) {
 9682:                     $active_chk = 'future';
 9683:                 }
 9684:             }
 9685:             if ($role_end > 0) {
 9686:                 if ($now > $role_end) {
 9687:                     $active_chk = 'previous';
 9688:                 }
 9689:             }
 9690:         }
 9691:     }
 9692:     return $active_chk;
 9693: }
 9694: 
 9695: ###############################################
 9696: 
 9697: =pod
 9698: 
 9699: =item * &get_sections()
 9700: 
 9701: Determines all the sections for a course including
 9702: sections with students and sections containing other roles.
 9703: Incoming parameters: 
 9704: 
 9705: 1. domain
 9706: 2. course number 
 9707: 3. reference to array containing roles for which sections should 
 9708: be gathered (optional).
 9709: 4. reference to array containing status types for which sections 
 9710: should be gathered (optional).
 9711: 
 9712: If the third argument is undefined, sections are gathered for any role. 
 9713: If the fourth argument is undefined, sections are gathered for any status.
 9714: Permissible values are 'active' or 'future' or 'previous'.
 9715:  
 9716: Returns section hash (keys are section IDs, values are
 9717: number of users in each section), subject to the
 9718: optional roles filter, optional status filter 
 9719: 
 9720: =cut
 9721: 
 9722: ###############################################
 9723: sub get_sections {
 9724:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9725:     if (!defined($cdom) || !defined($cnum)) {
 9726:         my $cid =  $env{'request.course.id'};
 9727: 
 9728: 	return if (!defined($cid));
 9729: 
 9730:         $cdom = $env{'course.'.$cid.'.domain'};
 9731:         $cnum = $env{'course.'.$cid.'.num'};
 9732:     }
 9733: 
 9734:     my %sectioncount;
 9735:     my $now = time;
 9736: 
 9737:     my $check_students = 1;
 9738:     my $only_students = 0;
 9739:     if (ref($possible_roles) eq 'ARRAY') {
 9740:         if (grep(/^st$/,@{$possible_roles})) {
 9741:             if (@{$possible_roles} == 1) {
 9742:                 $only_students = 1;
 9743:             }
 9744:         } else {
 9745:             $check_students = 0;
 9746:         }
 9747:     }
 9748: 
 9749:     if ($check_students) { 
 9750: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9751: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9752: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9753:         my $start_index = &Apache::loncoursedata::CL_START();
 9754:         my $end_index = &Apache::loncoursedata::CL_END();
 9755:         my $status;
 9756: 	while (my ($student,$data) = each(%$classlist)) {
 9757: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9758: 				                     $data->[$status_index],
 9759:                                                      $data->[$start_index],
 9760:                                                      $data->[$end_index]);
 9761:             if ($stu_status eq 'Active') {
 9762:                 $status = 'active';
 9763:             } elsif ($end < $now) {
 9764:                 $status = 'previous';
 9765:             } elsif ($start > $now) {
 9766:                 $status = 'future';
 9767:             } 
 9768: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9769:                 if ((!defined($possible_status)) || (($status ne '') && 
 9770:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9771: 		    $sectioncount{$section}++;
 9772:                 }
 9773: 	    }
 9774: 	}
 9775:     }
 9776:     if ($only_students) {
 9777:         return %sectioncount;
 9778:     }
 9779:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9780:     foreach my $user (sort(keys(%courseroles))) {
 9781: 	if ($user !~ /^(\w{2})/) { next; }
 9782: 	my ($role) = ($user =~ /^(\w{2})/);
 9783: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9784: 	my ($section,$status);
 9785: 	if ($role eq 'cr' &&
 9786: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9787: 	    $section=$1;
 9788: 	}
 9789: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9790: 	if (!defined($section) || $section eq '-1') { next; }
 9791:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9792:         if ($end == -1 && $start == -1) {
 9793:             next; #deleted role
 9794:         }
 9795:         if (!defined($possible_status)) { 
 9796:             $sectioncount{$section}++;
 9797:         } else {
 9798:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9799:                 $status = 'active';
 9800:             } elsif ($end < $now) {
 9801:                 $status = 'future';
 9802:             } elsif ($start > $now) {
 9803:                 $status = 'previous';
 9804:             }
 9805:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9806:                 $sectioncount{$section}++;
 9807:             }
 9808:         }
 9809:     }
 9810:     return %sectioncount;
 9811: }
 9812: 
 9813: ###############################################
 9814: 
 9815: =pod
 9816: 
 9817: =item * &get_course_users()
 9818: 
 9819: Retrieves usernames:domains for users in the specified course
 9820: with specific role(s), and access status. 
 9821: 
 9822: Incoming parameters:
 9823: 1. course domain
 9824: 2. course number
 9825: 3. access status: users must have - either active, 
 9826: previous, future, or all.
 9827: 4. reference to array of permissible roles
 9828: 5. reference to array of section restrictions (optional)
 9829: 6. reference to results object (hash of hashes).
 9830: 7. reference to optional userdata hash
 9831: 8. reference to optional statushash
 9832: 9. flag if privileged users (except those set to unhide in
 9833:    course settings) should be excluded    
 9834: Keys of top level results hash are roles.
 9835: Keys of inner hashes are username:domain, with 
 9836: values set to access type.
 9837: Optional userdata hash returns an array with arguments in the 
 9838: same order as loncoursedata::get_classlist() for student data.
 9839: 
 9840: Optional statushash returns
 9841: 
 9842: Entries for end, start, section and status are blank because
 9843: of the possibility of multiple values for non-student roles.
 9844: 
 9845: =cut
 9846: 
 9847: ###############################################
 9848: 
 9849: sub get_course_users {
 9850:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9851:     my %idx = ();
 9852:     my %seclists;
 9853: 
 9854:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9855:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9856:     $idx{end} = &Apache::loncoursedata::CL_END();
 9857:     $idx{start} = &Apache::loncoursedata::CL_START();
 9858:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9859:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9860:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9861:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9862: 
 9863:     if (grep(/^st$/,@{$roles})) {
 9864:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9865:         my $now = time;
 9866:         foreach my $student (keys(%{$classlist})) {
 9867:             my $match = 0;
 9868:             my $secmatch = 0;
 9869:             my $section = $$classlist{$student}[$idx{section}];
 9870:             my $status = $$classlist{$student}[$idx{status}];
 9871:             if ($section eq '') {
 9872:                 $section = 'none';
 9873:             }
 9874:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9875:                 if (grep(/^all$/,@{$sections})) {
 9876:                     $secmatch = 1;
 9877:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9878:                     if (grep(/^none$/,@{$sections})) {
 9879:                         $secmatch = 1;
 9880:                     }
 9881:                 } else {  
 9882: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9883: 		        $secmatch = 1;
 9884:                     }
 9885: 		}
 9886:                 if (!$secmatch) {
 9887:                     next;
 9888:                 }
 9889:             }
 9890:             if (defined($$types{'active'})) {
 9891:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9892:                     push(@{$$users{st}{$student}},'active');
 9893:                     $match = 1;
 9894:                 }
 9895:             }
 9896:             if (defined($$types{'previous'})) {
 9897:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9898:                     push(@{$$users{st}{$student}},'previous');
 9899:                     $match = 1;
 9900:                 }
 9901:             }
 9902:             if (defined($$types{'future'})) {
 9903:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9904:                     push(@{$$users{st}{$student}},'future');
 9905:                     $match = 1;
 9906:                 }
 9907:             }
 9908:             if ($match) {
 9909:                 push(@{$seclists{$student}},$section);
 9910:                 if (ref($userdata) eq 'HASH') {
 9911:                     $$userdata{$student} = $$classlist{$student};
 9912:                 }
 9913:                 if (ref($statushash) eq 'HASH') {
 9914:                     $statushash->{$student}{'st'}{$section} = $status;
 9915:                 }
 9916:             }
 9917:         }
 9918:     }
 9919:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9920:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9921:         my $now = time;
 9922:         my %displaystatus = ( previous => 'Expired',
 9923:                               active   => 'Active',
 9924:                               future   => 'Future',
 9925:                             );
 9926:         my (%nothide,@possdoms);
 9927:         if ($hidepriv) {
 9928:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9929:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9930:                 if ($user !~ /:/) {
 9931:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9932:                 } else {
 9933:                     $nothide{$user} = 1;
 9934:                 }
 9935:             }
 9936:             my @possdoms = ($cdom);
 9937:             if ($coursehash{'checkforpriv'}) {
 9938:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9939:             }
 9940:         }
 9941:         foreach my $person (sort(keys(%coursepersonnel))) {
 9942:             my $match = 0;
 9943:             my $secmatch = 0;
 9944:             my $status;
 9945:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9946:             $user =~ s/:$//;
 9947:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9948:             if ($end == -1 || $start == -1) {
 9949:                 next;
 9950:             }
 9951:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9952:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9953:                 my ($uname,$udom) = split(/:/,$user);
 9954:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9955:                     if (grep(/^all$/,@{$sections})) {
 9956:                         $secmatch = 1;
 9957:                     } elsif ($usec eq '') {
 9958:                         if (grep(/^none$/,@{$sections})) {
 9959:                             $secmatch = 1;
 9960:                         }
 9961:                     } else {
 9962:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9963:                             $secmatch = 1;
 9964:                         }
 9965:                     }
 9966:                     if (!$secmatch) {
 9967:                         next;
 9968:                     }
 9969:                 }
 9970:                 if ($usec eq '') {
 9971:                     $usec = 'none';
 9972:                 }
 9973:                 if ($uname ne '' && $udom ne '') {
 9974:                     if ($hidepriv) {
 9975:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9976:                             (!$nothide{$uname.':'.$udom})) {
 9977:                             next;
 9978:                         }
 9979:                     }
 9980:                     if ($end > 0 && $end < $now) {
 9981:                         $status = 'previous';
 9982:                     } elsif ($start > $now) {
 9983:                         $status = 'future';
 9984:                     } else {
 9985:                         $status = 'active';
 9986:                     }
 9987:                     foreach my $type (keys(%{$types})) { 
 9988:                         if ($status eq $type) {
 9989:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9990:                                 push(@{$$users{$role}{$user}},$type);
 9991:                             }
 9992:                             $match = 1;
 9993:                         }
 9994:                     }
 9995:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9996:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9997: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9998:                         }
 9999:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10000:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10001:                         }
10002:                         if (ref($statushash) eq 'HASH') {
10003:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10004:                         }
10005:                     }
10006:                 }
10007:             }
10008:         }
10009:         if (grep(/^ow$/,@{$roles})) {
10010:             if ((defined($cdom)) && (defined($cnum))) {
10011:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10012:                 if ( defined($csettings{'internal.courseowner'}) ) {
10013:                     my $owner = $csettings{'internal.courseowner'};
10014:                     next if ($owner eq '');
10015:                     my ($ownername,$ownerdom);
10016:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10017:                         $ownername = $1;
10018:                         $ownerdom = $2;
10019:                     } else {
10020:                         $ownername = $owner;
10021:                         $ownerdom = $cdom;
10022:                         $owner = $ownername.':'.$ownerdom;
10023:                     }
10024:                     @{$$users{'ow'}{$owner}} = 'any';
10025:                     if (defined($userdata) && 
10026: 			!exists($$userdata{$owner})) {
10027: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10028:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10029:                             push(@{$seclists{$owner}},'none');
10030:                         }
10031:                         if (ref($statushash) eq 'HASH') {
10032:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10033:                         }
10034: 		    }
10035:                 }
10036:             }
10037:         }
10038:         foreach my $user (keys(%seclists)) {
10039:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10040:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10041:         }
10042:     }
10043:     return;
10044: }
10045: 
10046: sub get_user_info {
10047:     my ($udom,$uname,$idx,$userdata) = @_;
10048:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10049: 	&plainname($uname,$udom,'lastname');
10050:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10051:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10052:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10053:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10054:     return;
10055: }
10056: 
10057: ###############################################
10058: 
10059: =pod
10060: 
10061: =item * &get_user_quota()
10062: 
10063: Retrieves quota assigned for storage of user files.
10064: Default is to report quota for portfolio files.
10065: 
10066: Incoming parameters:
10067: 1. user's username
10068: 2. user's domain
10069: 3. quota name - portfolio, author, or course
10070:    (if no quota name provided, defaults to portfolio).
10071: 4. crstype - official, unofficial, textbook, placement or community, 
10072:    if quota name is course
10073: 
10074: Returns:
10075: 1. Disk quota (in MB) assigned to student.
10076: 2. (Optional) Type of setting: custom or default
10077:    (individually assigned or default for user's 
10078:    institutional status).
10079: 3. (Optional) - User's institutional status (e.g., faculty, staff
10080:    or student - types as defined in localenroll::inst_usertypes 
10081:    for user's domain, which determines default quota for user.
10082: 4. (Optional) - Default quota which would apply to the user.
10083: 
10084: If a value has been stored in the user's environment, 
10085: it will return that, otherwise it returns the maximal default
10086: defined for the user's institutional status(es) in the domain.
10087: 
10088: =cut
10089: 
10090: ###############################################
10091: 
10092: 
10093: sub get_user_quota {
10094:     my ($uname,$udom,$quotaname,$crstype) = @_;
10095:     my ($quota,$quotatype,$settingstatus,$defquota);
10096:     if (!defined($udom)) {
10097:         $udom = $env{'user.domain'};
10098:     }
10099:     if (!defined($uname)) {
10100:         $uname = $env{'user.name'};
10101:     }
10102:     if (($udom eq '' || $uname eq '') ||
10103:         ($udom eq 'public') && ($uname eq 'public')) {
10104:         $quota = 0;
10105:         $quotatype = 'default';
10106:         $defquota = 0; 
10107:     } else {
10108:         my $inststatus;
10109:         if ($quotaname eq 'course') {
10110:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10111:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10112:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10113:             } else {
10114:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10115:                 $quota = $cenv{'internal.uploadquota'};
10116:             }
10117:         } else {
10118:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10119:                 if ($quotaname eq 'author') {
10120:                     $quota = $env{'environment.authorquota'};
10121:                 } else {
10122:                     $quota = $env{'environment.portfolioquota'};
10123:                 }
10124:                 $inststatus = $env{'environment.inststatus'};
10125:             } else {
10126:                 my %userenv = 
10127:                     &Apache::lonnet::get('environment',['portfolioquota',
10128:                                          'authorquota','inststatus'],$udom,$uname);
10129:                 my ($tmp) = keys(%userenv);
10130:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10131:                     if ($quotaname eq 'author') {
10132:                         $quota = $userenv{'authorquota'};
10133:                     } else {
10134:                         $quota = $userenv{'portfolioquota'};
10135:                     }
10136:                     $inststatus = $userenv{'inststatus'};
10137:                 } else {
10138:                     undef(%userenv);
10139:                 }
10140:             }
10141:         }
10142:         if ($quota eq '' || wantarray) {
10143:             if ($quotaname eq 'course') {
10144:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10145:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10146:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10147:                     ($crstype eq 'placement')) { 
10148:                     $defquota = $domdefs{$crstype.'quota'};
10149:                 }
10150:                 if ($defquota eq '') {
10151:                     $defquota = 500;
10152:                 }
10153:             } else {
10154:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10155:             }
10156:             if ($quota eq '') {
10157:                 $quota = $defquota;
10158:                 $quotatype = 'default';
10159:             } else {
10160:                 $quotatype = 'custom';
10161:             }
10162:         }
10163:     }
10164:     if (wantarray) {
10165:         return ($quota,$quotatype,$settingstatus,$defquota);
10166:     } else {
10167:         return $quota;
10168:     }
10169: }
10170: 
10171: ###############################################
10172: 
10173: =pod
10174: 
10175: =item * &default_quota()
10176: 
10177: Retrieves default quota assigned for storage of user portfolio files,
10178: given an (optional) user's institutional status.
10179: 
10180: Incoming parameters:
10181: 
10182: 1. domain
10183: 2. (Optional) institutional status(es).  This is a : separated list of 
10184:    status types (e.g., faculty, staff, student etc.)
10185:    which apply to the user for whom the default is being retrieved.
10186:    If the institutional status string in undefined, the domain
10187:    default quota will be returned.
10188: 3.  quota name - portfolio, author, or course
10189:    (if no quota name provided, defaults to portfolio).
10190: 
10191: Returns:
10192: 
10193: 1. Default disk quota (in MB) for user portfolios in the domain.
10194: 2. (Optional) institutional type which determined the value of the
10195:    default quota.
10196: 
10197: If a value has been stored in the domain's configuration db,
10198: it will return that, otherwise it returns 20 (for backwards 
10199: compatibility with domains which have not set up a configuration
10200: db file; the original statically defined portfolio quota was 20 MB). 
10201: 
10202: If the user's status includes multiple types (e.g., staff and student),
10203: the largest default quota which applies to the user determines the
10204: default quota returned.
10205: 
10206: =cut
10207: 
10208: ###############################################
10209: 
10210: 
10211: sub default_quota {
10212:     my ($udom,$inststatus,$quotaname) = @_;
10213:     my ($defquota,$settingstatus);
10214:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10215:                                             ['quotas'],$udom);
10216:     my $key = 'defaultquota';
10217:     if ($quotaname eq 'author') {
10218:         $key = 'authorquota';
10219:     }
10220:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10221:         if ($inststatus ne '') {
10222:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10223:             foreach my $item (@statuses) {
10224:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10225:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10226:                         if ($defquota eq '') {
10227:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10228:                             $settingstatus = $item;
10229:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10230:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10231:                             $settingstatus = $item;
10232:                         }
10233:                     }
10234:                 } elsif ($key eq 'defaultquota') {
10235:                     if ($quotahash{'quotas'}{$item} ne '') {
10236:                         if ($defquota eq '') {
10237:                             $defquota = $quotahash{'quotas'}{$item};
10238:                             $settingstatus = $item;
10239:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10240:                             $defquota = $quotahash{'quotas'}{$item};
10241:                             $settingstatus = $item;
10242:                         }
10243:                     }
10244:                 }
10245:             }
10246:         }
10247:         if ($defquota eq '') {
10248:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10249:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10250:             } elsif ($key eq 'defaultquota') {
10251:                 $defquota = $quotahash{'quotas'}{'default'};
10252:             }
10253:             $settingstatus = 'default';
10254:             if ($defquota eq '') {
10255:                 if ($quotaname eq 'author') {
10256:                     $defquota = 500;
10257:                 }
10258:             }
10259:         }
10260:     } else {
10261:         $settingstatus = 'default';
10262:         if ($quotaname eq 'author') {
10263:             $defquota = 500;
10264:         } else {
10265:             $defquota = 20;
10266:         }
10267:     }
10268:     if (wantarray) {
10269:         return ($defquota,$settingstatus);
10270:     } else {
10271:         return $defquota;
10272:     }
10273: }
10274: 
10275: ###############################################
10276: 
10277: =pod
10278: 
10279: =item * &excess_filesize_warning()
10280: 
10281: Returns warning message if upload of file to authoring space, or copying
10282: of existing file within authoring space will cause quota for the authoring
10283: space to be exceeded.
10284: 
10285: Same, if upload of a file directly to a course/community via Course Editor
10286: will cause quota for uploaded content for the course to be exceeded.
10287: 
10288: Inputs: 7 
10289: 1. username or coursenum
10290: 2. domain
10291: 3. context ('author' or 'course')
10292: 4. filename of file for which action is being requested
10293: 5. filesize (kB) of file
10294: 6. action being taken: copy or upload.
10295: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10296: 
10297: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10298:          otherwise return null.
10299: 
10300: =back
10301: 
10302: =cut
10303: 
10304: sub excess_filesize_warning {
10305:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10306:     my $current_disk_usage = 0;
10307:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10308:     if ($context eq 'author') {
10309:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10310:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10311:     } else {
10312:         foreach my $subdir ('docs','supplemental') {
10313:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10314:         }
10315:     }
10316:     $disk_quota = int($disk_quota * 1000);
10317:     if (($current_disk_usage + $filesize) > $disk_quota) {
10318:         return '<p class="LC_warning">'.
10319:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10320:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10321:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10322:                             $disk_quota,$current_disk_usage).
10323:                '</p>';
10324:     }
10325:     return;
10326: }
10327: 
10328: ###############################################
10329: 
10330: 
10331: 
10332: 
10333: sub get_secgrprole_info {
10334:     my ($cdom,$cnum,$needroles,$type)  = @_;
10335:     my %sections_count = &get_sections($cdom,$cnum);
10336:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10337:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10338:     my @groups = sort(keys(%curr_groups));
10339:     my $allroles = [];
10340:     my $rolehash;
10341:     my $accesshash = {
10342:                      active => 'Currently has access',
10343:                      future => 'Will have future access',
10344:                      previous => 'Previously had access',
10345:                   };
10346:     if ($needroles) {
10347:         $rolehash = {'all' => 'all'};
10348:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10349: 	if (&Apache::lonnet::error(%user_roles)) {
10350: 	    undef(%user_roles);
10351: 	}
10352:         foreach my $item (keys(%user_roles)) {
10353:             my ($role)=split(/\:/,$item,2);
10354:             if ($role eq 'cr') { next; }
10355:             if ($role =~ /^cr/) {
10356:                 $$rolehash{$role} = (split('/',$role))[3];
10357:             } else {
10358:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10359:             }
10360:         }
10361:         foreach my $key (sort(keys(%{$rolehash}))) {
10362:             push(@{$allroles},$key);
10363:         }
10364:         push (@{$allroles},'st');
10365:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10366:     }
10367:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10368: }
10369: 
10370: sub user_picker {
10371:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10372:     my $currdom = $dom;
10373:     my @alldoms = &Apache::lonnet::all_domains();
10374:     if (@alldoms == 1) {
10375:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10376:                                                ['directorysrch'],$alldoms[0]);
10377:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10378:         my $showdom = $domdesc;
10379:         if ($showdom eq '') {
10380:             $showdom = $dom;
10381:         }
10382:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10383:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10384:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10385:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10386:             }
10387:         }
10388:     }
10389:     my %curr_selected = (
10390:                         srchin => 'dom',
10391:                         srchby => 'lastname',
10392:                       );
10393:     my $srchterm;
10394:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10395:         if ($srch->{'srchby'} ne '') {
10396:             $curr_selected{'srchby'} = $srch->{'srchby'};
10397:         }
10398:         if ($srch->{'srchin'} ne '') {
10399:             $curr_selected{'srchin'} = $srch->{'srchin'};
10400:         }
10401:         if ($srch->{'srchtype'} ne '') {
10402:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10403:         }
10404:         if ($srch->{'srchdomain'} ne '') {
10405:             $currdom = $srch->{'srchdomain'};
10406:         }
10407:         $srchterm = $srch->{'srchterm'};
10408:     }
10409:     my %html_lt=&Apache::lonlocal::texthash(
10410:                     'usr'       => 'Search criteria',
10411:                     'doma'      => 'Domain/institution to search',
10412:                     'uname'     => 'username',
10413:                     'lastname'  => 'last name',
10414:                     'lastfirst' => 'last name, first name',
10415:                     'crs'       => 'in this course',
10416:                     'dom'       => 'in selected LON-CAPA domain', 
10417:                     'alc'       => 'all LON-CAPA',
10418:                     'instd'     => 'in institutional directory for selected domain',
10419:                     'exact'     => 'is',
10420:                     'contains'  => 'contains',
10421:                     'begins'    => 'begins with',
10422:                                        );
10423:     my %js_lt=&Apache::lonlocal::texthash(
10424:                     'youm'      => "You must include some text to search for.",
10425:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10426:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10427:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10428:                     'ymcd'      => "You must choose a domain when using a domain search.",
10429:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10430:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10431:                      'thfo'     => "The following need to be corrected before the search can be run:",
10432:                                        );
10433:     &html_escape(\%html_lt);
10434:     &js_escape(\%js_lt);
10435:     my $domform;
10436:     my $allow_blank = 1;
10437:     if ($fixeddom) {
10438:         $allow_blank = 0;
10439:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10440:     } else {
10441:         my $defdom = $env{'request.role.domain'};
10442:         my ($trusted,$untrusted);
10443:         if (($context eq 'requestcrs') || ($context eq 'course')) {
10444:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10445:         } elsif ($context eq 'author') {
10446:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10447:         } elsif ($context eq 'domain') {
10448:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10449:         }
10450:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10451:     }
10452:     my $srchinsel = ' <select name="srchin">';
10453: 
10454:     my @srchins = ('crs','dom','alc','instd');
10455: 
10456:     foreach my $option (@srchins) {
10457:         # FIXME 'alc' option unavailable until 
10458:         #       loncreateuser::print_user_query_page()
10459:         #       has been completed.
10460:         next if ($option eq 'alc');
10461:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10462:         next if ($option eq 'crs' && !$env{'request.course.id'});
10463:         next if (($option eq 'instd') && ($noinstd));
10464:         if ($curr_selected{'srchin'} eq $option) {
10465:             $srchinsel .= ' 
10466:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10467:         } else {
10468:             $srchinsel .= '
10469:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10470:         }
10471:     }
10472:     $srchinsel .= "\n  </select>\n";
10473: 
10474:     my $srchbysel =  ' <select name="srchby">';
10475:     foreach my $option ('lastname','lastfirst','uname') {
10476:         if ($curr_selected{'srchby'} eq $option) {
10477:             $srchbysel .= '
10478:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10479:         } else {
10480:             $srchbysel .= '
10481:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10482:          }
10483:     }
10484:     $srchbysel .= "\n  </select>\n";
10485: 
10486:     my $srchtypesel = ' <select name="srchtype">';
10487:     foreach my $option ('begins','contains','exact') {
10488:         if ($curr_selected{'srchtype'} eq $option) {
10489:             $srchtypesel .= '
10490:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10491:         } else {
10492:             $srchtypesel .= '
10493:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10494:         }
10495:     }
10496:     $srchtypesel .= "\n  </select>\n";
10497: 
10498:     my ($newuserscript,$new_user_create);
10499:     my $context_dom = $env{'request.role.domain'};
10500:     if ($context eq 'requestcrs') {
10501:         if ($env{'form.coursedom'} ne '') { 
10502:             $context_dom = $env{'form.coursedom'};
10503:         }
10504:     }
10505:     if ($forcenewuser) {
10506:         if (ref($srch) eq 'HASH') {
10507:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10508:                 if ($cancreate) {
10509:                     $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>';
10510:                 } else {
10511:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10512:                     my %usertypetext = (
10513:                         official   => 'institutional',
10514:                         unofficial => 'non-institutional',
10515:                     );
10516:                     $new_user_create = '<p class="LC_warning">'
10517:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10518:                                       .' '
10519:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10520:                                           ,'<a href="'.$helplink.'">','</a>')
10521:                                       .'</p><br />';
10522:                 }
10523:             }
10524:         }
10525: 
10526:         $newuserscript = <<"ENDSCRIPT";
10527: 
10528: function setSearch(createnew,callingForm) {
10529:     if (createnew == 1) {
10530:         for (var i=0; i<callingForm.srchby.length; i++) {
10531:             if (callingForm.srchby.options[i].value == 'uname') {
10532:                 callingForm.srchby.selectedIndex = i;
10533:             }
10534:         }
10535:         for (var i=0; i<callingForm.srchin.length; i++) {
10536:             if ( callingForm.srchin.options[i].value == 'dom') {
10537: 		callingForm.srchin.selectedIndex = i;
10538:             }
10539:         }
10540:         for (var i=0; i<callingForm.srchtype.length; i++) {
10541:             if (callingForm.srchtype.options[i].value == 'exact') {
10542:                 callingForm.srchtype.selectedIndex = i;
10543:             }
10544:         }
10545:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10546:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10547:                 callingForm.srchdomain.selectedIndex = i;
10548:             }
10549:         }
10550:     }
10551: }
10552: ENDSCRIPT
10553: 
10554:     }
10555: 
10556:     my $output = <<"END_BLOCK";
10557: <script type="text/javascript">
10558: // <![CDATA[
10559: function validateEntry(callingForm) {
10560: 
10561:     var checkok = 1;
10562:     var srchin;
10563:     for (var i=0; i<callingForm.srchin.length; i++) {
10564: 	if ( callingForm.srchin[i].checked ) {
10565: 	    srchin = callingForm.srchin[i].value;
10566: 	}
10567:     }
10568: 
10569:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10570:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10571:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10572:     var srchterm =  callingForm.srchterm.value;
10573:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10574:     var msg = "";
10575: 
10576:     if (srchterm == "") {
10577:         checkok = 0;
10578:         msg += "$js_lt{'youm'}\\n";
10579:     }
10580: 
10581:     if (srchtype== 'begins') {
10582:         if (srchterm.length < 2) {
10583:             checkok = 0;
10584:             msg += "$js_lt{'thte'}\\n";
10585:         }
10586:     }
10587: 
10588:     if (srchtype== 'contains') {
10589:         if (srchterm.length < 3) {
10590:             checkok = 0;
10591:             msg += "$js_lt{'thet'}\\n";
10592:         }
10593:     }
10594:     if (srchin == 'instd') {
10595:         if (srchdomain == '') {
10596:             checkok = 0;
10597:             msg += "$js_lt{'yomc'}\\n";
10598:         }
10599:     }
10600:     if (srchin == 'dom') {
10601:         if (srchdomain == '') {
10602:             checkok = 0;
10603:             msg += "$js_lt{'ymcd'}\\n";
10604:         }
10605:     }
10606:     if (srchby == 'lastfirst') {
10607:         if (srchterm.indexOf(",") == -1) {
10608:             checkok = 0;
10609:             msg += "$js_lt{'whus'}\\n";
10610:         }
10611:         if (srchterm.indexOf(",") == srchterm.length -1) {
10612:             checkok = 0;
10613:             msg += "$js_lt{'whse'}\\n";
10614:         }
10615:     }
10616:     if (checkok == 0) {
10617:         alert("$js_lt{'thfo'}\\n"+msg);
10618:         return;
10619:     }
10620:     if (checkok == 1) {
10621:         callingForm.submit();
10622:     }
10623: }
10624: 
10625: $newuserscript
10626: 
10627: // ]]>
10628: </script>
10629: 
10630: $new_user_create
10631: 
10632: END_BLOCK
10633: 
10634:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10635:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10636:                $domform.
10637:                &Apache::lonhtmlcommon::row_closure().
10638:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10639:                $srchbysel.
10640:                $srchtypesel. 
10641:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10642:                $srchinsel.
10643:                &Apache::lonhtmlcommon::row_closure(1). 
10644:                &Apache::lonhtmlcommon::end_pick_box().
10645:                '<br />';
10646:     return ($output,1);
10647: }
10648: 
10649: sub user_rule_check {
10650:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10651:     my ($response,%inst_response);
10652:     if (ref($usershash) eq 'HASH') {
10653:         if (keys(%{$usershash}) > 1) {
10654:             my (%by_username,%by_id,%userdoms);
10655:             my $checkid; 
10656:             if (ref($checks) eq 'HASH') {
10657:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10658:                     $checkid = 1;
10659:                 }
10660:             }
10661:             foreach my $user (keys(%{$usershash})) {
10662:                 my ($uname,$udom) = split(/:/,$user);
10663:                 if ($checkid) {
10664:                     if (ref($usershash->{$user}) eq 'HASH') {
10665:                         if ($usershash->{$user}->{'id'} ne '') {
10666:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10667:                             $userdoms{$udom} = 1;
10668:                             if (ref($inst_results) eq 'HASH') {
10669:                                 $inst_results->{$uname.':'.$udom} = {};
10670:                             }
10671:                         }
10672:                     }
10673:                 } else {
10674:                     $by_username{$udom}{$uname} = 1;
10675:                     $userdoms{$udom} = 1;
10676:                     if (ref($inst_results) eq 'HASH') {
10677:                         $inst_results->{$uname.':'.$udom} = {};
10678:                     }
10679:                 }
10680:             }
10681:             foreach my $udom (keys(%userdoms)) {
10682:                 if (!$got_rules->{$udom}) {
10683:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10684:                                                              ['usercreation'],$udom);
10685:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10686:                         foreach my $item ('username','id') {
10687:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10688:                                 $$curr_rules{$udom}{$item} =
10689:                                     $domconfig{'usercreation'}{$item.'_rule'};
10690:                             }
10691:                         }
10692:                     }
10693:                     $got_rules->{$udom} = 1;
10694:                 }
10695:             }
10696:             if ($checkid) {
10697:                 foreach my $udom (keys(%by_id)) {
10698:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10699:                     if ($outcome eq 'ok') {
10700:                         foreach my $id (keys(%{$by_id{$udom}})) {
10701:                             my $uname = $by_id{$udom}{$id};
10702:                             $inst_response{$uname.':'.$udom} = $outcome;
10703:                         }
10704:                         if (ref($results) eq 'HASH') {
10705:                             foreach my $uname (keys(%{$results})) {
10706:                                 if (exists($inst_response{$uname.':'.$udom})) {
10707:                                     $inst_response{$uname.':'.$udom} = $outcome;
10708:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10709:                                 }
10710:                             }
10711:                         }
10712:                     }
10713:                 }
10714:             } else {
10715:                 foreach my $udom (keys(%by_username)) {
10716:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10717:                     if ($outcome eq 'ok') {
10718:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10719:                             $inst_response{$uname.':'.$udom} = $outcome;
10720:                         }
10721:                         if (ref($results) eq 'HASH') {
10722:                             foreach my $uname (keys(%{$results})) {
10723:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10724:                             }
10725:                         }
10726:                     }
10727:                 }
10728:             }
10729:         } elsif (keys(%{$usershash}) == 1) {
10730:             my $user = (keys(%{$usershash}))[0];
10731:             my ($uname,$udom) = split(/:/,$user);
10732:             if (($udom ne '') && ($uname ne '')) {
10733:                 if (ref($usershash->{$user}) eq 'HASH') {
10734:                     if (ref($checks) eq 'HASH') {
10735:                         if (defined($checks->{'username'})) {
10736:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10737:                                 &Apache::lonnet::get_instuser($udom,$uname);
10738:                         } elsif (defined($checks->{'id'})) {
10739:                             if ($usershash->{$user}->{'id'} ne '') {
10740:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10741:                                     &Apache::lonnet::get_instuser($udom,undef,
10742:                                                                   $usershash->{$user}->{'id'});
10743:                             } else {
10744:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10745:                                     &Apache::lonnet::get_instuser($udom,$uname);
10746:                             }
10747:                         }
10748:                     } else {
10749:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10750:                             &Apache::lonnet::get_instuser($udom,$uname);
10751:                        return;
10752:                     }
10753:                     if (!$got_rules->{$udom}) {
10754:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10755:                                                                  ['usercreation'],$udom);
10756:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10757:                             foreach my $item ('username','id') {
10758:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10759:                                    $$curr_rules{$udom}{$item} = 
10760:                                        $domconfig{'usercreation'}{$item.'_rule'};
10761:                                 }
10762:                             }
10763:                         }
10764:                         $got_rules->{$udom} = 1;
10765:                     }
10766:                 }
10767:             } else {
10768:                 return;
10769:             }
10770:         } else {
10771:             return;
10772:         }
10773:         foreach my $user (keys(%{$usershash})) {
10774:             my ($uname,$udom) = split(/:/,$user);
10775:             next if (($udom eq '') || ($uname eq ''));
10776:             my $id;
10777:             if (ref($inst_results) eq 'HASH') {
10778:                 if (ref($inst_results->{$user}) eq 'HASH') {
10779:                     $id = $inst_results->{$user}->{'id'};
10780:                 }
10781:             }
10782:             if ($id eq '') { 
10783:                 if (ref($usershash->{$user})) {
10784:                     $id = $usershash->{$user}->{'id'};
10785:                 }
10786:             }
10787:             foreach my $item (keys(%{$checks})) {
10788:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10789:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10790:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10791:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10792:                                                                              $$curr_rules{$udom}{$item});
10793:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10794:                                 if ($rule_check{$rule}) {
10795:                                     $$rulematch{$user}{$item} = $rule;
10796:                                     if ($inst_response{$user} eq 'ok') {
10797:                                         if (ref($inst_results) eq 'HASH') {
10798:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10799:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10800:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10801:                                                 } elsif ($item eq 'id') {
10802:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10803:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10804:                                                     }
10805:                                                 }
10806:                                             }
10807:                                         }
10808:                                     }
10809:                                     last;
10810:                                 }
10811:                             }
10812:                         }
10813:                     }
10814:                 }
10815:             }
10816:         }
10817:     }
10818:     return;
10819: }
10820: 
10821: sub user_rule_formats {
10822:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10823:     my %text = ( 
10824:                  'username' => 'Usernames',
10825:                  'id'       => 'IDs',
10826:                );
10827:     my $output;
10828:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10829:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10830:         if (@{$ruleorder} > 0) {
10831:             $output = '<br />'.
10832:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10833:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10834:                       ' <ul>';
10835:             foreach my $rule (@{$ruleorder}) {
10836:                 if (ref($curr_rules) eq 'ARRAY') {
10837:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10838:                         if (ref($rules->{$rule}) eq 'HASH') {
10839:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10840:                                         $rules->{$rule}{'desc'}.'</li>';
10841:                         }
10842:                     }
10843:                 }
10844:             }
10845:             $output .= '</ul>';
10846:         }
10847:     }
10848:     return $output;
10849: }
10850: 
10851: sub instrule_disallow_msg {
10852:     my ($checkitem,$domdesc,$count,$mode) = @_;
10853:     my $response;
10854:     my %text = (
10855:                   item   => 'username',
10856:                   items  => 'usernames',
10857:                   match  => 'matches',
10858:                   do     => 'does',
10859:                   action => 'a username',
10860:                   one    => 'one',
10861:                );
10862:     if ($count > 1) {
10863:         $text{'item'} = 'usernames';
10864:         $text{'match'} ='match';
10865:         $text{'do'} = 'do';
10866:         $text{'action'} = 'usernames',
10867:         $text{'one'} = 'ones';
10868:     }
10869:     if ($checkitem eq 'id') {
10870:         $text{'items'} = 'IDs';
10871:         $text{'item'} = 'ID';
10872:         $text{'action'} = 'an ID';
10873:         if ($count > 1) {
10874:             $text{'item'} = 'IDs';
10875:             $text{'action'} = 'IDs';
10876:         }
10877:     }
10878:     $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 />';
10879:     if ($mode eq 'upload') {
10880:         if ($checkitem eq 'username') {
10881:             $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'}.");
10882:         } elsif ($checkitem eq 'id') {
10883:             $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.");
10884:         }
10885:     } elsif ($mode eq 'selfcreate') {
10886:         if ($checkitem eq 'id') {
10887:             $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.");
10888:         }
10889:     } else {
10890:         if ($checkitem eq 'username') {
10891:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10892:         } elsif ($checkitem eq 'id') {
10893:             $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.");
10894:         }
10895:     }
10896:     return $response;
10897: }
10898: 
10899: sub personal_data_fieldtitles {
10900:     my %fieldtitles = &Apache::lonlocal::texthash (
10901:                         id => 'Student/Employee ID',
10902:                         permanentemail => 'E-mail address',
10903:                         lastname => 'Last Name',
10904:                         firstname => 'First Name',
10905:                         middlename => 'Middle Name',
10906:                         generation => 'Generation',
10907:                         gen => 'Generation',
10908:                         inststatus => 'Affiliation',
10909:                    );
10910:     return %fieldtitles;
10911: }
10912: 
10913: sub sorted_inst_types {
10914:     my ($dom) = @_;
10915:     my ($usertypes,$order);
10916:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10917:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10918:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10919:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10920:     } else {
10921:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10922:     }
10923:     my $othertitle = &mt('All users');
10924:     if ($env{'request.course.id'}) {
10925:         $othertitle  = &mt('Any users');
10926:     }
10927:     my @types;
10928:     if (ref($order) eq 'ARRAY') {
10929:         @types = @{$order};
10930:     }
10931:     if (@types == 0) {
10932:         if (ref($usertypes) eq 'HASH') {
10933:             @types = sort(keys(%{$usertypes}));
10934:         }
10935:     }
10936:     if (keys(%{$usertypes}) > 0) {
10937:         $othertitle = &mt('Other users');
10938:     }
10939:     return ($othertitle,$usertypes,\@types);
10940: }
10941: 
10942: sub get_institutional_codes {
10943:     my ($settings,$allcourses,$LC_code) = @_;
10944: # Get complete list of course sections to update
10945:     my @currsections = ();
10946:     my @currxlists = ();
10947:     my $coursecode = $$settings{'internal.coursecode'};
10948: 
10949:     if ($$settings{'internal.sectionnums'} ne '') {
10950:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10951:     }
10952: 
10953:     if ($$settings{'internal.crosslistings'} ne '') {
10954:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10955:     }
10956: 
10957:     if (@currxlists > 0) {
10958:         foreach (@currxlists) {
10959:             if (m/^([^:]+):(\w*)$/) {
10960:                 unless (grep/^$1$/,@{$allcourses}) {
10961:                     push(@{$allcourses},$1);
10962:                     $$LC_code{$1} = $2;
10963:                 }
10964:             }
10965:         }
10966:     }
10967:  
10968:     if (@currsections > 0) {
10969:         foreach (@currsections) {
10970:             if (m/^(\w+):(\w*)$/) {
10971:                 my $sec = $coursecode.$1;
10972:                 my $lc_sec = $2;
10973:                 unless (grep/^$sec$/,@{$allcourses}) {
10974:                     push(@{$allcourses},$sec);
10975:                     $$LC_code{$sec} = $lc_sec;
10976:                 }
10977:             }
10978:         }
10979:     }
10980:     return;
10981: }
10982: 
10983: sub get_standard_codeitems {
10984:     return ('Year','Semester','Department','Number','Section');
10985: }
10986: 
10987: =pod
10988: 
10989: =head1 Slot Helpers
10990: 
10991: =over 4
10992: 
10993: =item * sorted_slots()
10994: 
10995: Sorts an array of slot names in order of an optional sort key,
10996: default sort is by slot start time (earliest first). 
10997: 
10998: Inputs:
10999: 
11000: =over 4
11001: 
11002: slotsarr  - Reference to array of unsorted slot names.
11003: 
11004: slots     - Reference to hash of hash, where outer hash keys are slot names.
11005: 
11006: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11007: 
11008: =back
11009: 
11010: Returns:
11011: 
11012: =over 4
11013: 
11014: sorted   - An array of slot names sorted by a specified sort key 
11015:            (default sort key is start time of the slot).
11016: 
11017: =back
11018: 
11019: =cut
11020: 
11021: 
11022: sub sorted_slots {
11023:     my ($slotsarr,$slots,$sortkey) = @_;
11024:     if ($sortkey eq '') {
11025:         $sortkey = 'starttime';
11026:     }
11027:     my @sorted;
11028:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11029:         @sorted =
11030:             sort {
11031:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11032:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11033:                      }
11034:                      if (ref($slots->{$a})) { return -1;}
11035:                      if (ref($slots->{$b})) { return 1;}
11036:                      return 0;
11037:                  } @{$slotsarr};
11038:     }
11039:     return @sorted;
11040: }
11041: 
11042: =pod
11043: 
11044: =item * get_future_slots()
11045: 
11046: Inputs:
11047: 
11048: =over 4
11049: 
11050: cnum - course number
11051: 
11052: cdom - course domain
11053: 
11054: now - current UNIX time
11055: 
11056: symb - optional symb
11057: 
11058: =back
11059: 
11060: Returns:
11061: 
11062: =over 4
11063: 
11064: sorted_reservable - ref to array of student_schedulable slots currently 
11065:                     reservable, ordered by end date of reservation period.
11066: 
11067: reservable_now - ref to hash of student_schedulable slots currently
11068:                  reservable.
11069: 
11070:     Keys in inner hash are:
11071:     (a) symb: either blank or symb to which slot use is restricted.
11072:     (b) endreserve: end date of reservation period.
11073:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11074:         selected.
11075: 
11076: sorted_future - ref to array of student_schedulable slots reservable in
11077:                 the future, ordered by start date of reservation period.
11078: 
11079: future_reservable - ref to hash of student_schedulable slots reservable
11080:                     in the future.
11081: 
11082:     Keys in inner hash are:
11083:     (a) symb: either blank or symb to which slot use is restricted.
11084:     (b) startreserve: start date of reservation period.
11085:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11086:         selected.
11087: 
11088: =back
11089: 
11090: =cut
11091: 
11092: sub get_future_slots {
11093:     my ($cnum,$cdom,$now,$symb) = @_;
11094:     my $map;
11095:     if ($symb) {
11096:         ($map) = &Apache::lonnet::decode_symb($symb);
11097:     }
11098:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11099:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11100:     foreach my $slot (keys(%slots)) {
11101:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11102:         if ($symb) {
11103:             if ($slots{$slot}->{'symb'} ne '') {
11104:                 my $canuse;
11105:                 my %oksymbs;
11106:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11107:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11108:                 if ($oksymbs{$symb}) {
11109:                     $canuse = 1;
11110:                 } else {
11111:                     foreach my $item (@slotsymbs) {
11112:                         if ($item =~ /\.(page|sequence)$/) {
11113:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11114:                             if (($map ne '') && ($map eq $sloturl)) {
11115:                                 $canuse = 1;
11116:                                 last;
11117:                             }
11118:                         }
11119:                     }
11120:                 }
11121:                 next unless ($canuse);
11122:             }
11123:         }
11124:         if (($slots{$slot}->{'starttime'} > $now) &&
11125:             ($slots{$slot}->{'endtime'} > $now)) {
11126:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11127:                 my $userallowed = 0;
11128:                 if ($slots{$slot}->{'allowedsections'}) {
11129:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11130:                     if (!defined($env{'request.role.sec'})
11131:                         && grep(/^No section assigned$/,@allowed_sec)) {
11132:                         $userallowed=1;
11133:                     } else {
11134:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11135:                             $userallowed=1;
11136:                         }
11137:                     }
11138:                     unless ($userallowed) {
11139:                         if (defined($env{'request.course.groups'})) {
11140:                             my @groups = split(/:/,$env{'request.course.groups'});
11141:                             foreach my $group (@groups) {
11142:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11143:                                     $userallowed=1;
11144:                                     last;
11145:                                 }
11146:                             }
11147:                         }
11148:                     }
11149:                 }
11150:                 if ($slots{$slot}->{'allowedusers'}) {
11151:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11152:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11153:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11154:                         $userallowed = 1;
11155:                     }
11156:                 }
11157:                 next unless($userallowed);
11158:             }
11159:             my $startreserve = $slots{$slot}->{'startreserve'};
11160:             my $endreserve = $slots{$slot}->{'endreserve'};
11161:             my $symb = $slots{$slot}->{'symb'};
11162:             my $uniqueperiod;
11163:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11164:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11165:             }
11166:             if (($startreserve < $now) &&
11167:                 (!$endreserve || $endreserve > $now)) {
11168:                 my $lastres = $endreserve;
11169:                 if (!$lastres) {
11170:                     $lastres = $slots{$slot}->{'starttime'};
11171:                 }
11172:                 $reservable_now{$slot} = {
11173:                                            symb       => $symb,
11174:                                            endreserve => $lastres,
11175:                                            uniqueperiod => $uniqueperiod,
11176:                                          };
11177:             } elsif (($startreserve > $now) &&
11178:                      (!$endreserve || $endreserve > $startreserve)) {
11179:                 $future_reservable{$slot} = {
11180:                                               symb         => $symb,
11181:                                               startreserve => $startreserve,
11182:                                               uniqueperiod => $uniqueperiod,
11183:                                             };
11184:             }
11185:         }
11186:     }
11187:     my @unsorted_reservable = keys(%reservable_now);
11188:     if (@unsorted_reservable > 0) {
11189:         @sorted_reservable = 
11190:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11191:     }
11192:     my @unsorted_future = keys(%future_reservable);
11193:     if (@unsorted_future > 0) {
11194:         @sorted_future =
11195:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11196:     }
11197:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11198: }
11199: 
11200: =pod
11201: 
11202: =back
11203: 
11204: =head1 HTTP Helpers
11205: 
11206: =over 4
11207: 
11208: =item * &get_unprocessed_cgi($query,$possible_names)
11209: 
11210: Modify the %env hash to contain unprocessed CGI form parameters held in
11211: $query.  The parameters listed in $possible_names (an array reference),
11212: will be set in $env{'form.name'} if they do not already exist.
11213: 
11214: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11215: $possible_names is an ref to an array of form element names.  As an example:
11216: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11217: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11218: 
11219: =cut
11220: 
11221: sub get_unprocessed_cgi {
11222:   my ($query,$possible_names)= @_;
11223:   # $Apache::lonxml::debug=1;
11224:   foreach my $pair (split(/&/,$query)) {
11225:     my ($name, $value) = split(/=/,$pair);
11226:     $name = &unescape($name);
11227:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11228:       $value =~ tr/+/ /;
11229:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11230:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11231:     }
11232:   }
11233: }
11234: 
11235: =pod
11236: 
11237: =item * &cacheheader() 
11238: 
11239: returns cache-controlling header code
11240: 
11241: =cut
11242: 
11243: sub cacheheader {
11244:     unless ($env{'request.method'} eq 'GET') { return ''; }
11245:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11246:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11247:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11248:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11249:     return $output;
11250: }
11251: 
11252: =pod
11253: 
11254: =item * &no_cache($r) 
11255: 
11256: specifies header code to not have cache
11257: 
11258: =cut
11259: 
11260: sub no_cache {
11261:     my ($r) = @_;
11262:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11263: 	$env{'request.method'} ne 'GET') { return ''; }
11264:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11265:     $r->no_cache(1);
11266:     $r->header_out("Expires" => $date);
11267:     $r->header_out("Pragma" => "no-cache");
11268: }
11269: 
11270: sub content_type {
11271:     my ($r,$type,$charset) = @_;
11272:     if ($r) {
11273: 	#  Note that printout.pl calls this with undef for $r.
11274: 	&no_cache($r);
11275:     }
11276:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11277:     unless ($charset) {
11278: 	$charset=&Apache::lonlocal::current_encoding;
11279:     }
11280:     if ($charset) { $type.='; charset='.$charset; }
11281:     if ($r) {
11282: 	$r->content_type($type);
11283:     } else {
11284: 	print("Content-type: $type\n\n");
11285:     }
11286: }
11287: 
11288: =pod
11289: 
11290: =item * &add_to_env($name,$value) 
11291: 
11292: adds $name to the %env hash with value
11293: $value, if $name already exists, the entry is converted to an array
11294: reference and $value is added to the array.
11295: 
11296: =cut
11297: 
11298: sub add_to_env {
11299:   my ($name,$value)=@_;
11300:   if (defined($env{$name})) {
11301:     if (ref($env{$name})) {
11302:       #already have multiple values
11303:       push(@{ $env{$name} },$value);
11304:     } else {
11305:       #first time seeing multiple values, convert hash entry to an arrayref
11306:       my $first=$env{$name};
11307:       undef($env{$name});
11308:       push(@{ $env{$name} },$first,$value);
11309:     }
11310:   } else {
11311:     $env{$name}=$value;
11312:   }
11313: }
11314: 
11315: =pod
11316: 
11317: =item * &get_env_multiple($name) 
11318: 
11319: gets $name from the %env hash, it seemlessly handles the cases where multiple
11320: values may be defined and end up as an array ref.
11321: 
11322: returns an array of values
11323: 
11324: =cut
11325: 
11326: sub get_env_multiple {
11327:     my ($name) = @_;
11328:     my @values;
11329:     if (defined($env{$name})) {
11330:         # exists is it an array
11331:         if (ref($env{$name})) {
11332:             @values=@{ $env{$name} };
11333:         } else {
11334:             $values[0]=$env{$name};
11335:         }
11336:     }
11337:     return(@values);
11338: }
11339: 
11340: # Looks at given dependencies, and returns something depending on the context.
11341: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11342: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11343: # For all other contexts, returns ($output, $counter, $numpathchg).
11344: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11345: # $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.
11346: # $numpathchg: integer with the number of cleaned up dependency paths.
11347: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11348: # \%mapping: hash reference clean path -> original path for all dependencies.
11349: # @param {string} actionurl - The path to the handler, indicative of the context.
11350: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11351: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11352: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11353: # @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)
11354: # @return {Array} - array depending on the context (not a reference)
11355: sub ask_for_embedded_content {
11356:     # NOTE: documentation was added afterwards, it could be wrong
11357:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11358:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11359:         %currsubfile,%unused,$rem);
11360:     my $counter = 0;
11361:     my $numnew = 0;
11362:     my $numremref = 0;
11363:     my $numinvalid = 0;
11364:     my $numpathchg = 0;
11365:     my $numexisting = 0;
11366:     my $numunused = 0;
11367:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11368:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11369:     my $heading = &mt('Upload embedded files');
11370:     my $buttontext = &mt('Upload');
11371: 
11372:     # fills these variables based on the context:
11373:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11374:     # $path, $fileloc, $title, $rem, $filename
11375:     if ($env{'request.course.id'}) {
11376:         if ($actionurl eq '/adm/dependencies') {
11377:             $navmap = Apache::lonnavmaps::navmap->new();
11378:         }
11379:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11380:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11381:     }
11382:     if (($actionurl eq '/adm/portfolio') || 
11383:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11384:         my $current_path='/';
11385:         if ($env{'form.currentpath'}) {
11386:             $current_path = $env{'form.currentpath'};
11387:         }
11388:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11389:             $udom = $cdom;
11390:             $uname = $cnum;
11391:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11392:         } else {
11393:             $udom = $env{'user.domain'};
11394:             $uname = $env{'user.name'};
11395:             $url = '/userfiles/portfolio';
11396:         }
11397:         $toplevel = $url.'/';
11398:         $url .= $current_path;
11399:         $getpropath = 1;
11400:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11401:              ($actionurl eq '/adm/imsimport')) { 
11402:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11403:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11404:         $toplevel = $url;
11405:         if ($rest ne '') {
11406:             $url .= $rest;
11407:         }
11408:     } elsif ($actionurl eq '/adm/coursedocs') {
11409:         if (ref($args) eq 'HASH') {
11410:             $url = $args->{'docs_url'};
11411:             $toplevel = $url;
11412:             if ($args->{'context'} eq 'paste') {
11413:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11414:                 ($path) = 
11415:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11416:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11417:                 $fileloc =~ s{^/}{};
11418:             }
11419:         }
11420:     } elsif ($actionurl eq '/adm/dependencies')  {
11421:         if ($env{'request.course.id'} ne '') {
11422:             if (ref($args) eq 'HASH') {
11423:                 $url = $args->{'docs_url'};
11424:                 $title = $args->{'docs_title'};
11425:                 $toplevel = $url; 
11426:                 unless ($toplevel =~ m{^/}) {
11427:                     $toplevel = "/$url";
11428:                 }
11429:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11430:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11431:                     $path = $1;
11432:                 } else {
11433:                     ($path) =
11434:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11435:                 }
11436:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11437:                     $fileloc = $toplevel;
11438:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11439:                     my ($udom,$uname,$fname) =
11440:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11441:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11442:                 } else {
11443:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11444:                 }
11445:                 $fileloc =~ s{^/}{};
11446:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11447:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11448:             }
11449:         }
11450:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11451:         $udom = $cdom;
11452:         $uname = $cnum;
11453:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11454:         $toplevel = $url;
11455:         $path = $url;
11456:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11457:         $fileloc =~ s{^/}{};
11458:     }
11459:     
11460:     # parses the dependency paths to get some info
11461:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11462:     # $newfiles: hash URL -> 1 for new files or external URLs
11463:     # (will be completed later)
11464:     # $mapping:
11465:     #   for external URLs: external URL -> external URL
11466:     #   for relative paths: clean path -> original path
11467:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11468:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11469:     foreach my $file (keys(%{$allfiles})) {
11470:         my $embed_file;
11471:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11472:             $embed_file = $1;
11473:         } else {
11474:             $embed_file = $file;
11475:         }
11476:         my ($absolutepath,$cleaned_file);
11477:         if ($embed_file =~ m{^\w+://}) {
11478:             $cleaned_file = $embed_file;
11479:             $newfiles{$cleaned_file} = 1;
11480:             $mapping{$cleaned_file} = $embed_file;
11481:         } else {
11482:             $cleaned_file = &clean_path($embed_file);
11483:             if ($embed_file =~ m{^/}) {
11484:                 $absolutepath = $embed_file;
11485:             }
11486:             if ($cleaned_file =~ m{/}) {
11487:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11488:                 $path = &check_for_traversal($path,$url,$toplevel);
11489:                 my $item = $fname;
11490:                 if ($path ne '') {
11491:                     $item = $path.'/'.$fname;
11492:                     $subdependencies{$path}{$fname} = 1;
11493:                 } else {
11494:                     $dependencies{$item} = 1;
11495:                 }
11496:                 if ($absolutepath) {
11497:                     $mapping{$item} = $absolutepath;
11498:                 } else {
11499:                     $mapping{$item} = $embed_file;
11500:                 }
11501:             } else {
11502:                 $dependencies{$embed_file} = 1;
11503:                 if ($absolutepath) {
11504:                     $mapping{$cleaned_file} = $absolutepath;
11505:                 } else {
11506:                     $mapping{$cleaned_file} = $embed_file;
11507:                 }
11508:             }
11509:         }
11510:     }
11511:     
11512:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11513:     # and lists
11514:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11515:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11516:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11517:     #                                    the path had to be cleaned up
11518:     # $existing: hash clean path -> 1 if the file exists
11519:     # $numexisting: number of keys in $existing
11520:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11521:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11522:     #                                      dependency subdirectories that are
11523:     #                                      not listed as dependencies, with some exceptions using $rem
11524:     my $dirptr = 16384;
11525:     foreach my $path (keys(%subdependencies)) {
11526:         $currsubfile{$path} = {};
11527:         if (($actionurl eq '/adm/portfolio') || 
11528:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11529:             my ($sublistref,$listerror) =
11530:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11531:             if (ref($sublistref) eq 'ARRAY') {
11532:                 foreach my $line (@{$sublistref}) {
11533:                     my ($file_name,$rest) = split(/\&/,$line,2);
11534:                     $currsubfile{$path}{$file_name} = 1;
11535:                 }
11536:             }
11537:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11538:             if (opendir(my $dir,$url.'/'.$path)) {
11539:                 my @subdir_list = grep(!/^\./,readdir($dir));
11540:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11541:             }
11542:         } elsif (($actionurl eq '/adm/dependencies') ||
11543:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11544:                   ($args->{'context'} eq 'paste')) ||
11545:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11546:             if ($env{'request.course.id'} ne '') {
11547:                 my $dir;
11548:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11549:                     $dir = $fileloc;
11550:                 } else {
11551:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11552:                 }
11553:                 if ($dir ne '') {
11554:                     my ($sublistref,$listerror) =
11555:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11556:                     if (ref($sublistref) eq 'ARRAY') {
11557:                         foreach my $line (@{$sublistref}) {
11558:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11559:                                 undef,$mtime)=split(/\&/,$line,12);
11560:                             unless (($testdir&$dirptr) ||
11561:                                     ($file_name =~ /^\.\.?$/)) {
11562:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11563:                             }
11564:                         }
11565:                     }
11566:                 }
11567:             }
11568:         }
11569:         foreach my $file (keys(%{$subdependencies{$path}})) {
11570:             if (exists($currsubfile{$path}{$file})) {
11571:                 my $item = $path.'/'.$file;
11572:                 unless ($mapping{$item} eq $item) {
11573:                     $pathchanges{$item} = 1;
11574:                 }
11575:                 $existing{$item} = 1;
11576:                 $numexisting ++;
11577:             } else {
11578:                 $newfiles{$path.'/'.$file} = 1;
11579:             }
11580:         }
11581:         if ($actionurl eq '/adm/dependencies') {
11582:             foreach my $path (keys(%currsubfile)) {
11583:                 if (ref($currsubfile{$path}) eq 'HASH') {
11584:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11585:                          unless ($subdependencies{$path}{$file}) {
11586:                              next if (($rem ne '') &&
11587:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11588:                                        (ref($navmap) &&
11589:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11590:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11591:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11592:                              $unused{$path.'/'.$file} = 1; 
11593:                          }
11594:                     }
11595:                 }
11596:             }
11597:         }
11598:     }
11599:     
11600:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11601:     # for files in $url or $fileloc (target directory) in some contexts
11602:     my %currfile;
11603:     if (($actionurl eq '/adm/portfolio') ||
11604:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11605:         my ($dirlistref,$listerror) =
11606:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11607:         if (ref($dirlistref) eq 'ARRAY') {
11608:             foreach my $line (@{$dirlistref}) {
11609:                 my ($file_name,$rest) = split(/\&/,$line,2);
11610:                 $currfile{$file_name} = 1;
11611:             }
11612:         }
11613:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11614:         if (opendir(my $dir,$url)) {
11615:             my @dir_list = grep(!/^\./,readdir($dir));
11616:             map {$currfile{$_} = 1;} @dir_list;
11617:         }
11618:     } elsif (($actionurl eq '/adm/dependencies') ||
11619:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11620:               ($args->{'context'} eq 'paste')) ||
11621:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11622:         if ($env{'request.course.id'} ne '') {
11623:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11624:             if ($dir ne '') {
11625:                 my ($dirlistref,$listerror) =
11626:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11627:                 if (ref($dirlistref) eq 'ARRAY') {
11628:                     foreach my $line (@{$dirlistref}) {
11629:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11630:                             $size,undef,$mtime)=split(/\&/,$line,12);
11631:                         unless (($testdir&$dirptr) ||
11632:                                 ($file_name =~ /^\.\.?$/)) {
11633:                             $currfile{$file_name} = [$size,$mtime];
11634:                         }
11635:                     }
11636:                 }
11637:             }
11638:         }
11639:     }
11640:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11641:     # are not in subdirectories, using $currfile
11642:     foreach my $file (keys(%dependencies)) {
11643:         if (exists($currfile{$file})) {
11644:             unless ($mapping{$file} eq $file) {
11645:                 $pathchanges{$file} = 1;
11646:             }
11647:             $existing{$file} = 1;
11648:             $numexisting ++;
11649:         } else {
11650:             $newfiles{$file} = 1;
11651:         }
11652:     }
11653:     foreach my $file (keys(%currfile)) {
11654:         unless (($file eq $filename) ||
11655:                 ($file eq $filename.'.bak') ||
11656:                 ($dependencies{$file})) {
11657:             if ($actionurl eq '/adm/dependencies') {
11658:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11659:                     next if (($rem ne '') &&
11660:                              (($env{"httpref.$rem".$file} ne '') ||
11661:                               (ref($navmap) &&
11662:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11663:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11664:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11665:                 }
11666:             }
11667:             $unused{$file} = 1;
11668:         }
11669:     }
11670:     
11671:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11672:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11673:         ($args->{'context'} eq 'paste')) {
11674:         $counter = scalar(keys(%existing));
11675:         $numpathchg = scalar(keys(%pathchanges));
11676:         return ($output,$counter,$numpathchg,\%existing);
11677:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11678:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11679:         $counter = scalar(keys(%existing));
11680:         $numpathchg = scalar(keys(%pathchanges));
11681:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11682:     }
11683:     
11684:     # returns HTML otherwise, with dependency results and to ask for more uploads
11685:     
11686:     # $upload_output: missing dependencies (with upload form)
11687:     # $modify_output: uploaded dependencies (in use)
11688:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11689:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11690:         if ($actionurl eq '/adm/dependencies') {
11691:             next if ($embed_file =~ m{^\w+://});
11692:         }
11693:         $upload_output .= &start_data_table_row().
11694:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11695:                           '<span class="LC_filename">'.$embed_file.'</span>';
11696:         unless ($mapping{$embed_file} eq $embed_file) {
11697:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11698:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11699:         }
11700:         $upload_output .= '</td>';
11701:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11702:             $upload_output.='<td align="right">'.
11703:                             '<span class="LC_info LC_fontsize_medium">'.
11704:                             &mt("URL points to web address").'</span>';
11705:             $numremref++;
11706:         } elsif ($args->{'error_on_invalid_names'}
11707:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11708:             $upload_output.='<td align="right"><span class="LC_warning">'.
11709:                             &mt('Invalid characters').'</span>';
11710:             $numinvalid++;
11711:         } else {
11712:             $upload_output .= '<td>'.
11713:                               &embedded_file_element('upload_embedded',$counter,
11714:                                                      $embed_file,\%mapping,
11715:                                                      $allfiles,$codebase,'upload');
11716:             $counter ++;
11717:             $numnew ++;
11718:         }
11719:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11720:     }
11721:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11722:         if ($actionurl eq '/adm/dependencies') {
11723:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11724:             $modify_output .= &start_data_table_row().
11725:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11726:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11727:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11728:                               '<td>'.$size.'</td>'.
11729:                               '<td>'.$mtime.'</td>'.
11730:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11731:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11732:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11733:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11734:                               &embedded_file_element('upload_embedded',$counter,
11735:                                                      $embed_file,\%mapping,
11736:                                                      $allfiles,$codebase,'modify').
11737:                               '</div></td>'.
11738:                               &end_data_table_row()."\n";
11739:             $counter ++;
11740:         } else {
11741:             $upload_output .= &start_data_table_row().
11742:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11743:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11744:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11745:                               &Apache::loncommon::end_data_table_row()."\n";
11746:         }
11747:     }
11748:     my $delidx = $counter;
11749:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11750:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11751:         $delete_output .= &start_data_table_row().
11752:                           '<td><img src="'.&icon($oldfile).'" />'.
11753:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11754:                           '<td>'.$size.'</td>'.
11755:                           '<td>'.$mtime.'</td>'.
11756:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11757:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11758:                           &embedded_file_element('upload_embedded',$delidx,
11759:                                                  $oldfile,\%mapping,$allfiles,
11760:                                                  $codebase,'delete').'</td>'.
11761:                           &end_data_table_row()."\n"; 
11762:         $numunused ++;
11763:         $delidx ++;
11764:     }
11765:     if ($upload_output) {
11766:         $upload_output = &start_data_table().
11767:                          $upload_output.
11768:                          &end_data_table()."\n";
11769:     }
11770:     if ($modify_output) {
11771:         $modify_output = &start_data_table().
11772:                          &start_data_table_header_row().
11773:                          '<th>'.&mt('File').'</th>'.
11774:                          '<th>'.&mt('Size (KB)').'</th>'.
11775:                          '<th>'.&mt('Modified').'</th>'.
11776:                          '<th>'.&mt('Upload replacement?').'</th>'.
11777:                          &end_data_table_header_row().
11778:                          $modify_output.
11779:                          &end_data_table()."\n";
11780:     }
11781:     if ($delete_output) {
11782:         $delete_output = &start_data_table().
11783:                          &start_data_table_header_row().
11784:                          '<th>'.&mt('File').'</th>'.
11785:                          '<th>'.&mt('Size (KB)').'</th>'.
11786:                          '<th>'.&mt('Modified').'</th>'.
11787:                          '<th>'.&mt('Delete?').'</th>'.
11788:                          &end_data_table_header_row().
11789:                          $delete_output.
11790:                          &end_data_table()."\n";
11791:     }
11792:     my $applies = 0;
11793:     if ($numremref) {
11794:         $applies ++;
11795:     }
11796:     if ($numinvalid) {
11797:         $applies ++;
11798:     }
11799:     if ($numexisting) {
11800:         $applies ++;
11801:     }
11802:     if ($counter || $numunused) {
11803:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11804:                   ' method="post" enctype="multipart/form-data">'."\n".
11805:                   $state.'<h3>'.$heading.'</h3>'; 
11806:         if ($actionurl eq '/adm/dependencies') {
11807:             if ($numnew) {
11808:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11809:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11810:                            $upload_output.'<br />'."\n";
11811:             }
11812:             if ($numexisting) {
11813:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11814:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11815:                            $modify_output.'<br />'."\n";
11816:                            $buttontext = &mt('Save changes');
11817:             }
11818:             if ($numunused) {
11819:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11820:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11821:                            $delete_output.'<br />'."\n";
11822:                            $buttontext = &mt('Save changes');
11823:             }
11824:         } else {
11825:             $output .= $upload_output.'<br />'."\n";
11826:         }
11827:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11828:                    $counter.'" />'."\n";
11829:         if ($actionurl eq '/adm/dependencies') { 
11830:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11831:                        $numnew.'" />'."\n";
11832:         } elsif ($actionurl eq '') {
11833:             $output .=  '<input type="hidden" name="phase" value="three" />';
11834:         }
11835:     } elsif ($applies) {
11836:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11837:         if ($applies > 1) {
11838:             $output .=  
11839:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11840:             if ($numremref) {
11841:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11842:             }
11843:             if ($numinvalid) {
11844:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11845:             }
11846:             if ($numexisting) {
11847:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11848:             }
11849:             $output .= '</ul><br />';
11850:         } elsif ($numremref) {
11851:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11852:         } elsif ($numinvalid) {
11853:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11854:         } elsif ($numexisting) {
11855:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11856:         }
11857:         $output .= $upload_output.'<br />';
11858:     }
11859:     my ($pathchange_output,$chgcount);
11860:     $chgcount = $counter;
11861:     if (keys(%pathchanges) > 0) {
11862:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11863:             if ($counter) {
11864:                 $output .= &embedded_file_element('pathchange',$chgcount,
11865:                                                   $embed_file,\%mapping,
11866:                                                   $allfiles,$codebase,'change');
11867:             } else {
11868:                 $pathchange_output .= 
11869:                     &start_data_table_row().
11870:                     '<td><input type ="checkbox" name="namechange" value="'.
11871:                     $chgcount.'" checked="checked" /></td>'.
11872:                     '<td>'.$mapping{$embed_file}.'</td>'.
11873:                     '<td>'.$embed_file.
11874:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11875:                                            \%mapping,$allfiles,$codebase,'change').
11876:                     '</td>'.&end_data_table_row();
11877:             }
11878:             $numpathchg ++;
11879:             $chgcount ++;
11880:         }
11881:     }
11882:     if (($counter) || ($numunused)) {
11883:         if ($numpathchg) {
11884:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11885:                        $numpathchg.'" />'."\n";
11886:         }
11887:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11888:             ($actionurl eq '/adm/imsimport')) {
11889:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11890:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11891:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11892:         } elsif ($actionurl eq '/adm/dependencies') {
11893:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11894:         }
11895:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11896:     } elsif ($numpathchg) {
11897:         my %pathchange = ();
11898:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11899:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11900:             $output .= '<p>'.&mt('or').'</p>'; 
11901:         }
11902:     }
11903:     return ($output,$counter,$numpathchg);
11904: }
11905: 
11906: =pod
11907: 
11908: =item * clean_path($name)
11909: 
11910: Performs clean-up of directories, subdirectories and filename in an
11911: embedded object, referenced in an HTML file which is being uploaded
11912: to a course or portfolio, where 
11913: "Upload embedded images/multimedia files if HTML file" checkbox was
11914: checked.
11915: 
11916: Clean-up is similar to replacements in lonnet::clean_filename()
11917: except each / between sub-directory and next level is preserved.
11918: 
11919: =cut
11920: 
11921: sub clean_path {
11922:     my ($embed_file) = @_;
11923:     $embed_file =~s{^/+}{};
11924:     my @contents;
11925:     if ($embed_file =~ m{/}) {
11926:         @contents = split(/\//,$embed_file);
11927:     } else {
11928:         @contents = ($embed_file);
11929:     }
11930:     my $lastidx = scalar(@contents)-1;
11931:     for (my $i=0; $i<=$lastidx; $i++) { 
11932:         $contents[$i]=~s{\\}{/}g;
11933:         $contents[$i]=~s/\s+/\_/g;
11934:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11935:         if ($i == $lastidx) {
11936:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11937:         }
11938:     }
11939:     if ($lastidx > 0) {
11940:         return join('/',@contents);
11941:     } else {
11942:         return $contents[0];
11943:     }
11944: }
11945: 
11946: sub embedded_file_element {
11947:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11948:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11949:                    (ref($codebase) eq 'HASH'));
11950:     my $output;
11951:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11952:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11953:     }
11954:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11955:                &escape($embed_file).'" />';
11956:     unless (($context eq 'upload_embedded') && 
11957:             ($mapping->{$embed_file} eq $embed_file)) {
11958:         $output .='
11959:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11960:     }
11961:     my $attrib;
11962:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11963:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11964:     }
11965:     $output .=
11966:         "\n\t\t".
11967:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11968:         $attrib.'" />';
11969:     if (exists($codebase->{$mapping->{$embed_file}})) {
11970:         $output .=
11971:             "\n\t\t".
11972:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11973:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11974:     }
11975:     return $output;
11976: }
11977: 
11978: sub get_dependency_details {
11979:     my ($currfile,$currsubfile,$embed_file) = @_;
11980:     my ($size,$mtime,$showsize,$showmtime);
11981:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11982:         if ($embed_file =~ m{/}) {
11983:             my ($path,$fname) = split(/\//,$embed_file);
11984:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11985:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11986:             }
11987:         } else {
11988:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11989:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11990:             }
11991:         }
11992:         $showsize = $size/1024.0;
11993:         $showsize = sprintf("%.1f",$showsize);
11994:         if ($mtime > 0) {
11995:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11996:         }
11997:     }
11998:     return ($showsize,$showmtime);
11999: }
12000: 
12001: sub ask_embedded_js {
12002:     return <<"END";
12003: <script type="text/javascript"">
12004: // <![CDATA[
12005: function toggleBrowse(counter) {
12006:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12007:     var fileid = document.getElementById('embedded_item_'+counter);
12008:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12009:     if (chkboxid.checked == true) {
12010:         uploaddivid.style.display='block';
12011:     } else {
12012:         uploaddivid.style.display='none';
12013:         fileid.value = '';
12014:     }
12015: }
12016: // ]]>
12017: </script>
12018: 
12019: END
12020: }
12021: 
12022: sub upload_embedded {
12023:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12024:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12025:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12026:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12027:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12028:         my $orig_uploaded_filename =
12029:             $env{'form.embedded_item_'.$i.'.filename'};
12030:         foreach my $type ('orig','ref','attrib','codebase') {
12031:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12032:                 $env{'form.embedded_'.$type.'_'.$i} =
12033:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12034:             }
12035:         }
12036:         my ($path,$fname) =
12037:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12038:         # no path, whole string is fname
12039:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12040:         $fname = &Apache::lonnet::clean_filename($fname);
12041:         # See if there is anything left
12042:         next if ($fname eq '');
12043: 
12044:         # Check if file already exists as a file or directory.
12045:         my ($state,$msg);
12046:         if ($context eq 'portfolio') {
12047:             my $port_path = $dirpath;
12048:             if ($group ne '') {
12049:                 $port_path = "groups/$group/$port_path";
12050:             }
12051:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12052:                                               $fname,$group,'embedded_item_'.$i,
12053:                                               $dir_root,$port_path,$disk_quota,
12054:                                               $current_disk_usage,$uname,$udom);
12055:             if ($state eq 'will_exceed_quota'
12056:                 || $state eq 'file_locked') {
12057:                 $output .= $msg;
12058:                 next;
12059:             }
12060:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12061:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12062:             if ($state eq 'exists') {
12063:                 $output .= $msg;
12064:                 next;
12065:             }
12066:         }
12067:         # Check if extension is valid
12068:         if (($fname =~ /\.(\w+)$/) &&
12069:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12070:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12071:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12072:             next;
12073:         } elsif (($fname =~ /\.(\w+)$/) &&
12074:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12075:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12076:             next;
12077:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12078:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12079:             next;
12080:         }
12081:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12082:         my $subdir = $path;
12083:         $subdir =~ s{/+$}{};
12084:         if ($context eq 'portfolio') {
12085:             my $result;
12086:             if ($state eq 'existingfile') {
12087:                 $result=
12088:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12089:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12090:             } else {
12091:                 $result=
12092:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12093:                                                     $dirpath.
12094:                                                     $env{'form.currentpath'}.$subdir);
12095:                 if ($result !~ m|^/uploaded/|) {
12096:                     $output .= '<span class="LC_error">'
12097:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12098:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12099:                                .'</span><br />';
12100:                     next;
12101:                 } else {
12102:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12103:                                $path.$fname.'</span>').'<br />';     
12104:                 }
12105:             }
12106:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12107:             my $extendedsubdir = $dirpath.'/'.$subdir;
12108:             $extendedsubdir =~ s{/+$}{};
12109:             my $result =
12110:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12111:             if ($result !~ m|^/uploaded/|) {
12112:                 $output .= '<span class="LC_error">'
12113:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12114:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12115:                            .'</span><br />';
12116:                     next;
12117:             } else {
12118:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12119:                            $path.$fname.'</span>').'<br />';
12120:                 if ($context eq 'syllabus') {
12121:                     &Apache::lonnet::make_public_indefinitely($result);
12122:                 }
12123:             }
12124:         } else {
12125: # Save the file
12126:             my $target = $env{'form.embedded_item_'.$i};
12127:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12128:             my $dest = $fullpath.$fname;
12129:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12130:             my @parts=split(/\//,"$dirpath/$path");
12131:             my $count;
12132:             my $filepath = $dir_root;
12133:             foreach my $subdir (@parts) {
12134:                 $filepath .= "/$subdir";
12135:                 if (!-e $filepath) {
12136:                     mkdir($filepath,0770);
12137:                 }
12138:             }
12139:             my $fh;
12140:             if (!open($fh,'>'.$dest)) {
12141:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12142:                 $output .= '<span class="LC_error">'.
12143:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12144:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12145:                            '</span><br />';
12146:             } else {
12147:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12148:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12149:                     $output .= '<span class="LC_error">'.
12150:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12151:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12152:                               '</span><br />';
12153:                 } else {
12154:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12155:                                $url.'</span>').'<br />';
12156:                     unless ($context eq 'testbank') {
12157:                         $footer .= &mt('View embedded file: [_1]',
12158:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12159:                     }
12160:                 }
12161:                 close($fh);
12162:             }
12163:         }
12164:         if ($env{'form.embedded_ref_'.$i}) {
12165:             $pathchange{$i} = 1;
12166:         }
12167:     }
12168:     if ($output) {
12169:         $output = '<p>'.$output.'</p>';
12170:     }
12171:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12172:     $returnflag = 'ok';
12173:     my $numpathchgs = scalar(keys(%pathchange));
12174:     if ($numpathchgs > 0) {
12175:         if ($context eq 'portfolio') {
12176:             $output .= '<p>'.&mt('or').'</p>';
12177:         } elsif ($context eq 'testbank') {
12178:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12179:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12180:             $returnflag = 'modify_orightml';
12181:         }
12182:     }
12183:     return ($output.$footer,$returnflag,$numpathchgs);
12184: }
12185: 
12186: sub modify_html_form {
12187:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12188:     my $end = 0;
12189:     my $modifyform;
12190:     if ($context eq 'upload_embedded') {
12191:         return unless (ref($pathchange) eq 'HASH');
12192:         if ($env{'form.number_embedded_items'}) {
12193:             $end += $env{'form.number_embedded_items'};
12194:         }
12195:         if ($env{'form.number_pathchange_items'}) {
12196:             $end += $env{'form.number_pathchange_items'};
12197:         }
12198:         if ($end) {
12199:             for (my $i=0; $i<$end; $i++) {
12200:                 if ($i < $env{'form.number_embedded_items'}) {
12201:                     next unless($pathchange->{$i});
12202:                 }
12203:                 $modifyform .=
12204:                     &start_data_table_row().
12205:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12206:                     'checked="checked" /></td>'.
12207:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12208:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12209:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12210:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12211:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12212:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12213:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12214:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12215:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12216:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12217:                     &end_data_table_row();
12218:             }
12219:         }
12220:     } else {
12221:         $modifyform = $pathchgtable;
12222:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12223:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12224:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12225:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12226:         }
12227:     }
12228:     if ($modifyform) {
12229:         if ($actionurl eq '/adm/dependencies') {
12230:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12231:         }
12232:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12233:                '<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".
12234:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12235:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12236:                '</ol></p>'."\n".'<p>'.
12237:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12238:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12239:                &start_data_table()."\n".
12240:                &start_data_table_header_row().
12241:                '<th>'.&mt('Change?').'</th>'.
12242:                '<th>'.&mt('Current reference').'</th>'.
12243:                '<th>'.&mt('Required reference').'</th>'.
12244:                &end_data_table_header_row()."\n".
12245:                $modifyform.
12246:                &end_data_table().'<br />'."\n".$hiddenstate.
12247:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12248:                '</form>'."\n";
12249:     }
12250:     return;
12251: }
12252: 
12253: sub modify_html_refs {
12254:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12255:     my $container;
12256:     if ($context eq 'portfolio') {
12257:         $container = $env{'form.container'};
12258:     } elsif ($context eq 'coursedoc') {
12259:         $container = $env{'form.primaryurl'};
12260:     } elsif ($context eq 'manage_dependencies') {
12261:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12262:         $container = "/$container";
12263:     } elsif ($context eq 'syllabus') {
12264:         $container = $url;
12265:     } else {
12266:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12267:     }
12268:     my (%allfiles,%codebase,$output,$content);
12269:     my @changes = &get_env_multiple('form.namechange');
12270:     unless ((@changes > 0) || ($context eq 'syllabus')) {
12271:         if (wantarray) {
12272:             return ('',0,0); 
12273:         } else {
12274:             return;
12275:         }
12276:     }
12277:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12278:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12279:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12280:             if (wantarray) {
12281:                 return ('',0,0);
12282:             } else {
12283:                 return;
12284:             }
12285:         } 
12286:         $content = &Apache::lonnet::getfile($container);
12287:         if ($content eq '-1') {
12288:             if (wantarray) {
12289:                 return ('',0,0);
12290:             } else {
12291:                 return;
12292:             }
12293:         }
12294:     } else {
12295:         unless ($container =~ /^\Q$dir_root\E/) {
12296:             if (wantarray) {
12297:                 return ('',0,0);
12298:             } else {
12299:                 return;
12300:             }
12301:         } 
12302:         if (open(my $fh,'<',$container)) {
12303:             $content = join('', <$fh>);
12304:             close($fh);
12305:         } else {
12306:             if (wantarray) {
12307:                 return ('',0,0);
12308:             } else {
12309:                 return;
12310:             }
12311:         }
12312:     }
12313:     my ($count,$codebasecount) = (0,0);
12314:     my $mm = new File::MMagic;
12315:     my $mime_type = $mm->checktype_contents($content);
12316:     if ($mime_type eq 'text/html') {
12317:         my $parse_result = 
12318:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12319:                                                     \%codebase,\$content);
12320:         if ($parse_result eq 'ok') {
12321:             foreach my $i (@changes) {
12322:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12323:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12324:                 if ($allfiles{$ref}) {
12325:                     my $newname =  $orig;
12326:                     my ($attrib_regexp,$codebase);
12327:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12328:                     if ($attrib_regexp =~ /:/) {
12329:                         $attrib_regexp =~ s/\:/|/g;
12330:                     }
12331:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12332:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12333:                         $count += $numchg;
12334:                         $allfiles{$newname} = $allfiles{$ref};
12335:                         delete($allfiles{$ref});
12336:                     }
12337:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12338:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12339:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12340:                         $codebasecount ++;
12341:                     }
12342:                 }
12343:             }
12344:             my $skiprewrites;
12345:             if ($count || $codebasecount) {
12346:                 my $saveresult;
12347:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12348:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12349:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12350:                     if ($url eq $container) {
12351:                         my ($fname) = ($container =~ m{/([^/]+)$});
12352:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12353:                                             $count,'<span class="LC_filename">'.
12354:                                             $fname.'</span>').'</p>';
12355:                     } else {
12356:                          $output = '<p class="LC_error">'.
12357:                                    &mt('Error: update failed for: [_1].',
12358:                                    '<span class="LC_filename">'.
12359:                                    $container.'</span>').'</p>';
12360:                     }
12361:                     if ($context eq 'syllabus') {
12362:                         unless ($saveresult eq 'ok') {
12363:                             $skiprewrites = 1;
12364:                         }
12365:                     }
12366:                 } else {
12367:                     if (open(my $fh,'>',$container)) {
12368:                         print $fh $content;
12369:                         close($fh);
12370:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12371:                                   $count,'<span class="LC_filename">'.
12372:                                   $container.'</span>').'</p>';
12373:                     } else {
12374:                          $output = '<p class="LC_error">'.
12375:                                    &mt('Error: could not update [_1].',
12376:                                    '<span class="LC_filename">'.
12377:                                    $container.'</span>').'</p>';
12378:                     }
12379:                 }
12380:             }
12381:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12382:                 my ($actionurl,$state);
12383:                 $actionurl = "/public/$udom/$uname/syllabus";
12384:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12385:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12386:                                               \%codebase,
12387:                                               {'context' => 'rewrites',
12388:                                                'ignore_remote_references' => 1,});
12389:                 if (ref($mapping) eq 'HASH') {
12390:                     my $rewrites = 0;
12391:                     foreach my $key (keys(%{$mapping})) {
12392:                         next if ($key =~ m{^https?://});
12393:                         my $ref = $mapping->{$key};
12394:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12395:                         my $attrib;
12396:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12397:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12398:                         }
12399:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12400:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12401:                             $rewrites += $numchg;
12402:                         }
12403:                     }
12404:                     if ($rewrites) {
12405:                         my $saveresult; 
12406:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12407:                         if ($url eq $container) {
12408:                             my ($fname) = ($container =~ m{/([^/]+)$});
12409:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12410:                                             $count,'<span class="LC_filename">'.
12411:                                             $fname.'</span>').'</p>';
12412:                         } else {
12413:                             $output .= '<p class="LC_error">'.
12414:                                        &mt('Error: could not update links in [_1].',
12415:                                        '<span class="LC_filename">'.
12416:                                        $container.'</span>').'</p>';
12417: 
12418:                         }
12419:                     }
12420:                 }
12421:             }
12422:         } else {
12423:             &logthis('Failed to parse '.$container.
12424:                      ' to modify references: '.$parse_result);
12425:         }
12426:     }
12427:     if (wantarray) {
12428:         return ($output,$count,$codebasecount);
12429:     } else {
12430:         return $output;
12431:     }
12432: }
12433: 
12434: sub check_for_existing {
12435:     my ($path,$fname,$element) = @_;
12436:     my ($state,$msg);
12437:     if (-d $path.'/'.$fname) {
12438:         $state = 'exists';
12439:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12440:     } elsif (-e $path.'/'.$fname) {
12441:         $state = 'exists';
12442:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12443:     }
12444:     if ($state eq 'exists') {
12445:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12446:     }
12447:     return ($state,$msg);
12448: }
12449: 
12450: sub check_for_upload {
12451:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12452:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12453:     my $filesize = length($env{'form.'.$element});
12454:     if (!$filesize) {
12455:         my $msg = '<span class="LC_error">'.
12456:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12457:                       '<span class="LC_filename">'.$fname.'</span>',
12458:                       $filesize).'<br />'.
12459:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12460:                   '</span>';
12461:         return ('zero_bytes',$msg);
12462:     }
12463:     $filesize =  $filesize/1000; #express in k (1024?)
12464:     my $getpropath = 1;
12465:     my ($dirlistref,$listerror) =
12466:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12467:     my $found_file = 0;
12468:     my $locked_file = 0;
12469:     my @lockers;
12470:     my $navmap;
12471:     if ($env{'request.course.id'}) {
12472:         $navmap = Apache::lonnavmaps::navmap->new();
12473:     }
12474:     if (ref($dirlistref) eq 'ARRAY') {
12475:         foreach my $line (@{$dirlistref}) {
12476:             my ($file_name,$rest)=split(/\&/,$line,2);
12477:             if ($file_name eq $fname){
12478:                 $file_name = $path.$file_name;
12479:                 if ($group ne '') {
12480:                     $file_name = $group.$file_name;
12481:                 }
12482:                 $found_file = 1;
12483:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12484:                     foreach my $lock (@lockers) {
12485:                         if (ref($lock) eq 'ARRAY') {
12486:                             my ($symb,$crsid) = @{$lock};
12487:                             if ($crsid eq $env{'request.course.id'}) {
12488:                                 if (ref($navmap)) {
12489:                                     my $res = $navmap->getBySymb($symb);
12490:                                     foreach my $part (@{$res->parts()}) { 
12491:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12492:                                         unless (($slot_status == $res->RESERVED) ||
12493:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12494:                                             $locked_file = 1;
12495:                                         }
12496:                                     }
12497:                                 } else {
12498:                                     $locked_file = 1;
12499:                                 }
12500:                             } else {
12501:                                 $locked_file = 1;
12502:                             }
12503:                         }
12504:                    }
12505:                 } else {
12506:                     my @info = split(/\&/,$rest);
12507:                     my $currsize = $info[6]/1000;
12508:                     if ($currsize < $filesize) {
12509:                         my $extra = $filesize - $currsize;
12510:                         if (($current_disk_usage + $extra) > $disk_quota) {
12511:                             my $msg = '<p class="LC_warning">'.
12512:                                       &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.',
12513:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12514:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12515:                                                    $disk_quota,$current_disk_usage).'</p>';
12516:                             return ('will_exceed_quota',$msg);
12517:                         }
12518:                     }
12519:                 }
12520:             }
12521:         }
12522:     }
12523:     if (($current_disk_usage + $filesize) > $disk_quota){
12524:         my $msg = '<p class="LC_warning">'.
12525:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12526:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12527:         return ('will_exceed_quota',$msg);
12528:     } elsif ($found_file) {
12529:         if ($locked_file) {
12530:             my $msg = '<p class="LC_warning">';
12531:             $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>');
12532:             $msg .= '</p>';
12533:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12534:             return ('file_locked',$msg);
12535:         } else {
12536:             my $msg = '<p class="LC_error">';
12537:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12538:             $msg .= '</p>';
12539:             return ('existingfile',$msg);
12540:         }
12541:     }
12542: }
12543: 
12544: sub check_for_traversal {
12545:     my ($path,$url,$toplevel) = @_;
12546:     my @parts=split(/\//,$path);
12547:     my $cleanpath;
12548:     my $fullpath = $url;
12549:     for (my $i=0;$i<@parts;$i++) {
12550:         next if ($parts[$i] eq '.');
12551:         if ($parts[$i] eq '..') {
12552:             $fullpath =~ s{([^/]+/)$}{};
12553:         } else {
12554:             $fullpath .= $parts[$i].'/';
12555:         }
12556:     }
12557:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12558:         $cleanpath = $1;
12559:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12560:         my $curr_toprel = $1;
12561:         my @parts = split(/\//,$curr_toprel);
12562:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12563:         my @urlparts = split(/\//,$url_toprel);
12564:         my $doubledots;
12565:         my $startdiff = -1;
12566:         for (my $i=0; $i<@urlparts; $i++) {
12567:             if ($startdiff == -1) {
12568:                 unless ($urlparts[$i] eq $parts[$i]) {
12569:                     $startdiff = $i;
12570:                     $doubledots .= '../';
12571:                 }
12572:             } else {
12573:                 $doubledots .= '../';
12574:             }
12575:         }
12576:         if ($startdiff > -1) {
12577:             $cleanpath = $doubledots;
12578:             for (my $i=$startdiff; $i<@parts; $i++) {
12579:                 $cleanpath .= $parts[$i].'/';
12580:             }
12581:         }
12582:     }
12583:     $cleanpath =~ s{(/)$}{};
12584:     return $cleanpath;
12585: }
12586: 
12587: sub is_archive_file {
12588:     my ($mimetype) = @_;
12589:     if (($mimetype eq 'application/octet-stream') ||
12590:         ($mimetype eq 'application/x-stuffit') ||
12591:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12592:         return 1;
12593:     }
12594:     return;
12595: }
12596: 
12597: sub decompress_form {
12598:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12599:     my %lt = &Apache::lonlocal::texthash (
12600:         this => 'This file is an archive file.',
12601:         camt => 'This file is a Camtasia archive file.',
12602:         itsc => 'Its contents are as follows:',
12603:         youm => 'You may wish to extract its contents.',
12604:         extr => 'Extract contents',
12605:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12606:         proa => 'Process automatically?',
12607:         yes  => 'Yes',
12608:         no   => 'No',
12609:         fold => 'Title for folder containing movie',
12610:         movi => 'Title for page containing embedded movie', 
12611:     );
12612:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12613:     my ($is_camtasia,$topdir,%toplevel,@paths);
12614:     my $info = &list_archive_contents($fileloc,\@paths);
12615:     if (@paths) {
12616:         foreach my $path (@paths) {
12617:             $path =~ s{^/}{};
12618:             if ($path =~ m{^([^/]+)/$}) {
12619:                 $topdir = $1;
12620:             }
12621:             if ($path =~ m{^([^/]+)/}) {
12622:                 $toplevel{$1} = $path;
12623:             } else {
12624:                 $toplevel{$path} = $path;
12625:             }
12626:         }
12627:     }
12628:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12629:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12630:                         "$topdir/media/",
12631:                         "$topdir/media/$topdir.mp4",
12632:                         "$topdir/media/FirstFrame.png",
12633:                         "$topdir/media/player.swf",
12634:                         "$topdir/media/swfobject.js",
12635:                         "$topdir/media/expressInstall.swf");
12636:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12637:                          "$topdir/$topdir.mp4",
12638:                          "$topdir/$topdir\_config.xml",
12639:                          "$topdir/$topdir\_controller.swf",
12640:                          "$topdir/$topdir\_embed.css",
12641:                          "$topdir/$topdir\_First_Frame.png",
12642:                          "$topdir/$topdir\_player.html",
12643:                          "$topdir/$topdir\_Thumbnails.png",
12644:                          "$topdir/playerProductInstall.swf",
12645:                          "$topdir/scripts/",
12646:                          "$topdir/scripts/config_xml.js",
12647:                          "$topdir/scripts/handlebars.js",
12648:                          "$topdir/scripts/jquery-1.7.1.min.js",
12649:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12650:                          "$topdir/scripts/modernizr.js",
12651:                          "$topdir/scripts/player-min.js",
12652:                          "$topdir/scripts/swfobject.js",
12653:                          "$topdir/skins/",
12654:                          "$topdir/skins/configuration_express.xml",
12655:                          "$topdir/skins/express_show/",
12656:                          "$topdir/skins/express_show/player-min.css",
12657:                          "$topdir/skins/express_show/spritesheet.png");
12658:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12659:                          "$topdir/$topdir.mp4",
12660:                          "$topdir/$topdir\_config.xml",
12661:                          "$topdir/$topdir\_controller.swf",
12662:                          "$topdir/$topdir\_embed.css",
12663:                          "$topdir/$topdir\_First_Frame.png",
12664:                          "$topdir/$topdir\_player.html",
12665:                          "$topdir/$topdir\_Thumbnails.png",
12666:                          "$topdir/playerProductInstall.swf",
12667:                          "$topdir/scripts/",
12668:                          "$topdir/scripts/config_xml.js",
12669:                          "$topdir/scripts/techsmith-smart-player.min.js",
12670:                          "$topdir/skins/",
12671:                          "$topdir/skins/configuration_express.xml",
12672:                          "$topdir/skins/express_show/",
12673:                          "$topdir/skins/express_show/spritesheet.min.css",
12674:                          "$topdir/skins/express_show/spritesheet.png",
12675:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12676:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12677:         if (@diffs == 0) {
12678:             $is_camtasia = 6;
12679:         } else {
12680:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12681:             if (@diffs == 0) {
12682:                 $is_camtasia = 8;
12683:             } else {
12684:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12685:                 if (@diffs == 0) {
12686:                     $is_camtasia = 8;
12687:                 }
12688:             }
12689:         }
12690:     }
12691:     my $output;
12692:     if ($is_camtasia) {
12693:         $output = <<"ENDCAM";
12694: <script type="text/javascript" language="Javascript">
12695: // <![CDATA[
12696: 
12697: function camtasiaToggle() {
12698:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12699:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12700:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12701:                 document.getElementById('camtasia_titles').style.display='block';
12702:             } else {
12703:                 document.getElementById('camtasia_titles').style.display='none';
12704:             }
12705:         }
12706:     }
12707:     return;
12708: }
12709: 
12710: // ]]>
12711: </script>
12712: <p>$lt{'camt'}</p>
12713: ENDCAM
12714:     } else {
12715:         $output = '<p>'.$lt{'this'};
12716:         if ($info eq '') {
12717:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12718:         } else {
12719:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12720:                        '<div><pre>'.$info.'</pre></div>';
12721:         }
12722:     }
12723:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12724:     my $duplicates;
12725:     my $num = 0;
12726:     if (ref($dirlist) eq 'ARRAY') {
12727:         foreach my $item (@{$dirlist}) {
12728:             if (ref($item) eq 'ARRAY') {
12729:                 if (exists($toplevel{$item->[0]})) {
12730:                     $duplicates .= 
12731:                         &start_data_table_row().
12732:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12733:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12734:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12735:                         'value="1" />'.&mt('Yes').'</label>'.
12736:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12737:                         '<td>'.$item->[0].'</td>';
12738:                     if ($item->[2]) {
12739:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12740:                     } else {
12741:                         $duplicates .= '<td>'.&mt('File').'</td>';
12742:                     }
12743:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12744:                                    '<td>'.
12745:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12746:                                    '</td>'.
12747:                                    &end_data_table_row();
12748:                     $num ++;
12749:                 }
12750:             }
12751:         }
12752:     }
12753:     my $itemcount;
12754:     if (@paths > 0) {
12755:         $itemcount = scalar(@paths);
12756:     } else {
12757:         $itemcount = 1;
12758:     }
12759:     if ($is_camtasia) {
12760:         $output .= $lt{'auto'}.'<br />'.
12761:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12762:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12763:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12764:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12765:                    $lt{'no'}.'</label></span><br />'.
12766:                    '<div id="camtasia_titles" style="display:block">'.
12767:                    &Apache::lonhtmlcommon::start_pick_box().
12768:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12769:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12770:                    &Apache::lonhtmlcommon::row_closure().
12771:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12772:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12773:                    &Apache::lonhtmlcommon::row_closure(1).
12774:                    &Apache::lonhtmlcommon::end_pick_box().
12775:                    '</div>';
12776:     }
12777:     $output .= 
12778:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12779:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12780:         "\n";
12781:     if ($duplicates ne '') {
12782:         $output .= '<p><span class="LC_warning">'.
12783:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12784:                    &start_data_table().
12785:                    &start_data_table_header_row().
12786:                    '<th>'.&mt('Overwrite?').'</th>'.
12787:                    '<th>'.&mt('Name').'</th>'.
12788:                    '<th>'.&mt('Type').'</th>'.
12789:                    '<th>'.&mt('Size').'</th>'.
12790:                    '<th>'.&mt('Last modified').'</th>'.
12791:                    &end_data_table_header_row().
12792:                    $duplicates.
12793:                    &end_data_table().
12794:                    '</p>';
12795:     }
12796:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12797:     if (ref($hiddenelements) eq 'HASH') {
12798:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12799:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12800:         }
12801:     }
12802:     $output .= <<"END";
12803: <br />
12804: <input type="submit" name="decompress" value="$lt{'extr'}" />
12805: </form>
12806: $noextract
12807: END
12808:     return $output;
12809: }
12810: 
12811: sub decompression_utility {
12812:     my ($program) = @_;
12813:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12814:     my $location;
12815:     if (grep(/^\Q$program\E$/,@utilities)) { 
12816:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12817:                          '/usr/sbin/') {
12818:             if (-x $dir.$program) {
12819:                 $location = $dir.$program;
12820:                 last;
12821:             }
12822:         }
12823:     }
12824:     return $location;
12825: }
12826: 
12827: sub list_archive_contents {
12828:     my ($file,$pathsref) = @_;
12829:     my (@cmd,$output);
12830:     my $needsregexp;
12831:     if ($file =~ /\.zip$/) {
12832:         @cmd = (&decompression_utility('unzip'),"-l");
12833:         $needsregexp = 1;
12834:     } elsif (($file =~ m/\.tar\.gz$/) ||
12835:              ($file =~ /\.tgz$/)) {
12836:         @cmd = (&decompression_utility('tar'),"-ztf");
12837:     } elsif ($file =~ /\.tar\.bz2$/) {
12838:         @cmd = (&decompression_utility('tar'),"-jtf");
12839:     } elsif ($file =~ m|\.tar$|) {
12840:         @cmd = (&decompression_utility('tar'),"-tf");
12841:     }
12842:     if (@cmd) {
12843:         undef($!);
12844:         undef($@);
12845:         if (open(my $fh,"-|", @cmd, $file)) {
12846:             while (my $line = <$fh>) {
12847:                 $output .= $line;
12848:                 chomp($line);
12849:                 my $item;
12850:                 if ($needsregexp) {
12851:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12852:                 } else {
12853:                     $item = $line;
12854:                 }
12855:                 if ($item ne '') {
12856:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12857:                         push(@{$pathsref},$item);
12858:                     } 
12859:                 }
12860:             }
12861:             close($fh);
12862:         }
12863:     }
12864:     return $output;
12865: }
12866: 
12867: sub decompress_uploaded_file {
12868:     my ($file,$dir) = @_;
12869:     &Apache::lonnet::appenv({'cgi.file' => $file});
12870:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12871:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12872:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12873:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12874:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12875:     my $decompressed = $env{'cgi.decompressed'};
12876:     &Apache::lonnet::delenv('cgi.file');
12877:     &Apache::lonnet::delenv('cgi.dir');
12878:     &Apache::lonnet::delenv('cgi.decompressed');
12879:     return ($decompressed,$result);
12880: }
12881: 
12882: sub process_decompression {
12883:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12884:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12885:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12886:                &mt('Unexpected file path.').'</p>'."\n";
12887:     }
12888:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12889:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12890:                &mt('Unexpected course context.').'</p>'."\n";
12891:     }
12892:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12893:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12894:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12895:     }
12896:     my ($dir,$error,$warning,$output);
12897:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12898:         $error = &mt('Filename not a supported archive file type.').
12899:                  '<br />'.&mt('Filename should end with one of: [_1].',
12900:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12901:     } else {
12902:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12903:         if ($docuhome eq 'no_host') {
12904:             $error = &mt('Could not determine home server for course.');
12905:         } else {
12906:             my @ids=&Apache::lonnet::current_machine_ids();
12907:             my $currdir = "$dir_root/$destination";
12908:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12909:                 $dir = &LONCAPA::propath($docudom,$docuname).
12910:                        "$dir_root/$destination";
12911:             } else {
12912:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12913:                        "$dir_root/$docudom/$docuname/$destination";
12914:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12915:                     $error = &mt('Archive file not found.');
12916:                 }
12917:             }
12918:             my (@to_overwrite,@to_skip);
12919:             if ($env{'form.archive_overwrite_total'} > 0) {
12920:                 my $total = $env{'form.archive_overwrite_total'};
12921:                 for (my $i=0; $i<$total; $i++) {
12922:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12923:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12924:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12925:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12926:                     }
12927:                 }
12928:             }
12929:             my $numskip = scalar(@to_skip);
12930:             my $numoverwrite = scalar(@to_overwrite);
12931:             if (($numskip) && (!$numoverwrite)) { 
12932:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12933:             } elsif ($dir eq '') {
12934:                 $error = &mt('Directory containing archive file unavailable.');
12935:             } elsif (!$error) {
12936:                 my ($decompressed,$display);
12937:                 if (($numskip) || ($numoverwrite)) {
12938:                     my $tempdir = time.'_'.$$.int(rand(10000));
12939:                     mkdir("$dir/$tempdir",0755);
12940:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12941:                         ($decompressed,$display) = 
12942:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12943:                         foreach my $item (@to_skip) {
12944:                             if (($item ne '') && ($item !~ /\.\./)) {
12945:                                 if (-f "$dir/$tempdir/$item") { 
12946:                                     unlink("$dir/$tempdir/$item");
12947:                                 } elsif (-d "$dir/$tempdir/$item") {
12948:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12949:                                 }
12950:                             }
12951:                         }
12952:                         foreach my $item (@to_overwrite) {
12953:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12954:                                 if (($item ne '') && ($item !~ /\.\./)) {
12955:                                     if (-f "$dir/$item") {
12956:                                         unlink("$dir/$item");
12957:                                     } elsif (-d "$dir/$item") {
12958:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12959:                                     }
12960:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12961:                                 }
12962:                             }
12963:                         }
12964:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12965:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12966:                         }
12967:                     }
12968:                 } else {
12969:                     ($decompressed,$display) = 
12970:                         &decompress_uploaded_file($file,$dir);
12971:                 }
12972:                 if ($decompressed eq 'ok') {
12973:                     $output = '<p class="LC_info">'.
12974:                               &mt('Files extracted successfully from archive.').
12975:                               '</p>'."\n";
12976:                     my ($warning,$result,@contents);
12977:                     my ($newdirlistref,$newlisterror) =
12978:                         &Apache::lonnet::dirlist($currdir,$docudom,
12979:                                                  $docuname,1);
12980:                     my (%is_dir,%changes,@newitems);
12981:                     my $dirptr = 16384;
12982:                     if (ref($newdirlistref) eq 'ARRAY') {
12983:                         foreach my $dir_line (@{$newdirlistref}) {
12984:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12985:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
12986:                                 push(@newitems,$item);
12987:                                 if ($dirptr&$testdir) {
12988:                                     $is_dir{$item} = 1;
12989:                                 }
12990:                                 $changes{$item} = 1;
12991:                             }
12992:                         }
12993:                     }
12994:                     if (keys(%changes) > 0) {
12995:                         foreach my $item (sort(@newitems)) {
12996:                             if ($changes{$item}) {
12997:                                 push(@contents,$item);
12998:                             }
12999:                         }
13000:                     }
13001:                     if (@contents > 0) {
13002:                         my $wantform;
13003:                         unless ($env{'form.autoextract_camtasia'}) {
13004:                             $wantform = 1;
13005:                         }
13006:                         my (%children,%parent,%dirorder,%titles);
13007:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13008:                                                                 $currdir,\%is_dir,
13009:                                                                 \%children,\%parent,
13010:                                                                 \@contents,\%dirorder,
13011:                                                                 \%titles,$wantform);
13012:                         if ($datatable ne '') {
13013:                             $output .= &archive_options_form('decompressed',$datatable,
13014:                                                              $count,$hiddenelem);
13015:                             my $startcount = 6;
13016:                             $output .= &archive_javascript($startcount,$count,
13017:                                                            \%titles,\%children);
13018:                         }
13019:                         if ($env{'form.autoextract_camtasia'}) {
13020:                             my $version = $env{'form.autoextract_camtasia'};
13021:                             my %displayed;
13022:                             my $total = 1;
13023:                             $env{'form.archive_directory'} = [];
13024:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13025:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13026:                                 $path =~ s{/$}{};
13027:                                 my $item;
13028:                                 if ($path ne '') {
13029:                                     $item = "$path/$titles{$i}";
13030:                                 } else {
13031:                                     $item = $titles{$i};
13032:                                 }
13033:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13034:                                 if ($item eq $contents[0]) {
13035:                                     push(@{$env{'form.archive_directory'}},$i);
13036:                                     $env{'form.archive_'.$i} = 'display';
13037:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13038:                                     $displayed{'folder'} = $i;
13039:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13040:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13041:                                     $env{'form.archive_'.$i} = 'display';
13042:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13043:                                     $displayed{'web'} = $i;
13044:                                 } else {
13045:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13046:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13047:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13048:                                         push(@{$env{'form.archive_directory'}},$i);
13049:                                     }
13050:                                     $env{'form.archive_'.$i} = 'dependency';
13051:                                 }
13052:                                 $total ++;
13053:                             }
13054:                             for (my $i=1; $i<$total; $i++) {
13055:                                 next if ($i == $displayed{'web'});
13056:                                 next if ($i == $displayed{'folder'});
13057:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13058:                             }
13059:                             $env{'form.phase'} = 'decompress_cleanup';
13060:                             $env{'form.archivedelete'} = 1;
13061:                             $env{'form.archive_count'} = $total-1;
13062:                             $output .=
13063:                                 &process_extracted_files('coursedocs',$docudom,
13064:                                                          $docuname,$destination,
13065:                                                          $dir_root,$hiddenelem);
13066:                         }
13067:                     } else {
13068:                         $warning = &mt('No new items extracted from archive file.');
13069:                     }
13070:                 } else {
13071:                     $output = $display;
13072:                     $error = &mt('An error occurred during extraction from the archive file.');
13073:                 }
13074:             }
13075:         }
13076:     }
13077:     if ($error) {
13078:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13079:                    $error.'</p>'."\n";
13080:     }
13081:     if ($warning) {
13082:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13083:     }
13084:     return $output;
13085: }
13086: 
13087: sub get_extracted {
13088:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13089:         $titles,$wantform) = @_;
13090:     my $count = 0;
13091:     my $depth = 0;
13092:     my $datatable;
13093:     my @hierarchy;
13094:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13095:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13096:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13097:     foreach my $item (@{$contents}) {
13098:         $count ++;
13099:         @{$dirorder->{$count}} = @hierarchy;
13100:         $titles->{$count} = $item;
13101:         &archive_hierarchy($depth,$count,$parent,$children);
13102:         if ($wantform) {
13103:             $datatable .= &archive_row($is_dir->{$item},$item,
13104:                                        $currdir,$depth,$count);
13105:         }
13106:         if ($is_dir->{$item}) {
13107:             $depth ++;
13108:             push(@hierarchy,$count);
13109:             $parent->{$depth} = $count;
13110:             $datatable .=
13111:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13112:                                            \$depth,\$count,\@hierarchy,$dirorder,
13113:                                            $children,$parent,$titles,$wantform);
13114:             $depth --;
13115:             pop(@hierarchy);
13116:         }
13117:     }
13118:     return ($count,$datatable);
13119: }
13120: 
13121: sub recurse_extracted_archive {
13122:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13123:         $children,$parent,$titles,$wantform) = @_;
13124:     my $result='';
13125:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13126:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13127:             (ref($dirorder) eq 'HASH')) {
13128:         return $result;
13129:     }
13130:     my $dirptr = 16384;
13131:     my ($newdirlistref,$newlisterror) =
13132:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13133:     if (ref($newdirlistref) eq 'ARRAY') {
13134:         foreach my $dir_line (@{$newdirlistref}) {
13135:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13136:             unless ($item =~ /^\.+$/) {
13137:                 $$count ++;
13138:                 @{$dirorder->{$$count}} = @{$hierarchy};
13139:                 $titles->{$$count} = $item;
13140:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13141: 
13142:                 my $is_dir;
13143:                 if ($dirptr&$testdir) {
13144:                     $is_dir = 1;
13145:                 }
13146:                 if ($wantform) {
13147:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13148:                 }
13149:                 if ($is_dir) {
13150:                     $$depth ++;
13151:                     push(@{$hierarchy},$$count);
13152:                     $parent->{$$depth} = $$count;
13153:                     $result .=
13154:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13155:                                                    $docuname,$depth,$count,
13156:                                                    $hierarchy,$dirorder,$children,
13157:                                                    $parent,$titles,$wantform);
13158:                     $$depth --;
13159:                     pop(@{$hierarchy});
13160:                 }
13161:             }
13162:         }
13163:     }
13164:     return $result;
13165: }
13166: 
13167: sub archive_hierarchy {
13168:     my ($depth,$count,$parent,$children) =@_;
13169:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13170:         if (exists($parent->{$depth})) {
13171:              $children->{$parent->{$depth}} .= $count.':';
13172:         }
13173:     }
13174:     return;
13175: }
13176: 
13177: sub archive_row {
13178:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13179:     my ($name) = ($item =~ m{([^/]+)$});
13180:     my %choices = &Apache::lonlocal::texthash (
13181:                                        'display'    => 'Add as file',
13182:                                        'dependency' => 'Include as dependency',
13183:                                        'discard'    => 'Discard',
13184:                                       );
13185:     if ($is_dir) {
13186:         $choices{'display'} = &mt('Add as folder'); 
13187:     }
13188:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13189:     my $offset = 0;
13190:     foreach my $action ('display','dependency','discard') {
13191:         $offset ++;
13192:         if ($action ne 'display') {
13193:             $offset ++;
13194:         }  
13195:         $output .= '<td><span class="LC_nobreak">'.
13196:                    '<label><input type="radio" name="archive_'.$count.
13197:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13198:         my $text = $choices{$action};
13199:         if ($is_dir) {
13200:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13201:             if ($action eq 'display') {
13202:                 $text = &mt('Add as folder');
13203:             }
13204:         } else {
13205:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13206: 
13207:         }
13208:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13209:         if ($action eq 'dependency') {
13210:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13211:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13212:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13213:                        '<option value=""></option>'."\n".
13214:                        '</select>'."\n".
13215:                        '</div>';
13216:         } elsif ($action eq 'display') {
13217:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13218:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13219:                        '</div>';
13220:         }
13221:         $output .= '</td>';
13222:     }
13223:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13224:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13225:     for (my $i=0; $i<$depth; $i++) {
13226:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13227:     }
13228:     if ($is_dir) {
13229:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13230:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13231:     } else {
13232:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13233:     }
13234:     $output .= '&nbsp;'.$name.'</td>'."\n".
13235:                &end_data_table_row();
13236:     return $output;
13237: }
13238: 
13239: sub archive_options_form {
13240:     my ($form,$display,$count,$hiddenelem) = @_;
13241:     my %lt = &Apache::lonlocal::texthash(
13242:                perm => 'Permanently remove archive file?',
13243:                hows => 'How should each extracted item be incorporated in the course?',
13244:                cont => 'Content actions for all',
13245:                addf => 'Add as folder/file',
13246:                incd => 'Include as dependency for a displayed file',
13247:                disc => 'Discard',
13248:                no   => 'No',
13249:                yes  => 'Yes',
13250:                save => 'Save',
13251:     );
13252:     my $output = <<"END";
13253: <form name="$form" method="post" action="">
13254: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13255: <label>
13256:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13257: </label>
13258: &nbsp;
13259: <label>
13260:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13261: </span>
13262: </p>
13263: <input type="hidden" name="phase" value="decompress_cleanup" />
13264: <br />$lt{'hows'}
13265: <div class="LC_columnSection">
13266:   <fieldset>
13267:     <legend>$lt{'cont'}</legend>
13268:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13269:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13270:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13271:   </fieldset>
13272: </div>
13273: END
13274:     return $output.
13275:            &start_data_table()."\n".
13276:            $display."\n".
13277:            &end_data_table()."\n".
13278:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13279:            $hiddenelem.
13280:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13281:            '</form>';
13282: }
13283: 
13284: sub archive_javascript {
13285:     my ($startcount,$numitems,$titles,$children) = @_;
13286:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13287:     my $maintitle = $env{'form.comment'};
13288:     my $scripttag = <<START;
13289: <script type="text/javascript">
13290: // <![CDATA[
13291: 
13292: function checkAll(form,prefix) {
13293:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13294:     for (var i=0; i < form.elements.length; i++) {
13295:         var id = form.elements[i].id;
13296:         if ((id != '') && (id != undefined)) {
13297:             if (idstr.test(id)) {
13298:                 if (form.elements[i].type == 'radio') {
13299:                     form.elements[i].checked = true;
13300:                     var nostart = i-$startcount;
13301:                     var offset = nostart%7;
13302:                     var count = (nostart-offset)/7;    
13303:                     dependencyCheck(form,count,offset);
13304:                 }
13305:             }
13306:         }
13307:     }
13308: }
13309: 
13310: function propagateCheck(form,count) {
13311:     if (count > 0) {
13312:         var startelement = $startcount + ((count-1) * 7);
13313:         for (var j=1; j<6; j++) {
13314:             if ((j != 2) && (j != 4)) {
13315:                 var item = startelement + j; 
13316:                 if (form.elements[item].type == 'radio') {
13317:                     if (form.elements[item].checked) {
13318:                         containerCheck(form,count,j);
13319:                         break;
13320:                     }
13321:                 }
13322:             }
13323:         }
13324:     }
13325: }
13326: 
13327: numitems = $numitems
13328: var titles = new Array(numitems);
13329: var parents = new Array(numitems);
13330: for (var i=0; i<numitems; i++) {
13331:     parents[i] = new Array;
13332: }
13333: var maintitle = '$maintitle';
13334: 
13335: START
13336: 
13337:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13338:         my @contents = split(/:/,$children->{$container});
13339:         for (my $i=0; $i<@contents; $i ++) {
13340:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13341:         }
13342:     }
13343: 
13344:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13345:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13346:     }
13347: 
13348:     $scripttag .= <<END;
13349: 
13350: function containerCheck(form,count,offset) {
13351:     if (count > 0) {
13352:         dependencyCheck(form,count,offset);
13353:         var item = (offset+$startcount)+7*(count-1);
13354:         form.elements[item].checked = true;
13355:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13356:             if (parents[count].length > 0) {
13357:                 for (var j=0; j<parents[count].length; j++) {
13358:                     containerCheck(form,parents[count][j],offset);
13359:                 }
13360:             }
13361:         }
13362:     }
13363: }
13364: 
13365: function dependencyCheck(form,count,offset) {
13366:     if (count > 0) {
13367:         var chosen = (offset+$startcount)+7*(count-1);
13368:         var depitem = $startcount + ((count-1) * 7) + 4;
13369:         var currtype = form.elements[depitem].type;
13370:         if (form.elements[chosen].value == 'dependency') {
13371:             document.getElementById('arc_depon_'+count).style.display='block'; 
13372:             form.elements[depitem].options.length = 0;
13373:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13374:             for (var i=1; i<=numitems; i++) {
13375:                 if (i == count) {
13376:                     continue;
13377:                 }
13378:                 var startelement = $startcount + (i-1) * 7;
13379:                 for (var j=1; j<6; j++) {
13380:                     if ((j != 2) && (j!= 4)) {
13381:                         var item = startelement + j;
13382:                         if (form.elements[item].type == 'radio') {
13383:                             if (form.elements[item].checked) {
13384:                                 if (form.elements[item].value == 'display') {
13385:                                     var n = form.elements[depitem].options.length;
13386:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13387:                                 }
13388:                             }
13389:                         }
13390:                     }
13391:                 }
13392:             }
13393:         } else {
13394:             document.getElementById('arc_depon_'+count).style.display='none';
13395:             form.elements[depitem].options.length = 0;
13396:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13397:         }
13398:         titleCheck(form,count,offset);
13399:     }
13400: }
13401: 
13402: function propagateSelect(form,count,offset) {
13403:     if (count > 0) {
13404:         var item = (1+offset+$startcount)+7*(count-1);
13405:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13406:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13407:             if (parents[count].length > 0) {
13408:                 for (var j=0; j<parents[count].length; j++) {
13409:                     containerSelect(form,parents[count][j],offset,picked);
13410:                 }
13411:             }
13412:         }
13413:     }
13414: }
13415: 
13416: function containerSelect(form,count,offset,picked) {
13417:     if (count > 0) {
13418:         var item = (offset+$startcount)+7*(count-1);
13419:         if (form.elements[item].type == 'radio') {
13420:             if (form.elements[item].value == 'dependency') {
13421:                 if (form.elements[item+1].type == 'select-one') {
13422:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13423:                         if (form.elements[item+1].options[i].value == picked) {
13424:                             form.elements[item+1].selectedIndex = i;
13425:                             break;
13426:                         }
13427:                     }
13428:                 }
13429:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13430:                     if (parents[count].length > 0) {
13431:                         for (var j=0; j<parents[count].length; j++) {
13432:                             containerSelect(form,parents[count][j],offset,picked);
13433:                         }
13434:                     }
13435:                 }
13436:             }
13437:         }
13438:     }
13439: }
13440: 
13441: function titleCheck(form,count,offset) {
13442:     if (count > 0) {
13443:         var chosen = (offset+$startcount)+7*(count-1);
13444:         var depitem = $startcount + ((count-1) * 7) + 2;
13445:         var currtype = form.elements[depitem].type;
13446:         if (form.elements[chosen].value == 'display') {
13447:             document.getElementById('arc_title_'+count).style.display='block';
13448:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13449:                 document.getElementById('archive_title_'+count).value=maintitle;
13450:             }
13451:         } else {
13452:             document.getElementById('arc_title_'+count).style.display='none';
13453:             if (currtype == 'text') { 
13454:                 document.getElementById('archive_title_'+count).value='';
13455:             }
13456:         }
13457:     }
13458:     return;
13459: }
13460: 
13461: // ]]>
13462: </script>
13463: END
13464:     return $scripttag;
13465: }
13466: 
13467: sub process_extracted_files {
13468:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13469:     my $numitems = $env{'form.archive_count'};
13470:     return if ((!$numitems) || ($numitems =~ /\D/));
13471:     my @ids=&Apache::lonnet::current_machine_ids();
13472:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13473:         %folders,%containers,%mapinner,%prompttofetch);
13474:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13475:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13476:         $prefix = &LONCAPA::propath($docudom,$docuname);
13477:         $pathtocheck = "$dir_root/$destination";
13478:         $dir = $dir_root;
13479:         $ishome = 1;
13480:     } else {
13481:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13482:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13483:         $dir = "$dir_root/$docudom/$docuname";
13484:     }
13485:     my $currdir = "$dir_root/$destination";
13486:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13487:     if ($env{'form.folderpath'}) {
13488:         my @items = split('&',$env{'form.folderpath'});
13489:         $folders{'0'} = $items[-2];
13490:         if ($env{'form.folderpath'} =~ /\:1$/) {
13491:             $containers{'0'}='page';
13492:         } else {  
13493:             $containers{'0'}='sequence';
13494:         }
13495:     }
13496:     my @archdirs = &get_env_multiple('form.archive_directory');
13497:     if ($numitems) {
13498:         for (my $i=1; $i<=$numitems; $i++) {
13499:             my $path = $env{'form.archive_content_'.$i};
13500:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13501:                 my $item = $1;
13502:                 $toplevelitems{$item} = $i;
13503:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13504:                     $is_dir{$item} = 1;
13505:                 }
13506:             }
13507:         }
13508:     }
13509:     my ($output,%children,%parent,%titles,%dirorder,$result);
13510:     if (keys(%toplevelitems) > 0) {
13511:         my @contents = sort(keys(%toplevelitems));
13512:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13513:                                            \%parent,\@contents,\%dirorder,\%titles);
13514:     }
13515:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13516:     if ($numitems) {
13517:         for (my $i=1; $i<=$numitems; $i++) {
13518:             next if ($env{'form.archive_'.$i} eq 'dependency');
13519:             my $path = $env{'form.archive_content_'.$i};
13520:             if ($path =~ /^\Q$pathtocheck\E/) {
13521:                 if ($env{'form.archive_'.$i} eq 'discard') {
13522:                     if ($prefix ne '' && $path ne '') {
13523:                         if (-e $prefix.$path) {
13524:                             if ((@archdirs > 0) && 
13525:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13526:                                 $todeletedir{$prefix.$path} = 1;
13527:                             } else {
13528:                                 $todelete{$prefix.$path} = 1;
13529:                             }
13530:                         }
13531:                     }
13532:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13533:                     my ($docstitle,$title,$url,$outer);
13534:                     ($title) = ($path =~ m{/([^/]+)$});
13535:                     $docstitle = $env{'form.archive_title_'.$i};
13536:                     if ($docstitle eq '') {
13537:                         $docstitle = $title;
13538:                     }
13539:                     $outer = 0;
13540:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13541:                         if (@{$dirorder{$i}} > 0) {
13542:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13543:                                 if ($env{'form.archive_'.$item} eq 'display') {
13544:                                     $outer = $item;
13545:                                     last;
13546:                                 }
13547:                             }
13548:                         }
13549:                     }
13550:                     my ($errtext,$fatal) = 
13551:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13552:                                                '/'.$folders{$outer}.'.'.
13553:                                                $containers{$outer});
13554:                     next if ($fatal);
13555:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13556:                         if ($context eq 'coursedocs') {
13557:                             $mapinner{$i} = time;
13558:                             $folders{$i} = 'default_'.$mapinner{$i};
13559:                             $containers{$i} = 'sequence';
13560:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13561:                                       $folders{$i}.'.'.$containers{$i};
13562:                             my $newidx = &LONCAPA::map::getresidx();
13563:                             $LONCAPA::map::resources[$newidx]=
13564:                                 $docstitle.':'.$url.':false:normal:res';
13565:                             push(@LONCAPA::map::order,$newidx);
13566:                             my ($outtext,$errtext) =
13567:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13568:                                                         $docuname.'/'.$folders{$outer}.
13569:                                                         '.'.$containers{$outer},1,1);
13570:                             $newseqid{$i} = $newidx;
13571:                             unless ($errtext) {
13572:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13573:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
13574:                                             '</li>'."\n";
13575:                             }
13576:                         }
13577:                     } else {
13578:                         if ($context eq 'coursedocs') {
13579:                             my $newidx=&LONCAPA::map::getresidx();
13580:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13581:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13582:                                       $title;
13583:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13584:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13585:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13586:                                 }
13587:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13588:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13589:                                 }
13590:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13591:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13592:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13593:                                         unless ($ishome) {
13594:                                             my $fetch = "$newdest{$i}/$title";
13595:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13596:                                             $prompttofetch{$fetch} = 1;
13597:                                         }
13598:                                     }
13599:                                 }
13600:                                 $LONCAPA::map::resources[$newidx]=
13601:                                     $docstitle.':'.$url.':false:normal:res';
13602:                                 push(@LONCAPA::map::order, $newidx);
13603:                                 my ($outtext,$errtext)=
13604:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13605:                                                             $docuname.'/'.$folders{$outer}.
13606:                                                             '.'.$containers{$outer},1,1);
13607:                                 unless ($errtext) {
13608:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13609:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13610:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13611:                                                    '</li>'."\n";
13612:                                     }
13613:                                 }
13614:                             } else {
13615:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13616:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13617:                             }
13618:                         }
13619:                     }
13620:                 }
13621:             } else {
13622:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13623:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
13624:             }
13625:         }
13626:         for (my $i=1; $i<=$numitems; $i++) {
13627:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13628:             my $path = $env{'form.archive_content_'.$i};
13629:             if ($path =~ /^\Q$pathtocheck\E/) {
13630:                 my ($title) = ($path =~ m{/([^/]+)$});
13631:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13632:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13633:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13634:                         my ($itemidx,$fullpath,$relpath);
13635:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13636:                             my $container = $dirorder{$referrer{$i}}->[-1];
13637:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13638:                                 if ($dirorder{$i}->[$j] eq $container) {
13639:                                     $itemidx = $j;
13640:                                 }
13641:                             }
13642:                         }
13643:                         if ($itemidx eq '') {
13644:                             $itemidx =  0;
13645:                         } 
13646:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13647:                             if ($mapinner{$referrer{$i}}) {
13648:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13649:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13650:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13651:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13652:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13653:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13654:                                             if (!-e $fullpath) {
13655:                                                 mkdir($fullpath,0755);
13656:                                             }
13657:                                         }
13658:                                     } else {
13659:                                         last;
13660:                                     }
13661:                                 }
13662:                             }
13663:                         } elsif ($newdest{$referrer{$i}}) {
13664:                             $fullpath = $newdest{$referrer{$i}};
13665:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13666:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13667:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13668:                                     last;
13669:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13670:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13671:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13672:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13673:                                         if (!-e $fullpath) {
13674:                                             mkdir($fullpath,0755);
13675:                                         }
13676:                                     }
13677:                                 } else {
13678:                                     last;
13679:                                 }
13680:                             }
13681:                         }
13682:                         if ($fullpath ne '') {
13683:                             if (-e "$prefix$path") {
13684:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13685:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13686:                                 }
13687:                             }
13688:                             if (-e "$fullpath/$title") {
13689:                                 my $showpath;
13690:                                 if ($relpath ne '') {
13691:                                     $showpath = "$relpath/$title";
13692:                                 } else {
13693:                                     $showpath = "/$title";
13694:                                 } 
13695:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13696:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13697:                                            '</li>'."\n";
13698:                                 unless ($ishome) {
13699:                                     my $fetch = "$fullpath/$title";
13700:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
13701:                                     $prompttofetch{$fetch} = 1;
13702:                                 }
13703:                             }
13704:                         }
13705:                     }
13706:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13707:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13708:                                     &HTML::Entities::encode($path,'<>&"'),
13709:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13710:                                 '<br />';
13711:                 }
13712:             } else {
13713:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13714:                                 &HTML::Entities::encode($path)).'<br />';
13715:             }
13716:         }
13717:         if (keys(%todelete)) {
13718:             foreach my $key (keys(%todelete)) {
13719:                 unlink($key);
13720:             }
13721:         }
13722:         if (keys(%todeletedir)) {
13723:             foreach my $key (keys(%todeletedir)) {
13724:                 rmdir($key);
13725:             }
13726:         }
13727:         foreach my $dir (sort(keys(%is_dir))) {
13728:             if (($pathtocheck ne '') && ($dir ne ''))  {
13729:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13730:             }
13731:         }
13732:         if ($result ne '') {
13733:             $output .= '<ul>'."\n".
13734:                        $result."\n".
13735:                        '</ul>';
13736:         }
13737:         unless ($ishome) {
13738:             my $replicationfail;
13739:             foreach my $item (keys(%prompttofetch)) {
13740:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13741:                 unless ($fetchresult eq 'ok') {
13742:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13743:                 }
13744:             }
13745:             if ($replicationfail) {
13746:                 $output .= '<p class="LC_error">'.
13747:                            &mt('Course home server failed to retrieve:').'<ul>'.
13748:                            $replicationfail.
13749:                            '</ul></p>';
13750:             }
13751:         }
13752:     } else {
13753:         $warning = &mt('No items found in archive.');
13754:     }
13755:     if ($error) {
13756:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13757:                    $error.'</p>'."\n";
13758:     }
13759:     if ($warning) {
13760:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13761:     }
13762:     return $output;
13763: }
13764: 
13765: sub cleanup_empty_dirs {
13766:     my ($path) = @_;
13767:     if (($path ne '') && (-d $path)) {
13768:         if (opendir(my $dirh,$path)) {
13769:             my @dircontents = grep(!/^\./,readdir($dirh));
13770:             my $numitems = 0;
13771:             foreach my $item (@dircontents) {
13772:                 if (-d "$path/$item") {
13773:                     &cleanup_empty_dirs("$path/$item");
13774:                     if (-e "$path/$item") {
13775:                         $numitems ++;
13776:                     }
13777:                 } else {
13778:                     $numitems ++;
13779:                 }
13780:             }
13781:             if ($numitems == 0) {
13782:                 rmdir($path);
13783:             }
13784:             closedir($dirh);
13785:         }
13786:     }
13787:     return;
13788: }
13789: 
13790: =pod
13791: 
13792: =item * &get_folder_hierarchy()
13793: 
13794: Provides hierarchy of names of folders/sub-folders containing the current
13795: item,
13796: 
13797: Inputs: 3
13798:      - $navmap - navmaps object
13799: 
13800:      - $map - url for map (either the trigger itself, or map containing
13801:                            the resource, which is the trigger).
13802: 
13803:      - $showitem - 1 => show title for map itself; 0 => do not show.
13804: 
13805: Outputs: 1 @pathitems - array of folder/subfolder names.
13806: 
13807: =cut
13808: 
13809: sub get_folder_hierarchy {
13810:     my ($navmap,$map,$showitem) = @_;
13811:     my @pathitems;
13812:     if (ref($navmap)) {
13813:         my $mapres = $navmap->getResourceByUrl($map);
13814:         if (ref($mapres)) {
13815:             my $pcslist = $mapres->map_hierarchy();
13816:             if ($pcslist ne '') {
13817:                 my @pcs = split(/,/,$pcslist);
13818:                 foreach my $pc (@pcs) {
13819:                     if ($pc == 1) {
13820:                         push(@pathitems,&mt('Main Content'));
13821:                     } else {
13822:                         my $res = $navmap->getByMapPc($pc);
13823:                         if (ref($res)) {
13824:                             my $title = $res->compTitle();
13825:                             $title =~ s/\W+/_/g;
13826:                             if ($title ne '') {
13827:                                 push(@pathitems,$title);
13828:                             }
13829:                         }
13830:                     }
13831:                 }
13832:             }
13833:             if ($showitem) {
13834:                 if ($mapres->{ID} eq '0.0') {
13835:                     push(@pathitems,&mt('Main Content'));
13836:                 } else {
13837:                     my $maptitle = $mapres->compTitle();
13838:                     $maptitle =~ s/\W+/_/g;
13839:                     if ($maptitle ne '') {
13840:                         push(@pathitems,$maptitle);
13841:                     }
13842:                 }
13843:             }
13844:         }
13845:     }
13846:     return @pathitems;
13847: }
13848: 
13849: =pod
13850: 
13851: =item * &get_turnedin_filepath()
13852: 
13853: Determines path in a user's portfolio file for storage of files uploaded
13854: to a specific essayresponse or dropbox item.
13855: 
13856: Inputs: 3 required + 1 optional.
13857: $symb is symb for resource, $uname and $udom are for current user (required).
13858: $caller is optional (can be "submission", if routine is called when storing
13859: an upoaded file when "Submit Answer" button was pressed).
13860: 
13861: Returns array containing $path and $multiresp. 
13862: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13863: than one file upload item.  Callers of routine should append partid as a 
13864: subdirectory to $path in cases where $multiresp is 1.
13865: 
13866: Called by: homework/essayresponse.pm and homework/structuretags.pm
13867: 
13868: =cut
13869: 
13870: sub get_turnedin_filepath {
13871:     my ($symb,$uname,$udom,$caller) = @_;
13872:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13873:     my $turnindir;
13874:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13875:     $turnindir = $userhash{'turnindir'};
13876:     my ($path,$multiresp);
13877:     if ($turnindir eq '') {
13878:         if ($caller eq 'submission') {
13879:             $turnindir = &mt('turned in');
13880:             $turnindir =~ s/\W+/_/g;
13881:             my %newhash = (
13882:                             'turnindir' => $turnindir,
13883:                           );
13884:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13885:         }
13886:     }
13887:     if ($turnindir ne '') {
13888:         $path = '/'.$turnindir.'/';
13889:         my ($multipart,$turnin,@pathitems);
13890:         my $navmap = Apache::lonnavmaps::navmap->new();
13891:         if (defined($navmap)) {
13892:             my $mapres = $navmap->getResourceByUrl($map);
13893:             if (ref($mapres)) {
13894:                 my $pcslist = $mapres->map_hierarchy();
13895:                 if ($pcslist ne '') {
13896:                     foreach my $pc (split(/,/,$pcslist)) {
13897:                         my $res = $navmap->getByMapPc($pc);
13898:                         if (ref($res)) {
13899:                             my $title = $res->compTitle();
13900:                             $title =~ s/\W+/_/g;
13901:                             if ($title ne '') {
13902:                                 if (($pc > 1) && (length($title) > 12)) {
13903:                                     $title = substr($title,0,12);
13904:                                 }
13905:                                 push(@pathitems,$title);
13906:                             }
13907:                         }
13908:                     }
13909:                 }
13910:                 my $maptitle = $mapres->compTitle();
13911:                 $maptitle =~ s/\W+/_/g;
13912:                 if ($maptitle ne '') {
13913:                     if (length($maptitle) > 12) {
13914:                         $maptitle = substr($maptitle,0,12);
13915:                     }
13916:                     push(@pathitems,$maptitle);
13917:                 }
13918:                 unless ($env{'request.state'} eq 'construct') {
13919:                     my $res = $navmap->getBySymb($symb);
13920:                     if (ref($res)) {
13921:                         my $partlist = $res->parts();
13922:                         my $totaluploads = 0;
13923:                         if (ref($partlist) eq 'ARRAY') {
13924:                             foreach my $part (@{$partlist}) {
13925:                                 my @types = $res->responseType($part);
13926:                                 my @ids = $res->responseIds($part);
13927:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13928:                                     if ($types[$i] eq 'essay') {
13929:                                         my $partid = $part.'_'.$ids[$i];
13930:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13931:                                             $totaluploads ++;
13932:                                         }
13933:                                     }
13934:                                 }
13935:                             }
13936:                             if ($totaluploads > 1) {
13937:                                 $multiresp = 1;
13938:                             }
13939:                         }
13940:                     }
13941:                 }
13942:             } else {
13943:                 return;
13944:             }
13945:         } else {
13946:             return;
13947:         }
13948:         my $restitle=&Apache::lonnet::gettitle($symb);
13949:         $restitle =~ s/\W+/_/g;
13950:         if ($restitle eq '') {
13951:             $restitle = ($resurl =~ m{/[^/]+$});
13952:             if ($restitle eq '') {
13953:                 $restitle = time;
13954:             }
13955:         }
13956:         if (length($restitle) > 12) {
13957:             $restitle = substr($restitle,0,12);
13958:         }
13959:         push(@pathitems,$restitle);
13960:         $path .= join('/',@pathitems);
13961:     }
13962:     return ($path,$multiresp);
13963: }
13964: 
13965: =pod
13966: 
13967: =back
13968: 
13969: =head1 CSV Upload/Handling functions
13970: 
13971: =over 4
13972: 
13973: =item * &upfile_store($r)
13974: 
13975: Store uploaded file, $r should be the HTTP Request object,
13976: needs $env{'form.upfile'}
13977: returns $datatoken to be put into hidden field
13978: 
13979: =cut
13980: 
13981: sub upfile_store {
13982:     my $r=shift;
13983:     $env{'form.upfile'}=~s/\r/\n/gs;
13984:     $env{'form.upfile'}=~s/\f/\n/gs;
13985:     $env{'form.upfile'}=~s/\n+/\n/gs;
13986:     $env{'form.upfile'}=~s/\n+$//gs;
13987: 
13988:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13989:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13990:                                      time.'_'.$$);
13991:     return if ($datatoken eq '');
13992: 
13993:     {
13994:         my $datafile = $r->dir_config('lonDaemons').
13995:                            '/tmp/'.$datatoken.'.tmp';
13996:         if ( open(my $fh,'>',$datafile) ) {
13997:             print $fh $env{'form.upfile'};
13998:             close($fh);
13999:         }
14000:     }
14001:     return $datatoken;
14002: }
14003: 
14004: =pod
14005: 
14006: =item * &load_tmp_file($r,$datatoken)
14007: 
14008: Load uploaded file from tmp, $r should be the HTTP Request object,
14009: $datatoken is the name to assign to the temporary file.
14010: sets $env{'form.upfile'} to the contents of the file
14011: 
14012: =cut
14013: 
14014: sub load_tmp_file {
14015:     my ($r,$datatoken) = @_;
14016:     return if ($datatoken eq '');
14017:     my @studentdata=();
14018:     {
14019:         my $studentfile = $r->dir_config('lonDaemons').
14020:                               '/tmp/'.$datatoken.'.tmp';
14021:         if ( open(my $fh,'<',$studentfile) ) {
14022:             @studentdata=<$fh>;
14023:             close($fh);
14024:         }
14025:     }
14026:     $env{'form.upfile'}=join('',@studentdata);
14027: }
14028: 
14029: sub valid_datatoken {
14030:     my ($datatoken) = @_;
14031:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14032:         return $datatoken;
14033:     }
14034:     return;
14035: }
14036: 
14037: =pod
14038: 
14039: =item * &upfile_record_sep()
14040: 
14041: Separate uploaded file into records
14042: returns array of records,
14043: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14044: 
14045: =cut
14046: 
14047: sub upfile_record_sep {
14048:     if ($env{'form.upfiletype'} eq 'xml') {
14049:     } else {
14050: 	my @records;
14051: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14052: 	    if ($line=~/^\s*$/) { next; }
14053: 	    push(@records,$line);
14054: 	}
14055: 	return @records;
14056:     }
14057: }
14058: 
14059: =pod
14060: 
14061: =item * &record_sep($record)
14062: 
14063: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14064: 
14065: =cut
14066: 
14067: sub takeleft {
14068:     my $index=shift;
14069:     return substr('0000'.$index,-4,4);
14070: }
14071: 
14072: sub record_sep {
14073:     my $record=shift;
14074:     my %components=();
14075:     if ($env{'form.upfiletype'} eq 'xml') {
14076:     } elsif ($env{'form.upfiletype'} eq 'space') {
14077:         my $i=0;
14078:         foreach my $field (split(/\s+/,$record)) {
14079:             $field=~s/^(\"|\')//;
14080:             $field=~s/(\"|\')$//;
14081:             $components{&takeleft($i)}=$field;
14082:             $i++;
14083:         }
14084:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14085:         my $i=0;
14086:         foreach my $field (split(/\t/,$record)) {
14087:             $field=~s/^(\"|\')//;
14088:             $field=~s/(\"|\')$//;
14089:             $components{&takeleft($i)}=$field;
14090:             $i++;
14091:         }
14092:     } else {
14093:         my $separator=',';
14094:         if ($env{'form.upfiletype'} eq 'semisv') {
14095:             $separator=';';
14096:         }
14097:         my $i=0;
14098: # the character we are looking for to indicate the end of a quote or a record 
14099:         my $looking_for=$separator;
14100: # do not add the characters to the fields
14101:         my $ignore=0;
14102: # we just encountered a separator (or the beginning of the record)
14103:         my $just_found_separator=1;
14104: # store the field we are working on here
14105:         my $field='';
14106: # work our way through all characters in record
14107:         foreach my $character ($record=~/(.)/g) {
14108:             if ($character eq $looking_for) {
14109:                if ($character ne $separator) {
14110: # Found the end of a quote, again looking for separator
14111:                   $looking_for=$separator;
14112:                   $ignore=1;
14113:                } else {
14114: # Found a separator, store away what we got
14115:                   $components{&takeleft($i)}=$field;
14116: 	          $i++;
14117:                   $just_found_separator=1;
14118:                   $ignore=0;
14119:                   $field='';
14120:                }
14121:                next;
14122:             }
14123: # single or double quotation marks after a separator indicate beginning of a quote
14124: # we are now looking for the end of the quote and need to ignore separators
14125:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14126:                $looking_for=$character;
14127:                next;
14128:             }
14129: # ignore would be true after we reached the end of a quote
14130:             if ($ignore) { next; }
14131:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14132:             $field.=$character;
14133:             $just_found_separator=0; 
14134:         }
14135: # catch the very last entry, since we never encountered the separator
14136:         $components{&takeleft($i)}=$field;
14137:     }
14138:     return %components;
14139: }
14140: 
14141: ######################################################
14142: ######################################################
14143: 
14144: =pod
14145: 
14146: =item * &upfile_select_html()
14147: 
14148: Return HTML code to select a file from the users machine and specify 
14149: the file type.
14150: 
14151: =cut
14152: 
14153: ######################################################
14154: ######################################################
14155: sub upfile_select_html {
14156:     my %Types = (
14157:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14158:                  semisv => &mt('Semicolon separated values'),
14159:                  space => &mt('Space separated'),
14160:                  tab   => &mt('Tabulator separated'),
14161: #                 xml   => &mt('HTML/XML'),
14162:                  );
14163:     my $Str = '<input type="file" name="upfile" size="50" />'.
14164:         '<br />'.&mt('Type').': <select name="upfiletype">';
14165:     foreach my $type (sort(keys(%Types))) {
14166:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14167:     }
14168:     $Str .= "</select>\n";
14169:     return $Str;
14170: }
14171: 
14172: sub get_samples {
14173:     my ($records,$toget) = @_;
14174:     my @samples=({});
14175:     my $got=0;
14176:     foreach my $rec (@$records) {
14177: 	my %temp = &record_sep($rec);
14178: 	if (! grep(/\S/, values(%temp))) { next; }
14179: 	if (%temp) {
14180: 	    $samples[$got]=\%temp;
14181: 	    $got++;
14182: 	    if ($got == $toget) { last; }
14183: 	}
14184:     }
14185:     return \@samples;
14186: }
14187: 
14188: ######################################################
14189: ######################################################
14190: 
14191: =pod
14192: 
14193: =item * &csv_print_samples($r,$records)
14194: 
14195: Prints a table of sample values from each column uploaded $r is an
14196: Apache Request ref, $records is an arrayref from
14197: &Apache::loncommon::upfile_record_sep
14198: 
14199: =cut
14200: 
14201: ######################################################
14202: ######################################################
14203: sub csv_print_samples {
14204:     my ($r,$records) = @_;
14205:     my $samples = &get_samples($records,5);
14206: 
14207:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14208:               &start_data_table_header_row());
14209:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14210:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14211:     $r->print(&end_data_table_header_row());
14212:     foreach my $hash (@$samples) {
14213: 	$r->print(&start_data_table_row());
14214: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14215: 	    $r->print('<td>');
14216: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14217: 	    $r->print('</td>');
14218: 	}
14219: 	$r->print(&end_data_table_row());
14220:     }
14221:     $r->print(&end_data_table().'<br />'."\n");
14222: }
14223: 
14224: ######################################################
14225: ######################################################
14226: 
14227: =pod
14228: 
14229: =item * &csv_print_select_table($r,$records,$d)
14230: 
14231: Prints a table to create associations between values and table columns.
14232: 
14233: $r is an Apache Request ref,
14234: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14235: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14236: 
14237: =cut
14238: 
14239: ######################################################
14240: ######################################################
14241: sub csv_print_select_table {
14242:     my ($r,$records,$d) = @_;
14243:     my $i=0;
14244:     my $samples = &get_samples($records,1);
14245:     $r->print(&mt('Associate columns with student attributes.')."\n".
14246: 	      &start_data_table().&start_data_table_header_row().
14247:               '<th>'.&mt('Attribute').'</th>'.
14248:               '<th>'.&mt('Column').'</th>'.
14249:               &end_data_table_header_row()."\n");
14250:     foreach my $array_ref (@$d) {
14251: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14252: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14253: 
14254: 	$r->print('<td><select name="f'.$i.'"'.
14255: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14256: 	$r->print('<option value="none"></option>');
14257: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14258: 	    $r->print('<option value="'.$sample.'"'.
14259:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14260:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14261: 	}
14262: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14263: 	$i++;
14264:     }
14265:     $r->print(&end_data_table());
14266:     $i--;
14267:     return $i;
14268: }
14269: 
14270: ######################################################
14271: ######################################################
14272: 
14273: =pod
14274: 
14275: =item * &csv_samples_select_table($r,$records,$d)
14276: 
14277: Prints a table of sample values from the upload and can make associate samples to internal names.
14278: 
14279: $r is an Apache Request ref,
14280: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14281: $d is an array of 2 element arrays (internal name, displayed name)
14282: 
14283: =cut
14284: 
14285: ######################################################
14286: ######################################################
14287: sub csv_samples_select_table {
14288:     my ($r,$records,$d) = @_;
14289:     my $i=0;
14290:     #
14291:     my $max_samples = 5;
14292:     my $samples = &get_samples($records,$max_samples);
14293:     $r->print(&start_data_table().
14294:               &start_data_table_header_row().'<th>'.
14295:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14296:               &end_data_table_header_row());
14297: 
14298:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14299: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14300: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14301: 	foreach my $option (@$d) {
14302: 	    my ($value,$display,$defaultcol)=@{ $option };
14303: 	    $r->print('<option value="'.$value.'"'.
14304:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14305:                       $display.'</option>');
14306: 	}
14307: 	$r->print('</select></td><td>');
14308: 	foreach my $line (0..($max_samples-1)) {
14309: 	    if (defined($samples->[$line]{$key})) { 
14310: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14311: 	    }
14312: 	}
14313: 	$r->print('</td>'.&end_data_table_row());
14314: 	$i++;
14315:     }
14316:     $r->print(&end_data_table());
14317:     $i--;
14318:     return($i);
14319: }
14320: 
14321: ######################################################
14322: ######################################################
14323: 
14324: =pod
14325: 
14326: =item * &clean_excel_name($name)
14327: 
14328: Returns a replacement for $name which does not contain any illegal characters.
14329: 
14330: =cut
14331: 
14332: ######################################################
14333: ######################################################
14334: sub clean_excel_name {
14335:     my ($name) = @_;
14336:     $name =~ s/[:\*\?\/\\]//g;
14337:     if (length($name) > 31) {
14338:         $name = substr($name,0,31);
14339:     }
14340:     return $name;
14341: }
14342: 
14343: =pod
14344: 
14345: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14346: 
14347: Returns either 1 or undef
14348: 
14349: 1 if the part is to be hidden, undef if it is to be shown
14350: 
14351: Arguments are:
14352: 
14353: $id the id of the part to be checked
14354: $symb, optional the symb of the resource to check
14355: $udom, optional the domain of the user to check for
14356: $uname, optional the username of the user to check for
14357: 
14358: =cut
14359: 
14360: sub check_if_partid_hidden {
14361:     my ($id,$symb,$udom,$uname) = @_;
14362:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14363: 					 $symb,$udom,$uname);
14364:     my $truth=1;
14365:     #if the string starts with !, then the list is the list to show not hide
14366:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14367:     my @hiddenlist=split(/,/,$hiddenparts);
14368:     foreach my $checkid (@hiddenlist) {
14369: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14370:     }
14371:     return !$truth;
14372: }
14373: 
14374: 
14375: ############################################################
14376: ############################################################
14377: 
14378: =pod
14379: 
14380: =back 
14381: 
14382: =head1 cgi-bin script and graphing routines
14383: 
14384: =over 4
14385: 
14386: =item * &get_cgi_id()
14387: 
14388: Inputs: none
14389: 
14390: Returns an id which can be used to pass environment variables
14391: to various cgi-bin scripts.  These environment variables will
14392: be removed from the users environment after a given time by
14393: the routine &Apache::lonnet::transfer_profile_to_env.
14394: 
14395: =cut
14396: 
14397: ############################################################
14398: ############################################################
14399: my $uniq=0;
14400: sub get_cgi_id {
14401:     $uniq=($uniq+1)%100000;
14402:     return (time.'_'.$$.'_'.$uniq);
14403: }
14404: 
14405: ############################################################
14406: ############################################################
14407: 
14408: =pod
14409: 
14410: =item * &DrawBarGraph()
14411: 
14412: Facilitates the plotting of data in a (stacked) bar graph.
14413: Puts plot definition data into the users environment in order for 
14414: graph.png to plot it.  Returns an <img> tag for the plot.
14415: The bars on the plot are labeled '1','2',...,'n'.
14416: 
14417: Inputs:
14418: 
14419: =over 4
14420: 
14421: =item $Title: string, the title of the plot
14422: 
14423: =item $xlabel: string, text describing the X-axis of the plot
14424: 
14425: =item $ylabel: string, text describing the Y-axis of the plot
14426: 
14427: =item $Max: scalar, the maximum Y value to use in the plot
14428: If $Max is < any data point, the graph will not be rendered.
14429: 
14430: =item $colors: array ref holding the colors to be used for the data sets when
14431: they are plotted.  If undefined, default values will be used.
14432: 
14433: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14434: 
14435: =item @Values: An array of array references.  Each array reference holds data
14436: to be plotted in a stacked bar chart.
14437: 
14438: =item If the final element of @Values is a hash reference the key/value
14439: pairs will be added to the graph definition.
14440: 
14441: =back
14442: 
14443: Returns:
14444: 
14445: An <img> tag which references graph.png and the appropriate identifying
14446: information for the plot.
14447: 
14448: =cut
14449: 
14450: ############################################################
14451: ############################################################
14452: sub DrawBarGraph {
14453:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14454:     #
14455:     if (! defined($colors)) {
14456:         $colors = ['#33ff00', 
14457:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14458:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14459:                   ]; 
14460:     }
14461:     my $extra_settings = {};
14462:     if (ref($Values[-1]) eq 'HASH') {
14463:         $extra_settings = pop(@Values);
14464:     }
14465:     #
14466:     my $identifier = &get_cgi_id();
14467:     my $id = 'cgi.'.$identifier;        
14468:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14469:         return '';
14470:     }
14471:     #
14472:     my @Labels;
14473:     if (defined($labels)) {
14474:         @Labels = @$labels;
14475:     } else {
14476:         for (my $i=0;$i<@{$Values[0]};$i++) {
14477:             push(@Labels,$i+1);
14478:         }
14479:     }
14480:     #
14481:     my $NumBars = scalar(@{$Values[0]});
14482:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14483:     my %ValuesHash;
14484:     my $NumSets=1;
14485:     foreach my $array (@Values) {
14486:         next if (! ref($array));
14487:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14488:             join(',',@$array);
14489:     }
14490:     #
14491:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14492:     if ($NumBars < 3) {
14493:         $width = 120+$NumBars*32;
14494:         $xskip = 1;
14495:         $bar_width = 30;
14496:     } elsif ($NumBars < 5) {
14497:         $width = 120+$NumBars*20;
14498:         $xskip = 1;
14499:         $bar_width = 20;
14500:     } elsif ($NumBars < 10) {
14501:         $width = 120+$NumBars*15;
14502:         $xskip = 1;
14503:         $bar_width = 15;
14504:     } elsif ($NumBars <= 25) {
14505:         $width = 120+$NumBars*11;
14506:         $xskip = 5;
14507:         $bar_width = 8;
14508:     } elsif ($NumBars <= 50) {
14509:         $width = 120+$NumBars*8;
14510:         $xskip = 5;
14511:         $bar_width = 4;
14512:     } else {
14513:         $width = 120+$NumBars*8;
14514:         $xskip = 5;
14515:         $bar_width = 4;
14516:     }
14517:     #
14518:     $Max = 1 if ($Max < 1);
14519:     if ( int($Max) < $Max ) {
14520:         $Max++;
14521:         $Max = int($Max);
14522:     }
14523:     $Title  = '' if (! defined($Title));
14524:     $xlabel = '' if (! defined($xlabel));
14525:     $ylabel = '' if (! defined($ylabel));
14526:     $ValuesHash{$id.'.title'}    = &escape($Title);
14527:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14528:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14529:     $ValuesHash{$id.'.y_max_value'} = $Max;
14530:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14531:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14532:     $ValuesHash{$id.'.PlotType'} = 'bar';
14533:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14534:     $ValuesHash{$id.'.height'}   = $height;
14535:     $ValuesHash{$id.'.width'}    = $width;
14536:     $ValuesHash{$id.'.xskip'}    = $xskip;
14537:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14538:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14539:     #
14540:     # Deal with other parameters
14541:     while (my ($key,$value) = each(%$extra_settings)) {
14542:         $ValuesHash{$id.'.'.$key} = $value;
14543:     }
14544:     #
14545:     &Apache::lonnet::appenv(\%ValuesHash);
14546:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14547: }
14548: 
14549: ############################################################
14550: ############################################################
14551: 
14552: =pod
14553: 
14554: =item * &DrawXYGraph()
14555: 
14556: Facilitates the plotting of data in an XY graph.
14557: Puts plot definition data into the users environment in order for 
14558: graph.png to plot it.  Returns an <img> tag for the plot.
14559: 
14560: Inputs:
14561: 
14562: =over 4
14563: 
14564: =item $Title: string, the title of the plot
14565: 
14566: =item $xlabel: string, text describing the X-axis of the plot
14567: 
14568: =item $ylabel: string, text describing the Y-axis of the plot
14569: 
14570: =item $Max: scalar, the maximum Y value to use in the plot
14571: If $Max is < any data point, the graph will not be rendered.
14572: 
14573: =item $colors: Array ref containing the hex color codes for the data to be 
14574: plotted in.  If undefined, default values will be used.
14575: 
14576: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14577: 
14578: =item $Ydata: Array ref containing Array refs.  
14579: Each of the contained arrays will be plotted as a separate curve.
14580: 
14581: =item %Values: hash indicating or overriding any default values which are 
14582: passed to graph.png.  
14583: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14584: 
14585: =back
14586: 
14587: Returns:
14588: 
14589: An <img> tag which references graph.png and the appropriate identifying
14590: information for the plot.
14591: 
14592: =cut
14593: 
14594: ############################################################
14595: ############################################################
14596: sub DrawXYGraph {
14597:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14598:     #
14599:     # Create the identifier for the graph
14600:     my $identifier = &get_cgi_id();
14601:     my $id = 'cgi.'.$identifier;
14602:     #
14603:     $Title  = '' if (! defined($Title));
14604:     $xlabel = '' if (! defined($xlabel));
14605:     $ylabel = '' if (! defined($ylabel));
14606:     my %ValuesHash = 
14607:         (
14608:          $id.'.title'  => &escape($Title),
14609:          $id.'.xlabel' => &escape($xlabel),
14610:          $id.'.ylabel' => &escape($ylabel),
14611:          $id.'.y_max_value'=> $Max,
14612:          $id.'.labels'     => join(',',@$Xlabels),
14613:          $id.'.PlotType'   => 'XY',
14614:          );
14615:     #
14616:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14617:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14618:     }
14619:     #
14620:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14621:         return '';
14622:     }
14623:     my $NumSets=1;
14624:     foreach my $array (@{$Ydata}){
14625:         next if (! ref($array));
14626:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14627:     }
14628:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14629:     #
14630:     # Deal with other parameters
14631:     while (my ($key,$value) = each(%Values)) {
14632:         $ValuesHash{$id.'.'.$key} = $value;
14633:     }
14634:     #
14635:     &Apache::lonnet::appenv(\%ValuesHash);
14636:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14637: }
14638: 
14639: ############################################################
14640: ############################################################
14641: 
14642: =pod
14643: 
14644: =item * &DrawXYYGraph()
14645: 
14646: Facilitates the plotting of data in an XY graph with two Y axes.
14647: Puts plot definition data into the users environment in order for 
14648: graph.png to plot it.  Returns an <img> tag for the plot.
14649: 
14650: Inputs:
14651: 
14652: =over 4
14653: 
14654: =item $Title: string, the title of the plot
14655: 
14656: =item $xlabel: string, text describing the X-axis of the plot
14657: 
14658: =item $ylabel: string, text describing the Y-axis of the plot
14659: 
14660: =item $colors: Array ref containing the hex color codes for the data to be 
14661: plotted in.  If undefined, default values will be used.
14662: 
14663: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14664: 
14665: =item $Ydata1: The first data set
14666: 
14667: =item $Min1: The minimum value of the left Y-axis
14668: 
14669: =item $Max1: The maximum value of the left Y-axis
14670: 
14671: =item $Ydata2: The second data set
14672: 
14673: =item $Min2: The minimum value of the right Y-axis
14674: 
14675: =item $Max2: The maximum value of the left Y-axis
14676: 
14677: =item %Values: hash indicating or overriding any default values which are 
14678: passed to graph.png.  
14679: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14680: 
14681: =back
14682: 
14683: Returns:
14684: 
14685: An <img> tag which references graph.png and the appropriate identifying
14686: information for the plot.
14687: 
14688: =cut
14689: 
14690: ############################################################
14691: ############################################################
14692: sub DrawXYYGraph {
14693:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14694:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14695:     #
14696:     # Create the identifier for the graph
14697:     my $identifier = &get_cgi_id();
14698:     my $id = 'cgi.'.$identifier;
14699:     #
14700:     $Title  = '' if (! defined($Title));
14701:     $xlabel = '' if (! defined($xlabel));
14702:     $ylabel = '' if (! defined($ylabel));
14703:     my %ValuesHash = 
14704:         (
14705:          $id.'.title'  => &escape($Title),
14706:          $id.'.xlabel' => &escape($xlabel),
14707:          $id.'.ylabel' => &escape($ylabel),
14708:          $id.'.labels' => join(',',@$Xlabels),
14709:          $id.'.PlotType' => 'XY',
14710:          $id.'.NumSets' => 2,
14711:          $id.'.two_axes' => 1,
14712:          $id.'.y1_max_value' => $Max1,
14713:          $id.'.y1_min_value' => $Min1,
14714:          $id.'.y2_max_value' => $Max2,
14715:          $id.'.y2_min_value' => $Min2,
14716:          );
14717:     #
14718:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14719:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14720:     }
14721:     #
14722:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14723:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14724:         return '';
14725:     }
14726:     my $NumSets=1;
14727:     foreach my $array ($Ydata1,$Ydata2){
14728:         next if (! ref($array));
14729:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14730:     }
14731:     #
14732:     # Deal with other parameters
14733:     while (my ($key,$value) = each(%Values)) {
14734:         $ValuesHash{$id.'.'.$key} = $value;
14735:     }
14736:     #
14737:     &Apache::lonnet::appenv(\%ValuesHash);
14738:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14739: }
14740: 
14741: ############################################################
14742: ############################################################
14743: 
14744: =pod
14745: 
14746: =back 
14747: 
14748: =head1 Statistics helper routines?  
14749: 
14750: Bad place for them but what the hell.
14751: 
14752: =over 4
14753: 
14754: =item * &chartlink()
14755: 
14756: Returns a link to the chart for a specific student.  
14757: 
14758: Inputs:
14759: 
14760: =over 4
14761: 
14762: =item $linktext: The text of the link
14763: 
14764: =item $sname: The students username
14765: 
14766: =item $sdomain: The students domain
14767: 
14768: =back
14769: 
14770: =back
14771: 
14772: =cut
14773: 
14774: ############################################################
14775: ############################################################
14776: sub chartlink {
14777:     my ($linktext, $sname, $sdomain) = @_;
14778:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14779:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14780:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14781:        '">'.$linktext.'</a>';
14782: }
14783: 
14784: #######################################################
14785: #######################################################
14786: 
14787: =pod
14788: 
14789: =head1 Course Environment Routines
14790: 
14791: =over 4
14792: 
14793: =item * &restore_course_settings()
14794: 
14795: =item * &store_course_settings()
14796: 
14797: Restores/Store indicated form parameters from the course environment.
14798: Will not overwrite existing values of the form parameters.
14799: 
14800: Inputs: 
14801: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14802: 
14803: a hash ref describing the data to be stored.  For example:
14804:    
14805: %Save_Parameters = ('Status' => 'scalar',
14806:     'chartoutputmode' => 'scalar',
14807:     'chartoutputdata' => 'scalar',
14808:     'Section' => 'array',
14809:     'Group' => 'array',
14810:     'StudentData' => 'array',
14811:     'Maps' => 'array');
14812: 
14813: Returns: both routines return nothing
14814: 
14815: =back
14816: 
14817: =cut
14818: 
14819: #######################################################
14820: #######################################################
14821: sub store_course_settings {
14822:     return &store_settings($env{'request.course.id'},@_);
14823: }
14824: 
14825: sub store_settings {
14826:     # save to the environment
14827:     # appenv the same items, just to be safe
14828:     my $udom  = $env{'user.domain'};
14829:     my $uname = $env{'user.name'};
14830:     my ($context,$prefix,$Settings) = @_;
14831:     my %SaveHash;
14832:     my %AppHash;
14833:     while (my ($setting,$type) = each(%$Settings)) {
14834:         my $basename = join('.','internal',$context,$prefix,$setting);
14835:         my $envname = 'environment.'.$basename;
14836:         if (exists($env{'form.'.$setting})) {
14837:             # Save this value away
14838:             if ($type eq 'scalar' &&
14839:                 (! exists($env{$envname}) || 
14840:                  $env{$envname} ne $env{'form.'.$setting})) {
14841:                 $SaveHash{$basename} = $env{'form.'.$setting};
14842:                 $AppHash{$envname}   = $env{'form.'.$setting};
14843:             } elsif ($type eq 'array') {
14844:                 my $stored_form;
14845:                 if (ref($env{'form.'.$setting})) {
14846:                     $stored_form = join(',',
14847:                                         map {
14848:                                             &escape($_);
14849:                                         } sort(@{$env{'form.'.$setting}}));
14850:                 } else {
14851:                     $stored_form = 
14852:                         &escape($env{'form.'.$setting});
14853:                 }
14854:                 # Determine if the array contents are the same.
14855:                 if ($stored_form ne $env{$envname}) {
14856:                     $SaveHash{$basename} = $stored_form;
14857:                     $AppHash{$envname}   = $stored_form;
14858:                 }
14859:             }
14860:         }
14861:     }
14862:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14863:                                           $udom,$uname);
14864:     if ($put_result !~ /^(ok|delayed)/) {
14865:         &Apache::lonnet::logthis('unable to save form parameters, '.
14866:                                  'got error:'.$put_result);
14867:     }
14868:     # Make sure these settings stick around in this session, too
14869:     &Apache::lonnet::appenv(\%AppHash);
14870:     return;
14871: }
14872: 
14873: sub restore_course_settings {
14874:     return &restore_settings($env{'request.course.id'},@_);
14875: }
14876: 
14877: sub restore_settings {
14878:     my ($context,$prefix,$Settings) = @_;
14879:     while (my ($setting,$type) = each(%$Settings)) {
14880:         next if (exists($env{'form.'.$setting}));
14881:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14882:             '.'.$setting;
14883:         if (exists($env{$envname})) {
14884:             if ($type eq 'scalar') {
14885:                 $env{'form.'.$setting} = $env{$envname};
14886:             } elsif ($type eq 'array') {
14887:                 $env{'form.'.$setting} = [ 
14888:                                            map { 
14889:                                                &unescape($_); 
14890:                                            } split(',',$env{$envname})
14891:                                            ];
14892:             }
14893:         }
14894:     }
14895: }
14896: 
14897: #######################################################
14898: #######################################################
14899: 
14900: =pod
14901: 
14902: =head1 Domain E-mail Routines  
14903: 
14904: =over 4
14905: 
14906: =item * &build_recipient_list()
14907: 
14908: Build recipient lists for following types of e-mail:
14909: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14910: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14911: module change checking, student/employee ID conflict checks, as
14912: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14913: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14914: 
14915: Inputs:
14916: defmail (scalar - email address of default recipient), 
14917: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14918: requestsmail, updatesmail, or idconflictsmail).
14919: 
14920: defdom (domain for which to retrieve configuration settings),
14921: 
14922: origmail (scalar - email address of recipient from loncapa.conf, 
14923: i.e., predates configuration by DC via domainprefs.pm
14924: 
14925: $requname username of requester (if mailing type is helpdeskmail)
14926: 
14927: $requdom domain of requester (if mailing type is helpdeskmail)
14928: 
14929: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14930: 
14931: 
14932: Returns: comma separated list of addresses to which to send e-mail.
14933: 
14934: =back
14935: 
14936: =cut
14937: 
14938: ############################################################
14939: ############################################################
14940: sub build_recipient_list {
14941:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14942:     my @recipients;
14943:     my ($otheremails,$lastresort,$allbcc,$addtext);
14944:     my %domconfig =
14945:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14946:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14947:         if (exists($domconfig{'contacts'}{$mailing})) {
14948:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14949:                 my @contacts = ('adminemail','supportemail');
14950:                 foreach my $item (@contacts) {
14951:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14952:                         my $addr = $domconfig{'contacts'}{$item}; 
14953:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14954:                             push(@recipients,$addr);
14955:                         }
14956:                     }
14957:                 }
14958:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14959:                 if ($mailing eq 'helpdeskmail') {
14960:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14961:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14962:                         my @ok_bccs;
14963:                         foreach my $bcc (@bccs) {
14964:                             $bcc =~ s/^\s+//g;
14965:                             $bcc =~ s/\s+$//g;
14966:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14967:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14968:                                     push(@ok_bccs,$bcc);
14969:                                 }
14970:                             }
14971:                         }
14972:                         if (@ok_bccs > 0) {
14973:                             $allbcc = join(', ',@ok_bccs);
14974:                         }
14975:                     }
14976:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14977:                 }
14978:             }
14979:         } elsif ($origmail ne '') {
14980:             $lastresort = $origmail;
14981:         }
14982:         if ($mailing eq 'helpdeskmail') {
14983:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14984:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14985:                 my ($inststatus,$inststatus_checked);
14986:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14987:                     ($env{'user.domain'} ne 'public')) {
14988:                     $inststatus_checked = 1;
14989:                     $inststatus = $env{'environment.inststatus'};
14990:                 }
14991:                 unless ($inststatus_checked) {
14992:                     if (($requname ne '') && ($requdom ne '')) {
14993:                         if (($requname =~ /^$match_username$/) &&
14994:                             ($requdom =~ /^$match_domain$/) &&
14995:                             (&Apache::lonnet::domain($requdom))) {
14996:                             my $requhome = &Apache::lonnet::homeserver($requname,
14997:                                                                       $requdom);
14998:                             unless ($requhome eq 'no_host') {
14999:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15000:                                 $inststatus = $userenv{'inststatus'};
15001:                                 $inststatus_checked = 1;
15002:                             }
15003:                         }
15004:                     }
15005:                 }
15006:                 unless ($inststatus_checked) {
15007:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15008:                         my %srch = (srchby     => 'email',
15009:                                     srchdomain => $defdom,
15010:                                     srchterm   => $reqemail,
15011:                                     srchtype   => 'exact');
15012:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15013:                         foreach my $uname (keys(%srch_results)) {
15014:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15015:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15016:                                 $inststatus_checked = 1;
15017:                                 last;
15018:                             }
15019:                         }
15020:                         unless ($inststatus_checked) {
15021:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15022:                             if ($dirsrchres eq 'ok') {
15023:                                 foreach my $uname (keys(%srch_results)) {
15024:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15025:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15026:                                         $inststatus_checked = 1;
15027:                                         last;
15028:                                     }
15029:                                 }
15030:                             }
15031:                         }
15032:                     }
15033:                 }
15034:                 if ($inststatus ne '') {
15035:                     foreach my $status (split(/\:/,$inststatus)) {
15036:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15037:                             my @contacts = ('adminemail','supportemail');
15038:                             foreach my $item (@contacts) {
15039:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15040:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15041:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15042:                                         push(@recipients,$addr);
15043:                                     }
15044:                                 }
15045:                             }
15046:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15047:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15048:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15049:                                 my @ok_bccs;
15050:                                 foreach my $bcc (@bccs) {
15051:                                     $bcc =~ s/^\s+//g;
15052:                                     $bcc =~ s/\s+$//g;
15053:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15054:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15055:                                             push(@ok_bccs,$bcc);
15056:                                         }
15057:                                     }
15058:                                 }
15059:                                 if (@ok_bccs > 0) {
15060:                                     $allbcc = join(', ',@ok_bccs);
15061:                                 }
15062:                             }
15063:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15064:                             last;
15065:                         }
15066:                     }
15067:                 }
15068:             }
15069:         }
15070:     } elsif ($origmail ne '') {
15071:         $lastresort = $origmail;
15072:     }
15073:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15074:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15075:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15076:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15077:             my %what = (
15078:                           perlvar => 1,
15079:                        );
15080:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15081:             if ($primary) {
15082:                 my $gotaddr;
15083:                 my ($result,$returnhash) =
15084:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15085:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15086:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15087:                         $lastresort = $returnhash->{'lonSupportEMail'};
15088:                         $gotaddr = 1;
15089:                     }
15090:                 }
15091:                 unless ($gotaddr) {
15092:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15093:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15094:                     unless ($uintdom eq $intdom) {
15095:                         my %domconfig =
15096:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15097:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15098:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15099:                                 my @contacts = ('adminemail','supportemail');
15100:                                 foreach my $item (@contacts) {
15101:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15102:                                         my $addr = $domconfig{'contacts'}{$item};
15103:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15104:                                             push(@recipients,$addr);
15105:                                         }
15106:                                     }
15107:                                 }
15108:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15109:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15110:                                 }
15111:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15112:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15113:                                     my @ok_bccs;
15114:                                     foreach my $bcc (@bccs) {
15115:                                         $bcc =~ s/^\s+//g;
15116:                                         $bcc =~ s/\s+$//g;
15117:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15118:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15119:                                                 push(@ok_bccs,$bcc);
15120:                                             }
15121:                                         }
15122:                                     }
15123:                                     if (@ok_bccs > 0) {
15124:                                         $allbcc = join(', ',@ok_bccs);
15125:                                     }
15126:                                 }
15127:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15128:                             }
15129:                         }
15130:                     }
15131:                 }
15132:             }
15133:         }
15134:     }
15135:     if (defined($defmail)) {
15136:         if ($defmail ne '') {
15137:             push(@recipients,$defmail);
15138:         }
15139:     }
15140:     if ($otheremails) {
15141:         my @others;
15142:         if ($otheremails =~ /,/) {
15143:             @others = split(/,/,$otheremails);
15144:         } else {
15145:             push(@others,$otheremails);
15146:         }
15147:         foreach my $addr (@others) {
15148:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15149:                 push(@recipients,$addr);
15150:             }
15151:         }
15152:     }
15153:     if ($mailing eq 'helpdeskmail') {
15154:         if ((!@recipients) && ($lastresort ne '')) {
15155:             push(@recipients,$lastresort);
15156:         }
15157:     } elsif ($lastresort ne '') {
15158:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15159:             push(@recipients,$lastresort);
15160:         }
15161:     }
15162:     my $recipientlist = join(',',@recipients);
15163:     if (wantarray) {
15164:         return ($recipientlist,$allbcc,$addtext);
15165:     } else {
15166:         return $recipientlist;
15167:     }
15168: }
15169: 
15170: ############################################################
15171: ############################################################
15172: 
15173: =pod
15174: 
15175: =over 4
15176: 
15177: =item * &mime_email()
15178: 
15179: Sends an email with a possible attachment
15180: 
15181: Inputs:
15182: 
15183: =over 4
15184: 
15185: from -              Sender's email address
15186: 
15187: to -                Email address of recipient
15188: 
15189: subject -           Subject of email
15190: 
15191: body -              Body of email
15192: 
15193: cc_string -         Carbon copy email address
15194: 
15195: bcc -               Blind carbon copy email address
15196: 
15197: type -              File type of attachment
15198: 
15199: attachment_path -   Path of file to be attached
15200: 
15201: file_name -         Name of file to be attached
15202: 
15203: attachment_text -   The body of an attachment of type "TEXT"
15204: 
15205: =back
15206: 
15207: =back
15208: 
15209: =cut
15210: 
15211: ############################################################
15212: ############################################################
15213: 
15214: sub mime_email {
15215:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
15216:         $file_name, $attachment_text) = @_;
15217:     my $msg = MIME::Lite->new(
15218:              From    => $from,
15219:              To      => $to,
15220:              Subject => $subject,
15221:              Type    =>'TEXT',
15222:              Data    => $body,
15223:              );
15224:     if ($cc_string ne '') {
15225:         $msg->add("Cc" => $cc_string);
15226:     }
15227:     if ($bcc ne '') {
15228:         $msg->add("Bcc" => $bcc);
15229:     }
15230:     $msg->attr("content-type"         => "text/plain");
15231:     $msg->attr("content-type.charset" => "UTF-8");
15232:     # Attach file if given
15233:     if ($attachment_path) {
15234:         unless ($file_name) {
15235:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15236:         }
15237:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15238:         $msg->attach(Type     => $type,
15239:                      Path     => $attachment_path,
15240:                      Filename => $file_name
15241:                      );
15242:     # Otherwise attach text if given
15243:     } elsif ($attachment_text) {
15244:         $msg->attach(Type => 'TEXT',
15245:                      Data => $attachment_text);
15246:     }
15247:     # Send it
15248:     $msg->send('sendmail');
15249: }
15250: 
15251: ############################################################
15252: ############################################################
15253: 
15254: =pod
15255: 
15256: =head1 Course Catalog Routines
15257: 
15258: =over 4
15259: 
15260: =item * &gather_categories()
15261: 
15262: Converts category definitions - keys of categories hash stored in  
15263: coursecategories in configuration.db on the primary library server in a 
15264: domain - to an array.  Also generates javascript and idx hash used to 
15265: generate Domain Coordinator interface for editing Course Categories.
15266: 
15267: Inputs:
15268: 
15269: categories (reference to hash of category definitions).
15270: 
15271: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15272:       categories and subcategories).
15273: 
15274: idx (reference to hash of counters used in Domain Coordinator interface for 
15275:       editing Course Categories).
15276: 
15277: jsarray (reference to array of categories used to create Javascript arrays for
15278:          Domain Coordinator interface for editing Course Categories).
15279: 
15280: Returns: nothing
15281: 
15282: Side effects: populates cats, idx and jsarray. 
15283: 
15284: =cut
15285: 
15286: sub gather_categories {
15287:     my ($categories,$cats,$idx,$jsarray) = @_;
15288:     my %counters;
15289:     my $num = 0;
15290:     foreach my $item (keys(%{$categories})) {
15291:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15292:         if ($container eq '' && $depth == 0) {
15293:             $cats->[$depth][$categories->{$item}] = $cat;
15294:         } else {
15295:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15296:         }
15297:         my ($escitem,$tail) = split(/:/,$item,2);
15298:         if ($counters{$tail} eq '') {
15299:             $counters{$tail} = $num;
15300:             $num ++;
15301:         }
15302:         if (ref($idx) eq 'HASH') {
15303:             $idx->{$item} = $counters{$tail};
15304:         }
15305:         if (ref($jsarray) eq 'ARRAY') {
15306:             push(@{$jsarray->[$counters{$tail}]},$item);
15307:         }
15308:     }
15309:     return;
15310: }
15311: 
15312: =pod
15313: 
15314: =item * &extract_categories()
15315: 
15316: Used to generate breadcrumb trails for course categories.
15317: 
15318: Inputs:
15319: 
15320: categories (reference to hash of category definitions).
15321: 
15322: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15323:       categories and subcategories).
15324: 
15325: trails (reference to array of breacrumb trails for each category).
15326: 
15327: allitems (reference to hash - key is category key 
15328:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15329: 
15330: idx (reference to hash of counters used in Domain Coordinator interface for
15331:       editing Course Categories).
15332: 
15333: jsarray (reference to array of categories used to create Javascript arrays for
15334:          Domain Coordinator interface for editing Course Categories).
15335: 
15336: subcats (reference to hash of arrays containing all subcategories within each 
15337:          category, -recursive)
15338: 
15339: maxd (reference to hash used to hold max depth for all top-level categories).
15340: 
15341: Returns: nothing
15342: 
15343: Side effects: populates trails and allitems hash references.
15344: 
15345: =cut
15346: 
15347: sub extract_categories {
15348:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15349:     if (ref($categories) eq 'HASH') {
15350:         &gather_categories($categories,$cats,$idx,$jsarray);
15351:         if (ref($cats->[0]) eq 'ARRAY') {
15352:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15353:                 my $name = $cats->[0][$i];
15354:                 my $item = &escape($name).'::0';
15355:                 my $trailstr;
15356:                 if ($name eq 'instcode') {
15357:                     $trailstr = &mt('Official courses (with institutional codes)');
15358:                 } elsif ($name eq 'communities') {
15359:                     $trailstr = &mt('Communities');
15360:                 } elsif ($name eq 'placement') {
15361:                     $trailstr = &mt('Placement Tests');
15362:                 } else {
15363:                     $trailstr = $name;
15364:                 }
15365:                 if ($allitems->{$item} eq '') {
15366:                     push(@{$trails},$trailstr);
15367:                     $allitems->{$item} = scalar(@{$trails})-1;
15368:                 }
15369:                 my @parents = ($name);
15370:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15371:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15372:                         my $category = $cats->[1]{$name}[$j];
15373:                         if (ref($subcats) eq 'HASH') {
15374:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15375:                         }
15376:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15377:                     }
15378:                 } else {
15379:                     if (ref($subcats) eq 'HASH') {
15380:                         $subcats->{$item} = [];
15381:                     }
15382:                     if (ref($maxd) eq 'HASH') {
15383:                         $maxd->{$name} = 1;
15384:                     }
15385:                 }
15386:             }
15387:         }
15388:     }
15389:     return;
15390: }
15391: 
15392: =pod
15393: 
15394: =item * &recurse_categories()
15395: 
15396: Recursively used to generate breadcrumb trails for course categories.
15397: 
15398: Inputs:
15399: 
15400: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15401:       categories and subcategories).
15402: 
15403: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15404: 
15405: category (current course category, for which breadcrumb trail is being generated).
15406: 
15407: trails (reference to array of breadcrumb trails for each category).
15408: 
15409: allitems (reference to hash - key is category key
15410:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15411: 
15412: parents (array containing containers directories for current category, 
15413:          back to top level). 
15414: 
15415: Returns: nothing
15416: 
15417: Side effects: populates trails and allitems hash references
15418: 
15419: =cut
15420: 
15421: sub recurse_categories {
15422:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15423:     my $shallower = $depth - 1;
15424:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15425:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15426:             my $name = $cats->[$depth]{$category}[$k];
15427:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15428:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15429:             if ($allitems->{$item} eq '') {
15430:                 push(@{$trails},$trailstr);
15431:                 $allitems->{$item} = scalar(@{$trails})-1;
15432:             }
15433:             my $deeper = $depth+1;
15434:             push(@{$parents},$category);
15435:             if (ref($subcats) eq 'HASH') {
15436:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15437:                 for (my $j=@{$parents}; $j>=0; $j--) {
15438:                     my $higher;
15439:                     if ($j > 0) {
15440:                         $higher = &escape($parents->[$j]).':'.
15441:                                   &escape($parents->[$j-1]).':'.$j;
15442:                     } else {
15443:                         $higher = &escape($parents->[$j]).'::'.$j;
15444:                     }
15445:                     push(@{$subcats->{$higher}},$subcat);
15446:                 }
15447:             }
15448:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15449:                                 $subcats,$maxd);
15450:             pop(@{$parents});
15451:         }
15452:     } else {
15453:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15454:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15455:         if ($allitems->{$item} eq '') {
15456:             push(@{$trails},$trailstr);
15457:             $allitems->{$item} = scalar(@{$trails})-1;
15458:         }
15459:         if (ref($maxd) eq 'HASH') {
15460:             if ($depth > $maxd->{$parents->[0]}) {
15461:                 $maxd->{$parents->[0]} = $depth;
15462:             }
15463:         }
15464:     }
15465:     return;
15466: }
15467: 
15468: =pod
15469: 
15470: =item * &assign_categories_table()
15471: 
15472: Create a datatable for display of hierarchical categories in a domain,
15473: with checkboxes to allow a course to be categorized. 
15474: 
15475: Inputs:
15476: 
15477: cathash - reference to hash of categories defined for the domain (from
15478:           configuration.db)
15479: 
15480: currcat - scalar with an & separated list of categories assigned to a course. 
15481: 
15482: type    - scalar contains course type (Course or Community).
15483: 
15484: disabled - scalar (optional) contains disabled="disabled" if input elements are
15485:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15486: 
15487: Returns: $output (markup to be displayed) 
15488: 
15489: =cut
15490: 
15491: sub assign_categories_table {
15492:     my ($cathash,$currcat,$type,$disabled) = @_;
15493:     my $output;
15494:     if (ref($cathash) eq 'HASH') {
15495:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15496:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15497:         $maxdepth = scalar(@cats);
15498:         if (@cats > 0) {
15499:             my $itemcount = 0;
15500:             if (ref($cats[0]) eq 'ARRAY') {
15501:                 my @currcategories;
15502:                 if ($currcat ne '') {
15503:                     @currcategories = split('&',$currcat);
15504:                 }
15505:                 my $table;
15506:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15507:                     my $parent = $cats[0][$i];
15508:                     next if ($parent eq 'instcode');
15509:                     if ($type eq 'Community') {
15510:                         next unless ($parent eq 'communities');
15511:                     } elsif ($type eq 'Placement') {
15512:                         next unless ($parent eq 'placement');
15513:                     } else {
15514:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15515:                     }
15516:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15517:                     my $item = &escape($parent).'::0';
15518:                     my $checked = '';
15519:                     if (@currcategories > 0) {
15520:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15521:                             $checked = ' checked="checked"';
15522:                         }
15523:                     }
15524:                     my $parent_title = $parent;
15525:                     if ($parent eq 'communities') {
15526:                         $parent_title = &mt('Communities');
15527:                     } elsif ($parent eq 'placement') {
15528:                         $parent_title = &mt('Placement Tests');
15529:                     }
15530:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15531:                               '<input type="checkbox" name="usecategory" value="'.
15532:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15533:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15534:                     my $depth = 1;
15535:                     push(@path,$parent);
15536:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15537:                     pop(@path);
15538:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15539:                     $itemcount ++;
15540:                 }
15541:                 if ($itemcount) {
15542:                     $output = &Apache::loncommon::start_data_table().
15543:                               $table.
15544:                               &Apache::loncommon::end_data_table();
15545:                 }
15546:             }
15547:         }
15548:     }
15549:     return $output;
15550: }
15551: 
15552: =pod
15553: 
15554: =item * &assign_category_rows()
15555: 
15556: Create a datatable row for display of nested categories in a domain,
15557: with checkboxes to allow a course to be categorized,called recursively.
15558: 
15559: Inputs:
15560: 
15561: itemcount - track row number for alternating colors
15562: 
15563: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15564:       categories and subcategories.
15565: 
15566: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15567: 
15568: parent - parent of current category item
15569: 
15570: path - Array containing all categories back up through the hierarchy from the
15571:        current category to the top level.
15572: 
15573: currcategories - reference to array of current categories assigned to the course
15574: 
15575: disabled - scalar (optional) contains disabled="disabled" if input elements are
15576:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15577: 
15578: Returns: $output (markup to be displayed).
15579: 
15580: =cut
15581: 
15582: sub assign_category_rows {
15583:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15584:     my ($text,$name,$item,$chgstr);
15585:     if (ref($cats) eq 'ARRAY') {
15586:         my $maxdepth = scalar(@{$cats});
15587:         if (ref($cats->[$depth]) eq 'HASH') {
15588:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15589:                 my $numchildren = @{$cats->[$depth]{$parent}};
15590:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15591:                 $text .= '<td><table class="LC_data_table">';
15592:                 for (my $j=0; $j<$numchildren; $j++) {
15593:                     $name = $cats->[$depth]{$parent}[$j];
15594:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15595:                     my $deeper = $depth+1;
15596:                     my $checked = '';
15597:                     if (ref($currcategories) eq 'ARRAY') {
15598:                         if (@{$currcategories} > 0) {
15599:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15600:                                 $checked = ' checked="checked"';
15601:                             }
15602:                         }
15603:                     }
15604:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15605:                              '<input type="checkbox" name="usecategory" value="'.
15606:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15607:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15608:                              '</td><td>';
15609:                     if (ref($path) eq 'ARRAY') {
15610:                         push(@{$path},$name);
15611:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15612:                         pop(@{$path});
15613:                     }
15614:                     $text .= '</td></tr>';
15615:                 }
15616:                 $text .= '</table></td>';
15617:             }
15618:         }
15619:     }
15620:     return $text;
15621: }
15622: 
15623: =pod
15624: 
15625: =back
15626: 
15627: =cut
15628: 
15629: ############################################################
15630: ############################################################
15631: 
15632: 
15633: sub commit_customrole {
15634:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15635:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15636:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15637:                          ($end?', ending '.localtime($end):'').': <b>'.
15638:               &Apache::lonnet::assigncustomrole(
15639:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15640:                  '</b><br />';
15641:     return $output;
15642: }
15643: 
15644: sub commit_standardrole {
15645:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15646:     my ($output,$logmsg,$linefeed);
15647:     if ($context eq 'auto') {
15648:         $linefeed = "\n";
15649:     } else {
15650:         $linefeed = "<br />\n";
15651:     }  
15652:     if ($three eq 'st') {
15653:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15654:                                          $one,$two,$sec,$context,$credits);
15655:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15656:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15657:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15658:         } else {
15659:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15660:                ($start?', '.&mt('starting').' '.localtime($start):'').
15661:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15662:             if ($context eq 'auto') {
15663:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15664:             } else {
15665:                $output .= '<b>'.$result.'</b>'.$linefeed.
15666:                &mt('Add to classlist').': <b>ok</b>';
15667:             }
15668:             $output .= $linefeed;
15669:         }
15670:     } else {
15671:         $output = &mt('Assigning').' '.$three.' in '.$url.
15672:                ($start?', '.&mt('starting').' '.localtime($start):'').
15673:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15674:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15675:         if ($context eq 'auto') {
15676:             $output .= $result.$linefeed;
15677:         } else {
15678:             $output .= '<b>'.$result.'</b>'.$linefeed;
15679:         }
15680:     }
15681:     return $output;
15682: }
15683: 
15684: sub commit_studentrole {
15685:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15686:         $credits) = @_;
15687:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15688:     if ($context eq 'auto') {
15689:         $linefeed = "\n";
15690:     } else {
15691:         $linefeed = '<br />'."\n";
15692:     }
15693:     if (defined($one) && defined($two)) {
15694:         my $cid=$one.'_'.$two;
15695:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15696:         my $secchange = 0;
15697:         my $expire_role_result;
15698:         my $modify_section_result;
15699:         if ($oldsec ne '-1') { 
15700:             if ($oldsec ne $sec) {
15701:                 $secchange = 1;
15702:                 my $now = time;
15703:                 my $uurl='/'.$cid;
15704:                 $uurl=~s/\_/\//g;
15705:                 if ($oldsec) {
15706:                     $uurl.='/'.$oldsec;
15707:                 }
15708:                 $oldsecurl = $uurl;
15709:                 $expire_role_result = 
15710:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15711:                 if ($env{'request.course.sec'} ne '') { 
15712:                     if ($expire_role_result eq 'refused') {
15713:                         my @roles = ('st');
15714:                         my @statuses = ('previous');
15715:                         my @roledoms = ($one);
15716:                         my $withsec = 1;
15717:                         my %roleshash = 
15718:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15719:                                               \@statuses,\@roles,\@roledoms,$withsec);
15720:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15721:                             my ($oldstart,$oldend) = 
15722:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15723:                             if ($oldend > 0 && $oldend <= $now) {
15724:                                 $expire_role_result = 'ok';
15725:                             }
15726:                         }
15727:                     }
15728:                 }
15729:                 $result = $expire_role_result;
15730:             }
15731:         }
15732:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15733:             $modify_section_result = 
15734:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15735:                                                            undef,undef,undef,$sec,
15736:                                                            $end,$start,'','',$cid,
15737:                                                            '',$context,$credits);
15738:             if ($modify_section_result =~ /^ok/) {
15739:                 if ($secchange == 1) {
15740:                     if ($sec eq '') {
15741:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15742:                     } else {
15743:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15744:                     }
15745:                 } elsif ($oldsec eq '-1') {
15746:                     if ($sec eq '') {
15747:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15748:                     } else {
15749:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15750:                     }
15751:                 } else {
15752:                     if ($sec eq '') {
15753:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15754:                     } else {
15755:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15756:                     }
15757:                 }
15758:             } else {
15759:                 if ($secchange) { 
15760:                     $$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;
15761:                 } else {
15762:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15763:                 }
15764:             }
15765:             $result = $modify_section_result;
15766:         } elsif ($secchange == 1) {
15767:             if ($oldsec eq '') {
15768:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15769:             } else {
15770:                 $$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;
15771:             }
15772:             if ($expire_role_result eq 'refused') {
15773:                 my $newsecurl = '/'.$cid;
15774:                 $newsecurl =~ s/\_/\//g;
15775:                 if ($sec ne '') {
15776:                     $newsecurl.='/'.$sec;
15777:                 }
15778:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15779:                     if ($sec eq '') {
15780:                         $$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;
15781:                     } else {
15782:                         $$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;
15783:                     }
15784:                 }
15785:             }
15786:         }
15787:     } else {
15788:         $$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;
15789:         $result = "error: incomplete course id\n";
15790:     }
15791:     return $result;
15792: }
15793: 
15794: sub show_role_extent {
15795:     my ($scope,$context,$role) = @_;
15796:     $scope =~ s{^/}{};
15797:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15798:     push(@courseroles,'co');
15799:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15800:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15801:         $scope =~ s{/}{_};
15802:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15803:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15804:         my ($audom,$auname) = split(/\//,$scope);
15805:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15806:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15807:     } else {
15808:         $scope =~ s{/$}{};
15809:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15810:                    &Apache::lonnet::domain($scope,'description').'</span>');
15811:     }
15812: }
15813: 
15814: ############################################################
15815: ############################################################
15816: 
15817: sub check_clone {
15818:     my ($args,$linefeed) = @_;
15819:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15820:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15821:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15822:     my $clonemsg;
15823:     my $can_clone = 0;
15824:     my $lctype = lc($args->{'crstype'});
15825:     if ($lctype ne 'community') {
15826:         $lctype = 'course';
15827:     }
15828:     if ($clonehome eq 'no_host') {
15829:         if ($args->{'crstype'} eq 'Community') {
15830:             $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'});
15831:         } else {
15832:             $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'});
15833:         }     
15834:     } else {
15835: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15836:         if ($args->{'crstype'} eq 'Community') {
15837:             if ($clonedesc{'type'} ne 'Community') {
15838:                 $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'});
15839:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15840:             }
15841:         }
15842: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15843:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15844: 	    $can_clone = 1;
15845: 	} else {
15846: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15847: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15848:             if ($clonehash{'cloners'} eq '') {
15849:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15850:                 if ($domdefs{'canclone'}) {
15851:                     unless ($domdefs{'canclone'} eq 'none') {
15852:                         if ($domdefs{'canclone'} eq 'domain') {
15853:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15854:                                 $can_clone = 1;
15855:                             }
15856:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15857:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15858:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15859:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15860:                                 $can_clone = 1;
15861:                             }
15862:                         }
15863:                     }
15864:                 }
15865:             } else {
15866: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15867:                 if (grep(/^\*$/,@cloners)) {
15868:                     $can_clone = 1;
15869:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15870:                     $can_clone = 1;
15871:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15872:                     $can_clone = 1;
15873:                 }
15874:                 unless ($can_clone) {
15875:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15876:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15877:                         my (%gotdomdefaults,%gotcodedefaults);
15878:                         foreach my $cloner (@cloners) {
15879:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15880:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15881:                                 my (%codedefaults,@code_order);
15882:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15883:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15884:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15885:                                     }
15886:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15887:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15888:                                     }
15889:                                 } else {
15890:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15891:                                                                             \%codedefaults,
15892:                                                                             \@code_order);
15893:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15894:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15895:                                 }
15896:                                 if (@code_order > 0) {
15897:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15898:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15899:                                                                                 $args->{'crscode'})) {
15900:                                         $can_clone = 1;
15901:                                         last;
15902:                                     }
15903:                                 }
15904:                             }
15905:                         }
15906:                     }
15907:                 }
15908:             }
15909:             unless ($can_clone) {
15910:                 my $ccrole = 'cc';
15911:                 if ($args->{'crstype'} eq 'Community') {
15912:                     $ccrole = 'co';
15913:                 }
15914: 	        my %roleshash =
15915: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15916: 					          $args->{'ccdomain'},
15917:                                                   'userroles',['active'],[$ccrole],
15918: 					          [$args->{'clonedomain'}]);
15919: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15920:                     $can_clone = 1;
15921:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15922:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15923:                     $can_clone = 1;
15924:                 }
15925:             }
15926:             unless ($can_clone) {
15927:                 if ($args->{'crstype'} eq 'Community') {
15928:                     $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'});
15929:                 } else {
15930:                     $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'});
15931:                 }
15932: 	    }
15933:         }
15934:     }
15935:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15936: }
15937: 
15938: sub construct_course {
15939:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15940:         $cnum,$category,$coderef) = @_;
15941:     my $outcome;
15942:     my $linefeed =  '<br />'."\n";
15943:     if ($context eq 'auto') {
15944:         $linefeed = "\n";
15945:     }
15946: 
15947: #
15948: # Are we cloning?
15949: #
15950:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15951:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15952: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15953: 	if ($context ne 'auto') {
15954:             if ($clonemsg ne '') {
15955: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15956:             }
15957: 	}
15958: 	$outcome .= $clonemsg.$linefeed;
15959: 
15960:         if (!$can_clone) {
15961: 	    return (0,$outcome);
15962: 	}
15963:     }
15964: 
15965: #
15966: # Open course
15967: #
15968:     my $showncrstype;
15969:     if ($args->{'crstype'} eq 'Placement') {
15970:         $showncrstype = 'placement test'; 
15971:     } else {  
15972:         $showncrstype = lc($args->{'crstype'});
15973:     }
15974:     my %cenv=();
15975:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15976:                                              $args->{'cdescr'},
15977:                                              $args->{'curl'},
15978:                                              $args->{'course_home'},
15979:                                              $args->{'nonstandard'},
15980:                                              $args->{'crscode'},
15981:                                              $args->{'ccuname'}.':'.
15982:                                              $args->{'ccdomain'},
15983:                                              $args->{'crstype'},
15984:                                              $cnum,$context,$category);
15985: 
15986:     # Note: The testing routines depend on this being output; see 
15987:     # Utils::Course. This needs to at least be output as a comment
15988:     # if anyone ever decides to not show this, and Utils::Course::new
15989:     # will need to be suitably modified.
15990:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15991:     if ($$courseid =~ /^error:/) {
15992:         return (0,$outcome);
15993:     }
15994: 
15995: #
15996: # Check if created correctly
15997: #
15998:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15999:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16000:     if ($crsuhome eq 'no_host') {
16001:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
16002:         return (0,$outcome);
16003:     }
16004:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16005: 
16006: #
16007: # Do the cloning
16008: #   
16009:     if ($can_clone && $cloneid) {
16010: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
16011: 	if ($context ne 'auto') {
16012: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
16013: 	}
16014: 	$outcome .= $clonemsg.$linefeed;
16015: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16016: # Copy all files
16017: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
16018: # Restore URL
16019: 	$cenv{'url'}=$oldcenv{'url'};
16020: # Restore title
16021: 	$cenv{'description'}=$oldcenv{'description'};
16022: # Restore creation date, creator and creation context.
16023:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16024:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16025:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16026: # Mark as cloned
16027: 	$cenv{'clonedfrom'}=$cloneid;
16028: # Need to clone grading mode
16029:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16030:         $cenv{'grading'}=$newenv{'grading'};
16031: # Do not clone these environment entries
16032:         &Apache::lonnet::del('environment',
16033:                   ['default_enrollment_start_date',
16034:                    'default_enrollment_end_date',
16035:                    'question.email',
16036:                    'policy.email',
16037:                    'comment.email',
16038:                    'pch.users.denied',
16039:                    'plc.users.denied',
16040:                    'hidefromcat',
16041:                    'checkforpriv',
16042:                    'categories',
16043:                    'internal.uniquecode'],
16044:                    $$crsudom,$$crsunum);
16045:         if ($args->{'textbook'}) {
16046:             $cenv{'internal.textbook'} = $args->{'textbook'};
16047:         }
16048:     }
16049: 
16050: #
16051: # Set environment (will override cloned, if existing)
16052: #
16053:     my @sections = ();
16054:     my @xlists = ();
16055:     if ($args->{'crstype'}) {
16056:         $cenv{'type'}=$args->{'crstype'};
16057:     }
16058:     if ($args->{'crsid'}) {
16059:         $cenv{'courseid'}=$args->{'crsid'};
16060:     }
16061:     if ($args->{'crscode'}) {
16062:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16063:     }
16064:     if ($args->{'crsquota'} ne '') {
16065:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16066:     } else {
16067:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16068:     }
16069:     if ($args->{'ccuname'}) {
16070:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16071:                                         ':'.$args->{'ccdomain'};
16072:     } else {
16073:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16074:     }
16075:     if ($args->{'defaultcredits'}) {
16076:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16077:     }
16078:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16079:     if ($args->{'crssections'}) {
16080:         $cenv{'internal.sectionnums'} = '';
16081:         if ($args->{'crssections'} =~ m/,/) {
16082:             @sections = split/,/,$args->{'crssections'};
16083:         } else {
16084:             $sections[0] = $args->{'crssections'};
16085:         }
16086:         if (@sections > 0) {
16087:             foreach my $item (@sections) {
16088:                 my ($sec,$gp) = split/:/,$item;
16089:                 my $class = $args->{'crscode'}.$sec;
16090:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16091:                 $cenv{'internal.sectionnums'} .= $item.',';
16092:                 unless ($addcheck eq 'ok') {
16093:                     push(@badclasses,$class);
16094:                 }
16095:             }
16096:             $cenv{'internal.sectionnums'} =~ s/,$//;
16097:         }
16098:     }
16099: # do not hide course coordinator from staff listing, 
16100: # even if privileged
16101:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16102: # add course coordinator's domain to domains to check for privileged users
16103: # if different to course domain
16104:     if ($$crsudom ne $args->{'ccdomain'}) {
16105:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16106:     }
16107: # add crosslistings
16108:     if ($args->{'crsxlist'}) {
16109:         $cenv{'internal.crosslistings'}='';
16110:         if ($args->{'crsxlist'} =~ m/,/) {
16111:             @xlists = split/,/,$args->{'crsxlist'};
16112:         } else {
16113:             $xlists[0] = $args->{'crsxlist'};
16114:         }
16115:         if (@xlists > 0) {
16116:             foreach my $item (@xlists) {
16117:                 my ($xl,$gp) = split/:/,$item;
16118:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16119:                 $cenv{'internal.crosslistings'} .= $item.',';
16120:                 unless ($addcheck eq 'ok') {
16121:                     push(@badclasses,$xl);
16122:                 }
16123:             }
16124:             $cenv{'internal.crosslistings'} =~ s/,$//;
16125:         }
16126:     }
16127:     if ($args->{'autoadds'}) {
16128:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16129:     }
16130:     if ($args->{'autodrops'}) {
16131:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16132:     }
16133: # check for notification of enrollment changes
16134:     my @notified = ();
16135:     if ($args->{'notify_owner'}) {
16136:         if ($args->{'ccuname'} ne '') {
16137:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16138:         }
16139:     }
16140:     if ($args->{'notify_dc'}) {
16141:         if ($uname ne '') { 
16142:             push(@notified,$uname.':'.$udom);
16143:         }
16144:     }
16145:     if (@notified > 0) {
16146:         my $notifylist;
16147:         if (@notified > 1) {
16148:             $notifylist = join(',',@notified);
16149:         } else {
16150:             $notifylist = $notified[0];
16151:         }
16152:         $cenv{'internal.notifylist'} = $notifylist;
16153:     }
16154:     if (@badclasses > 0) {
16155:         my %lt=&Apache::lonlocal::texthash(
16156:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16157:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16158:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16159:         );
16160:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16161:                            &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'};
16162:         if ($context eq 'auto') {
16163:             $outcome .= $badclass_msg.$linefeed;
16164:         } else {
16165:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16166:         }
16167:         foreach my $item (@badclasses) {
16168:             if ($context eq 'auto') {
16169:                 $outcome .= " - $item\n";
16170:             } else {
16171:                 $outcome .= "<li>$item</li>\n";
16172:             }
16173:         }
16174:         if ($context eq 'auto') {
16175:             $outcome .= $linefeed;
16176:         } else {
16177:             $outcome .= "</ul><br /><br /></div>\n";
16178:         } 
16179:     }
16180:     if ($args->{'no_end_date'}) {
16181:         $args->{'endaccess'} = 0;
16182:     }
16183:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16184:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16185:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16186:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16187:     if ($args->{'showphotos'}) {
16188:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16189:     }
16190:     $cenv{'internal.authtype'} = $args->{'authtype'};
16191:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16192:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16193:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16194:             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'); 
16195:             if ($context eq 'auto') {
16196:                 $outcome .= $krb_msg;
16197:             } else {
16198:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16199:             }
16200:             $outcome .= $linefeed;
16201:         }
16202:     }
16203:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16204:        if ($args->{'setpolicy'}) {
16205:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16206:        }
16207:        if ($args->{'setcontent'}) {
16208:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16209:        }
16210:        if ($args->{'setcomment'}) {
16211:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16212:        }
16213:     }
16214:     if ($args->{'reshome'}) {
16215: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16216: 	$cenv{'reshome'}=~s/\/+$/\//;
16217:     }
16218: #
16219: # course has keyed access
16220: #
16221:     if ($args->{'setkeys'}) {
16222:        $cenv{'keyaccess'}='yes';
16223:     }
16224: # if specified, key authority is not course, but user
16225: # only active if keyaccess is yes
16226:     if ($args->{'keyauth'}) {
16227: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16228: 	$user = &LONCAPA::clean_username($user);
16229: 	$domain = &LONCAPA::clean_username($domain);
16230: 	if ($user ne '' && $domain ne '') {
16231: 	    $cenv{'keyauth'}=$user.':'.$domain;
16232: 	}
16233:     }
16234: 
16235: #
16236: #  generate and store uniquecode (available to course requester), if course should have one.
16237: #
16238:     if ($args->{'uniquecode'}) {
16239:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16240:         if ($code) {
16241:             $cenv{'internal.uniquecode'} = $code;
16242:             my %crsinfo =
16243:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16244:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16245:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16246:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16247:             } 
16248:             if (ref($coderef)) {
16249:                 $$coderef = $code;
16250:             }
16251:         }
16252:     }
16253: 
16254:     if ($args->{'disresdis'}) {
16255:         $cenv{'pch.roles.denied'}='st';
16256:     }
16257:     if ($args->{'disablechat'}) {
16258:         $cenv{'plc.roles.denied'}='st';
16259:     }
16260: 
16261:     # Record we've not yet viewed the Course Initialization Helper for this 
16262:     # course
16263:     $cenv{'course.helper.not.run'} = 1;
16264:     #
16265:     # Use new Randomseed
16266:     #
16267:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16268:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16269:     #
16270:     # The encryption code and receipt prefix for this course
16271:     #
16272:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16273:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16274:     #
16275:     # By default, use standard grading
16276:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16277: 
16278:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16279:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16280: #
16281: # Open all assignments
16282: #
16283:     if ($args->{'openall'}) {
16284:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16285:        my %storecontent = ($storeunder         => time,
16286:                            $storeunder.'.type' => 'date_start');
16287:        
16288:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
16289:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16290:    }
16291: #
16292: # Set first page
16293: #
16294:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16295: 	    || ($cloneid)) {
16296: 	use LONCAPA::map;
16297: 	$outcome .= &mt('Setting first resource').': ';
16298: 
16299: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16300:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16301: 
16302:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16303:         my $title; my $url;
16304:         if ($args->{'firstres'} eq 'syl') {
16305: 	    $title=&mt('Syllabus');
16306:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16307:         } else {
16308:             $title=&mt('Table of Contents');
16309:             $url='/adm/navmaps';
16310:         }
16311: 
16312:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16313: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16314: 
16315: 	if ($errtext) { $fatal=2; }
16316:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16317:     }
16318: 
16319: # 
16320: # Set params for Placement Tests
16321: #
16322:     if ($args->{'crstype'} eq 'Placement') {
16323:        my %storecontent; 
16324:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16325:        my %defaults = (
16326:                         buttonshide   => { value => 'yes',
16327:                                            type => 'string_yesno',},
16328:                         type          => { value => 'randomizetry',
16329:                                            type  => 'string_questiontype',},
16330:                         maxtries      => { value => 1,
16331:                                            type => 'int_pos',},
16332:                         problemstatus => { value => 'no',
16333:                                            type  => 'string_problemstatus',},
16334:                       );
16335:        foreach my $key (keys(%defaults)) {
16336:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16337:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16338:        }
16339:        &Apache::lonnet::cput
16340:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
16341:     }
16342: 
16343:     return (1,$outcome);
16344: }
16345: 
16346: sub make_unique_code {
16347:     my ($cdom,$cnum) = @_;
16348:     # get lock on uniquecodes db
16349:     my $lockhash = {
16350:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16351:                                                   ':'.$env{'user.domain'},
16352:                    };
16353:     my $tries = 0;
16354:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16355:     my ($code,$error);
16356:   
16357:     while (($gotlock ne 'ok') && ($tries<3)) {
16358:         $tries ++;
16359:         sleep 1;
16360:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16361:     }
16362:     if ($gotlock eq 'ok') {
16363:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16364:         my $gotcode;
16365:         my $attempts = 0;
16366:         while ((!$gotcode) && ($attempts < 100)) {
16367:             $code = &generate_code();
16368:             if (!exists($currcodes{$code})) {
16369:                 $gotcode = 1;
16370:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16371:                     $error = 'nostore';
16372:                 }
16373:             }
16374:             $attempts ++;
16375:         }
16376:         my @del_lock = ($cnum."\0".'uniquecodes');
16377:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16378:     } else {
16379:         $error = 'nolock';
16380:     }
16381:     return ($code,$error);
16382: }
16383: 
16384: sub generate_code {
16385:     my $code;
16386:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16387:     for (my $i=0; $i<6; $i++) {
16388:         my $lettnum = int (rand 2);
16389:         my $item = '';
16390:         if ($lettnum) {
16391:             $item = $letts[int( rand(18) )];
16392:         } else {
16393:             $item = 1+int( rand(8) );
16394:         }
16395:         $code .= $item;
16396:     }
16397:     return $code;
16398: }
16399: 
16400: ############################################################
16401: ############################################################
16402: 
16403: # Community, Course and Placement Test
16404: sub course_type {
16405:     my ($cid) = @_;
16406:     if (!defined($cid)) {
16407:         $cid = $env{'request.course.id'};
16408:     }
16409:     if (defined($env{'course.'.$cid.'.type'})) {
16410:         return $env{'course.'.$cid.'.type'};
16411:     } else {
16412:         return 'Course';
16413:     }
16414: }
16415: 
16416: sub group_term {
16417:     my $crstype = &course_type();
16418:     my %names = (
16419:                   'Course' => 'group',
16420:                   'Community' => 'group',
16421:                   'Placement' => 'group',
16422:                 );
16423:     return $names{$crstype};
16424: }
16425: 
16426: sub course_types {
16427:     my @types = ('official','unofficial','community','textbook','placement','lti');
16428:     my %typename = (
16429:                          official   => 'Official course',
16430:                          unofficial => 'Unofficial course',
16431:                          community  => 'Community',
16432:                          textbook   => 'Textbook course',
16433:                          placement  => 'Placement test',
16434:                          lti        => 'LTI provider',
16435:                    );
16436:     return (\@types,\%typename);
16437: }
16438: 
16439: sub icon {
16440:     my ($file)=@_;
16441:     my $curfext = lc((split(/\./,$file))[-1]);
16442:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16443:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16444:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16445: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16446: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16447: 	            $curfext.".gif") {
16448: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16449: 		$curfext.".gif";
16450: 	}
16451:     }
16452:     return &lonhttpdurl($iconname);
16453: } 
16454: 
16455: sub lonhttpdurl {
16456: #
16457: # Had been used for "small fry" static images on separate port 8080.
16458: # Modify here if lightweight http functionality desired again.
16459: # Currently eliminated due to increasing firewall issues.
16460: #
16461:     my ($url)=@_;
16462:     return $url;
16463: }
16464: 
16465: sub connection_aborted {
16466:     my ($r)=@_;
16467:     $r->print(" ");$r->rflush();
16468:     my $c = $r->connection;
16469:     return $c->aborted();
16470: }
16471: 
16472: #    Escapes strings that may have embedded 's that will be put into
16473: #    strings as 'strings'.
16474: sub escape_single {
16475:     my ($input) = @_;
16476:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16477:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16478:     return $input;
16479: }
16480: 
16481: #  Same as escape_single, but escape's "'s  This 
16482: #  can be used for  "strings"
16483: sub escape_double {
16484:     my ($input) = @_;
16485:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16486:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16487:     return $input;
16488: }
16489:  
16490: #   Escapes the last element of a full URL.
16491: sub escape_url {
16492:     my ($url)   = @_;
16493:     my @urlslices = split(/\//, $url,-1);
16494:     my $lastitem = &escape(pop(@urlslices));
16495:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16496: }
16497: 
16498: sub compare_arrays {
16499:     my ($arrayref1,$arrayref2) = @_;
16500:     my (@difference,%count);
16501:     @difference = ();
16502:     %count = ();
16503:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16504:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16505:         foreach my $element (keys(%count)) {
16506:             if ($count{$element} == 1) {
16507:                 push(@difference,$element);
16508:             }
16509:         }
16510:     }
16511:     return @difference;
16512: }
16513: 
16514: sub lon_status_items {
16515:     my %defaults = (
16516:                      E         => 100,
16517:                      W         => 4,
16518:                      N         => 1,
16519:                      U         => 5,
16520:                      threshold => 200,
16521:                      sysmail   => 2500,
16522:                    );
16523:     my %names = (
16524:                    E => 'Errors',
16525:                    W => 'Warnings',
16526:                    N => 'Notices',
16527:                    U => 'Unsent',
16528:                 );
16529:     return (\%defaults,\%names);
16530: }
16531: 
16532: # -------------------------------------------------------- Initialize user login
16533: sub init_user_environment {
16534:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16535:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16536: 
16537:     my $public=($username eq 'public' && $domain eq 'public');
16538: 
16539:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16540:     my $now=time;
16541: 
16542:     if ($public) {
16543: 	my $max_public=100;
16544: 	my $oldest;
16545: 	my $oldest_time=0;
16546: 	for(my $next=1;$next<=$max_public;$next++) {
16547: 	    if (-e $lonids."/publicuser_$next.id") {
16548: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16549: 		if ($mtime<$oldest_time || !$oldest_time) {
16550: 		    $oldest_time=$mtime;
16551: 		    $oldest=$next;
16552: 		}
16553: 	    } else {
16554: 		$cookie="publicuser_$next";
16555: 		last;
16556: 	    }
16557: 	}
16558: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16559:     } else {
16560: 	# See if old ID present, if so, remove if this isn't a robot,
16561: 	# killing any existing non-robot sessions
16562: 	if (!$args->{'robot'}) {
16563: 	    opendir(DIR,$lonids);
16564: 	    while ($filename=readdir(DIR)) {
16565: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16566:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16567:                             &GDBM_READER(),0640)) {
16568:                         my $linkedfile;
16569:                         if (exists($oldenv{'user.linkedenv'})) {
16570:                             $linkedfile = $oldenv{'user.linkedenv'};
16571:                         }
16572:                         untie(%oldenv);
16573:                         if (unlink("$lonids/$filename")) {
16574:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16575:                                 if (-l "$lonids/$linkedfile.id") {
16576:                                     unlink("$lonids/$linkedfile.id");
16577:                                 }
16578:                             }
16579:                         }
16580:                     } else {
16581:                         unlink($lonids.'/'.$filename);
16582:                     }
16583: 		}
16584: 	    }
16585: 	    closedir(DIR);
16586: # If there is a undeleted lockfile for the user's paste buffer remove it.
16587:             my $namespace = 'nohist_courseeditor';
16588:             my $lockingkey = 'paste'."\0".'locked_num';
16589:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16590:                                                 $domain,$username);
16591:             if (exists($lockhash{$lockingkey})) {
16592:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16593:                 unless ($delresult eq 'ok') {
16594:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16595:                 }
16596:             }
16597: 	}
16598: # Give them a new cookie
16599: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16600: 		                   : $now.$$.int(rand(10000)));
16601: 	$cookie="$username\_$id\_$domain\_$authhost";
16602:     
16603: # Initialize roles
16604: 
16605: 	($userroles,$firstaccenv,$timerintenv) = 
16606:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16607:     }
16608: # ------------------------------------ Check browser type and MathML capability
16609: 
16610:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16611:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16612: 
16613: # ------------------------------------------------------------- Get environment
16614: 
16615:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16616:     my ($tmp) = keys(%userenv);
16617:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16618: 	undef(%userenv);
16619:     }
16620:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16621: 	$form->{'interface'}=$userenv{'interface'};
16622:     }
16623:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16624: 
16625: # --------------- Do not trust query string to be put directly into environment
16626:     foreach my $option ('interface','localpath','localres') {
16627:         $form->{$option}=~s/[\n\r\=]//gs;
16628:     }
16629: # --------------------------------------------------------- Write first profile
16630: 
16631:     {
16632: 	my %initial_env = 
16633: 	    ("user.name"          => $username,
16634: 	     "user.domain"        => $domain,
16635: 	     "user.home"          => $authhost,
16636: 	     "browser.type"       => $clientbrowser,
16637: 	     "browser.version"    => $clientversion,
16638: 	     "browser.mathml"     => $clientmathml,
16639: 	     "browser.unicode"    => $clientunicode,
16640: 	     "browser.os"         => $clientos,
16641:              "browser.mobile"     => $clientmobile,
16642:              "browser.info"       => $clientinfo,
16643:              "browser.osversion"  => $clientosversion,
16644: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16645: 	     "request.course.fn"  => '',
16646: 	     "request.course.uri" => '',
16647: 	     "request.course.sec" => '',
16648: 	     "request.role"       => 'cm',
16649: 	     "request.role.adv"   => $env{'user.adv'},
16650: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16651: 
16652:         if ($form->{'localpath'}) {
16653: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16654: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16655:         }
16656: 	
16657: 	if ($form->{'interface'}) {
16658: 	    $form->{'interface'}=~s/\W//gs;
16659: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16660: 	    $env{'browser.interface'}=$form->{'interface'};
16661: 	}
16662: 
16663:         if ($form->{'iptoken'}) {
16664:             my $lonhost = $r->dir_config('lonHostID');
16665:             $initial_env{"user.noloadbalance"} = $lonhost;
16666:             $env{'user.noloadbalance'} = $lonhost;
16667:         }
16668: 
16669:         if ($form->{'noloadbalance'}) {
16670:             my @hosts = &Apache::lonnet::current_machine_ids();
16671:             my $hosthere = $form->{'noloadbalance'};
16672:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16673:                 $initial_env{"user.noloadbalance"} = $hosthere;
16674:                 $env{'user.noloadbalance'} = $hosthere;
16675:             }
16676:         }
16677: 
16678:         unless ($domain eq 'public') {
16679:             my %is_adv = ( is_adv => $env{'user.adv'} );
16680:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16681: 
16682:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16683:                 $userenv{'availabletools.'.$tool} = 
16684:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16685:                                                       undef,\%userenv,\%domdef,\%is_adv);
16686:             }
16687: 
16688:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
16689:                 $userenv{'canrequest.'.$crstype} =
16690:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16691:                                                       'reload','requestcourses',
16692:                                                       \%userenv,\%domdef,\%is_adv);
16693:             }
16694: 
16695:             $userenv{'canrequest.author'} =
16696:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16697:                                                   'reload','requestauthor',
16698:                                                   \%userenv,\%domdef,\%is_adv);
16699:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16700:                                                  $domain,$username);
16701:             my $reqstatus = $reqauthor{'author_status'};
16702:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16703:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16704:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16705:                                                       $reqauthor{'author'}{'timestamp'};
16706:                 }
16707:             }
16708:             my ($types,$typename) = &course_types();
16709:             if (ref($types) eq 'ARRAY') {
16710:                 my @options = ('approval','validate','autolimit');
16711:                 my $optregex = join('|',@options);
16712:                 my (%willtrust,%trustchecked);
16713:                 foreach my $type (@{$types}) {
16714:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
16715:                     if ($dom_str ne '') {
16716:                         my $updatedstr = '';
16717:                         my @possdomains = split(',',$dom_str);
16718:                         foreach my $entry (@possdomains) {
16719:                             my ($extdom,$extopt) = split(':',$entry);
16720:                             unless ($trustchecked{$extdom}) {
16721:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
16722:                                 $trustchecked{$extdom} = 1;
16723:                             }
16724:                             if ($willtrust{$extdom}) {
16725:                                 $updatedstr .= $entry.',';
16726:                             }
16727:                         }
16728:                         $updatedstr =~ s/,$//;
16729:                         if ($updatedstr) {
16730:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
16731:                         } else {
16732:                             delete($userenv{'reqcrsotherdom.'.$type});
16733:                         }
16734:                     }
16735:                 }
16736:             }
16737:         }
16738: 	$env{'user.environment'} = "$lonids/$cookie.id";
16739: 
16740: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16741: 		 &GDBM_WRCREAT(),0640)) {
16742: 	    &_add_to_env(\%disk_env,\%initial_env);
16743: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16744: 	    &_add_to_env(\%disk_env,$userroles);
16745:             if (ref($firstaccenv) eq 'HASH') {
16746:                 &_add_to_env(\%disk_env,$firstaccenv);
16747:             }
16748:             if (ref($timerintenv) eq 'HASH') {
16749:                 &_add_to_env(\%disk_env,$timerintenv);
16750:             }
16751: 	    if (ref($args->{'extra_env'})) {
16752: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16753: 	    }
16754: 	    untie(%disk_env);
16755: 	} else {
16756: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16757: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16758: 	    return 'error: '.$!;
16759: 	}
16760:     }
16761:     $env{'request.role'}='cm';
16762:     $env{'request.role.adv'}=$env{'user.adv'};
16763:     $env{'browser.type'}=$clientbrowser;
16764: 
16765:     return $cookie;
16766: 
16767: }
16768: 
16769: sub _add_to_env {
16770:     my ($idf,$env_data,$prefix) = @_;
16771:     if (ref($env_data) eq 'HASH') {
16772:         while (my ($key,$value) = each(%$env_data)) {
16773: 	    $idf->{$prefix.$key} = $value;
16774: 	    $env{$prefix.$key}   = $value;
16775:         }
16776:     }
16777: }
16778: 
16779: # --- Get the symbolic name of a problem and the url
16780: sub get_symb {
16781:     my ($request,$silent) = @_;
16782:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16783:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16784:     if ($symb eq '') {
16785:         if (!$silent) {
16786:             if (ref($request)) { 
16787:                 $request->print("Unable to handle ambiguous references:$url:.");
16788:             }
16789:             return ();
16790:         }
16791:     }
16792:     &Apache::lonenc::check_decrypt(\$symb);
16793:     return ($symb);
16794: }
16795: 
16796: # --------------------------------------------------------------Get annotation
16797: 
16798: sub get_annotation {
16799:     my ($symb,$enc) = @_;
16800: 
16801:     my $key = $symb;
16802:     if (!$enc) {
16803:         $key =
16804:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16805:     }
16806:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16807:     return $annotation{$key};
16808: }
16809: 
16810: sub clean_symb {
16811:     my ($symb,$delete_enc) = @_;
16812: 
16813:     &Apache::lonenc::check_decrypt(\$symb);
16814:     my $enc = $env{'request.enc'};
16815:     if ($delete_enc) {
16816:         delete($env{'request.enc'});
16817:     }
16818: 
16819:     return ($symb,$enc);
16820: }
16821: 
16822: ############################################################
16823: ############################################################
16824: 
16825: =pod
16826: 
16827: =head1 Routines for building display used to search for courses
16828: 
16829: 
16830: =over 4
16831: 
16832: =item * &build_filters()
16833: 
16834: Create markup for a table used to set filters to use when selecting
16835: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16836: and quotacheck.pl
16837: 
16838: 
16839: Inputs:
16840: 
16841: filterlist - anonymous array of fields to include as potential filters 
16842: 
16843: crstype - course type
16844: 
16845: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16846:               to pop-open a course selector (will contain "extra element"). 
16847: 
16848: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16849: 
16850: filter - anonymous hash of criteria and their values
16851: 
16852: action - form action
16853: 
16854: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16855: 
16856: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16857: 
16858: cloneruname - username of owner of new course who wants to clone
16859: 
16860: clonerudom - domain of owner of new course who wants to clone
16861: 
16862: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16863: 
16864: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16865: 
16866: codedom - domain
16867: 
16868: formname - value of form element named "form". 
16869: 
16870: fixeddom - domain, if fixed.
16871: 
16872: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16873: 
16874: cnameelement - name of form element in form on opener page which will receive title of selected course 
16875: 
16876: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16877: 
16878: cdomelement - name of form element in form on opener page which will receive domain of selected course
16879: 
16880: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16881: 
16882: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16883: 
16884: clonewarning - warning message about missing information for intended course owner when DC creates a course
16885: 
16886: 
16887: Returns: $output - HTML for display of search criteria, and hidden form elements.
16888: 
16889: 
16890: Side Effects: None
16891: 
16892: =cut
16893: 
16894: # ---------------------------------------------- search for courses based on last activity etc.
16895: 
16896: sub build_filters {
16897:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16898:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16899:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16900:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16901:         $clonetext,$clonewarning) = @_;
16902:     my ($list,$jscript);
16903:     my $onchange = 'javascript:updateFilters(this)';
16904:     my ($domainselectform,$sincefilterform,$createdfilterform,
16905:         $ownerdomselectform,$persondomselectform,$instcodeform,
16906:         $typeselectform,$instcodetitle);
16907:     if ($formname eq '') {
16908:         $formname = $caller;
16909:     }
16910:     foreach my $item (@{$filterlist}) {
16911:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16912:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16913:             if ($item eq 'domainfilter') {
16914:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16915:             } elsif ($item eq 'coursefilter') {
16916:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16917:             } elsif ($item eq 'ownerfilter') {
16918:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16919:             } elsif ($item eq 'ownerdomfilter') {
16920:                 $filter->{'ownerdomfilter'} =
16921:                     &LONCAPA::clean_domain($filter->{$item});
16922:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16923:                                                        'ownerdomfilter',1);
16924:             } elsif ($item eq 'personfilter') {
16925:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16926:             } elsif ($item eq 'persondomfilter') {
16927:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16928:                                                         'persondomfilter',1);
16929:             } else {
16930:                 $filter->{$item} =~ s/\W//g;
16931:             }
16932:             if (!$filter->{$item}) {
16933:                 $filter->{$item} = '';
16934:             }
16935:         }
16936:         if ($item eq 'domainfilter') {
16937:             my $allow_blank = 1;
16938:             if ($formname eq 'portform') {
16939:                 $allow_blank=0;
16940:             } elsif ($formname eq 'studentform') {
16941:                 $allow_blank=0;
16942:             }
16943:             if ($fixeddom) {
16944:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16945:                                     ' value="'.$codedom.'" />'.
16946:                                     &Apache::lonnet::domain($codedom,'description');
16947:             } else {
16948:                 $domainselectform = &select_dom_form($filter->{$item},
16949:                                                      'domainfilter',
16950:                                                       $allow_blank,'',$onchange);
16951:             }
16952:         } else {
16953:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16954:         }
16955:     }
16956: 
16957:     # last course activity filter and selection
16958:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16959: 
16960:     # course created filter and selection
16961:     if (exists($filter->{'createdfilter'})) {
16962:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16963:     }
16964: 
16965:     my $prefix = $crstype;
16966:     if ($crstype eq 'Placement') {
16967:         $prefix = 'Placement Test'
16968:     }
16969:     my %lt = &Apache::lonlocal::texthash(
16970:                 'cac' => "$prefix Activity",
16971:                 'ccr' => "$prefix Created",
16972:                 'cde' => "$prefix Title",
16973:                 'cdo' => "$prefix Domain",
16974:                 'ins' => 'Institutional Code',
16975:                 'inc' => 'Institutional Categorization',
16976:                 'cow' => "$prefix Owner/Co-owner",
16977:                 'cop' => "$prefix Personnel Includes",
16978:                 'cog' => 'Type',
16979:              );
16980: 
16981:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16982:         my $typeval = 'Course';
16983:         if ($crstype eq 'Community') {
16984:             $typeval = 'Community';
16985:         } elsif ($crstype eq 'Placement') {
16986:             $typeval = 'Placement';
16987:         }
16988:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16989:     } else {
16990:         $typeselectform =  '<select name="type" size="1"';
16991:         if ($onchange) {
16992:             $typeselectform .= ' onchange="'.$onchange.'"';
16993:         }
16994:         $typeselectform .= '>'."\n";
16995:         foreach my $posstype ('Course','Community','Placement') {
16996:             my $shown;
16997:             if ($posstype eq 'Placement') {
16998:                 $shown = &mt('Placement Test');
16999:             } else {
17000:                 $shown = &mt($posstype);
17001:             }
17002:             $typeselectform.='<option value="'.$posstype.'"'.
17003:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17004:         }
17005:         $typeselectform.="</select>";
17006:     }
17007: 
17008:     my ($cloneableonlyform,$cloneabletitle);
17009:     if (exists($filter->{'cloneableonly'})) {
17010:         my $cloneableon = '';
17011:         my $cloneableoff = ' checked="checked"';
17012:         if ($filter->{'cloneableonly'}) {
17013:             $cloneableon = $cloneableoff;
17014:             $cloneableoff = '';
17015:         }
17016:         $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>';
17017:         if ($formname eq 'ccrs') {
17018:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17019:         } else {
17020:             $cloneabletitle = &mt('Cloneable by you');
17021:         }
17022:     }
17023:     my $officialjs;
17024:     if ($crstype eq 'Course') {
17025:         if (exists($filter->{'instcodefilter'})) {
17026: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17027: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17028:             if ($codedom) { 
17029:                 $officialjs = 1;
17030:                 ($instcodeform,$jscript,$$numtitlesref) =
17031:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17032:                                                                   $officialjs,$codetitlesref);
17033:                 if ($jscript) {
17034:                     $jscript = '<script type="text/javascript">'."\n".
17035:                                '// <![CDATA['."\n".
17036:                                $jscript."\n".
17037:                                '// ]]>'."\n".
17038:                                '</script>'."\n";
17039:                 }
17040:             }
17041:             if ($instcodeform eq '') {
17042:                 $instcodeform =
17043:                     '<input type="text" name="instcodefilter" size="10" value="'.
17044:                     $list->{'instcodefilter'}.'" />';
17045:                 $instcodetitle = $lt{'ins'};
17046:             } else {
17047:                 $instcodetitle = $lt{'inc'};
17048:             }
17049:             if ($fixeddom) {
17050:                 $instcodetitle .= '<br />('.$codedom.')';
17051:             }
17052:         }
17053:     }
17054:     my $output = qq|
17055: <form method="post" name="filterpicker" action="$action">
17056: <input type="hidden" name="form" value="$formname" />
17057: |;
17058:     if ($formname eq 'modifycourse') {
17059:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17060:                    '<input type="hidden" name="prevphase" value="'.
17061:                    $prevphase.'" />'."\n";
17062:     } elsif ($formname eq 'quotacheck') {
17063:         $output .= qq|
17064: <input type="hidden" name="sortby" value="" />
17065: <input type="hidden" name="sortorder" value="" />
17066: |;
17067:     } else {
17068:         my $name_input;
17069:         if ($cnameelement ne '') {
17070:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17071:                           $cnameelement.'" />';
17072:         }
17073:         $output .= qq|
17074: <input type="hidden" name="cnumelement" value="$cnumelement" />
17075: <input type="hidden" name="cdomelement" value="$cdomelement" />
17076: $name_input
17077: $roleelement
17078: $multelement
17079: $typeelement
17080: |;
17081:         if ($formname eq 'portform') {
17082:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17083:         }
17084:     }
17085:     if ($fixeddom) {
17086:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17087:     }
17088:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17089:     if ($sincefilterform) {
17090:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17091:                   .$sincefilterform
17092:                   .&Apache::lonhtmlcommon::row_closure();
17093:     }
17094:     if ($createdfilterform) {
17095:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17096:                   .$createdfilterform
17097:                   .&Apache::lonhtmlcommon::row_closure();
17098:     }
17099:     if ($domainselectform) {
17100:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17101:                   .$domainselectform
17102:                   .&Apache::lonhtmlcommon::row_closure();
17103:     }
17104:     if ($typeselectform) {
17105:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17106:             $output .= $typeselectform;
17107:         } else {
17108:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17109:                       .$typeselectform
17110:                       .&Apache::lonhtmlcommon::row_closure();
17111:         }
17112:     }
17113:     if ($instcodeform) {
17114:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17115:                   .$instcodeform
17116:                   .&Apache::lonhtmlcommon::row_closure();
17117:     }
17118:     if (exists($filter->{'ownerfilter'})) {
17119:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17120:                    '<table><tr><td>'.&mt('Username').'<br />'.
17121:                    '<input type="text" name="ownerfilter" size="20" value="'.
17122:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17123:                    $ownerdomselectform.'</td></tr></table>'.
17124:                    &Apache::lonhtmlcommon::row_closure();
17125:     }
17126:     if (exists($filter->{'personfilter'})) {
17127:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17128:                    '<table><tr><td>'.&mt('Username').'<br />'.
17129:                    '<input type="text" name="personfilter" size="20" value="'.
17130:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17131:                    $persondomselectform.'</td></tr></table>'.
17132:                    &Apache::lonhtmlcommon::row_closure();
17133:     }
17134:     if (exists($filter->{'coursefilter'})) {
17135:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17136:                   .'<input type="text" name="coursefilter" size="25" value="'
17137:                   .$list->{'coursefilter'}.'" />'
17138:                   .&Apache::lonhtmlcommon::row_closure();
17139:     }
17140:     if ($cloneableonlyform) {
17141:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17142:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17143:     }
17144:     if (exists($filter->{'descriptfilter'})) {
17145:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17146:                   .'<input type="text" name="descriptfilter" size="40" value="'
17147:                   .$list->{'descriptfilter'}.'" />'
17148:                   .&Apache::lonhtmlcommon::row_closure(1);
17149:     }
17150:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17151:                '<input type="hidden" name="updater" value="" />'."\n".
17152:                '<input type="submit" name="gosearch" value="'.
17153:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17154:     return $jscript.$clonewarning.$output;
17155: }
17156: 
17157: =pod 
17158: 
17159: =item * &timebased_select_form()
17160: 
17161: Create markup for a dropdown list used to select a time-based
17162: filter e.g., Course Activity, Course Created, when searching for courses
17163: or communities
17164: 
17165: Inputs:
17166: 
17167: item - name of form element (sincefilter or createdfilter)
17168: 
17169: filter - anonymous hash of criteria and their values
17170: 
17171: Returns: HTML for a select box contained a blank, then six time selections,
17172:          with value set in incoming form variables currently selected. 
17173: 
17174: Side Effects: None
17175: 
17176: =cut
17177: 
17178: sub timebased_select_form {
17179:     my ($item,$filter) = @_;
17180:     if (ref($filter) eq 'HASH') {
17181:         $filter->{$item} =~ s/[^\d-]//g;
17182:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17183:         return &select_form(
17184:                             $filter->{$item},
17185:                             $item,
17186:                             {      '-1' => '',
17187:                                 '86400' => &mt('today'),
17188:                                '604800' => &mt('last week'),
17189:                               '2592000' => &mt('last month'),
17190:                               '7776000' => &mt('last three months'),
17191:                              '15552000' => &mt('last six months'),
17192:                              '31104000' => &mt('last year'),
17193:                     'select_form_order' =>
17194:                            ['-1','86400','604800','2592000','7776000',
17195:                             '15552000','31104000']});
17196:     }
17197: }
17198: 
17199: =pod
17200: 
17201: =item * &js_changer()
17202: 
17203: Create script tag containing Javascript used to submit course search form
17204: when course type or domain is changed, and also to hide 'Searching ...' on
17205: page load completion for page showing search result.
17206: 
17207: Inputs: None
17208: 
17209: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
17210: 
17211: Side Effects: None
17212: 
17213: =cut
17214: 
17215: sub js_changer {
17216:     return <<ENDJS;
17217: <script type="text/javascript">
17218: // <![CDATA[
17219: function updateFilters(caller) {
17220:     if (typeof(caller) != "undefined") {
17221:         document.filterpicker.updater.value = caller.name;
17222:     }
17223:     document.filterpicker.submit();
17224: }
17225: 
17226: function hideSearching() {
17227:     if (document.getElementById('searching')) {
17228:         document.getElementById('searching').style.display = 'none';
17229:     }
17230:     return;
17231: }
17232: 
17233: // ]]>
17234: </script>
17235: 
17236: ENDJS
17237: }
17238: 
17239: =pod
17240: 
17241: =item * &search_courses()
17242: 
17243: Process selected filters form course search form and pass to lonnet::courseiddump
17244: to retrieve a hash for which keys are courseIDs which match the selected filters.
17245: 
17246: Inputs:
17247: 
17248: dom - domain being searched 
17249: 
17250: type - course type ('Course' or 'Community' or '.' if any).
17251: 
17252: filter - anonymous hash of criteria and their values
17253: 
17254: numtitles - for institutional codes - number of categories
17255: 
17256: cloneruname - optional username of new course owner
17257: 
17258: clonerudom - optional domain of new course owner
17259: 
17260: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
17261:             (used when DC is using course creation form)
17262: 
17263: codetitles - reference to array of titles of components in institutional codes (official courses).
17264: 
17265: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17266:            (and so can clone automatically)
17267: 
17268: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17269: 
17270: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
17271:               courses to clone 
17272: 
17273: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17274: 
17275: 
17276: Side Effects: None
17277: 
17278: =cut
17279: 
17280: 
17281: sub search_courses {
17282:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17283:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17284:     my (%courses,%showcourses,$cloner);
17285:     if (($filter->{'ownerfilter'} ne '') ||
17286:         ($filter->{'ownerdomfilter'} ne '')) {
17287:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17288:                                        $filter->{'ownerdomfilter'};
17289:     }
17290:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17291:         if (!$filter->{$item}) {
17292:             $filter->{$item}='.';
17293:         }
17294:     }
17295:     my $now = time;
17296:     my $timefilter =
17297:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17298:     my ($createdbefore,$createdafter);
17299:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17300:         $createdbefore = $now;
17301:         $createdafter = $now-$filter->{'createdfilter'};
17302:     }
17303:     my ($instcodefilter,$regexpok);
17304:     if ($numtitles) {
17305:         if ($env{'form.official'} eq 'on') {
17306:             $instcodefilter =
17307:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17308:             $regexpok = 1;
17309:         } elsif ($env{'form.official'} eq 'off') {
17310:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17311:             unless ($instcodefilter eq '') {
17312:                 $regexpok = -1;
17313:             }
17314:         }
17315:     } else {
17316:         $instcodefilter = $filter->{'instcodefilter'};
17317:     }
17318:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17319:     if ($type eq '') { $type = '.'; }
17320: 
17321:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17322:         $cloner = $cloneruname.':'.$clonerudom;
17323:     }
17324:     %courses = &Apache::lonnet::courseiddump($dom,
17325:                                              $filter->{'descriptfilter'},
17326:                                              $timefilter,
17327:                                              $instcodefilter,
17328:                                              $filter->{'combownerfilter'},
17329:                                              $filter->{'coursefilter'},
17330:                                              undef,undef,$type,$regexpok,undef,undef,
17331:                                              undef,undef,$cloner,$cc_clone,
17332:                                              $filter->{'cloneableonly'},
17333:                                              $createdbefore,$createdafter,undef,
17334:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17335:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17336:         my $ccrole;
17337:         if ($type eq 'Community') {
17338:             $ccrole = 'co';
17339:         } else {
17340:             $ccrole = 'cc';
17341:         }
17342:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17343:                                                      $filter->{'persondomfilter'},
17344:                                                      'userroles',undef,
17345:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17346:                                                      $dom);
17347:         foreach my $role (keys(%rolehash)) {
17348:             my ($cnum,$cdom,$courserole) = split(':',$role);
17349:             my $cid = $cdom.'_'.$cnum;
17350:             if (exists($courses{$cid})) {
17351:                 if (ref($courses{$cid}) eq 'HASH') {
17352:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17353:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17354:                             push(@{$courses{$cid}{roles}},$courserole);
17355:                         }
17356:                     } else {
17357:                         $courses{$cid}{roles} = [$courserole];
17358:                     }
17359:                     $showcourses{$cid} = $courses{$cid};
17360:                 }
17361:             }
17362:         }
17363:         %courses = %showcourses;
17364:     }
17365:     return %courses;
17366: }
17367: 
17368: =pod
17369: 
17370: =back
17371: 
17372: =head1 Routines for version requirements for current course.
17373: 
17374: =over 4
17375: 
17376: =item * &check_release_required()
17377: 
17378: Compares required LON-CAPA version with version on server, and
17379: if required version is newer looks for a server with the required version.
17380: 
17381: Looks first at servers in user's owen domain; if none suitable, looks at
17382: servers in course's domain are permitted to host sessions for user's domain.
17383: 
17384: Inputs:
17385: 
17386: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17387: 
17388: $courseid - Course ID of current course
17389: 
17390: $rolecode - User's current role in course (for switchserver query string).
17391: 
17392: $required - LON-CAPA version needed by course (format: Major.Minor).
17393: 
17394: 
17395: Returns:
17396: 
17397: $switchserver - query string tp append to /adm/switchserver call (if 
17398:                 current server's LON-CAPA version is too old. 
17399: 
17400: $warning - Message is displayed if no suitable server could be found.
17401: 
17402: =cut
17403: 
17404: sub check_release_required {
17405:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17406:     my ($switchserver,$warning);
17407:     if ($required ne '') {
17408:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17409:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17410:         if ($reqdmajor ne '' && $reqdminor ne '') {
17411:             my $otherserver;
17412:             if (($major eq '' && $minor eq '') ||
17413:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17414:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17415:                 my $switchlcrev =
17416:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17417:                                                            $userdomserver);
17418:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17419:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17420:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17421:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17422:                     if ($cdom ne $env{'user.domain'}) {
17423:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17424:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17425:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17426:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17427:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17428:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17429:                         my $canhost =
17430:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17431:                                                               $coursedomserver,
17432:                                                               $remoterev,
17433:                                                               $udomdefaults{'remotesessions'},
17434:                                                               $defdomdefaults{'hostedsessions'});
17435: 
17436:                         if ($canhost) {
17437:                             $otherserver = $coursedomserver;
17438:                         } else {
17439:                             $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.");
17440:                         }
17441:                     } else {
17442:                         $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).");
17443:                     }
17444:                 } else {
17445:                     $otherserver = $userdomserver;
17446:                 }
17447:             }
17448:             if ($otherserver ne '') {
17449:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17450:             }
17451:         }
17452:     }
17453:     return ($switchserver,$warning);
17454: }
17455: 
17456: =pod
17457: 
17458: =item * &check_release_result()
17459: 
17460: Inputs:
17461: 
17462: $switchwarning - Warning message if no suitable server found to host session.
17463: 
17464: $switchserver - query string to append to /adm/switchserver containing lonHostID
17465:                 and current role.
17466: 
17467: Returns: HTML to display with information about requirement to switch server.
17468:          Either displaying warning with link to Roles/Courses screen or
17469:          display link to switchserver.
17470: 
17471: =cut
17472: 
17473: sub check_release_result {
17474:     my ($switchwarning,$switchserver) = @_;
17475:     my $output = &start_page('Selected course unavailable on this server').
17476:                  '<p class="LC_warning">';
17477:     if ($switchwarning) {
17478:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17479:         if (&show_course()) {
17480:             $output .= &mt('Display courses');
17481:         } else {
17482:             $output .= &mt('Display roles');
17483:         }
17484:         $output .= '</a>';
17485:     } elsif ($switchserver) {
17486:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17487:                    '<br />'.
17488:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17489:                    &mt('Switch Server').
17490:                    '</a>';
17491:     }
17492:     $output .= '</p>'.&end_page();
17493:     return $output;
17494: }
17495: 
17496: =pod
17497: 
17498: =item * &needs_coursereinit()
17499: 
17500: Determine if course contents stored for user's session needs to be
17501: refreshed, because content has changed since "Big Hash" last tied.
17502: 
17503: Check for change is made if time last checked is more than 10 minutes ago
17504: (by default).
17505: 
17506: Inputs:
17507: 
17508: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17509: 
17510: $interval (optional) - Time which may elapse (in s) between last check for content
17511:                        change in current course. (default: 600 s).  
17512: 
17513: Returns: an array; first element is:
17514: 
17515: =over 4
17516: 
17517: 'switch' - if content updates mean user's session
17518:            needs to be switched to a server running a newer LON-CAPA version
17519:  
17520: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17521:            on current server hosting user's session                
17522: 
17523: ''       - if no action required.
17524: 
17525: =back
17526: 
17527: If first item element is 'switch':
17528: 
17529: second item is $switchwarning - Warning message if no suitable server found to host session. 
17530: 
17531: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17532:                               and current role. 
17533: 
17534: otherwise: no other elements returned.
17535: 
17536: =back
17537: 
17538: =cut
17539: 
17540: sub needs_coursereinit {
17541:     my ($loncaparev,$interval) = @_;
17542:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17543:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17544:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17545:     my $now = time;
17546:     if ($interval eq '') {
17547:         $interval = 600;
17548:     }
17549:     if (($now-$env{'request.course.timechecked'})>$interval) {
17550:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17551:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17552:         if ($blocked) {
17553:             return ();
17554:         }
17555:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17556:         if ($lastchange > $env{'request.course.tied'}) {
17557:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17558:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17559:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17560:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17561:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17562:                                              $curr_reqd_hash{'internal.releaserequired'}});
17563:                     my ($switchserver,$switchwarning) =
17564:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17565:                                                 $curr_reqd_hash{'internal.releaserequired'});
17566:                     if ($switchwarning ne '' || $switchserver ne '') {
17567:                         return ('switch',$switchwarning,$switchserver);
17568:                     }
17569:                 }
17570:             }
17571:             return ('update');
17572:         }
17573:     }
17574:     return ();
17575: }
17576: 
17577: sub update_content_constraints {
17578:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
17579:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17580:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17581:     my (%checkresponsetypes,%checkcrsrestypes);
17582:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17583:         my ($item,$name,$value) = split(/:/,$key);
17584:         if ($item eq 'resourcetag') {
17585:             if ($name eq 'responsetype') {
17586:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17587:             }
17588:         } elsif ($item eq 'course') {
17589:             if ($name eq 'courserestype') {
17590:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
17591:             }
17592:         }
17593:     }
17594:     my $navmap = Apache::lonnavmaps::navmap->new();
17595:     if (defined($navmap)) {
17596:         my (%allresponses,%allcrsrestypes);
17597:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
17598:             if ($res->is_tool()) {
17599:                 if ($allcrsrestypes{'exttool'}) {
17600:                     $allcrsrestypes{'exttool'} ++;
17601:                 } else {
17602:                     $allcrsrestypes{'exttool'} = 1;
17603:                 }
17604:                 next;
17605:             }
17606:             my %responses = $res->responseTypes();
17607:             foreach my $key (keys(%responses)) {
17608:                 next unless(exists($checkresponsetypes{$key}));
17609:                 $allresponses{$key} += $responses{$key};
17610:             }
17611:         }
17612:         foreach my $key (keys(%allresponses)) {
17613:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17614:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17615:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17616:             }
17617:         }
17618:         foreach my $key (keys(%allcrsrestypes)) {
17619:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
17620:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17621:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17622:             }
17623:         }
17624:         undef($navmap);
17625:     }
17626:     my (@resources,@order,@resparms,@zombies);
17627:     if ($keeporder) {
17628:         use LONCAPA::map;
17629:         @resources = @LONCAPA::map::resources;
17630:         @order = @LONCAPA::map::order;
17631:         @resparms = @LONCAPA::map::resparms;
17632:         @zombies = @LONCAPA::map::zombies;
17633:     }
17634:     my $suppmap = 'supplemental.sequence';
17635:     my ($suppcount,$supptools,$errors) = (0,0,0);
17636:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
17637:                                                             $suppcount,$supptools,$errors);
17638:     if ($keeporder) {
17639:         @LONCAPA::map::resources = @resources;
17640:         @LONCAPA::map::order = @order;
17641:         @LONCAPA::map::resparms = @resparms;
17642:         @LONCAPA::map::zombies = @zombies;
17643:     }
17644:     if ($supptools) {
17645:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
17646:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17647:             ($reqdmajor,$reqdminor) = ($major,$minor);
17648:         }
17649:     }
17650:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17651:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17652:     }
17653:     return;
17654: }
17655: 
17656: sub allmaps_incourse {
17657:     my ($cdom,$cnum,$chome,$cid) = @_;
17658:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17659:         $cid = $env{'request.course.id'};
17660:         $cdom = $env{'course.'.$cid.'.domain'};
17661:         $cnum = $env{'course.'.$cid.'.num'};
17662:         $chome = $env{'course.'.$cid.'.home'};
17663:     }
17664:     my %allmaps = ();
17665:     my $lastchange =
17666:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17667:     if ($lastchange > $env{'request.course.tied'}) {
17668:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17669:         unless ($ferr) {
17670:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
17671:         }
17672:     }
17673:     my $navmap = Apache::lonnavmaps::navmap->new();
17674:     if (defined($navmap)) {
17675:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17676:             $allmaps{$res->src()} = 1;
17677:         }
17678:     }
17679:     return \%allmaps;
17680: }
17681: 
17682: sub parse_supplemental_title {
17683:     my ($title) = @_;
17684: 
17685:     my ($foldertitle,$renametitle);
17686:     if ($title =~ /&amp;&amp;&amp;/) {
17687:         $title = &HTML::Entites::decode($title);
17688:     }
17689:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17690:         $renametitle=$4;
17691:         my ($time,$uname,$udom) = ($1,$2,$3);
17692:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17693:         my $name =  &plainname($uname,$udom);
17694:         $name = &HTML::Entities::encode($name,'"<>&\'');
17695:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17696:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17697:             $name.': <br />'.$foldertitle;
17698:     }
17699:     if (wantarray) {
17700:         return ($title,$foldertitle,$renametitle);
17701:     }
17702:     return $title;
17703: }
17704: 
17705: sub recurse_supplemental {
17706:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
17707:     if ($suppmap) {
17708:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17709:         if ($fatal) {
17710:             $errors ++;
17711:         } else {
17712:             if ($#LONCAPA::map::resources > 0) {
17713:                 foreach my $res (@LONCAPA::map::resources) {
17714:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17715:                     if (($src ne '') && ($status eq 'res')) {
17716:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17717:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
17718:                                                                    $numfiles,$numexttools,$errors);
17719:                         } else {
17720:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
17721:                                 $numexttools ++;
17722:                             }
17723:                             $numfiles ++;
17724:                         }
17725:                     }
17726:                 }
17727:             }
17728:         }
17729:     }
17730:     return ($numfiles,$numexttools,$errors);
17731: }
17732: 
17733: sub symb_to_docspath {
17734:     my ($symb,$navmapref) = @_;
17735:     return unless ($symb && ref($navmapref));
17736:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17737:     if ($resurl=~/\.(sequence|page)$/) {
17738:         $mapurl=$resurl;
17739:     } elsif ($resurl eq 'adm/navmaps') {
17740:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17741:     }
17742:     my $mapresobj;
17743:     unless (ref($$navmapref)) {
17744:         $$navmapref = Apache::lonnavmaps::navmap->new();
17745:     }
17746:     if (ref($$navmapref)) {
17747:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17748:     }
17749:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17750:     my $type=$2;
17751:     my $path;
17752:     if (ref($mapresobj)) {
17753:         my $pcslist = $mapresobj->map_hierarchy();
17754:         if ($pcslist ne '') {
17755:             foreach my $pc (split(/,/,$pcslist)) {
17756:                 next if ($pc <= 1);
17757:                 my $res = $$navmapref->getByMapPc($pc);
17758:                 if (ref($res)) {
17759:                     my $thisurl = $res->src();
17760:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17761:                     my $thistitle = $res->title();
17762:                     $path .= '&'.
17763:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17764:                              &escape($thistitle).
17765:                              ':'.$res->randompick().
17766:                              ':'.$res->randomout().
17767:                              ':'.$res->encrypted().
17768:                              ':'.$res->randomorder().
17769:                              ':'.$res->is_page();
17770:                 }
17771:             }
17772:         }
17773:         $path =~ s/^\&//;
17774:         my $maptitle = $mapresobj->title();
17775:         if ($mapurl eq 'default') {
17776:             $maptitle = 'Main Content';
17777:         }
17778:         $path .= (($path ne '')? '&' : '').
17779:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17780:                  &escape($maptitle).
17781:                  ':'.$mapresobj->randompick().
17782:                  ':'.$mapresobj->randomout().
17783:                  ':'.$mapresobj->encrypted().
17784:                  ':'.$mapresobj->randomorder().
17785:                  ':'.$mapresobj->is_page();
17786:     } else {
17787:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17788:         my $ispage = (($type eq 'page')? 1 : '');
17789:         if ($mapurl eq 'default') {
17790:             $maptitle = 'Main Content';
17791:         }
17792:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17793:                 &escape($maptitle).':::::'.$ispage;
17794:     }
17795:     unless ($mapurl eq 'default') {
17796:         $path = 'default&'.
17797:                 &escape('Main Content').
17798:                 ':::::&'.$path;
17799:     }
17800:     return $path;
17801: }
17802: 
17803: sub captcha_display {
17804:     my ($context,$lonhost,$defdom) = @_;
17805:     my ($output,$error);
17806:     my ($captcha,$pubkey,$privkey,$version) = 
17807:         &get_captcha_config($context,$lonhost,$defdom);
17808:     if ($captcha eq 'original') {
17809:         $output = &create_captcha();
17810:         unless ($output) {
17811:             $error = 'captcha';
17812:         }
17813:     } elsif ($captcha eq 'recaptcha') {
17814:         $output = &create_recaptcha($pubkey,$version);
17815:         unless ($output) {
17816:             $error = 'recaptcha';
17817:         }
17818:     }
17819:     return ($output,$error,$captcha,$version);
17820: }
17821: 
17822: sub captcha_response {
17823:     my ($context,$lonhost,$defdom) = @_;
17824:     my ($captcha_chk,$captcha_error);
17825:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17826:     if ($captcha eq 'original') {
17827:         ($captcha_chk,$captcha_error) = &check_captcha();
17828:     } elsif ($captcha eq 'recaptcha') {
17829:         $captcha_chk = &check_recaptcha($privkey,$version);
17830:     } else {
17831:         $captcha_chk = 1;
17832:     }
17833:     return ($captcha_chk,$captcha_error);
17834: }
17835: 
17836: sub get_captcha_config {
17837:     my ($context,$lonhost,$dom_in_effect) = @_;
17838:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17839:     my $hostname = &Apache::lonnet::hostname($lonhost);
17840:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17841:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17842:     if ($context eq 'usercreation') {
17843:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17844:         if (ref($domconfig{$context}) eq 'HASH') {
17845:             $hashtocheck = $domconfig{$context}{'cancreate'};
17846:             if (ref($hashtocheck) eq 'HASH') {
17847:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17848:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17849:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17850:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17851:                     }
17852:                     if ($privkey && $pubkey) {
17853:                         $captcha = 'recaptcha';
17854:                         $version = $hashtocheck->{'recaptchaversion'};
17855:                         if ($version ne '2') {
17856:                             $version = 1;
17857:                         }
17858:                     } else {
17859:                         $captcha = 'original';
17860:                     }
17861:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17862:                     $captcha = 'original';
17863:                 }
17864:             }
17865:         } else {
17866:             $captcha = 'captcha';
17867:         }
17868:     } elsif ($context eq 'login') {
17869:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17870:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17871:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17872:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17873:             if ($privkey && $pubkey) {
17874:                 $captcha = 'recaptcha';
17875:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17876:                 if ($version ne '2') {
17877:                     $version = 1; 
17878:                 }
17879:             } else {
17880:                 $captcha = 'original';
17881:             }
17882:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17883:             $captcha = 'original';
17884:         }
17885:     } elsif ($context eq 'passwords') {
17886:         if ($dom_in_effect) {
17887:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17888:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17889:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17890:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17891:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17892:                 }
17893:                 if ($privkey && $pubkey) {
17894:                     $captcha = 'recaptcha';
17895:                     $version = $passwdconf{'recaptchaversion'};
17896:                     if ($version ne '2') {
17897:                         $version = 1;
17898:                     }
17899:                 } else {
17900:                     $captcha = 'original';
17901:                 }
17902:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17903:                 $captcha = 'original';
17904:             }
17905:         }
17906:     } 
17907:     return ($captcha,$pubkey,$privkey,$version);
17908: }
17909: 
17910: sub create_captcha {
17911:     my %captcha_params = &captcha_settings();
17912:     my ($output,$maxtries,$tries) = ('',10,0);
17913:     while ($tries < $maxtries) {
17914:         $tries ++;
17915:         my $captcha = Authen::Captcha->new (
17916:                                            output_folder => $captcha_params{'output_dir'},
17917:                                            data_folder   => $captcha_params{'db_dir'},
17918:                                           );
17919:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17920: 
17921:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17922:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17923:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17924:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17925:                       '<br />'.
17926:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17927:             last;
17928:         }
17929:     }
17930:     if ($output eq '') {
17931:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17932:     }
17933:     return $output;
17934: }
17935: 
17936: sub captcha_settings {
17937:     my %captcha_params = (
17938:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17939:                            www_output_dir => "/captchaspool",
17940:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17941:                            numchars       => '5',
17942:                          );
17943:     return %captcha_params;
17944: }
17945: 
17946: sub check_captcha {
17947:     my ($captcha_chk,$captcha_error);
17948:     my $code = $env{'form.code'};
17949:     my $md5sum = $env{'form.crypt'};
17950:     my %captcha_params = &captcha_settings();
17951:     my $captcha = Authen::Captcha->new(
17952:                       output_folder => $captcha_params{'output_dir'},
17953:                       data_folder   => $captcha_params{'db_dir'},
17954:                   );
17955:     $captcha_chk = $captcha->check_code($code,$md5sum);
17956:     my %captcha_hash = (
17957:                         0       => 'Code not checked (file error)',
17958:                        -1      => 'Failed: code expired',
17959:                        -2      => 'Failed: invalid code (not in database)',
17960:                        -3      => 'Failed: invalid code (code does not match crypt)',
17961:     );
17962:     if ($captcha_chk != 1) {
17963:         $captcha_error = $captcha_hash{$captcha_chk}
17964:     }
17965:     return ($captcha_chk,$captcha_error);
17966: }
17967: 
17968: sub create_recaptcha {
17969:     my ($pubkey,$version) = @_;
17970:     if ($version >= 2) {
17971:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17972:     } else {
17973:         my $use_ssl;
17974:         if ($ENV{'SERVER_PORT'} == 443) {
17975:             $use_ssl = 1;
17976:         }
17977:         my $captcha = Captcha::reCAPTCHA->new;
17978:         return $captcha->get_options_setter({theme => 'white'})."\n".
17979:                $captcha->get_html($pubkey,undef,$use_ssl).
17980:                &mt('If the text is hard to read, [_1] will replace them.',
17981:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17982:                '<br /><br />';
17983:     }
17984: }
17985: 
17986: sub check_recaptcha {
17987:     my ($privkey,$version) = @_;
17988:     my $captcha_chk;
17989:     if ($version >= 2) {
17990:         my %info = (
17991:                      secret   => $privkey, 
17992:                      response => $env{'form.g-recaptcha-response'},
17993:                      remoteip => $ENV{'REMOTE_ADDR'},
17994:                    );
17995:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
17996:         $request->content(join('&',map {
17997:                          my $name = escape($_);
17998:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
17999:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
18000:                          : &escape($info{$_}) );
18001:         } keys(%info)));
18002:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18003:         if ($response->is_success)  {
18004:             my $data = JSON::DWIW->from_json($response->decoded_content);
18005:             if (ref($data) eq 'HASH') {
18006:                 if ($data->{'success'}) {
18007:                     $captcha_chk = 1;
18008:                 }
18009:             }
18010:         }
18011:     } else {
18012:         my $captcha = Captcha::reCAPTCHA->new;
18013:         my $captcha_result =
18014:             $captcha->check_answer(
18015:                                     $privkey,
18016:                                     $ENV{'REMOTE_ADDR'},
18017:                                     $env{'form.recaptcha_challenge_field'},
18018:                                     $env{'form.recaptcha_response_field'},
18019:                                   );
18020:         if ($captcha_result->{is_valid}) {
18021:             $captcha_chk = 1;
18022:         }
18023:     }
18024:     return $captcha_chk;
18025: }
18026: 
18027: sub emailusername_info {
18028:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18029:     my %titles = &Apache::lonlocal::texthash (
18030:                      lastname      => 'Last Name',
18031:                      firstname     => 'First Name',
18032:                      institution   => 'School/college/university',
18033:                      location      => "School's city, state/province, country",
18034:                      web           => "School's web address",
18035:                      officialemail => 'E-mail address at institution (if different)',
18036:                      id            => 'Student/Employee ID',
18037:                  );
18038:     return (\@fields,\%titles);
18039: }
18040: 
18041: sub cleanup_html {
18042:     my ($incoming) = @_;
18043:     my $outgoing;
18044:     if ($incoming ne '') {
18045:         $outgoing = $incoming;
18046:         $outgoing =~ s/;/&#059;/g;
18047:         $outgoing =~ s/\#/&#035;/g;
18048:         $outgoing =~ s/\&/&#038;/g;
18049:         $outgoing =~ s/</&#060;/g;
18050:         $outgoing =~ s/>/&#062;/g;
18051:         $outgoing =~ s/\(/&#040/g;
18052:         $outgoing =~ s/\)/&#041;/g;
18053:         $outgoing =~ s/"/&#034;/g;
18054:         $outgoing =~ s/'/&#039;/g;
18055:         $outgoing =~ s/\$/&#036;/g;
18056:         $outgoing =~ s{/}{&#047;}g;
18057:         $outgoing =~ s/=/&#061;/g;
18058:         $outgoing =~ s/\\/&#092;/g
18059:     }
18060:     return $outgoing;
18061: }
18062: 
18063: # Checks for critical messages and returns a redirect url if one exists.
18064: # $interval indicates how often to check for messages.
18065: # $context is the calling context -- roles, grades, contents, menu or flip. 
18066: sub critical_redirect {
18067:     my ($interval,$context) = @_;
18068:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18069:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18070:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18071:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18072:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
18073:             if ($blocked) {
18074:                 my $checkrole = "cm./$cdom/$cnum";
18075:                 if ($env{'request.course.sec'} ne '') {
18076:                     $checkrole .= "/$env{'request.course.sec'}";
18077:                 }
18078:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18079:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18080:                     return;
18081:                 }
18082:             }
18083:         }
18084:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
18085:                                         $env{'user.name'});
18086:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18087:         my $redirecturl;
18088:         if ($what[0]) {
18089: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
18090: 	        $redirecturl='/adm/email?critical=display';
18091: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
18092:                 return (1, $url);
18093:             }
18094:         }
18095:     } 
18096:     return ();
18097: }
18098: 
18099: # Use:
18100: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18101: #
18102: ##################################################
18103: #          password associated functions         #
18104: ##################################################
18105: sub des_keys {
18106:     # Make a new key for DES encryption.
18107:     # Each key has two parts which are returned separately.
18108:     # Please note:  Each key must be passed through the &hex function
18109:     # before it is output to the web browser.  The hex versions cannot
18110:     # be used to decrypt.
18111:     my @hexstr=('0','1','2','3','4','5','6','7',
18112:                 '8','9','a','b','c','d','e','f');
18113:     my $lkey='';
18114:     for (0..7) {
18115:         $lkey.=$hexstr[rand(15)];
18116:     }
18117:     my $ukey='';
18118:     for (0..7) {
18119:         $ukey.=$hexstr[rand(15)];
18120:     }
18121:     return ($lkey,$ukey);
18122: }
18123: 
18124: sub des_decrypt {
18125:     my ($key,$cyphertext) = @_;
18126:     my $keybin=pack("H16",$key);
18127:     my $cypher;
18128:     if ($Crypt::DES::VERSION>=2.03) {
18129:         $cypher=new Crypt::DES $keybin;
18130:     } else {
18131:         $cypher=new DES $keybin;
18132:     }
18133:     my $plaintext='';
18134:     my $cypherlength = length($cyphertext);
18135:     my $numchunks = int($cypherlength/32);
18136:     for (my $j=0; $j<$numchunks; $j++) {
18137:         my $start = $j*32;
18138:         my $cypherblock = substr($cyphertext,$start,32);
18139:         my $chunk =
18140:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18141:         $chunk .=
18142:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18143:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18144:         $plaintext .= $chunk;
18145:     }
18146:     return $plaintext;
18147: }
18148: 
18149: sub make_short_symbs {
18150:     my ($cdom,$cnum,$navmap) = @_;
18151:     return unless (ref($navmap));
18152:     my ($numnew,@errors);
18153:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18154:     if (@toshorten) {
18155:         my (%maps,%resources,%titles);
18156:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18157:                                                                'shorturls',$cdom,$cnum);
18158:         my %tocreate;
18159:         if (keys(%resources)) {
18160:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18161:                 my $symb = $resources{$item};
18162:                 if ($symb) {
18163:                     $tocreate{$cnum.'&'.$symb} = 1;
18164:                 }
18165:             }
18166:         }
18167:         if (keys(%tocreate)) {
18168:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18169:             my $su = Short::URL->new(no_vowels => 1);
18170:             my $init = '';
18171:             my (%newunique,%addcourse,%courseonly,%failed);
18172:             # get lock on tiny db
18173:             my $now = time;
18174:             my $lockhash = {
18175:                                 "lock\0$now" => $env{'user.name'}.
18176:                                                 ':'.$env{'user.domain'},
18177:                             };
18178:             my $tries = 0;
18179:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18180:             my ($code,$error);
18181:             while (($gotlock ne 'ok') && ($tries<3)) {
18182:                 $tries ++;
18183:                 sleep 1;
18184:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18185:             }
18186:             if ($gotlock eq 'ok') {
18187:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18188:                                        \%addcourse,\%courseonly,\%failed);
18189:                 if (keys(%failed)) {
18190:                     my $numfailed = scalar(keys(%failed));
18191:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18192:                 }
18193:                 if (keys(%newunique)) {
18194:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18195:                     if ($putres eq 'ok') {
18196:                         $numnew = scalar(keys(%newunique));
18197:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18198:                         unless ($newputres eq 'ok') {
18199:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18200:                         }
18201:                     } else {
18202:                         push(@errors,&mt('error: could not store unique six character URLs'));
18203:                     }
18204:                 }
18205:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18206:                 unless ($dellockres eq 'ok') {
18207:                     push(@errors,&mt('error: could not release lockfile'));
18208:                 }
18209:             } else {
18210:                 push(@errors,&mt('error: could not obtain lockfile'));
18211:             }
18212:             if (keys(%courseonly)) {
18213:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18214:                 if ($result ne 'ok') {
18215:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18216:                 }
18217:             }
18218:         }
18219:     }
18220:     return ($numnew,\@errors);
18221: }
18222: 
18223: sub shorten_symbs {
18224:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18225:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18226:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18227:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18228:     my (%possibles,%collisions);
18229:     foreach my $key (keys(%{$tocreate})) {
18230:         my $num = String::CRC32::crc32($key);
18231:         my $tiny = $su->encode($num,$init);
18232:         if ($tiny) {
18233:             $possibles{$tiny} = $key;
18234:         }
18235:     }
18236:     if (!$init) {
18237:         $init = 1;
18238:     } else {
18239:         $init ++;
18240:     }
18241:     if (keys(%possibles)) {
18242:         my @posstiny = keys(%possibles);
18243:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18244:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18245:         if (keys(%currtiny)) {
18246:             foreach my $key (keys(%currtiny)) {
18247:                 next if ($currtiny{$key} eq '');
18248:                 if ($currtiny{$key} eq $possibles{$key}) {
18249:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18250:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18251:                         $courseonly->{$tsymb} = $key;
18252:                     }
18253:                 } else {
18254:                     $collisions{$possibles{$key}} = 1;
18255:                 }
18256:                 delete($possibles{$key});
18257:             }
18258:         }
18259:         foreach my $key (keys(%possibles)) {
18260:             $newunique->{$key} = $possibles{$key};
18261:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18262:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18263:                 $addcourse->{$tsymb} = $key;
18264:             }
18265:         }
18266:     }
18267:     if (keys(%collisions)) {
18268:         if ($init <5) {
18269:             if (!$init) {
18270:                 $init = 1;
18271:             } else {
18272:                 $init ++;
18273:             }
18274:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18275:                                    $newunique,$addcourse,$courseonly,$failed);
18276:         } else {
18277:             foreach my $key (keys(%collisions)) {
18278:                 $failed->{$key} = 1;
18279:             }
18280:         }
18281:     }
18282:     return $init;
18283: }
18284: 
18285: sub is_nonframeable {
18286:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18287:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18288:     return if (($remprotocol eq '') || ($remhost eq ''));
18289: 
18290:     $remprotocol = lc($remprotocol);
18291:     $remhost = lc($remhost);
18292:     my $remport = 80;
18293:     if ($remprotocol eq 'https') {
18294:         $remport = 443;
18295:     }
18296:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18297:     if ($cached) {
18298:         unless ($nocache) {
18299:             if ($result) {
18300:                 return 1;
18301:             } else {
18302:                 return 0;
18303:             }
18304:         }
18305:     }
18306:     my $uselink;
18307:     my $request = new HTTP::Request('HEAD',$url);
18308:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
18309:     if ($response->is_success()) {
18310:         my $secpolicy = lc($response->header('content-security-policy'));
18311:         my $xframeop = lc($response->header('x-frame-options'));
18312:         $secpolicy =~ s/^\s+|\s+$//g;
18313:         $xframeop =~ s/^\s+|\s+$//g;
18314:         if (($secpolicy ne '') || ($xframeop ne '')) {
18315:             my $remotehost = $remprotocol.'://'.$remhost;
18316:             my ($origin,$protocol,$port);
18317:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18318:                 $port = $ENV{'SERVER_PORT'};
18319:             } else {
18320:                 $port = 80;
18321:             }
18322:             if ($absolute eq '') {
18323:                 $protocol = 'http:';
18324:                 if ($port == 443) {
18325:                     $protocol = 'https:';
18326:                 }
18327:                 $origin = $protocol.'//'.lc($hostname);
18328:             } else {
18329:                 $origin = lc($absolute);
18330:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18331:             }
18332:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18333:                 my $framepolicy = $1;
18334:                 $framepolicy =~ s/^\s+|\s+$//g;
18335:                 my @policies = split(/\s+/,$framepolicy);
18336:                 if (@policies) {
18337:                     if (grep(/^\Q'none'\E$/,@policies)) {
18338:                         $uselink = 1;
18339:                     } else {
18340:                         $uselink = 1;
18341:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18342:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18343:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18344:                             undef($uselink);
18345:                         }
18346:                         if ($uselink) {
18347:                             if (grep(/^\Q'self'\E$/,@policies)) {
18348:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18349:                                     undef($uselink);
18350:                                 }
18351:                             }
18352:                         }
18353:                         if ($uselink) {
18354:                             my @possok;
18355:                             if ($ip ne '') {
18356:                                 push(@possok,$ip);
18357:                             }
18358:                             my $hoststr = '';
18359:                             foreach my $part (reverse(split(/\./,$hostname))) {
18360:                                 if ($hoststr eq '') {
18361:                                     $hoststr = $part;
18362:                                 } else {
18363:                                     $hoststr = "$part.$hoststr";
18364:                                 }
18365:                                 if ($hoststr eq $hostname) {
18366:                                     push(@possok,$hostname);
18367:                                 } else {
18368:                                     push(@possok,"*.$hoststr");
18369:                                 }
18370:                             }
18371:                             if (@possok) {
18372:                                 foreach my $poss (@possok) {
18373:                                     last if (!$uselink);
18374:                                     foreach my $policy (@policies) {
18375:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18376:                                             undef($uselink);
18377:                                             last;
18378:                                         }
18379:                                     }
18380:                                 }
18381:                             }
18382:                         }
18383:                     }
18384:                 }
18385:             } elsif ($xframeop ne '') {
18386:                 $uselink = 1;
18387:                 my @policies = split(/\s*,\s*/,$xframeop);
18388:                 if (@policies) {
18389:                     unless (grep(/^deny$/,@policies)) {
18390:                         if ($origin ne '') {
18391:                             if (grep(/^sameorigin$/,@policies)) {
18392:                                 if ($remotehost eq $origin) {
18393:                                     undef($uselink);
18394:                                 }
18395:                             }
18396:                             if ($uselink) {
18397:                                 foreach my $policy (@policies) {
18398:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18399:                                         my $allowfrom = $1;
18400:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18401:                                             undef($uselink);
18402:                                             last;
18403:                                         }
18404:                                     }
18405:                                 }
18406:                             }
18407:                         }
18408:                     }
18409:                 }
18410:             }
18411:         }
18412:     }
18413:     if ($nocache) {
18414:         if ($cached) {
18415:             my $devalidate;
18416:             if ($uselink && !$result) {
18417:                 $devalidate = 1;
18418:             } elsif (!$uselink && $result) {
18419:                 $devalidate = 1;
18420:             }
18421:             if ($devalidate) {
18422:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18423:             }
18424:         }
18425:     } else {
18426:         if ($uselink) {
18427:             $result = 1;
18428:         } else {
18429:             $result = 0;
18430:         }
18431:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18432:     }
18433:     return $uselink;
18434: }
18435: 
18436: 1;
18437: __END__;
18438: 

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