File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1331: download - view: text, annotated - select for diffs
Sun May 5 23:19:47 2019 UTC (5 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Response to incorrect Captcha on account creation page is to display a page
  containing a link back to the form, instead of a call to &invalid_state().
- Rules for length and/or characters in a LON-CAPA password (internal auth)
  checked server-side when a user self-creates a user account.
  - rule-checking code moved from lonpreferences.pm to loncommon.pm to
    facilitate reuse.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1331 2019/05/05 23:19:47 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,courseadvonly) {
  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 (courseadvonly) { url+="&courseadvonly=1"; }
  455:         var title = 'Student_Browser';
  456:         var options = 'scrollbars=1,resizable=1,menubar=0';
  457:         options += ',width=700,height=600';
  458:         stdeditbrowser = open(url,title,options,'1');
  459:         stdeditbrowser.focus();
  460:     }
  461: // ]]>
  462: </script>
  463: ENDSTDBRW
  464: }
  465: 
  466: sub resourcebrowser_javascript {
  467:    unless ($env{'request.course.id'}) { return ''; }
  468:    return (<<'ENDRESBRW');
  469: <script type="text/javascript" language="Javascript">
  470: // <![CDATA[
  471:     var reseditbrowser;
  472:     function openresbrowser(formname,reslink) {
  473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  474:         var title = 'Resource_Browser';
  475:         var options = 'scrollbars=1,resizable=1,menubar=0';
  476:         options += ',width=700,height=500';
  477:         reseditbrowser = open(url,title,options,'1');
  478:         reseditbrowser.focus();
  479:     }
  480: // ]]>
  481: </script>
  482: ENDRESBRW
  483: }
  484: 
  485: sub selectstudent_link {
  486:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  490:    if ($env{'request.course.id'}) {  
  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  493: 					'/'.$env{'request.course.sec'})) {
  494: 	   return '';
  495:        }
  496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  497:        if ($courseadvonly)  {
  498:            $callargs .= ",'',1,1";
  499:        }
  500:        return '<span class="LC_nobreak">'.
  501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  502:               &mt('Select User').'</a></span>';
  503:    }
  504:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  505:        $callargs .= ",'',1"; 
  506:        return '<span class="LC_nobreak">'.
  507:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  508:               &mt('Select User').'</a></span>';
  509:    }
  510:    return '';
  511: }
  512: 
  513: sub selectresource_link {
  514:    my ($form,$reslink,$arg)=@_;
  515:    
  516:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  517:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  518:    unless ($env{'request.course.id'}) { return $arg; }
  519:    return '<span class="LC_nobreak">'.
  520:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  521:               $arg.'</a></span>';
  522: }
  523: 
  524: 
  525: 
  526: sub authorbrowser_javascript {
  527:     return <<"ENDAUTHORBRW";
  528: <script type="text/javascript" language="JavaScript">
  529: // <![CDATA[
  530: var stdeditbrowser;
  531: 
  532: function openauthorbrowser(formname,udom) {
  533:     var url = '/adm/pickauthor?';
  534:     url += 'form='+formname+'&roledom='+udom;
  535:     var title = 'Author_Browser';
  536:     var options = 'scrollbars=1,resizable=1,menubar=0';
  537:     options += ',width=700,height=600';
  538:     stdeditbrowser = open(url,title,options,'1');
  539:     stdeditbrowser.focus();
  540: }
  541: 
  542: // ]]>
  543: </script>
  544: ENDAUTHORBRW
  545: }
  546: 
  547: sub coursebrowser_javascript {
  548:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  549:         $credits_element,$instcode) = @_;
  550:     my $wintitle = 'Course_Browser';
  551:     if ($crstype eq 'Community') {
  552:         $wintitle = 'Community_Browser';
  553:     }
  554:     my $id_functions = &javascript_index_functions();
  555:     my $output = '
  556: <script type="text/javascript" language="JavaScript">
  557: // <![CDATA[
  558:     var stdeditbrowser;'."\n";
  559: 
  560:     $output .= <<"ENDSTDBRW";
  561:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  562:         var url = '/adm/pickcourse?';
  563:         var formid = getFormIdByName(formname);
  564:         var domainfilter = getDomainFromSelectbox(formname,udom);
  565:         if (domainfilter != null) {
  566:            if (domainfilter != '') {
  567:                url += 'domainfilter='+domainfilter+'&';
  568: 	   }
  569:         }
  570:         url += 'form=' + formname + '&cnumelement='+uname+
  571: 	                            '&cdomelement='+udom+
  572:                                     '&cnameelement='+desc;
  573:         if (extra_element !=null && extra_element != '') {
  574:             if (formname == 'rolechoice' || formname == 'studentform') {
  575:                 url += '&roleelement='+extra_element;
  576:                 if (domainfilter == null || domainfilter == '') {
  577:                     url += '&domainfilter='+extra_element;
  578:                 }
  579:             }
  580:             else {
  581:                 if (formname == 'portform') {
  582:                     url += '&setroles='+extra_element;
  583:                 } else {
  584:                     if (formname == 'rules') {
  585:                         url += '&fixeddom='+extra_element; 
  586:                     }
  587:                 }
  588:             }     
  589:         }
  590:         if (type != null && type != '') {
  591:             url += '&type='+type;
  592:         }
  593:         if (type_elem != null && type_elem != '') {
  594:             url += '&typeelement='+type_elem;
  595:         }
  596:         if (formname == 'ccrs') {
  597:             var ownername = document.forms[formid].ccuname.value;
  598:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  599:             url += '&cloner='+ownername+':'+ownerdom;
  600:             if (type == 'Course') {
  601:                 url += '&crscode='+document.forms[formid].crscode.value;
  602:             }
  603:         }
  604:         if (formname == 'requestcrs') {
  605:             url += '&crsdom=$domainfilter&crscode=$instcode';
  606:         }
  607:         if (multflag !=null && multflag != '') {
  608:             url += '&multiple='+multflag;
  609:         }
  610:         var title = '$wintitle';
  611:         var options = 'scrollbars=1,resizable=1,menubar=0';
  612:         options += ',width=700,height=600';
  613:         stdeditbrowser = open(url,title,options,'1');
  614:         stdeditbrowser.focus();
  615:     }
  616: $id_functions
  617: ENDSTDBRW
  618:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  619:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  620:                                       $credits_element);
  621:     }
  622:     $output .= '
  623: // ]]>
  624: </script>';
  625:     return $output;
  626: }
  627: 
  628: sub javascript_index_functions {
  629:     return <<"ENDJS";
  630: 
  631: function getFormIdByName(formname) {
  632:     for (var i=0;i<document.forms.length;i++) {
  633:         if (document.forms[i].name == formname) {
  634:             return i;
  635:         }
  636:     }
  637:     return -1;
  638: }
  639: 
  640: function getIndexByName(formid,item) {
  641:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  642:         if (document.forms[formid].elements[i].name == item) {
  643:             return i;
  644:         }
  645:     }
  646:     return -1;
  647: }
  648: 
  649: function getDomainFromSelectbox(formname,udom) {
  650:     var userdom;
  651:     var formid = getFormIdByName(formname);
  652:     if (formid > -1) {
  653:         var domid = getIndexByName(formid,udom);
  654:         if (domid > -1) {
  655:             if (document.forms[formid].elements[domid].type == 'select-one') {
  656:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  657:             }
  658:             if (document.forms[formid].elements[domid].type == 'hidden') {
  659:                 userdom=document.forms[formid].elements[domid].value;
  660:             }
  661:         }
  662:     }
  663:     return userdom;
  664: }
  665: 
  666: ENDJS
  667: 
  668: }
  669: 
  670: sub javascript_array_indexof {
  671:     return <<ENDJS;
  672: <script type="text/javascript" language="JavaScript">
  673: // <![CDATA[
  674: 
  675: if (!Array.prototype.indexOf) {
  676:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  677:         "use strict";
  678:         if (this === void 0 || this === null) {
  679:             throw new TypeError();
  680:         }
  681:         var t = Object(this);
  682:         var len = t.length >>> 0;
  683:         if (len === 0) {
  684:             return -1;
  685:         }
  686:         var n = 0;
  687:         if (arguments.length > 0) {
  688:             n = Number(arguments[1]);
  689:             if (n !== n) { // shortcut for verifying if it is NaN
  690:                 n = 0;
  691:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  692:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  693:             }
  694:         }
  695:         if (n >= len) {
  696:             return -1;
  697:         }
  698:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  699:         for (; k < len; k++) {
  700:             if (k in t && t[k] === searchElement) {
  701:                 return k;
  702:             }
  703:         }
  704:         return -1;
  705:     }
  706: }
  707: 
  708: // ]]>
  709: </script>
  710: 
  711: ENDJS
  712: 
  713: }
  714: 
  715: sub userbrowser_javascript {
  716:     my $id_functions = &javascript_index_functions();
  717:     return <<"ENDUSERBRW";
  718: 
  719: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  720:     var url = '/adm/pickuser?';
  721:     var userdom = getDomainFromSelectbox(formname,udom);
  722:     if (userdom != null) {
  723:        if (userdom != '') {
  724:            url += 'srchdom='+userdom+'&';
  725:        }
  726:     }
  727:     url += 'form=' + formname + '&unameelement='+uname+
  728:                                 '&udomelement='+udom+
  729:                                 '&ulastelement='+ulast+
  730:                                 '&ufirstelement='+ufirst+
  731:                                 '&uemailelement='+uemail+
  732:                                 '&hideudomelement='+hideudom+
  733:                                 '&coursedom='+crsdom;
  734:     if ((caller != null) && (caller != undefined)) {
  735:         url += '&caller='+caller;
  736:     }
  737:     var title = 'User_Browser';
  738:     var options = 'scrollbars=1,resizable=1,menubar=0';
  739:     options += ',width=700,height=600';
  740:     var stdeditbrowser = open(url,title,options,'1');
  741:     stdeditbrowser.focus();
  742: }
  743: 
  744: function fix_domain (formname,udom,origdom,uname) {
  745:     var formid = getFormIdByName(formname);
  746:     if (formid > -1) {
  747:         var unameid = getIndexByName(formid,uname);
  748:         var domid = getIndexByName(formid,udom);
  749:         var hidedomid = getIndexByName(formid,origdom);
  750:         if (hidedomid > -1) {
  751:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  752:             var unameval = document.forms[formid].elements[unameid].value;
  753:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  754:                 if (domid > -1) {
  755:                     var slct = document.forms[formid].elements[domid];
  756:                     if (slct.type == 'select-one') {
  757:                         var i;
  758:                         for (i=0;i<slct.length;i++) {
  759:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  760:                         }
  761:                     }
  762:                     if (slct.type == 'hidden') {
  763:                         slct.value = fixeddom;
  764:                     }
  765:                 }
  766:             }
  767:         }
  768:     }
  769:     return;
  770: }
  771: 
  772: $id_functions
  773: ENDUSERBRW
  774: }
  775: 
  776: sub setsec_javascript {
  777:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  778:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  779:         $communityrolestr);
  780:     if ($role_element ne '') {
  781:         my @allroles = ('st','ta','ep','in','ad');
  782:         foreach my $crstype ('Course','Community') {
  783:             if ($crstype eq 'Community') {
  784:                 foreach my $role (@allroles) {
  785:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  786:                 }
  787:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  788:             } else {
  789:                 foreach my $role (@allroles) {
  790:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  791:                 }
  792:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  793:             }
  794:         }
  795:         $rolestr = '"'.join('","',@allroles).'"';
  796:         $courserolestr = '"'.join('","',@courserolenames).'"';
  797:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  798:     }
  799:     my $setsections = qq|
  800: function setSect(sectionlist) {
  801:     var sectionsArray = new Array();
  802:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  803:         sectionsArray = sectionlist.split(",");
  804:     }
  805:     var numSections = sectionsArray.length;
  806:     document.$formname.$sec_element.length = 0;
  807:     if (numSections == 0) {
  808:         document.$formname.$sec_element.multiple=false;
  809:         document.$formname.$sec_element.size=1;
  810:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  811:     } else {
  812:         if (numSections == 1) {
  813:             document.$formname.$sec_element.multiple=false;
  814:             document.$formname.$sec_element.size=1;
  815:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  816:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  817:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  818:         } else {
  819:             for (var i=0; i<numSections; i++) {
  820:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  821:             }
  822:             document.$formname.$sec_element.multiple=true
  823:             if (numSections < 3) {
  824:                 document.$formname.$sec_element.size=numSections;
  825:             } else {
  826:                 document.$formname.$sec_element.size=3;
  827:             }
  828:             document.$formname.$sec_element.options[0].selected = false
  829:         }
  830:     }
  831: }
  832: 
  833: function setRole(crstype) {
  834: |;
  835:     if ($role_element eq '') {
  836:         $setsections .= '    return;
  837: }
  838: ';
  839:     } else {
  840:         $setsections .= qq|
  841:     var elementLength = document.$formname.$role_element.length;
  842:     var allroles = Array($rolestr);
  843:     var courserolenames = Array($courserolestr);
  844:     var communityrolenames = Array($communityrolestr);
  845:     if (elementLength != undefined) {
  846:         if (document.$formname.$role_element.options[5].value == 'cc') {
  847:             if (crstype == 'Course') {
  848:                 return;
  849:             } else {
  850:                 allroles[5] = 'co';
  851:                 for (var i=0; i<6; i++) {
  852:                     document.$formname.$role_element.options[i].value = allroles[i];
  853:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  854:                 }
  855:             }
  856:         } else {
  857:             if (crstype == 'Community') {
  858:                 return;
  859:             } else {
  860:                 allroles[5] = 'cc';
  861:                 for (var i=0; i<6; i++) {
  862:                     document.$formname.$role_element.options[i].value = allroles[i];
  863:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  864:                 }
  865:             }
  866:         }
  867:     }
  868:     return;
  869: }
  870: |;
  871:     }
  872:     if ($credits_element) {
  873:         $setsections .= qq|
  874: function setCredits(defaultcredits) {
  875:     document.$formname.$credits_element.value = defaultcredits;
  876:     return;
  877: }
  878: |;
  879:     }
  880:     return $setsections;
  881: }
  882: 
  883: sub selectcourse_link {
  884:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  885:        $typeelement) = @_;
  886:    my $type = $selecttype;
  887:    my $linktext = &mt('Select Course');
  888:    if ($selecttype eq 'Community') {
  889:        $linktext = &mt('Select Community');
  890:    } elsif ($selecttype eq 'Placement') {
  891:        $linktext = &mt('Select Placement Test'); 
  892:    } elsif ($selecttype eq 'Course/Community') {
  893:        $linktext = &mt('Select Course/Community');
  894:        $type = '';
  895:    } elsif ($selecttype eq 'Select') {
  896:        $linktext = &mt('Select');
  897:        $type = '';
  898:    }
  899:    return '<span class="LC_nobreak">'
  900:          ."<a href='"
  901:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  902:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  903:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  904:          ."'>".$linktext.'</a>'
  905:          .'</span>';
  906: }
  907: 
  908: sub selectauthor_link {
  909:    my ($form,$udom)=@_;
  910:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  911:           &mt('Select Author').'</a>';
  912: }
  913: 
  914: sub selectuser_link {
  915:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  916:         $coursedom,$linktext,$caller) = @_;
  917:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  918:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  919:            ');">'.$linktext.'</a>';
  920: }
  921: 
  922: sub check_uncheck_jscript {
  923:     my $jscript = <<"ENDSCRT";
  924: function checkAll(field) {
  925:     if (field.length > 0) {
  926:         for (i = 0; i < field.length; i++) {
  927:             if (!field[i].disabled) { 
  928:                 field[i].checked = true;
  929:             }
  930:         }
  931:     } else {
  932:         if (!field.disabled) { 
  933:             field.checked = true;
  934:         }
  935:     }
  936: }
  937:  
  938: function uncheckAll(field) {
  939:     if (field.length > 0) {
  940:         for (i = 0; i < field.length; i++) {
  941:             field[i].checked = false ;
  942:         }
  943:     } else {
  944:         field.checked = false ;
  945:     }
  946: }
  947: ENDSCRT
  948:     return $jscript;
  949: }
  950: 
  951: sub select_timezone {
  952:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  953:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  954:    if ($includeempty) {
  955:        $output .= '<option value=""';
  956:        if (($selected eq '') || ($selected eq 'local')) {
  957:            $output .= ' selected="selected" ';
  958:        }
  959:        $output .= '> </option>';
  960:    }
  961:    my @timezones = DateTime::TimeZone->all_names;
  962:    foreach my $tzone (@timezones) {
  963:        $output.= '<option value="'.$tzone.'"';
  964:        if ($tzone eq $selected) {
  965:            $output.=' selected="selected"';
  966:        }
  967:        $output.=">$tzone</option>\n";
  968:    }
  969:    $output.="</select>";
  970:    return $output;
  971: }
  972: 
  973: sub select_datelocale {
  974:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  975:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  976:     if ($includeempty) {
  977:         $output .= '<option value=""';
  978:         if ($selected eq '') {
  979:             $output .= ' selected="selected" ';
  980:         }
  981:         $output .= '> </option>';
  982:     }
  983:     my @languages = &Apache::lonlocal::preferred_languages();
  984:     my (@possibles,%locale_names);
  985:     my @locales = DateTime::Locale->ids();
  986:     foreach my $id (@locales) {
  987:         if ($id ne '') {
  988:             my ($en_terr,$native_terr);
  989:             my $loc = DateTime::Locale->load($id);
  990:             if (ref($loc)) {
  991:                 $en_terr = $loc->name();
  992:                 $native_terr = $loc->native_name();
  993:                 if (grep(/^en$/,@languages) || !@languages) {
  994:                     if ($en_terr ne '') {
  995:                         $locale_names{$id} = '('.$en_terr.')';
  996:                     } elsif ($native_terr ne '') {
  997:                         $locale_names{$id} = $native_terr;
  998:                     }
  999:                 } else {
 1000:                     if ($native_terr ne '') {
 1001:                         $locale_names{$id} = $native_terr.' ';
 1002:                     } elsif ($en_terr ne '') {
 1003:                         $locale_names{$id} = '('.$en_terr.')';
 1004:                     }
 1005:                 }
 1006:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1007:                 push(@possibles,$id);
 1008:             } 
 1009:         }
 1010:     }
 1011:     foreach my $item (sort(@possibles)) {
 1012:         $output.= '<option value="'.$item.'"';
 1013:         if ($item eq $selected) {
 1014:             $output.=' selected="selected"';
 1015:         }
 1016:         $output.=">$item";
 1017:         if ($locale_names{$item} ne '') {
 1018:             $output.='  '.$locale_names{$item};
 1019:         }
 1020:         $output.="</option>\n";
 1021:     }
 1022:     $output.="</select>";
 1023:     return $output;
 1024: }
 1025: 
 1026: sub select_language {
 1027:     my ($name,$selected,$includeempty,$noedit) = @_;
 1028:     my %langchoices;
 1029:     if ($includeempty) {
 1030:         %langchoices = ('' => 'No language preference');
 1031:     }
 1032:     foreach my $id (&languageids()) {
 1033:         my $code = &supportedlanguagecode($id);
 1034:         if ($code) {
 1035:             $langchoices{$code} = &plainlanguagedescription($id);
 1036:         }
 1037:     }
 1038:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1039:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1040: }
 1041: 
 1042: =pod
 1043: 
 1044: 
 1045: =item * &list_languages()
 1046: 
 1047: Returns an array reference that is suitable for use in language prompters.
 1048: Each array element is itself a two element array.  The first element
 1049: is the language code.  The second element a descsriptiuon of the 
 1050: language itself.  This is suitable for use in e.g.
 1051: &Apache::edit::select_arg (once dereferenced that is).
 1052: 
 1053: =cut 
 1054: 
 1055: sub list_languages {
 1056:     my @lang_choices;
 1057: 
 1058:     foreach my $id (&languageids()) {
 1059: 	my $code = &supportedlanguagecode($id);
 1060: 	if ($code) {
 1061: 	    my $selector    = $supported_codes{$id};
 1062: 	    my $description = &plainlanguagedescription($id);
 1063: 	    push(@lang_choices, [$selector, $description]);
 1064: 	}
 1065:     }
 1066:     return \@lang_choices;
 1067: }
 1068: 
 1069: =pod
 1070: 
 1071: =item * &linked_select_forms(...)
 1072: 
 1073: linked_select_forms returns a string containing a <script></script> block
 1074: and html for two <select> menus.  The select menus will be linked in that
 1075: changing the value of the first menu will result in new values being placed
 1076: in the second menu.  The values in the select menu will appear in alphabetical
 1077: order unless a defined order is provided.
 1078: 
 1079: linked_select_forms takes the following ordered inputs:
 1080: 
 1081: =over 4
 1082: 
 1083: =item * $formname, the name of the <form> tag
 1084: 
 1085: =item * $middletext, the text which appears between the <select> tags
 1086: 
 1087: =item * $firstdefault, the default value for the first menu
 1088: 
 1089: =item * $firstselectname, the name of the first <select> tag
 1090: 
 1091: =item * $secondselectname, the name of the second <select> tag
 1092: 
 1093: =item * $hashref, a reference to a hash containing the data for the menus.
 1094: 
 1095: =item * $menuorder, the order of values in the first menu
 1096: 
 1097: =item * $onchangefirst, additional javascript call to execute for an onchange
 1098:         event for the first <select> tag
 1099: 
 1100: =item * $onchangesecond, additional javascript call to execute for an onchange
 1101:         event for the second <select> tag
 1102: 
 1103: =item * $suffix, to differentiate separate uses of select2data javascript
 1104:         objects in a page.
 1105: 
 1106: =back 
 1107: 
 1108: Below is an example of such a hash.  Only the 'text', 'default', and 
 1109: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1110: values for the first select menu.  The text that coincides with the 
 1111: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1112: and text for the second menu are given in the hash pointed to by 
 1113: $menu{$choice1}->{'select2'}.  
 1114: 
 1115:  my %menu = ( A1 => { text =>"Choice A1" ,
 1116:                        default => "B3",
 1117:                        select2 => { 
 1118:                            B1 => "Choice B1",
 1119:                            B2 => "Choice B2",
 1120:                            B3 => "Choice B3",
 1121:                            B4 => "Choice B4"
 1122:                            },
 1123:                        order => ['B4','B3','B1','B2'],
 1124:                    },
 1125:                A2 => { text =>"Choice A2" ,
 1126:                        default => "C2",
 1127:                        select2 => { 
 1128:                            C1 => "Choice C1",
 1129:                            C2 => "Choice C2",
 1130:                            C3 => "Choice C3"
 1131:                            },
 1132:                        order => ['C2','C1','C3'],
 1133:                    },
 1134:                A3 => { text =>"Choice A3" ,
 1135:                        default => "D6",
 1136:                        select2 => { 
 1137:                            D1 => "Choice D1",
 1138:                            D2 => "Choice D2",
 1139:                            D3 => "Choice D3",
 1140:                            D4 => "Choice D4",
 1141:                            D5 => "Choice D5",
 1142:                            D6 => "Choice D6",
 1143:                            D7 => "Choice D7"
 1144:                            },
 1145:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1146:                    }
 1147:                );
 1148: 
 1149: =cut
 1150: 
 1151: sub linked_select_forms {
 1152:     my ($formname,
 1153:         $middletext,
 1154:         $firstdefault,
 1155:         $firstselectname,
 1156:         $secondselectname, 
 1157:         $hashref,
 1158:         $menuorder,
 1159:         $onchangefirst,
 1160:         $onchangesecond,
 1161:         $suffix
 1162:         ) = @_;
 1163:     my $second = "document.$formname.$secondselectname";
 1164:     my $first = "document.$formname.$firstselectname";
 1165:     # output the javascript to do the changing
 1166:     my $result = '';
 1167:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1168:     $result.="// <![CDATA[\n";
 1169:     $result.="var select2data${suffix} = new Object();\n";
 1170:     $" = '","';
 1171:     my $debug = '';
 1172:     foreach my $s1 (sort(keys(%$hashref))) {
 1173:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1174:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1175:             $hashref->{$s1}->{'default'}."');\n";
 1176:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1177:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1178:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1179:             @s2values = @{$hashref->{$s1}->{'order'}};
 1180:         }
 1181:         $result.="\"@s2values\");\n";
 1182:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1183:         my @s2texts;
 1184:         foreach my $value (@s2values) {
 1185:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1186:         }
 1187:         $result.="\"@s2texts\");\n";
 1188:     }
 1189:     $"=' ';
 1190:     $result.= <<"END";
 1191: 
 1192: function select1${suffix}_changed() {
 1193:     // Determine new choice
 1194:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1195:     // update select2
 1196:     var values     = select2data${suffix}[newvalue].values;
 1197:     var texts      = select2data${suffix}[newvalue].texts;
 1198:     var select2def = select2data${suffix}[newvalue].def;
 1199:     var i;
 1200:     // out with the old
 1201:     $second.options.length = 0;
 1202:     // in with the new
 1203:     for (i=0;i<values.length; i++) {
 1204:         $second.options[i] = new Option(values[i]);
 1205:         $second.options[i].value = values[i];
 1206:         $second.options[i].text = texts[i];
 1207:         if (values[i] == select2def) {
 1208:             $second.options[i].selected = true;
 1209:         }
 1210:     }
 1211: }
 1212: // ]]>
 1213: </script>
 1214: END
 1215:     # output the initial values for the selection lists
 1216:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1217:     my @order = sort(keys(%{$hashref}));
 1218:     if (ref($menuorder) eq 'ARRAY') {
 1219:         @order = @{$menuorder};
 1220:     }
 1221:     foreach my $value (@order) {
 1222:         $result.="    <option value=\"$value\" ";
 1223:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1224:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1225:     }
 1226:     $result .= "</select>\n";
 1227:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1228:     $result .= $middletext;
 1229:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1230:     if ($onchangesecond) {
 1231:         $result .= ' onchange="'.$onchangesecond.'"';
 1232:     }
 1233:     $result .= ">\n";
 1234:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1235:     
 1236:     my @secondorder = sort(keys(%select2));
 1237:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1238:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1239:     }
 1240:     foreach my $value (@secondorder) {
 1241:         $result.="    <option value=\"$value\" ";        
 1242:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1243:         $result.=">".&mt($select2{$value})."</option>\n";
 1244:     }
 1245:     $result .= "</select>\n";
 1246:     #    return $debug;
 1247:     return $result;
 1248: }   #  end of sub linked_select_forms {
 1249: 
 1250: =pod
 1251: 
 1252: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1253: 
 1254: Returns a string corresponding to an HTML link to the given help
 1255: $topic, where $topic corresponds to the name of a .tex file in
 1256: /home/httpd/html/adm/help/tex, with underscores replaced by
 1257: spaces. 
 1258: 
 1259: $text will optionally be linked to the same topic, allowing you to
 1260: link text in addition to the graphic. If you do not want to link
 1261: text, but wish to specify one of the later parameters, pass an
 1262: empty string. 
 1263: 
 1264: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1265: the link will not open a new window. If false, the link will open
 1266: a new window using Javascript. (Default is false.) 
 1267: 
 1268: $width and $height are optional numerical parameters that will
 1269: override the width and height of the popped up window, which may
 1270: be useful for certain help topics with big pictures included.
 1271: 
 1272: $imgid is the id of the img tag used for the help icon. This may be
 1273: used in a javascript call to switch the image src.  See 
 1274: lonhtmlcommon::htmlareaselectactive() for an example.
 1275: 
 1276: =cut
 1277: 
 1278: sub help_open_topic {
 1279:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1280:     $text = "" if (not defined $text);
 1281:     $stayOnPage = 0 if (not defined $stayOnPage);
 1282:     $width = 500 if (not defined $width);
 1283:     $height = 400 if (not defined $height);
 1284:     my $filename = $topic;
 1285:     $filename =~ s/ /_/g;
 1286: 
 1287:     my $template = "";
 1288:     my $link;
 1289:     
 1290:     $topic=~s/\W/\_/g;
 1291: 
 1292:     if (!$stayOnPage) {
 1293: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1294:     } elsif ($stayOnPage eq 'popup') {
 1295:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1296:     } else {
 1297: 	$link = "/adm/help/${filename}.hlp";
 1298:     }
 1299: 
 1300:     # Add the text
 1301:     my $target = ' target="_top"';
 1302:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1303:         $target = '';
 1304:     }
 1305:     if ($text ne "") {	
 1306: 	$template.='<span class="LC_help_open_topic">'
 1307:                   .'<a'.$target.' href="'.$link.'">'
 1308:                   .$text.'</a>';
 1309:     }
 1310: 
 1311:     # (Always) Add the graphic
 1312:     my $title = &mt('Online Help');
 1313:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1314:     if ($imgid ne '') {
 1315:         $imgid = ' id="'.$imgid.'"';
 1316:     }
 1317:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1318:               .'<img src="'.$helpicon.'" border="0"'
 1319:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1320:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1321:               .' /></a>';
 1322:     if ($text ne "") {	
 1323:         $template.='</span>';
 1324:     }
 1325:     return $template;
 1326: 
 1327: }
 1328: 
 1329: # This is a quicky function for Latex cheatsheet editing, since it 
 1330: # appears in at least four places
 1331: sub helpLatexCheatsheet {
 1332:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1333:     my $out;
 1334:     my $addOther = '';
 1335:     if ($topic) {
 1336: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1337:     }
 1338:     $out = '<span>' # Start cheatsheet
 1339: 	  .$addOther
 1340:           .'<span>'
 1341: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1342: 	  .'</span> <span>'
 1343: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1344: 	  .'</span>';
 1345:     unless ($not_author) {
 1346:         $out .= '<span>'
 1347:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1348:                .'</span> <span>'
 1349:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1350: 	       .'</span>';
 1351:     }
 1352:     $out .= '</span>'; # End cheatsheet
 1353:     return $out;
 1354: }
 1355: 
 1356: sub general_help {
 1357:     my $helptopic='Student_Intro';
 1358:     if ($env{'request.role'}=~/^(ca|au)/) {
 1359: 	$helptopic='Authoring_Intro';
 1360:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1361: 	$helptopic='Course_Coordination_Intro';
 1362:     } elsif ($env{'request.role'}=~/^dc/) {
 1363:         $helptopic='Domain_Coordination_Intro';
 1364:     }
 1365:     return $helptopic;
 1366: }
 1367: 
 1368: sub update_help_link {
 1369:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1370:     my $origurl = $ENV{'REQUEST_URI'};
 1371:     $origurl=~s|^/~|/priv/|;
 1372:     my $timestamp = time;
 1373:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1374:         $$datum = &escape($$datum);
 1375:     }
 1376: 
 1377:     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";
 1378:     my $output .= <<"ENDOUTPUT";
 1379: <script type="text/javascript">
 1380: // <![CDATA[
 1381: banner_link = '$banner_link';
 1382: // ]]>
 1383: </script>
 1384: ENDOUTPUT
 1385:     return $output;
 1386: }
 1387: 
 1388: # now just updates the help link and generates a blue icon
 1389: sub help_open_menu {
 1390:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1391: 	= @_;    
 1392:     $stayOnPage = 1;
 1393:     my $output;
 1394:     if ($component_help) {
 1395: 	if (!$text) {
 1396: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1397: 				       $width,$height);
 1398: 	} else {
 1399: 	    my $help_text;
 1400: 	    $help_text=&unescape($topic);
 1401: 	    $output='<table><tr><td>'.
 1402: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1403: 				 $width,$height).'</td></tr></table>';
 1404: 	}
 1405:     }
 1406:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1407:     return $output.$banner_link;
 1408: }
 1409: 
 1410: sub top_nav_help {
 1411:     my ($text) = @_;
 1412:     $text = &mt($text);
 1413:     my $stay_on_page = 1;
 1414: 
 1415:     my ($link,$banner_link);
 1416:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1417:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1418: 	                         : "javascript:helpMenu('open')";
 1419:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1420:     }
 1421:     my $title = &mt('Get help');
 1422:     if ($link) {
 1423:         return <<"END";
 1424: $banner_link
 1425: <a href="$link" title="$title">$text</a>
 1426: END
 1427:     } else {
 1428:         return '&nbsp;'.$text.'&nbsp;';
 1429:     }
 1430: }
 1431: 
 1432: sub help_menu_js {
 1433:     my ($httphost) = @_;
 1434:     my $stayOnPage = 1;
 1435:     my $width = 620;
 1436:     my $height = 600;
 1437:     my $helptopic=&general_help();
 1438:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1439:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1440:     my $start_page =
 1441:         &Apache::loncommon::start_page('Help Menu', undef,
 1442: 				       {'frameset'    => 1,
 1443: 					'js_ready'    => 1,
 1444:                                         'use_absolute' => $httphost,
 1445: 					'add_entries' => {
 1446: 					    'border' => '0', 
 1447: 					    'rows'   => "110,*",},});
 1448:     my $end_page =
 1449:         &Apache::loncommon::end_page({'frameset' => 1,
 1450: 				      'js_ready' => 1,});
 1451: 
 1452:     my $template .= <<"ENDTEMPLATE";
 1453: <script type="text/javascript">
 1454: // <![CDATA[
 1455: // <!-- BEGIN LON-CAPA Internal
 1456: var banner_link = '';
 1457: function helpMenu(target) {
 1458:     var caller = this;
 1459:     if (target == 'open') {
 1460:         var newWindow = null;
 1461:         try {
 1462:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1463:         }
 1464:         catch(error) {
 1465:             writeHelp(caller);
 1466:             return;
 1467:         }
 1468:         if (newWindow) {
 1469:             caller = newWindow;
 1470:         }
 1471:     }
 1472:     writeHelp(caller);
 1473:     return;
 1474: }
 1475: function writeHelp(caller) {
 1476:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1477:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1478:     caller.document.close();
 1479:     caller.focus();
 1480: }
 1481: // END LON-CAPA Internal -->
 1482: // ]]>
 1483: </script>
 1484: ENDTEMPLATE
 1485:     return $template;
 1486: }
 1487: 
 1488: sub help_open_bug {
 1489:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1490:     unless ($env{'user.adv'}) { return ''; }
 1491:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1492:     $text = "" if (not defined $text);
 1493: 	$stayOnPage=1;
 1494:     $width = 600 if (not defined $width);
 1495:     $height = 600 if (not defined $height);
 1496: 
 1497:     $topic=~s/\W+/\+/g;
 1498:     my $link='';
 1499:     my $template='';
 1500:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1501: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1502:     if (!$stayOnPage)
 1503:     {
 1504: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1505:     }
 1506:     else
 1507:     {
 1508: 	$link = $url;
 1509:     }
 1510: 
 1511:     my $target = ' target="_top"';
 1512:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1513:         $target = '';
 1514:     }
 1515:     # Add the text
 1516:     if ($text ne "")
 1517:     {
 1518: 	$template .= 
 1519:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1520:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1521:     }
 1522: 
 1523:     # Add the graphic
 1524:     my $title = &mt('Report a Bug');
 1525:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1526:     $template .= <<"ENDTEMPLATE";
 1527:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1528: ENDTEMPLATE
 1529:     if ($text ne '') { $template.='</td></tr></table>' };
 1530:     return $template;
 1531: 
 1532: }
 1533: 
 1534: sub help_open_faq {
 1535:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1536:     unless ($env{'user.adv'}) { return ''; }
 1537:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1538:     $text = "" if (not defined $text);
 1539: 	$stayOnPage=1;
 1540:     $width = 350 if (not defined $width);
 1541:     $height = 400 if (not defined $height);
 1542: 
 1543:     $topic=~s/\W+/\+/g;
 1544:     my $link='';
 1545:     my $template='';
 1546:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1547:     if (!$stayOnPage)
 1548:     {
 1549: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1550:     }
 1551:     else
 1552:     {
 1553: 	$link = $url;
 1554:     }
 1555: 
 1556:     # Add the text
 1557:     if ($text ne "")
 1558:     {
 1559: 	$template .= 
 1560:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1561:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1562:     }
 1563: 
 1564:     # Add the graphic
 1565:     my $title = &mt('View the FAQ');
 1566:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1567:     $template .= <<"ENDTEMPLATE";
 1568:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1569: ENDTEMPLATE
 1570:     if ($text ne '') { $template.='</td></tr></table>' };
 1571:     return $template;
 1572: 
 1573: }
 1574: 
 1575: ###############################################################
 1576: ###############################################################
 1577: 
 1578: =pod
 1579: 
 1580: =item * &change_content_javascript():
 1581: 
 1582: This and the next function allow you to create small sections of an
 1583: otherwise static HTML page that you can update on the fly with
 1584: Javascript, even in Netscape 4.
 1585: 
 1586: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1587: must be written to the HTML page once. It will prove the Javascript
 1588: function "change(name, content)". Calling the change function with the
 1589: name of the section 
 1590: you want to update, matching the name passed to C<changable_area>, and
 1591: the new content you want to put in there, will put the content into
 1592: that area.
 1593: 
 1594: B<Note>: Netscape 4 only reserves enough space for the changable area
 1595: to contain room for the original contents. You need to "make space"
 1596: for whatever changes you wish to make, and be B<sure> to check your
 1597: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1598: it's adequate for updating a one-line status display, but little more.
 1599: This script will set the space to 100% width, so you only need to
 1600: worry about height in Netscape 4.
 1601: 
 1602: Modern browsers are much less limiting, and if you can commit to the
 1603: user not using Netscape 4, this feature may be used freely with
 1604: pretty much any HTML.
 1605: 
 1606: =cut
 1607: 
 1608: sub change_content_javascript {
 1609:     # If we're on Netscape 4, we need to use Layer-based code
 1610:     if ($env{'browser.type'} eq 'netscape' &&
 1611: 	$env{'browser.version'} =~ /^4\./) {
 1612: 	return (<<NETSCAPE4);
 1613: 	function change(name, content) {
 1614: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1615: 	    doc.open();
 1616: 	    doc.write(content);
 1617: 	    doc.close();
 1618: 	}
 1619: NETSCAPE4
 1620:     } else {
 1621: 	# Otherwise, we need to use semi-standards-compliant code
 1622: 	# (technically, "innerHTML" isn't standard but the equivalent
 1623: 	# is really scary, and every useful browser supports it
 1624: 	return (<<DOMBASED);
 1625: 	function change(name, content) {
 1626: 	    element = document.getElementById(name);
 1627: 	    element.innerHTML = content;
 1628: 	}
 1629: DOMBASED
 1630:     }
 1631: }
 1632: 
 1633: =pod
 1634: 
 1635: =item * &changable_area($name,$origContent):
 1636: 
 1637: This provides a "changable area" that can be modified on the fly via
 1638: the Javascript code provided in C<change_content_javascript>. $name is
 1639: the name you will use to reference the area later; do not repeat the
 1640: same name on a given HTML page more then once. $origContent is what
 1641: the area will originally contain, which can be left blank.
 1642: 
 1643: =cut
 1644: 
 1645: sub changable_area {
 1646:     my ($name, $origContent) = @_;
 1647: 
 1648:     if ($env{'browser.type'} eq 'netscape' &&
 1649: 	$env{'browser.version'} =~ /^4\./) {
 1650: 	# If this is netscape 4, we need to use the Layer tag
 1651: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1652:     } else {
 1653: 	return "<span id='$name'>$origContent</span>";
 1654:     }
 1655: }
 1656: 
 1657: =pod
 1658: 
 1659: =item * &viewport_geometry_js 
 1660: 
 1661: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1662: 
 1663: =cut
 1664: 
 1665: 
 1666: sub viewport_geometry_js { 
 1667:     return <<"GEOMETRY";
 1668: var Geometry = {};
 1669: function init_geometry() {
 1670:     if (Geometry.init) { return };
 1671:     Geometry.init=1;
 1672:     if (window.innerHeight) {
 1673:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1674:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1675:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1676:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1677:     }
 1678:     else if (document.documentElement && document.documentElement.clientHeight) {
 1679:         Geometry.getViewportHeight =
 1680:             function() { return document.documentElement.clientHeight; };
 1681:         Geometry.getViewportWidth =
 1682:             function() { return document.documentElement.clientWidth; };
 1683: 
 1684:         Geometry.getHorizontalScroll =
 1685:             function() { return document.documentElement.scrollLeft; };
 1686:         Geometry.getVerticalScroll =
 1687:             function() { return document.documentElement.scrollTop; };
 1688:     }
 1689:     else if (document.body.clientHeight) {
 1690:         Geometry.getViewportHeight =
 1691:             function() { return document.body.clientHeight; };
 1692:         Geometry.getViewportWidth =
 1693:             function() { return document.body.clientWidth; };
 1694:         Geometry.getHorizontalScroll =
 1695:             function() { return document.body.scrollLeft; };
 1696:         Geometry.getVerticalScroll =
 1697:             function() { return document.body.scrollTop; };
 1698:     }
 1699: }
 1700: 
 1701: GEOMETRY
 1702: }
 1703: 
 1704: =pod
 1705: 
 1706: =item * &viewport_size_js()
 1707: 
 1708: 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. 
 1709: 
 1710: =cut
 1711: 
 1712: sub viewport_size_js {
 1713:     my $geometry = &viewport_geometry_js();
 1714:     return <<"DIMS";
 1715: 
 1716: $geometry
 1717: 
 1718: function getViewportDims(width,height) {
 1719:     init_geometry();
 1720:     width.value = Geometry.getViewportWidth();
 1721:     height.value = Geometry.getViewportHeight();
 1722:     return;
 1723: }
 1724: 
 1725: DIMS
 1726: }
 1727: 
 1728: =pod
 1729: 
 1730: =item * &resize_textarea_js()
 1731: 
 1732: emits the needed javascript to resize a textarea to be as big as possible
 1733: 
 1734: creates a function resize_textrea that takes two IDs first should be
 1735: the id of the element to resize, second should be the id of a div that
 1736: surrounds everything that comes after the textarea, this routine needs
 1737: to be attached to the <body> for the onload and onresize events.
 1738: 
 1739: =back
 1740: 
 1741: =cut
 1742: 
 1743: sub resize_textarea_js {
 1744:     my $geometry = &viewport_geometry_js();
 1745:     return <<"RESIZE";
 1746:     <script type="text/javascript">
 1747: // <![CDATA[
 1748: $geometry
 1749: 
 1750: function getX(element) {
 1751:     var x = 0;
 1752:     while (element) {
 1753: 	x += element.offsetLeft;
 1754: 	element = element.offsetParent;
 1755:     }
 1756:     return x;
 1757: }
 1758: function getY(element) {
 1759:     var y = 0;
 1760:     while (element) {
 1761: 	y += element.offsetTop;
 1762: 	element = element.offsetParent;
 1763:     }
 1764:     return y;
 1765: }
 1766: 
 1767: 
 1768: function resize_textarea(textarea_id,bottom_id) {
 1769:     init_geometry();
 1770:     var textarea        = document.getElementById(textarea_id);
 1771:     //alert(textarea);
 1772: 
 1773:     var textarea_top    = getY(textarea);
 1774:     var textarea_height = textarea.offsetHeight;
 1775:     var bottom          = document.getElementById(bottom_id);
 1776:     var bottom_top      = getY(bottom);
 1777:     var bottom_height   = bottom.offsetHeight;
 1778:     var window_height   = Geometry.getViewportHeight();
 1779:     var fudge           = 23;
 1780:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1781:     if (new_height < 300) {
 1782: 	new_height = 300;
 1783:     }
 1784:     textarea.style.height=new_height+'px';
 1785: }
 1786: // ]]>
 1787: </script>
 1788: RESIZE
 1789: 
 1790: }
 1791: 
 1792: sub colorfuleditor_js {
 1793:     my $browse_or_search;
 1794:     my $respath;
 1795:     my ($cnum,$cdom) = &crsauthor_url();
 1796:     if ($cnum) {
 1797:         $respath = "/res/$cdom/$cnum/";
 1798:         my %js_lt = &Apache::lonlocal::texthash(
 1799:             sunm => 'Sub-directory name',
 1800:             save => 'Save page to make this permanent',
 1801:         );
 1802:         &js_escape(\%js_lt);
 1803:         $browse_or_search = <<"END";
 1804: 
 1805:     function toggleChooser(form,element,titleid,only,search) {
 1806:         var disp = 'none';
 1807:         if (document.getElementById('chooser_'+element)) {
 1808:             var curr = document.getElementById('chooser_'+element).style.display;
 1809:             if (curr == 'none') {
 1810:                 disp='inline';
 1811:                 if (form.elements['chooser_'+element].length) {
 1812:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1813:                         form.elements['chooser_'+element][i].checked = false;
 1814:                     }
 1815:                 }
 1816:                 toggleResImport(form,element);
 1817:             }
 1818:             document.getElementById('chooser_'+element).style.display = disp;
 1819:         }
 1820:     }
 1821: 
 1822:     function toggleCrsFile(form,element,numdirs) {
 1823:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1824:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1825:             if (curr == 'none') {
 1826:                 if (numdirs) {
 1827:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1828:                     if (numdirs > 1) {
 1829:                         window['select1'+element+'_changed']();
 1830:                     }
 1831:                 }
 1832:             } 
 1833:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1834:             
 1835:         }
 1836:         if (document.getElementById('chooser_'+element+'_upload')) {
 1837:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1838:             if (document.getElementById('uploadcrsres_'+element)) {
 1839:                 document.getElementById('uploadcrsres_'+element).value = '';
 1840:             }
 1841:         }
 1842:         return;
 1843:     }
 1844: 
 1845:     function toggleCrsUpload(form,element,numcrsdirs) {
 1846:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1847:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1848:         }
 1849:         if (document.getElementById('chooser_'+element+'_upload')) {
 1850:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1851:             if (curr == 'none') {
 1852:                 if (numcrsdirs) {
 1853:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1854:                    form.elements['newsubdir_'+element][0].checked = true;
 1855:                    toggleNewsubdir(form,element);
 1856:                 }
 1857:             }
 1858:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1859:         }
 1860:         return;
 1861:     }
 1862: 
 1863:     function toggleResImport(form,element) {
 1864:         var choices = new Array('crsres','upload');
 1865:         for (var i=0; i<choices.length; i++) {
 1866:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1867:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1868:             }
 1869:         }
 1870:     }
 1871: 
 1872:     function toggleNewsubdir(form,element) {
 1873:         var newsub = form.elements['newsubdir_'+element];
 1874:         if (newsub) {
 1875:             if (newsub.length) {
 1876:                 for (var j=0; j<newsub.length; j++) {
 1877:                     if (newsub[j].checked) {
 1878:                         if (document.getElementById('newsubdirname_'+element)) {
 1879:                             if (newsub[j].value == '1') {
 1880:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1881:                                 if (document.getElementById('newsubdir_'+element)) {
 1882:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1883:                                 }
 1884:                             } else {
 1885:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1886:                                 document.getElementById('newsubdirname_'+element).value = "";
 1887:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1888:                             }
 1889:                         }
 1890:                         break; 
 1891:                     }
 1892:                 }
 1893:             }
 1894:         }
 1895:     }
 1896: 
 1897:     function updateCrsFile(form,element) {
 1898:         var directory = form.elements['coursepath_'+element];
 1899:         var filename = form.elements['coursefile_'+element];
 1900:         var path = directory.options[directory.selectedIndex].value;
 1901:         var file = filename.options[filename.selectedIndex].value;
 1902:         form.elements[element].value = '$respath';
 1903:         if (path == '/') {
 1904:             form.elements[element].value += file;
 1905:         } else {
 1906:             form.elements[element].value += path+'/'+file;
 1907:         }
 1908:         unClean();
 1909:         if (document.getElementById('previewimg_'+element)) {
 1910:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1911:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1912:         }
 1913:         if (document.getElementById('showimg_'+element)) {
 1914:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1915:         }
 1916:         toggleChooser(form,element);
 1917:         return;
 1918:     }
 1919: 
 1920:     function uploadDone(suffix,name) {
 1921:         if (name) {
 1922: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1923:             unClean();
 1924:             toggleChooser(document.forms["lonhomework"],suffix);
 1925:         }
 1926:     }
 1927: 
 1928: \$(document).ready(function(){
 1929: 
 1930:     \$(document).delegate('form :submit', 'click', function( event ) {
 1931:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1932:             var buttonId = this.id;
 1933:             var suffix = buttonId.toString();
 1934:             suffix = suffix.replace(/^crsupload_/,'');
 1935:             event.preventDefault();
 1936:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1937:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1938:             \$(this.form).submit();
 1939:             document.lonhomework.target = '';
 1940:             if (document.getElementById('crsuploadto_'+suffix)) {
 1941:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1942:             }
 1943:             return false;
 1944:         }
 1945:     });
 1946: });
 1947: END
 1948:     }
 1949:     return <<"COLORFULEDIT"
 1950: <script type="text/javascript">
 1951: // <![CDATA[>
 1952:     function fold_box(curDepth, lastresource){
 1953: 
 1954:     // we need a list because there can be several blocks you need to fold in one tag
 1955:         var block = document.getElementsByName('foldblock_'+curDepth);
 1956:     // but there is only one folding button per tag
 1957:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1958: 
 1959:         if(block.item(0).style.display == 'none'){
 1960: 
 1961:             foldbutton.value = '@{[&mt("Hide")]}';
 1962:             for (i = 0; i < block.length; i++){
 1963:                 block.item(i).style.display = '';
 1964:             }
 1965:         }else{
 1966: 
 1967:             foldbutton.value = '@{[&mt("Show")]}';
 1968:             for (i = 0; i < block.length; i++){
 1969:                 // block.item(i).style.visibility = 'collapse';
 1970:                 block.item(i).style.display = 'none';
 1971:             }
 1972:         };
 1973:         saveState(lastresource);
 1974:     }
 1975: 
 1976:     function saveState (lastresource) {
 1977: 
 1978:         var tag_list = getTagList();
 1979:         if(tag_list != null){
 1980:             var timestamp = new Date().getTime();
 1981:             var key = lastresource;
 1982: 
 1983:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1984:             // starting with timestamp
 1985:             var value = timestamp+';';
 1986: 
 1987:             // building the list of key-value pairs
 1988:             for(var i = 0; i < tag_list.length; i++){
 1989:                 value += tag_list[i]+',';
 1990:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1991:             }
 1992: 
 1993:             // only iterate whole storage if nothing to override
 1994:             if(localStorage.getItem(key) == null){        
 1995: 
 1996:                 // prevent storage from growing large
 1997:                 if(localStorage.length > 50){
 1998:                     var regex_getTimestamp = /^(?:\d)+;/;
 1999:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2000:                     var oldest_key;
 2001:                     
 2002:                     for(var i = 1; i < localStorage.length; i++){
 2003:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2004:                             oldest_key = localStorage.key(i);
 2005:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2006:                         }
 2007:                     }
 2008:                     localStorage.removeItem(oldest_key);
 2009:                 }
 2010:             }
 2011:             localStorage.setItem(key,value);
 2012:         }
 2013:     }
 2014: 
 2015:     // restore folding status of blocks (on page load)
 2016:     function restoreState (lastresource) {
 2017:         if(localStorage.getItem(lastresource) != null){
 2018:             var key = lastresource;
 2019:             var value = localStorage.getItem(key);
 2020:             var regex_delTimestamp = /^\d+;/;
 2021: 
 2022:             value.replace(regex_delTimestamp, '');
 2023: 
 2024:             var valueArr = value.split(';');
 2025:             var pairs;
 2026:             var elements;
 2027:             for (var i = 0; i < valueArr.length; i++){
 2028:                 pairs = valueArr[i].split(',');
 2029:                 elements = document.getElementsByName(pairs[0]);
 2030: 
 2031:                 for (var j = 0; j < elements.length; j++){  
 2032:                     elements[j].style.display = pairs[1];
 2033:                     if (pairs[1] == "none"){
 2034:                         var regex_id = /([_\\d]+)\$/;
 2035:                         regex_id.exec(pairs[0]);
 2036:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2037:                     }
 2038:                 }
 2039:             }
 2040:         }
 2041:     }
 2042: 
 2043:     function getTagList () {
 2044:         
 2045:         var stringToSearch = document.lonhomework.innerHTML;
 2046: 
 2047:         var ret = new Array();
 2048:         var regex_findBlock = /(foldblock_.*?)"/g;
 2049:         var tag_list = stringToSearch.match(regex_findBlock);
 2050: 
 2051:         if(tag_list != null){
 2052:             for(var i = 0; i < tag_list.length; i++){            
 2053:                 ret.push(tag_list[i].replace(/"/, ''));
 2054:             }
 2055:         }
 2056:         return ret;
 2057:     }
 2058: 
 2059:     function saveScrollPosition (resource) {
 2060:         var tag_list = getTagList();
 2061: 
 2062:         // we dont always want to jump to the first block
 2063:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2064:         if(\$(window).scrollTop() > 170){
 2065:             if(tag_list != null){
 2066:                 var result;
 2067:                 for(var i = 0; i < tag_list.length; i++){
 2068:                     if(isElementInViewport(tag_list[i])){
 2069:                         result += tag_list[i]+';';
 2070:                     }
 2071:                 }
 2072:                 sessionStorage.setItem('anchor_'+resource, result);
 2073:             }
 2074:         } else {
 2075:             // we dont need to save zero, just delete the item to leave everything tidy
 2076:             sessionStorage.removeItem('anchor_'+resource);
 2077:         }
 2078:     }
 2079: 
 2080:     function restoreScrollPosition(resource){
 2081: 
 2082:         var elem = sessionStorage.getItem('anchor_'+resource);
 2083:         if(elem != null){
 2084:             var tag_list = elem.split(';');
 2085:             var elem_list;
 2086: 
 2087:             for(var i = 0; i < tag_list.length; i++){
 2088:                 elem_list = document.getElementsByName(tag_list[i]);
 2089:                 
 2090:                 if(elem_list.length > 0){
 2091:                     elem = elem_list[0];
 2092:                     break;
 2093:                 }
 2094:             }
 2095:             elem.scrollIntoView();
 2096:         }
 2097:     }
 2098: 
 2099:     function isElementInViewport(el) {
 2100: 
 2101:         // change to last element instead of first
 2102:         var elem = document.getElementsByName(el);
 2103:         var rect = elem[0].getBoundingClientRect();
 2104: 
 2105:         return (
 2106:             rect.top >= 0 &&
 2107:             rect.left >= 0 &&
 2108:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2109:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2110:         );
 2111:     }
 2112:     
 2113:     function autosize(depth){
 2114:         var cmInst = window['cm'+depth];
 2115:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2116: 
 2117:         // is fixed size, switching to dynamic
 2118:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2119:             cmInst.setSize("","auto");
 2120:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2121:             sessionStorage.setItem("autosized_"+depth, "yes");
 2122: 
 2123:         // is dynamic size, switching to fixed
 2124:         } else {
 2125:             cmInst.setSize("","300px");
 2126:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2127:             sessionStorage.removeItem("autosized_"+depth);
 2128:         }
 2129:     }
 2130: 
 2131: $browse_or_search
 2132: 
 2133: // ]]>
 2134: </script>
 2135: COLORFULEDIT
 2136: }
 2137: 
 2138: sub xmleditor_js {
 2139:     return <<XMLEDIT
 2140: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2141: <script type="text/javascript">
 2142: // <![CDATA[>
 2143: 
 2144:     function saveScrollPosition (resource) {
 2145: 
 2146:         var scrollPos = \$(window).scrollTop();
 2147:         sessionStorage.setItem(resource,scrollPos);
 2148:     }
 2149: 
 2150:     function restoreScrollPosition(resource){
 2151: 
 2152:         var scrollPos = sessionStorage.getItem(resource);
 2153:         \$(window).scrollTop(scrollPos);
 2154:     }
 2155: 
 2156:     // unless internet explorer
 2157:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2158: 
 2159:         \$(document).ready(function() {
 2160:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2161:         });
 2162:     }
 2163: 
 2164:     // inserts text at cursor position into codemirror (xml editor only)
 2165:     function insertText(text){
 2166:         cm.focus();
 2167:         var curPos = cm.getCursor();
 2168:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2169:     }
 2170: // ]]>
 2171: </script>
 2172: XMLEDIT
 2173: }
 2174: 
 2175: sub insert_folding_button {
 2176:     my $curDepth = $Apache::lonxml::curdepth;
 2177:     my $lastresource = $env{'request.ambiguous'};
 2178: 
 2179:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2180:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2181: }
 2182: 
 2183: sub crsauthor_url {
 2184:     my ($url) = @_;
 2185:     if ($url eq '') {
 2186:         $url = $ENV{'REQUEST_URI'};
 2187:     }
 2188:     my ($cnum,$cdom);
 2189:     if ($env{'request.course.id'}) {
 2190:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2191:         if ($audom ne '' && $auname ne '') {
 2192:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2193:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2194:                 $cnum = $auname;
 2195:                 $cdom = $audom;
 2196:             }
 2197:         }
 2198:     }
 2199:     return ($cnum,$cdom);
 2200: }
 2201: 
 2202: sub import_crsauthor_form {
 2203:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2204:     return (0) unless ($env{'request.course.id'});
 2205:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2206:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2207:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2208:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2209:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2210:     my @ids=&Apache::lonnet::current_machine_ids();
 2211:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2212:     
 2213:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2214:         $is_home = 1;
 2215:     }
 2216:     $relpath = "/priv/$cdom/$cnum";
 2217:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2218:     my %lt = &Apache::lonlocal::texthash (
 2219:         fnam => 'Filename',
 2220:         dire => 'Directory',
 2221:     );
 2222:     my $numdirs = scalar(keys(%files));
 2223:     my (%possexts,$singledir,@singledirfiles);
 2224:     if ($only) {
 2225:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2226:     }
 2227:     my (%nonemptydirs,$possdirs);
 2228:     if ($numdirs > 1) {
 2229:         my @order;
 2230:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2231:             if (ref($files{$key}) eq 'HASH') {
 2232:                 my $shown = $key;
 2233:                 if ($key eq '') {
 2234:                     $shown = '/';
 2235:                 }
 2236:                 my @ordered = ();
 2237:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2238:                     next if ($file =~ /\.rights$/);
 2239:                     if ($only) {
 2240:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2241:                         unless ($possexts{lc($ext)}) {
 2242:                             next;
 2243:                         }
 2244:                     }
 2245:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2246:                     push(@ordered,$file);
 2247:                 }
 2248:                 if (@ordered) {
 2249:                     push(@order,$key);
 2250:                     $nonemptydirs{$key} = 1;
 2251:                     $selimport_menus{$key}->{'text'} = $shown;
 2252:                     $selimport_menus{$key}->{'default'} = '';
 2253:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2254:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2255:                 }
 2256:             }
 2257:         }
 2258:         $possdirs = scalar(keys(%nonemptydirs));
 2259:         if ($possdirs > 1) {
 2260:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2261:             $output = $lt{'dire'}.
 2262:                       &linked_select_forms($form,'<br />'.
 2263:                                            $lt{'fnam'},'',
 2264:                                            $firstselectname,$secondselectname,
 2265:                                            \%selimport_menus,\@order,
 2266:                                            $onchangefirst,'',$suffix).'<br />';
 2267:         } elsif ($possdirs == 1) {
 2268:             $singledir = (keys(%nonemptydirs))[0];
 2269:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2270:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2271:             }
 2272:             delete($selimport_menus{$singledir});
 2273:         }
 2274:     } elsif ($numdirs == 1) {
 2275:         $singledir = (keys(%files))[0];
 2276:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2277:             if ($only) {
 2278:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2279:                 unless ($possexts{lc($ext)}) {
 2280:                     next;
 2281:                 }
 2282:             } else {
 2283:                 next if ($file =~ /\.rights$/);
 2284:             }
 2285:             push(@singledirfiles,$file);
 2286:         }
 2287:         if (@singledirfiles) {
 2288:             $possdirs = 1;
 2289:         }
 2290:     }
 2291:     if (($possdirs == 1) && (@singledirfiles)) {
 2292:         my $showdir = $singledir;
 2293:         if ($singledir eq '') {
 2294:             $showdir = '/';
 2295:         }
 2296:         $output = $lt{'dire'}.
 2297:                   '<select name="'.$firstselectname.'">'.
 2298:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2299:                   '</select><br />'.
 2300:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2301:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2302:         foreach my $file (@singledirfiles) {
 2303:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2304:         }
 2305:         $output .= '</select><br />'."\n";
 2306:     }
 2307:     return ($possdirs,$output);
 2308: }
 2309: 
 2310: =pod
 2311: 
 2312: =head1 Excel and CSV file utility routines
 2313: 
 2314: =cut
 2315: 
 2316: ###############################################################
 2317: ###############################################################
 2318: 
 2319: =pod
 2320: 
 2321: =over 4
 2322: 
 2323: =item * &csv_translate($text) 
 2324: 
 2325: Translate $text to allow it to be output as a 'comma separated values' 
 2326: format.
 2327: 
 2328: =cut
 2329: 
 2330: ###############################################################
 2331: ###############################################################
 2332: sub csv_translate {
 2333:     my $text = shift;
 2334:     $text =~ s/\"/\"\"/g;
 2335:     $text =~ s/\n/ /g;
 2336:     return $text;
 2337: }
 2338: 
 2339: ###############################################################
 2340: ###############################################################
 2341: 
 2342: =pod
 2343: 
 2344: =item * &define_excel_formats()
 2345: 
 2346: Define some commonly used Excel cell formats.
 2347: 
 2348: Currently supported formats:
 2349: 
 2350: =over 4
 2351: 
 2352: =item header
 2353: 
 2354: =item bold
 2355: 
 2356: =item h1
 2357: 
 2358: =item h2
 2359: 
 2360: =item h3
 2361: 
 2362: =item h4
 2363: 
 2364: =item i
 2365: 
 2366: =item date
 2367: 
 2368: =back
 2369: 
 2370: Inputs: $workbook
 2371: 
 2372: Returns: $format, a hash reference.
 2373: 
 2374: 
 2375: =cut
 2376: 
 2377: ###############################################################
 2378: ###############################################################
 2379: sub define_excel_formats {
 2380:     my ($workbook) = @_;
 2381:     my $format;
 2382:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2383:                                                 bottom    => 1,
 2384:                                                 align     => 'center');
 2385:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2386:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2387:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2388:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2389:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2390:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2391:     $format->{'date'} = $workbook->add_format(num_format=>
 2392:                                             'mm/dd/yyyy hh:mm:ss');
 2393:     return $format;
 2394: }
 2395: 
 2396: ###############################################################
 2397: ###############################################################
 2398: 
 2399: =pod
 2400: 
 2401: =item * &create_workbook()
 2402: 
 2403: Create an Excel worksheet.  If it fails, output message on the
 2404: request object and return undefs.
 2405: 
 2406: Inputs: Apache request object
 2407: 
 2408: Returns (undef) on failure, 
 2409:     Excel worksheet object, scalar with filename, and formats 
 2410:     from &Apache::loncommon::define_excel_formats on success
 2411: 
 2412: =cut
 2413: 
 2414: ###############################################################
 2415: ###############################################################
 2416: sub create_workbook {
 2417:     my ($r) = @_;
 2418:         #
 2419:     # Create the excel spreadsheet
 2420:     my $filename = '/prtspool/'.
 2421:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2422:         time.'_'.rand(1000000000).'.xls';
 2423:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2424:     if (! defined($workbook)) {
 2425:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2426:         $r->print(
 2427:             '<p class="LC_error">'
 2428:            .&mt('Problems occurred in creating the new Excel file.')
 2429:            .' '.&mt('This error has been logged.')
 2430:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2431:            .'</p>'
 2432:         );
 2433:         return (undef);
 2434:     }
 2435:     #
 2436:     $workbook->set_tempdir(LONCAPA::tempdir());
 2437:     #
 2438:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2439:     return ($workbook,$filename,$format);
 2440: }
 2441: 
 2442: ###############################################################
 2443: ###############################################################
 2444: 
 2445: =pod
 2446: 
 2447: =item * &create_text_file()
 2448: 
 2449: Create a file to write to and eventually make available to the user.
 2450: If file creation fails, outputs an error message on the request object and 
 2451: return undefs.
 2452: 
 2453: Inputs: Apache request object, and file suffix
 2454: 
 2455: Returns (undef) on failure, 
 2456:     Filehandle and filename on success.
 2457: 
 2458: =cut
 2459: 
 2460: ###############################################################
 2461: ###############################################################
 2462: sub create_text_file {
 2463:     my ($r,$suffix) = @_;
 2464:     if (! defined($suffix)) { $suffix = 'txt'; };
 2465:     my $fh;
 2466:     my $filename = '/prtspool/'.
 2467:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2468:         time.'_'.rand(1000000000).'.'.$suffix;
 2469:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2470:     if (! defined($fh)) {
 2471:         $r->log_error("Couldn't open $filename for output $!");
 2472:         $r->print(
 2473:             '<p class="LC_error">'
 2474:            .&mt('Problems occurred in creating the output file.')
 2475:            .' '.&mt('This error has been logged.')
 2476:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2477:            .'</p>'
 2478:         );
 2479:     }
 2480:     return ($fh,$filename)
 2481: }
 2482: 
 2483: 
 2484: =pod 
 2485: 
 2486: =back
 2487: 
 2488: =cut
 2489: 
 2490: ###############################################################
 2491: ##        Home server <option> list generating code          ##
 2492: ###############################################################
 2493: 
 2494: # ------------------------------------------
 2495: 
 2496: sub domain_select {
 2497:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2498:     my @possdoms;
 2499:     if (ref($incdoms) eq 'ARRAY') {
 2500:         @possdoms = @{$incdoms};
 2501:     } else {
 2502:         @possdoms = &Apache::lonnet::all_domains();
 2503:     }
 2504: 
 2505:     my %domains=map { 
 2506: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2507:     } @possdoms;
 2508: 
 2509:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2510:         foreach my $dom (@{$excdoms}) {
 2511:             delete($domains{$dom});
 2512:         }
 2513:     }
 2514: 
 2515:     if ($multiple) {
 2516: 	$domains{''}=&mt('Any domain');
 2517: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2518: 	return &multiple_select_form($name,$value,4,\%domains);
 2519:     } else {
 2520: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2521: 	return &select_form($name,$value,\%domains);
 2522:     }
 2523: }
 2524: 
 2525: #-------------------------------------------
 2526: 
 2527: =pod
 2528: 
 2529: =head1 Routines for form select boxes
 2530: 
 2531: =over 4
 2532: 
 2533: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2534: 
 2535: Returns a string containing a <select> element int multiple mode
 2536: 
 2537: 
 2538: Args:
 2539:   $name - name of the <select> element
 2540:   $value - scalar or array ref of values that should already be selected
 2541:   $size - number of rows long the select element is
 2542:   $hash - the elements should be 'option' => 'shown text'
 2543:           (shown text should already have been &mt())
 2544:   $order - (optional) array ref of the order to show the elements in
 2545: 
 2546: =cut
 2547: 
 2548: #-------------------------------------------
 2549: sub multiple_select_form {
 2550:     my ($name,$value,$size,$hash,$order)=@_;
 2551:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2552:     my $output='';
 2553:     if (! defined($size)) {
 2554:         $size = 4;
 2555:         if (scalar(keys(%$hash))<4) {
 2556:             $size = scalar(keys(%$hash));
 2557:         }
 2558:     }
 2559:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2560:     my @order;
 2561:     if (ref($order) eq 'ARRAY')  {
 2562:         @order = @{$order};
 2563:     } else {
 2564:         @order = sort(keys(%$hash));
 2565:     }
 2566:     if (exists($$hash{'select_form_order'})) {
 2567:         @order = @{$$hash{'select_form_order'}};
 2568:     }
 2569:         
 2570:     foreach my $key (@order) {
 2571:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2572:         $output.='selected="selected" ' if ($selected{$key});
 2573:         $output.='>'.$hash->{$key}."</option>\n";
 2574:     }
 2575:     $output.="</select>\n";
 2576:     return $output;
 2577: }
 2578: 
 2579: #-------------------------------------------
 2580: 
 2581: =pod
 2582: 
 2583: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2584: 
 2585: Returns a string containing a <select name='$name' size='1'> form to 
 2586: allow a user to select options from a ref to a hash containing:
 2587: option_name => displayed text. An optional $onchange can include
 2588: a javascript onchange item, e.g., onchange="this.form.submit();".
 2589: An optional arg -- $readonly -- if true will cause the select form
 2590: to be disabled, e.g., for the case where an instructor has a section-
 2591: specific role, and is viewing/modifying parameters. 
 2592: 
 2593: See lonrights.pm for an example invocation and use.
 2594: 
 2595: =cut
 2596: 
 2597: #-------------------------------------------
 2598: sub select_form {
 2599:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2600:     return unless (ref($hashref) eq 'HASH');
 2601:     if ($onchange) {
 2602:         $onchange = ' onchange="'.$onchange.'"';
 2603:     }
 2604:     my $disabled;
 2605:     if ($readonly) {
 2606:         $disabled = ' disabled="disabled"';
 2607:     }
 2608:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2609:     my @keys;
 2610:     if (exists($hashref->{'select_form_order'})) {
 2611: 	@keys=@{$hashref->{'select_form_order'}};
 2612:     } else {
 2613: 	@keys=sort(keys(%{$hashref}));
 2614:     }
 2615:     foreach my $key (@keys) {
 2616:         $selectform.=
 2617: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2618:             ($key eq $def ? 'selected="selected" ' : '').
 2619:                 ">".$hashref->{$key}."</option>\n";
 2620:     }
 2621:     $selectform.="</select>";
 2622:     return $selectform;
 2623: }
 2624: 
 2625: # For display filters
 2626: 
 2627: sub display_filter {
 2628:     my ($context) = @_;
 2629:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2630:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2631:     my $phraseinput = 'hidden';
 2632:     my $includeinput = 'hidden';
 2633:     my ($checked,$includetypestext);
 2634:     if ($env{'form.displayfilter'} eq 'containing') {
 2635:         $phraseinput = 'text'; 
 2636:         if ($context eq 'parmslog') {
 2637:             $includeinput = 'checkbox';
 2638:             if ($env{'form.includetypes'}) {
 2639:                 $checked = ' checked="checked"';
 2640:             }
 2641:             $includetypestext = &mt('Include parameter types');
 2642:         }
 2643:     } else {
 2644:         $includetypestext = '&nbsp;';
 2645:     }
 2646:     my ($additional,$secondid,$thirdid);
 2647:     if ($context eq 'parmslog') {
 2648:         $additional = 
 2649:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2650:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2651:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2652:             '</label>';
 2653:         $secondid = 'includetypes';
 2654:         $thirdid = 'includetypestext';
 2655:     }
 2656:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2657:                                                     '$secondid','$thirdid')";
 2658:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2659: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2660: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2661: 	   '</label></span> <span class="LC_nobreak">'.
 2662:            &mt('Filter: [_1]',
 2663: 	   &select_form($env{'form.displayfilter'},
 2664: 			'displayfilter',
 2665: 			{'currentfolder' => 'Current folder/page',
 2666: 			 'containing' => 'Containing phrase',
 2667: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2668: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2669:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2670:                          '" />'.$additional;
 2671: }
 2672: 
 2673: sub display_filter_js {
 2674:     my $includetext = &mt('Include parameter types');
 2675:     return <<"ENDJS";
 2676:   
 2677: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2678:     var firstType = 'hidden';
 2679:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2680:         firstType = 'text';
 2681:     }
 2682:     firstObject = document.getElementById(firstid);
 2683:     if (typeof(firstObject) == 'object') {
 2684:         if (firstObject.type != firstType) {
 2685:             changeInputType(firstObject,firstType);
 2686:         }
 2687:     }
 2688:     if (context == 'parmslog') {
 2689:         var secondType = 'hidden';
 2690:         if (firstType == 'text') {
 2691:             secondType = 'checkbox';
 2692:         }
 2693:         secondObject = document.getElementById(secondid);  
 2694:         if (typeof(secondObject) == 'object') {
 2695:             if (secondObject.type != secondType) {
 2696:                 changeInputType(secondObject,secondType);
 2697:             }
 2698:         }
 2699:         var textItem = document.getElementById(thirdid);
 2700:         var currtext = textItem.innerHTML;
 2701:         var newtext;
 2702:         if (firstType == 'text') {
 2703:             newtext = '$includetext';
 2704:         } else {
 2705:             newtext = '&nbsp;';
 2706:         }
 2707:         if (currtext != newtext) {
 2708:             textItem.innerHTML = newtext;
 2709:         }
 2710:     }
 2711:     return;
 2712: }
 2713: 
 2714: function changeInputType(oldObject,newType) {
 2715:     var newObject = document.createElement('input');
 2716:     newObject.type = newType;
 2717:     if (oldObject.size) {
 2718:         newObject.size = oldObject.size;
 2719:     }
 2720:     if (oldObject.value) {
 2721:         newObject.value = oldObject.value;
 2722:     }
 2723:     if (oldObject.name) {
 2724:         newObject.name = oldObject.name;
 2725:     }
 2726:     if (oldObject.id) {
 2727:         newObject.id = oldObject.id;
 2728:     }
 2729:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2730:     return;
 2731: }
 2732: 
 2733: ENDJS
 2734: }
 2735: 
 2736: sub gradeleveldescription {
 2737:     my $gradelevel=shift;
 2738:     my %gradelevels=(0 => 'Not specified',
 2739: 		     1 => 'Grade 1',
 2740: 		     2 => 'Grade 2',
 2741: 		     3 => 'Grade 3',
 2742: 		     4 => 'Grade 4',
 2743: 		     5 => 'Grade 5',
 2744: 		     6 => 'Grade 6',
 2745: 		     7 => 'Grade 7',
 2746: 		     8 => 'Grade 8',
 2747: 		     9 => 'Grade 9',
 2748: 		     10 => 'Grade 10',
 2749: 		     11 => 'Grade 11',
 2750: 		     12 => 'Grade 12',
 2751: 		     13 => 'Grade 13',
 2752: 		     14 => '100 Level',
 2753: 		     15 => '200 Level',
 2754: 		     16 => '300 Level',
 2755: 		     17 => '400 Level',
 2756: 		     18 => 'Graduate Level');
 2757:     return &mt($gradelevels{$gradelevel});
 2758: }
 2759: 
 2760: sub select_level_form {
 2761:     my ($deflevel,$name)=@_;
 2762:     unless ($deflevel) { $deflevel=0; }
 2763:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2764:     for (my $i=0; $i<=18; $i++) {
 2765:         $selectform.="<option value=\"$i\" ".
 2766:             ($i==$deflevel ? 'selected="selected" ' : '').
 2767:                 ">".&gradeleveldescription($i)."</option>\n";
 2768:     }
 2769:     $selectform.="</select>";
 2770:     return $selectform;
 2771: }
 2772: 
 2773: #-------------------------------------------
 2774: 
 2775: =pod
 2776: 
 2777: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2778: 
 2779: Returns a string containing a <select name='$name' size='1'> form to 
 2780: allow a user to select the domain to preform an operation in.  
 2781: See loncreateuser.pm for an example invocation and use.
 2782: 
 2783: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2784: selected");
 2785: 
 2786: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2787: 
 2788: 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.
 2789: 
 2790: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2791: 
 2792: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2793: 
 2794: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2795: 
 2796: =cut
 2797: 
 2798: #-------------------------------------------
 2799: sub select_dom_form {
 2800:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2801:     if ($onchange) {
 2802:         $onchange = ' onchange="'.$onchange.'"';
 2803:     }
 2804:     if ($disabled) {
 2805:         $disabled = ' disabled="disabled"';
 2806:     }
 2807:     my (@domains,%exclude);
 2808:     if (ref($incdoms) eq 'ARRAY') {
 2809:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2810:     } else {
 2811:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2812:     }
 2813:     if ($includeempty) { @domains=('',@domains); }
 2814:     if (ref($excdoms) eq 'ARRAY') {
 2815:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2816:     }
 2817:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2818:     foreach my $dom (@domains) {
 2819:         next if ($exclude{$dom});
 2820:         $selectdomain.="<option value=\"$dom\" ".
 2821:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2822:         if ($showdomdesc) {
 2823:             if ($dom ne '') {
 2824:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2825:                 if ($domdesc ne '') {
 2826:                     $selectdomain .= ' ('.$domdesc.')';
 2827:                 }
 2828:             } 
 2829:         }
 2830:         $selectdomain .= "</option>\n";
 2831:     }
 2832:     $selectdomain.="</select>";
 2833:     return $selectdomain;
 2834: }
 2835: 
 2836: #-------------------------------------------
 2837: 
 2838: =pod
 2839: 
 2840: =item * &home_server_form_item($domain,$name,$defaultflag)
 2841: 
 2842: input: 4 arguments (two required, two optional) - 
 2843:     $domain - domain of new user
 2844:     $name - name of form element
 2845:     $default - Value of 'default' causes a default item to be first 
 2846:                             option, and selected by default. 
 2847:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2848:                             if 1 server found, or default, if 0 found.
 2849: output: returns 2 items: 
 2850: (a) form element which contains either:
 2851:    (i) <select name="$name">
 2852:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2853:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2854:        </select>
 2855:        form item if there are multiple library servers in $domain, or
 2856:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2857:        if there is only one library server in $domain.
 2858: 
 2859: (b) number of library servers found.
 2860: 
 2861: See loncreateuser.pm for example of use.
 2862: 
 2863: =cut
 2864: 
 2865: #-------------------------------------------
 2866: sub home_server_form_item {
 2867:     my ($domain,$name,$default,$hide) = @_;
 2868:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2869:     my $result;
 2870:     my $numlib = keys(%servers);
 2871:     if ($numlib > 1) {
 2872:         $result .= '<select name="'.$name.'" />'."\n";
 2873:         if ($default) {
 2874:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2875:                        '</option>'."\n";
 2876:         }
 2877:         foreach my $hostid (sort(keys(%servers))) {
 2878:             $result.= '<option value="'.$hostid.'">'.
 2879: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2880:         }
 2881:         $result .= '</select>'."\n";
 2882:     } elsif ($numlib == 1) {
 2883:         my $hostid;
 2884:         foreach my $item (keys(%servers)) {
 2885:             $hostid = $item;
 2886:         }
 2887:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2888:                    $hostid.'" />';
 2889:                    if (!$hide) {
 2890:                        $result .= $hostid.' '.$servers{$hostid};
 2891:                    }
 2892:                    $result .= "\n";
 2893:     } elsif ($default) {
 2894:         $result .= '<input type="hidden" name="'.$name.
 2895:                    '" value="default" />';
 2896:                    if (!$hide) {
 2897:                        $result .= &mt('default');
 2898:                    }
 2899:                    $result .= "\n";
 2900:     }
 2901:     return ($result,$numlib);
 2902: }
 2903: 
 2904: =pod
 2905: 
 2906: =back 
 2907: 
 2908: =cut
 2909: 
 2910: ###############################################################
 2911: ##                  Decoding User Agent                      ##
 2912: ###############################################################
 2913: 
 2914: =pod
 2915: 
 2916: =head1 Decoding the User Agent
 2917: 
 2918: =over 4
 2919: 
 2920: =item * &decode_user_agent()
 2921: 
 2922: Inputs: $r
 2923: 
 2924: Outputs:
 2925: 
 2926: =over 4
 2927: 
 2928: =item * $httpbrowser
 2929: 
 2930: =item * $clientbrowser
 2931: 
 2932: =item * $clientversion
 2933: 
 2934: =item * $clientmathml
 2935: 
 2936: =item * $clientunicode
 2937: 
 2938: =item * $clientos
 2939: 
 2940: =item * $clientmobile
 2941: 
 2942: =item * $clientinfo
 2943: 
 2944: =item * $clientosversion
 2945: 
 2946: =back
 2947: 
 2948: =back 
 2949: 
 2950: =cut
 2951: 
 2952: ###############################################################
 2953: ###############################################################
 2954: sub decode_user_agent {
 2955:     my ($r)=@_;
 2956:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2957:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2958:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2959:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2960:     my $clientbrowser='unknown';
 2961:     my $clientversion='0';
 2962:     my $clientmathml='';
 2963:     my $clientunicode='0';
 2964:     my $clientmobile=0;
 2965:     my $clientosversion='';
 2966:     for (my $i=0;$i<=$#browsertype;$i++) {
 2967:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2968: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2969: 	    $clientbrowser=$bname;
 2970:             $httpbrowser=~/$vreg/i;
 2971: 	    $clientversion=$1;
 2972:             $clientmathml=($clientversion>=$minv);
 2973:             $clientunicode=($clientversion>=$univ);
 2974: 	}
 2975:     }
 2976:     my $clientos='unknown';
 2977:     my $clientinfo;
 2978:     if (($httpbrowser=~/linux/i) ||
 2979:         ($httpbrowser=~/unix/i) ||
 2980:         ($httpbrowser=~/ux/i) ||
 2981:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2982:     if (($httpbrowser=~/vax/i) ||
 2983:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2984:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2985:     if (($httpbrowser=~/mac/i) ||
 2986:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2987:     if ($httpbrowser=~/win/i) {
 2988:         $clientos='win';
 2989:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2990:             $clientosversion = $1;
 2991:         }
 2992:     }
 2993:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2994:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2995:         $clientmobile=lc($1);
 2996:     }
 2997:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2998:         $clientinfo = 'firefox-'.$1;
 2999:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3000:         $clientinfo = 'chromeframe-'.$1;
 3001:     }
 3002:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3003:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3004:             $clientosversion);
 3005: }
 3006: 
 3007: ###############################################################
 3008: ##    Authentication changing form generation subroutines    ##
 3009: ###############################################################
 3010: ##
 3011: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3012: ## hash, and have reasonable default values.
 3013: ##
 3014: ##    formname = the name given in the <form> tag.
 3015: #-------------------------------------------
 3016: 
 3017: =pod
 3018: 
 3019: =head1 Authentication Routines
 3020: 
 3021: =over 4
 3022: 
 3023: =item * &authform_xxxxxx()
 3024: 
 3025: The authform_xxxxxx subroutines provide javascript and html forms which 
 3026: handle some of the conveniences required for authentication forms.  
 3027: This is not an optimal method, but it works.  
 3028: 
 3029: =over 4
 3030: 
 3031: =item * authform_header
 3032: 
 3033: =item * authform_authorwarning
 3034: 
 3035: =item * authform_nochange
 3036: 
 3037: =item * authform_kerberos
 3038: 
 3039: =item * authform_internal
 3040: 
 3041: =item * authform_filesystem
 3042: 
 3043: =item * authform_lti
 3044: 
 3045: =back
 3046: 
 3047: See loncreateuser.pm for invocation and use examples.
 3048: 
 3049: =cut
 3050: 
 3051: #-------------------------------------------
 3052: sub authform_header{  
 3053:     my %in = (
 3054:         formname => 'cu',
 3055:         kerb_def_dom => '',
 3056:         @_,
 3057:     );
 3058:     $in{'formname'} = 'document.' . $in{'formname'};
 3059:     my $result='';
 3060: 
 3061: #---------------------------------------------- Code for upper case translation
 3062:     my $Javascript_toUpperCase;
 3063:     unless ($in{kerb_def_dom}) {
 3064:         $Javascript_toUpperCase =<<"END";
 3065:         switch (choice) {
 3066:            case 'krb': currentform.elements[choicearg].value =
 3067:                currentform.elements[choicearg].value.toUpperCase();
 3068:                break;
 3069:            default:
 3070:         }
 3071: END
 3072:     } else {
 3073:         $Javascript_toUpperCase = "";
 3074:     }
 3075: 
 3076:     my $radioval = "'nochange'";
 3077:     if (defined($in{'curr_authtype'})) {
 3078:         if ($in{'curr_authtype'} ne '') {
 3079:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3080:         }
 3081:     }
 3082:     my $argfield = 'null';
 3083:     if (defined($in{'mode'})) {
 3084:         if ($in{'mode'} eq 'modifycourse')  {
 3085:             if (defined($in{'curr_autharg'})) {
 3086:                 if ($in{'curr_autharg'} ne '') {
 3087:                     $argfield = "'$in{'curr_autharg'}'";
 3088:                 }
 3089:             }
 3090:         }
 3091:     }
 3092: 
 3093:     $result.=<<"END";
 3094: var current = new Object();
 3095: current.radiovalue = $radioval;
 3096: current.argfield = $argfield;
 3097: 
 3098: function changed_radio(choice,currentform) {
 3099:     var choicearg = choice + 'arg';
 3100:     // If a radio button in changed, we need to change the argfield
 3101:     if (current.radiovalue != choice) {
 3102:         current.radiovalue = choice;
 3103:         if (current.argfield != null) {
 3104:             currentform.elements[current.argfield].value = '';
 3105:         }
 3106:         if (choice == 'nochange') {
 3107:             current.argfield = null;
 3108:         } else {
 3109:             current.argfield = choicearg;
 3110:             switch(choice) {
 3111:                 case 'krb': 
 3112:                     currentform.elements[current.argfield].value = 
 3113:                         "$in{'kerb_def_dom'}";
 3114:                 break;
 3115:               default:
 3116:                 break;
 3117:             }
 3118:         }
 3119:     }
 3120:     return;
 3121: }
 3122: 
 3123: function changed_text(choice,currentform) {
 3124:     var choicearg = choice + 'arg';
 3125:     if (currentform.elements[choicearg].value !='') {
 3126:         $Javascript_toUpperCase
 3127:         // clear old field
 3128:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3129:             currentform.elements[current.argfield].value = '';
 3130:         }
 3131:         current.argfield = choicearg;
 3132:     }
 3133:     set_auth_radio_buttons(choice,currentform);
 3134:     return;
 3135: }
 3136: 
 3137: function set_auth_radio_buttons(newvalue,currentform) {
 3138:     var numauthchoices = currentform.login.length;
 3139:     if (typeof numauthchoices  == "undefined") {
 3140:         return;
 3141:     } 
 3142:     var i=0;
 3143:     while (i < numauthchoices) {
 3144:         if (currentform.login[i].value == newvalue) { break; }
 3145:         i++;
 3146:     }
 3147:     if (i == numauthchoices) {
 3148:         return;
 3149:     }
 3150:     current.radiovalue = newvalue;
 3151:     currentform.login[i].checked = true;
 3152:     return;
 3153: }
 3154: END
 3155:     return $result;
 3156: }
 3157: 
 3158: sub authform_authorwarning {
 3159:     my $result='';
 3160:     $result='<i>'.
 3161:         &mt('As a general rule, only authors or co-authors should be '.
 3162:             'filesystem authenticated '.
 3163:             '(which allows access to the server filesystem).')."</i>\n";
 3164:     return $result;
 3165: }
 3166: 
 3167: sub authform_nochange {
 3168:     my %in = (
 3169:               formname => 'document.cu',
 3170:               kerb_def_dom => 'MSU.EDU',
 3171:               @_,
 3172:           );
 3173:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3174:     my $result;
 3175:     if (!$authnum) {
 3176:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3177:     } else {
 3178:         $result = '<label>'.&mt('[_1] Do not change login data',
 3179:                   '<input type="radio" name="login" value="nochange" '.
 3180:                   'checked="checked" onclick="'.
 3181:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3182: 	    '</label>';
 3183:     }
 3184:     return $result;
 3185: }
 3186: 
 3187: sub authform_kerberos {
 3188:     my %in = (
 3189:               formname => 'document.cu',
 3190:               kerb_def_dom => 'MSU.EDU',
 3191:               kerb_def_auth => 'krb4',
 3192:               @_,
 3193:               );
 3194:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3195:         $autharg,$jscall,$disabled);
 3196:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3197:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3198:        $check5 = ' checked="checked"';
 3199:     } else {
 3200:        $check4 = ' checked="checked"';
 3201:     }
 3202:     if ($in{'readonly'}) {
 3203:         $disabled = ' disabled="disabled"';
 3204:     }
 3205:     $krbarg = $in{'kerb_def_dom'};
 3206:     if (defined($in{'curr_authtype'})) {
 3207:         if ($in{'curr_authtype'} eq 'krb') {
 3208:             $krbcheck = ' checked="checked"';
 3209:             if (defined($in{'mode'})) {
 3210:                 if ($in{'mode'} eq 'modifyuser') {
 3211:                     $krbcheck = '';
 3212:                 }
 3213:             }
 3214:             if (defined($in{'curr_kerb_ver'})) {
 3215:                 if ($in{'curr_krb_ver'} eq '5') {
 3216:                     $check5 = ' checked="checked"';
 3217:                     $check4 = '';
 3218:                 } else {
 3219:                     $check4 = ' checked="checked"';
 3220:                     $check5 = '';
 3221:                 }
 3222:             }
 3223:             if (defined($in{'curr_autharg'})) {
 3224:                 $krbarg = $in{'curr_autharg'};
 3225:             }
 3226:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3227:                 if (defined($in{'curr_autharg'})) {
 3228:                     $result = 
 3229:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3230:         $in{'curr_autharg'},$krbver);
 3231:                 } else {
 3232:                     $result =
 3233:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3234:                 }
 3235:                 return $result; 
 3236:             }
 3237:         }
 3238:     } else {
 3239:         if ($authnum == 1) {
 3240:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3241:         }
 3242:     }
 3243:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3244:         return;
 3245:     } elsif ($authtype eq '') {
 3246:         if (defined($in{'mode'})) {
 3247:             if ($in{'mode'} eq 'modifycourse') {
 3248:                 if ($authnum == 1) {
 3249:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3250:                 }
 3251:             }
 3252:         }
 3253:     }
 3254:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3255:     if ($authtype eq '') {
 3256:         $authtype = '<input type="radio" name="login" value="krb" '.
 3257:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3258:                     $krbcheck.$disabled.' />';
 3259:     }
 3260:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3261:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3262:          $in{'curr_authtype'} eq 'krb5') ||
 3263:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3264:          $in{'curr_authtype'} eq 'krb4')) {
 3265:         $result .= &mt
 3266:         ('[_1] Kerberos authenticated with domain [_2] '.
 3267:          '[_3] Version 4 [_4] Version 5 [_5]',
 3268:          '<label>'.$authtype,
 3269:          '</label><input type="text" size="10" name="krbarg" '.
 3270:              'value="'.$krbarg.'" '.
 3271:              'onchange="'.$jscall.'"'.$disabled.' />',
 3272:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3273:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3274: 	 '</label>');
 3275:     } elsif ($can_assign{'krb4'}) {
 3276:         $result .= &mt
 3277:         ('[_1] Kerberos authenticated with domain [_2] '.
 3278:          '[_3] Version 4 [_4]',
 3279:          '<label>'.$authtype,
 3280:          '</label><input type="text" size="10" name="krbarg" '.
 3281:              'value="'.$krbarg.'" '.
 3282:              'onchange="'.$jscall.'"'.$disabled.' />',
 3283:          '<label><input type="hidden" name="krbver" value="4" />',
 3284:          '</label>');
 3285:     } elsif ($can_assign{'krb5'}) {
 3286:         $result .= &mt
 3287:         ('[_1] Kerberos authenticated with domain [_2] '.
 3288:          '[_3] Version 5 [_4]',
 3289:          '<label>'.$authtype,
 3290:          '</label><input type="text" size="10" name="krbarg" '.
 3291:              'value="'.$krbarg.'" '.
 3292:              'onchange="'.$jscall.'"'.$disabled.' />',
 3293:          '<label><input type="hidden" name="krbver" value="5" />',
 3294:          '</label>');
 3295:     }
 3296:     return $result;
 3297: }
 3298: 
 3299: sub authform_internal {
 3300:     my %in = (
 3301:                 formname => 'document.cu',
 3302:                 kerb_def_dom => 'MSU.EDU',
 3303:                 @_,
 3304:                 );
 3305:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3306:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3307:     if ($in{'readonly'}) {
 3308:         $disabled = ' disabled="disabled"';
 3309:     }
 3310:     if (defined($in{'curr_authtype'})) {
 3311:         if ($in{'curr_authtype'} eq 'int') {
 3312:             if ($can_assign{'int'}) {
 3313:                 $intcheck = 'checked="checked" ';
 3314:                 if (defined($in{'mode'})) {
 3315:                     if ($in{'mode'} eq 'modifyuser') {
 3316:                         $intcheck = '';
 3317:                     }
 3318:                 }
 3319:                 if (defined($in{'curr_autharg'})) {
 3320:                     $intarg = $in{'curr_autharg'};
 3321:                 }
 3322:             } else {
 3323:                 $result = &mt('Currently internally authenticated.');
 3324:                 return $result;
 3325:             }
 3326:         }
 3327:     } else {
 3328:         if ($authnum == 1) {
 3329:             $authtype = '<input type="hidden" name="login" value="int" />';
 3330:         }
 3331:     }
 3332:     if (!$can_assign{'int'}) {
 3333:         return;
 3334:     } elsif ($authtype eq '') {
 3335:         if (defined($in{'mode'})) {
 3336:             if ($in{'mode'} eq 'modifycourse') {
 3337:                 if ($authnum == 1) {
 3338:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3339:                 }
 3340:             }
 3341:         }
 3342:     }
 3343:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3344:     if ($authtype eq '') {
 3345:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3346:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3347:     }
 3348:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3349:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3350:     $result = &mt
 3351:         ('[_1] Internally authenticated (with initial password [_2])',
 3352:          '<label>'.$authtype,'</label>'.$autharg);
 3353:     $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>';
 3354:     return $result;
 3355: }
 3356: 
 3357: sub authform_local {
 3358:     my %in = (
 3359:               formname => 'document.cu',
 3360:               kerb_def_dom => 'MSU.EDU',
 3361:               @_,
 3362:               );
 3363:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3364:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3365:     if ($in{'readonly'}) {
 3366:         $disabled = ' disabled="disabled"';
 3367:     } 
 3368:     if (defined($in{'curr_authtype'})) {
 3369:         if ($in{'curr_authtype'} eq 'loc') {
 3370:             if ($can_assign{'loc'}) {
 3371:                 $loccheck = 'checked="checked" ';
 3372:                 if (defined($in{'mode'})) {
 3373:                     if ($in{'mode'} eq 'modifyuser') {
 3374:                         $loccheck = '';
 3375:                     }
 3376:                 }
 3377:                 if (defined($in{'curr_autharg'})) {
 3378:                     $locarg = $in{'curr_autharg'};
 3379:                 }
 3380:             } else {
 3381:                 $result = &mt('Currently using local (institutional) authentication.');
 3382:                 return $result;
 3383:             }
 3384:         }
 3385:     } else {
 3386:         if ($authnum == 1) {
 3387:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3388:         }
 3389:     }
 3390:     if (!$can_assign{'loc'}) {
 3391:         return;
 3392:     } elsif ($authtype eq '') {
 3393:         if (defined($in{'mode'})) {
 3394:             if ($in{'mode'} eq 'modifycourse') {
 3395:                 if ($authnum == 1) {
 3396:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3397:                 }
 3398:             }
 3399:         }
 3400:     }
 3401:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3402:     if ($authtype eq '') {
 3403:         $authtype = '<input type="radio" name="login" value="loc" '.
 3404:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3405:                     $jscall.'"'.$disabled.' />';
 3406:     }
 3407:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3408:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3409:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3410:                   '<label>'.$authtype,'</label>'.$autharg);
 3411:     return $result;
 3412: }
 3413: 
 3414: sub authform_filesystem {
 3415:     my %in = (
 3416:               formname => 'document.cu',
 3417:               kerb_def_dom => 'MSU.EDU',
 3418:               @_,
 3419:               );
 3420:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3421:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3422:     if ($in{'readonly'}) {
 3423:         $disabled = ' disabled="disabled"';
 3424:     }
 3425:     if (defined($in{'curr_authtype'})) {
 3426:         if ($in{'curr_authtype'} eq 'fsys') {
 3427:             if ($can_assign{'fsys'}) {
 3428:                 $fsyscheck = 'checked="checked" ';
 3429:                 if (defined($in{'mode'})) {
 3430:                     if ($in{'mode'} eq 'modifyuser') {
 3431:                         $fsyscheck = '';
 3432:                     }
 3433:                 }
 3434:             } else {
 3435:                 $result = &mt('Currently Filesystem Authenticated.');
 3436:                 return $result;
 3437:             }
 3438:         }
 3439:     } else {
 3440:         if ($authnum == 1) {
 3441:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3442:         }
 3443:     }
 3444:     if (!$can_assign{'fsys'}) {
 3445:         return;
 3446:     } elsif ($authtype eq '') {
 3447:         if (defined($in{'mode'})) {
 3448:             if ($in{'mode'} eq 'modifycourse') {
 3449:                 if ($authnum == 1) {
 3450:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3451:                 }
 3452:             }
 3453:         }
 3454:     }
 3455:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3456:     if ($authtype eq '') {
 3457:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3458:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3459:                     $jscall.'"'.$disabled.' />';
 3460:     }
 3461:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3462:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3463:     $result = &mt
 3464:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3465:          '<label>'.$authtype,'</label>'.$autharg);
 3466:     return $result;
 3467: }
 3468: 
 3469: sub authform_lti {
 3470:     my %in = (
 3471:               formname => 'document.cu',
 3472:               kerb_def_dom => 'MSU.EDU',
 3473:               @_,
 3474:               );
 3475:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3476:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3477:     if ($in{'readonly'}) {
 3478:         $disabled = ' disabled="disabled"';
 3479:     }
 3480:     if (defined($in{'curr_authtype'})) {
 3481:         if ($in{'curr_authtype'} eq 'lti') {
 3482:             if ($can_assign{'lti'}) {
 3483:                 $lticheck = 'checked="checked" ';
 3484:                 if (defined($in{'mode'})) {
 3485:                     if ($in{'mode'} eq 'modifyuser') {
 3486:                         $lticheck = '';
 3487:                     }
 3488:                 }
 3489:             } else {
 3490:                 $result = &mt('Currently LTI Authenticated.');
 3491:                 return $result;
 3492:             }
 3493:         }
 3494:     } else {
 3495:         if ($authnum == 1) {
 3496:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3497:         }
 3498:     }
 3499:     if (!$can_assign{'lti'}) {
 3500:         return;
 3501:     } elsif ($authtype eq '') {
 3502:         if (defined($in{'mode'})) {
 3503:             if ($in{'mode'} eq 'modifycourse') {
 3504:                 if ($authnum == 1) {
 3505:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3506:                 }
 3507:             }
 3508:         }
 3509:     }
 3510:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3511:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3512:         $authtype = '<input type="radio" name="login" value="lti" '.
 3513:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3514:                     $jscall.'"'.$disabled.' />';
 3515:     }
 3516:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3517:     if ($authtype) {
 3518:         $result = &mt('[_1] LTI Authenticated',
 3519:                       '<label>'.$authtype.'</label>'.$autharg);
 3520:     } else {
 3521:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3522:                   $autharg;
 3523:     }
 3524:     return $result;
 3525: }
 3526: 
 3527: sub get_assignable_auth {
 3528:     my ($dom) = @_;
 3529:     if ($dom eq '') {
 3530:         $dom = $env{'request.role.domain'};
 3531:     }
 3532:     my %can_assign = (
 3533:                           krb4 => 1,
 3534:                           krb5 => 1,
 3535:                           int  => 1,
 3536:                           loc  => 1,
 3537:                           lti  => 1,
 3538:                      );
 3539:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3540:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3541:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3542:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3543:             my $context;
 3544:             if ($env{'request.role'} =~ /^au/) {
 3545:                 $context = 'author';
 3546:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3547:                 $context = 'domain';
 3548:             } elsif ($env{'request.course.id'}) {
 3549:                 $context = 'course';
 3550:             }
 3551:             if ($context) {
 3552:                 if (ref($authhash->{$context}) eq 'HASH') {
 3553:                    %can_assign = %{$authhash->{$context}}; 
 3554:                 }
 3555:             }
 3556:         }
 3557:     }
 3558:     my $authnum = 0;
 3559:     foreach my $key (keys(%can_assign)) {
 3560:         if ($can_assign{$key}) {
 3561:             $authnum ++;
 3562:         }
 3563:     }
 3564:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3565:         $authnum --;
 3566:     }
 3567:     return ($authnum,%can_assign);
 3568: }
 3569: 
 3570: sub check_passwd_rules {
 3571:     my ($domain,$plainpass) = @_;
 3572:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3573:     my ($min,$max,@chars,@brokerule,$warning);
 3574:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3575:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3576:             $min = $passwdconf{'min'};
 3577:         }
 3578:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3579:             $max = $passwdconf{'max'};
 3580:         }
 3581:         @chars = @{$passwdconf{'chars'}};
 3582:     } else {
 3583:         $min = 7;
 3584:     }
 3585:     if (($min) && (length($plainpass) < $min)) {
 3586:         push(@brokerule,'min');
 3587:     }
 3588:     if (($max) && (length($plainpass) > $max)) {
 3589:         push(@brokerule,'max');
 3590:     }
 3591:     if (@chars) {
 3592:         my %rules;
 3593:         map { $rules{$_} = 1; } @chars;
 3594:         if ($rules{'uc'}) {
 3595:             unless ($plainpass =~ /[A-Z]/) {
 3596:                 push(@brokerule,'uc');
 3597:             }
 3598:         }
 3599:         if ($rules{'lc'}) {
 3600:             unless ($plainpass =~ /a-z/) {
 3601:                 push(@brokerule,'lc');
 3602:             }
 3603:         }
 3604:         if ($rules{'num'}) {
 3605:             unless ($plainpass =~ /\d/) {
 3606:                 push(@brokerule,'num');
 3607:             }
 3608:         }
 3609:         if ($rules{'spec'}) {
 3610:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3611:                 push(@brokerule,'spec');
 3612:             }
 3613:         }
 3614:     }
 3615:     if (@brokerule) {
 3616:         my %rulenames = &Apache::lonlocal::texthash(
 3617:             uc   => 'At least one upper case letter',
 3618:             lc   => 'At least one lower case letter',
 3619:             num  => 'At least one number',
 3620:             spec => 'At least one non-alphanumeric',
 3621:         );
 3622:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3623:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3624:         $rulenames{'num'} .= ': 0123456789';
 3625:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3626:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3627:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3628:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3629:         foreach my $rule ('min','max','uc','ls','num','spec') {
 3630:             if (grep(/^$rule$/,@brokerule)) {
 3631:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3632:             }
 3633:         }
 3634:         $warning .= '</ul>';
 3635:     }
 3636:     return $warning;
 3637: }
 3638: 
 3639: ###############################################################
 3640: ##    Get Kerberos Defaults for Domain                 ##
 3641: ###############################################################
 3642: ##
 3643: ## Returns default kerberos version and an associated argument
 3644: ## as listed in file domain.tab. If not listed, provides
 3645: ## appropriate default domain and kerberos version.
 3646: ##
 3647: #-------------------------------------------
 3648: 
 3649: =pod
 3650: 
 3651: =item * &get_kerberos_defaults()
 3652: 
 3653: get_kerberos_defaults($target_domain) returns the default kerberos
 3654: version and domain. If not found, it defaults to version 4 and the 
 3655: domain of the server.
 3656: 
 3657: =over 4
 3658: 
 3659: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3660: 
 3661: =back
 3662: 
 3663: =back
 3664: 
 3665: =cut
 3666: 
 3667: #-------------------------------------------
 3668: sub get_kerberos_defaults {
 3669:     my $domain=shift;
 3670:     my ($krbdef,$krbdefdom);
 3671:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3672:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3673:         $krbdef = $domdefaults{'auth_def'};
 3674:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3675:     } else {
 3676:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3677:         my $krbdefdom=$1;
 3678:         $krbdefdom=~tr/a-z/A-Z/;
 3679:         $krbdef = "krb4";
 3680:     }
 3681:     return ($krbdef,$krbdefdom);
 3682: }
 3683: 
 3684: 
 3685: ###############################################################
 3686: ##                Thesaurus Functions                        ##
 3687: ###############################################################
 3688: 
 3689: =pod
 3690: 
 3691: =head1 Thesaurus Functions
 3692: 
 3693: =over 4
 3694: 
 3695: =item * &initialize_keywords()
 3696: 
 3697: Initializes the package variable %Keywords if it is empty.  Uses the
 3698: package variable $thesaurus_db_file.
 3699: 
 3700: =cut
 3701: 
 3702: ###################################################
 3703: 
 3704: sub initialize_keywords {
 3705:     return 1 if (scalar keys(%Keywords));
 3706:     # If we are here, %Keywords is empty, so fill it up
 3707:     #   Make sure the file we need exists...
 3708:     if (! -e $thesaurus_db_file) {
 3709:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3710:                                  " failed because it does not exist");
 3711:         return 0;
 3712:     }
 3713:     #   Set up the hash as a database
 3714:     my %thesaurus_db;
 3715:     if (! tie(%thesaurus_db,'GDBM_File',
 3716:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3717:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3718:                                  $thesaurus_db_file);
 3719:         return 0;
 3720:     } 
 3721:     #  Get the average number of appearances of a word.
 3722:     my $avecount = $thesaurus_db{'average.count'};
 3723:     #  Put keywords (those that appear > average) into %Keywords
 3724:     while (my ($word,$data)=each (%thesaurus_db)) {
 3725:         my ($count,undef) = split /:/,$data;
 3726:         $Keywords{$word}++ if ($count > $avecount);
 3727:     }
 3728:     untie %thesaurus_db;
 3729:     # Remove special values from %Keywords.
 3730:     foreach my $value ('total.count','average.count') {
 3731:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3732:   }
 3733:     return 1;
 3734: }
 3735: 
 3736: ###################################################
 3737: 
 3738: =pod
 3739: 
 3740: =item * &keyword($word)
 3741: 
 3742: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3743: than the average number of times in the thesaurus database.  Calls 
 3744: &initialize_keywords
 3745: 
 3746: =cut
 3747: 
 3748: ###################################################
 3749: 
 3750: sub keyword {
 3751:     return if (!&initialize_keywords());
 3752:     my $word=lc(shift());
 3753:     $word=~s/\W//g;
 3754:     return exists($Keywords{$word});
 3755: }
 3756: 
 3757: ###############################################################
 3758: 
 3759: =pod 
 3760: 
 3761: =item * &get_related_words()
 3762: 
 3763: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3764: an array of words.  If the keyword is not in the thesaurus, an empty array
 3765: will be returned.  The order of the words returned is determined by the
 3766: database which holds them.
 3767: 
 3768: Uses global $thesaurus_db_file.
 3769: 
 3770: 
 3771: =cut
 3772: 
 3773: ###############################################################
 3774: sub get_related_words {
 3775:     my $keyword = shift;
 3776:     my %thesaurus_db;
 3777:     if (! -e $thesaurus_db_file) {
 3778:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3779:                                  "failed because the file does not exist");
 3780:         return ();
 3781:     }
 3782:     if (! tie(%thesaurus_db,'GDBM_File',
 3783:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3784:         return ();
 3785:     } 
 3786:     my @Words=();
 3787:     my $count=0;
 3788:     if (exists($thesaurus_db{$keyword})) {
 3789: 	# The first element is the number of times
 3790: 	# the word appears.  We do not need it now.
 3791: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3792: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3793: 	my $threshold=$mostfrequentcount/10;
 3794:         foreach my $possibleword (@RelatedWords) {
 3795:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3796:             if ($wordcount>$threshold) {
 3797: 		push(@Words,$word);
 3798:                 $count++;
 3799:                 if ($count>10) { last; }
 3800: 	    }
 3801:         }
 3802:     }
 3803:     untie %thesaurus_db;
 3804:     return @Words;
 3805: }
 3806: ###############################################################
 3807: #
 3808: #  Spell checking
 3809: #
 3810: 
 3811: =pod
 3812: 
 3813: =back
 3814: 
 3815: =head1 Spell checking
 3816: 
 3817: =over 4
 3818: 
 3819: =item * &check_spelling($wordlist $language)
 3820: 
 3821: Takes a string containing words and feeds it to an external
 3822: spellcheck program via a pipeline. Returns a string containing
 3823: them mis-spelled words.
 3824: 
 3825: Parameters:
 3826: 
 3827: =over 4
 3828: 
 3829: =item - $wordlist
 3830: 
 3831: String that will be fed into the spellcheck program.
 3832: 
 3833: =item - $language
 3834: 
 3835: Language string that specifies the language for which the spell
 3836: check will be performed.
 3837: 
 3838: =back
 3839: 
 3840: =back
 3841: 
 3842: Note: This sub assumes that aspell is installed.
 3843: 
 3844: 
 3845: =cut
 3846: 
 3847: 
 3848: sub check_spelling {
 3849:     my ($wordlist, $language) = @_;
 3850:     my @misspellings;
 3851:     
 3852:     # Generate the speller and set the langauge.
 3853:     # if explicitly selected:
 3854: 
 3855:     my $speller = Text::Aspell->new;
 3856:     if ($language) {
 3857: 	$speller->set_option('lang', $language);
 3858:     }
 3859: 
 3860:     # Turn the word list into an array of words by splittingon whitespace
 3861: 
 3862:     my @words = split(/\s+/, $wordlist);
 3863: 
 3864:     foreach my $word (@words) {
 3865: 	if(! $speller->check($word)) {
 3866: 	    push(@misspellings, $word);
 3867: 	}
 3868:     }
 3869:     return join(' ', @misspellings);
 3870:     
 3871: }
 3872: 
 3873: # -------------------------------------------------------------- Plaintext name
 3874: =pod
 3875: 
 3876: =head1 User Name Functions
 3877: 
 3878: =over 4
 3879: 
 3880: =item * &plainname($uname,$udom,$first)
 3881: 
 3882: Takes a users logon name and returns it as a string in
 3883: "first middle last generation" form 
 3884: if $first is set to 'lastname' then it returns it as
 3885: 'lastname generation, firstname middlename' if their is a lastname
 3886: 
 3887: =cut
 3888: 
 3889: 
 3890: ###############################################################
 3891: sub plainname {
 3892:     my ($uname,$udom,$first)=@_;
 3893:     return if (!defined($uname) || !defined($udom));
 3894:     my %names=&getnames($uname,$udom);
 3895:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3896: 					  $names{'middlename'},
 3897: 					  $names{'lastname'},
 3898: 					  $names{'generation'},$first);
 3899:     $name=~s/^\s+//;
 3900:     $name=~s/\s+$//;
 3901:     $name=~s/\s+/ /g;
 3902:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3903:     return $name;
 3904: }
 3905: 
 3906: # -------------------------------------------------------------------- Nickname
 3907: =pod
 3908: 
 3909: =item * &nickname($uname,$udom)
 3910: 
 3911: Gets a users name and returns it as a string as
 3912: 
 3913: "&quot;nickname&quot;"
 3914: 
 3915: if the user has a nickname or
 3916: 
 3917: "first middle last generation"
 3918: 
 3919: if the user does not
 3920: 
 3921: =cut
 3922: 
 3923: sub nickname {
 3924:     my ($uname,$udom)=@_;
 3925:     return if (!defined($uname) || !defined($udom));
 3926:     my %names=&getnames($uname,$udom);
 3927:     my $name=$names{'nickname'};
 3928:     if ($name) {
 3929:        $name='&quot;'.$name.'&quot;'; 
 3930:     } else {
 3931:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3932: 	     $names{'lastname'}.' '.$names{'generation'};
 3933:        $name=~s/\s+$//;
 3934:        $name=~s/\s+/ /g;
 3935:     }
 3936:     return $name;
 3937: }
 3938: 
 3939: sub getnames {
 3940:     my ($uname,$udom)=@_;
 3941:     return if (!defined($uname) || !defined($udom));
 3942:     if ($udom eq 'public' && $uname eq 'public') {
 3943: 	return ('lastname' => &mt('Public'));
 3944:     }
 3945:     my $id=$uname.':'.$udom;
 3946:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3947:     if ($cached) {
 3948: 	return %{$names};
 3949:     } else {
 3950: 	my %loadnames=&Apache::lonnet::get('environment',
 3951:                     ['firstname','middlename','lastname','generation','nickname'],
 3952: 					 $udom,$uname);
 3953: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3954: 	return %loadnames;
 3955:     }
 3956: }
 3957: 
 3958: # -------------------------------------------------------------------- getemails
 3959: 
 3960: =pod
 3961: 
 3962: =item * &getemails($uname,$udom)
 3963: 
 3964: Gets a user's email information and returns it as a hash with keys:
 3965: notification, critnotification, permanentemail
 3966: 
 3967: For notification and critnotification, values are comma-separated lists 
 3968: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3969:  
 3970: 
 3971: =cut
 3972: 
 3973: 
 3974: sub getemails {
 3975:     my ($uname,$udom)=@_;
 3976:     if ($udom eq 'public' && $uname eq 'public') {
 3977: 	return;
 3978:     }
 3979:     if (!$udom) { $udom=$env{'user.domain'}; }
 3980:     if (!$uname) { $uname=$env{'user.name'}; }
 3981:     my $id=$uname.':'.$udom;
 3982:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3983:     if ($cached) {
 3984: 	return %{$names};
 3985:     } else {
 3986: 	my %loadnames=&Apache::lonnet::get('environment',
 3987:                     			   ['notification','critnotification',
 3988: 					    'permanentemail'],
 3989: 					   $udom,$uname);
 3990: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3991: 	return %loadnames;
 3992:     }
 3993: }
 3994: 
 3995: sub flush_email_cache {
 3996:     my ($uname,$udom)=@_;
 3997:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3998:     if (!$uname) { $uname=$env{'user.name'};   }
 3999:     return if ($udom eq 'public' && $uname eq 'public');
 4000:     my $id=$uname.':'.$udom;
 4001:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4002: }
 4003: 
 4004: # -------------------------------------------------------------------- getlangs
 4005: 
 4006: =pod
 4007: 
 4008: =item * &getlangs($uname,$udom)
 4009: 
 4010: Gets a user's language preference and returns it as a hash with key:
 4011: language.
 4012: 
 4013: =cut
 4014: 
 4015: 
 4016: sub getlangs {
 4017:     my ($uname,$udom) = @_;
 4018:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4019:     if (!$uname) { $uname=$env{'user.name'};   }
 4020:     my $id=$uname.':'.$udom;
 4021:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4022:     if ($cached) {
 4023:         return %{$langs};
 4024:     } else {
 4025:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4026:                                            $udom,$uname);
 4027:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4028:         return %loadlangs;
 4029:     }
 4030: }
 4031: 
 4032: sub flush_langs_cache {
 4033:     my ($uname,$udom)=@_;
 4034:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4035:     if (!$uname) { $uname=$env{'user.name'};   }
 4036:     return if ($udom eq 'public' && $uname eq 'public');
 4037:     my $id=$uname.':'.$udom;
 4038:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4039: }
 4040: 
 4041: # ------------------------------------------------------------------ Screenname
 4042: 
 4043: =pod
 4044: 
 4045: =item * &screenname($uname,$udom)
 4046: 
 4047: Gets a users screenname and returns it as a string
 4048: 
 4049: =cut
 4050: 
 4051: sub screenname {
 4052:     my ($uname,$udom)=@_;
 4053:     if ($uname eq $env{'user.name'} &&
 4054: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4055:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4056:     return $names{'screenname'};
 4057: }
 4058: 
 4059: 
 4060: # ------------------------------------------------------------- Confirm Wrapper
 4061: =pod
 4062: 
 4063: =item * &confirmwrapper($message)
 4064: 
 4065: Wrap messages about completion of operation in box
 4066: 
 4067: =cut
 4068: 
 4069: sub confirmwrapper {
 4070:     my ($message)=@_;
 4071:     if ($message) {
 4072:         return "\n".'<div class="LC_confirm_box">'."\n"
 4073:                .$message."\n"
 4074:                .'</div>'."\n";
 4075:     } else {
 4076:         return $message;
 4077:     }
 4078: }
 4079: 
 4080: # ------------------------------------------------------------- Message Wrapper
 4081: 
 4082: sub messagewrapper {
 4083:     my ($link,$username,$domain,$subject,$text)=@_;
 4084:     return 
 4085:         '<a href="/adm/email?compose=individual&amp;'.
 4086:         'recname='.$username.'&amp;recdom='.$domain.
 4087: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4088:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4089: }
 4090: 
 4091: # --------------------------------------------------------------- Notes Wrapper
 4092: 
 4093: sub noteswrapper {
 4094:     my ($link,$un,$do)=@_;
 4095:     return 
 4096: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4097: }
 4098: 
 4099: # ------------------------------------------------------------- Aboutme Wrapper
 4100: 
 4101: sub aboutmewrapper {
 4102:     my ($link,$username,$domain,$target,$class)=@_;
 4103:     if (!defined($username)  && !defined($domain)) {
 4104:         return;
 4105:     }
 4106:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4107: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4108: }
 4109: 
 4110: # ------------------------------------------------------------ Syllabus Wrapper
 4111: 
 4112: sub syllabuswrapper {
 4113:     my ($linktext,$coursedir,$domain)=@_;
 4114:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4115: }
 4116: 
 4117: # -----------------------------------------------------------------------------
 4118: 
 4119: sub track_student_link {
 4120:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4121:     my $link ="/adm/trackstudent?";
 4122:     my $title = 'View recent activity';
 4123:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4124:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4125:         $link .= "selected_student=$sname:$sdom";
 4126:         $title .= ' of this student';
 4127:     } 
 4128:     if (defined($target) && $target !~ /^\s*$/) {
 4129:         $target = qq{target="$target"};
 4130:     } else {
 4131:         $target = '';
 4132:     }
 4133:     if ($start) { $link.='&amp;start='.$start; }
 4134:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4135:     $title = &mt($title);
 4136:     $linktext = &mt($linktext);
 4137:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4138: 	&help_open_topic('View_recent_activity');
 4139: }
 4140: 
 4141: sub slot_reservations_link {
 4142:     my ($linktext,$sname,$sdom,$target) = @_;
 4143:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4144:     my $title = 'View slot reservation history';
 4145:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4146:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4147:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4148:         $title .= ' of this student';
 4149:     }
 4150:     if (defined($target) && $target !~ /^\s*$/) {
 4151:         $target = qq{target="$target"};
 4152:     } else {
 4153:         $target = '';
 4154:     }
 4155:     $title = &mt($title);
 4156:     $linktext = &mt($linktext);
 4157:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4158: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4159: 
 4160: }
 4161: 
 4162: # ===================================================== Display a student photo
 4163: 
 4164: 
 4165: sub student_image_tag {
 4166:     my ($domain,$user)=@_;
 4167:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4168:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4169: 	return '<img src="'.$imgsrc.'" align="right" />';
 4170:     } else {
 4171: 	return '';
 4172:     }
 4173: }
 4174: 
 4175: =pod
 4176: 
 4177: =back
 4178: 
 4179: =head1 Access .tab File Data
 4180: 
 4181: =over 4
 4182: 
 4183: =item * &languageids() 
 4184: 
 4185: returns list of all language ids
 4186: 
 4187: =cut
 4188: 
 4189: sub languageids {
 4190:     return sort(keys(%language));
 4191: }
 4192: 
 4193: =pod
 4194: 
 4195: =item * &languagedescription() 
 4196: 
 4197: returns description of a specified language id
 4198: 
 4199: =cut
 4200: 
 4201: sub languagedescription {
 4202:     my $code=shift;
 4203:     return  ($supported_language{$code}?'* ':'').
 4204:             $language{$code}.
 4205: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4206: }
 4207: 
 4208: =pod
 4209: 
 4210: =item * &plainlanguagedescription
 4211: 
 4212: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4213: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4214: 
 4215: =cut
 4216: 
 4217: sub plainlanguagedescription {
 4218:     my $code=shift;
 4219:     return $language{$code};
 4220: }
 4221: 
 4222: =pod
 4223: 
 4224: =item * &supportedlanguagecode
 4225: 
 4226: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4227: code.
 4228: 
 4229: =cut
 4230: 
 4231: sub supportedlanguagecode {
 4232:     my $code=shift;
 4233:     return $supported_language{$code};
 4234: }
 4235: 
 4236: =pod
 4237: 
 4238: =item * &latexlanguage()
 4239: 
 4240: Given a language key code returns the correspondnig language to use
 4241: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4242: is no supported hyphenation for the language code.
 4243: 
 4244: =cut
 4245: 
 4246: sub latexlanguage {
 4247:     my $code = shift;
 4248:     return $latex_language{$code};
 4249: }
 4250: 
 4251: =pod
 4252: 
 4253: =item * &latexhyphenation()
 4254: 
 4255: Same as above but what's supplied is the language as it might be stored
 4256: in the metadata.
 4257: 
 4258: =cut
 4259: 
 4260: sub latexhyphenation {
 4261:     my $key = shift;
 4262:     return $latex_language_bykey{$key};
 4263: }
 4264: 
 4265: =pod
 4266: 
 4267: =item * &copyrightids() 
 4268: 
 4269: returns list of all copyrights
 4270: 
 4271: =cut
 4272: 
 4273: sub copyrightids {
 4274:     return sort(keys(%cprtag));
 4275: }
 4276: 
 4277: =pod
 4278: 
 4279: =item * &copyrightdescription() 
 4280: 
 4281: returns description of a specified copyright id
 4282: 
 4283: =cut
 4284: 
 4285: sub copyrightdescription {
 4286:     return &mt($cprtag{shift(@_)});
 4287: }
 4288: 
 4289: =pod
 4290: 
 4291: =item * &source_copyrightids() 
 4292: 
 4293: returns list of all source copyrights
 4294: 
 4295: =cut
 4296: 
 4297: sub source_copyrightids {
 4298:     return sort(keys(%scprtag));
 4299: }
 4300: 
 4301: =pod
 4302: 
 4303: =item * &source_copyrightdescription() 
 4304: 
 4305: returns description of a specified source copyright id
 4306: 
 4307: =cut
 4308: 
 4309: sub source_copyrightdescription {
 4310:     return &mt($scprtag{shift(@_)});
 4311: }
 4312: 
 4313: =pod
 4314: 
 4315: =item * &filecategories() 
 4316: 
 4317: returns list of all file categories
 4318: 
 4319: =cut
 4320: 
 4321: sub filecategories {
 4322:     return sort(keys(%category_extensions));
 4323: }
 4324: 
 4325: =pod
 4326: 
 4327: =item * &filecategorytypes() 
 4328: 
 4329: returns list of file types belonging to a given file
 4330: category
 4331: 
 4332: =cut
 4333: 
 4334: sub filecategorytypes {
 4335:     my ($cat) = @_;
 4336:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4337:         return @{$category_extensions{lc($cat)}};
 4338:     } else {
 4339:         return ();
 4340:     }
 4341: }
 4342: 
 4343: =pod
 4344: 
 4345: =item * &fileembstyle() 
 4346: 
 4347: returns embedding style for a specified file type
 4348: 
 4349: =cut
 4350: 
 4351: sub fileembstyle {
 4352:     return $fe{lc(shift(@_))};
 4353: }
 4354: 
 4355: sub filemimetype {
 4356:     return $fm{lc(shift(@_))};
 4357: }
 4358: 
 4359: 
 4360: sub filecategoryselect {
 4361:     my ($name,$value)=@_;
 4362:     return &select_form($value,$name,
 4363:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4364: }
 4365: 
 4366: =pod
 4367: 
 4368: =item * &filedescription() 
 4369: 
 4370: returns description for a specified file type
 4371: 
 4372: =cut
 4373: 
 4374: sub filedescription {
 4375:     my $file_description = $fd{lc(shift())};
 4376:     $file_description =~ s:([\[\]]):~$1:g;
 4377:     return &mt($file_description);
 4378: }
 4379: 
 4380: =pod
 4381: 
 4382: =item * &filedescriptionex() 
 4383: 
 4384: returns description for a specified file type with
 4385: extra formatting
 4386: 
 4387: =cut
 4388: 
 4389: sub filedescriptionex {
 4390:     my $ex=shift;
 4391:     my $file_description = $fd{lc($ex)};
 4392:     $file_description =~ s:([\[\]]):~$1:g;
 4393:     return '.'.$ex.' '.&mt($file_description);
 4394: }
 4395: 
 4396: # End of .tab access
 4397: =pod
 4398: 
 4399: =back
 4400: 
 4401: =cut
 4402: 
 4403: # ------------------------------------------------------------------ File Types
 4404: sub fileextensions {
 4405:     return sort(keys(%fe));
 4406: }
 4407: 
 4408: # ----------------------------------------------------------- Display Languages
 4409: # returns a hash with all desired display languages
 4410: #
 4411: 
 4412: sub display_languages {
 4413:     my %languages=();
 4414:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4415: 	$languages{$lang}=1;
 4416:     }
 4417:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4418:     if ($env{'form.displaylanguage'}) {
 4419: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4420: 	    $languages{$lang}=1;
 4421:         }
 4422:     }
 4423:     return %languages;
 4424: }
 4425: 
 4426: sub languages {
 4427:     my ($possible_langs) = @_;
 4428:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4429:     if (!ref($possible_langs)) {
 4430: 	if( wantarray ) {
 4431: 	    return @preferred_langs;
 4432: 	} else {
 4433: 	    return $preferred_langs[0];
 4434: 	}
 4435:     }
 4436:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4437:     my @preferred_possibilities;
 4438:     foreach my $preferred_lang (@preferred_langs) {
 4439: 	if (exists($possibilities{$preferred_lang})) {
 4440: 	    push(@preferred_possibilities, $preferred_lang);
 4441: 	}
 4442:     }
 4443:     if( wantarray ) {
 4444: 	return @preferred_possibilities;
 4445:     }
 4446:     return $preferred_possibilities[0];
 4447: }
 4448: 
 4449: sub user_lang {
 4450:     my ($touname,$toudom,$fromcid) = @_;
 4451:     my @userlangs;
 4452:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4453:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4454:                     $env{'course.'.$fromcid.'.languages'}));
 4455:     } else {
 4456:         my %langhash = &getlangs($touname,$toudom);
 4457:         if ($langhash{'languages'} ne '') {
 4458:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4459:         } else {
 4460:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4461:             if ($domdefs{'lang_def'} ne '') {
 4462:                 @userlangs = ($domdefs{'lang_def'});
 4463:             }
 4464:         }
 4465:     }
 4466:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4467:     my $user_lh = Apache::localize->get_handle(@languages);
 4468:     return $user_lh;
 4469: }
 4470: 
 4471: 
 4472: ###############################################################
 4473: ##               Student Answer Attempts                     ##
 4474: ###############################################################
 4475: 
 4476: =pod
 4477: 
 4478: =head1 Alternate Problem Views
 4479: 
 4480: =over 4
 4481: 
 4482: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4483:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4484: 
 4485: Return string with previous attempt on problem. Arguments:
 4486: 
 4487: =over 4
 4488: 
 4489: =item * $symb: Problem, including path
 4490: 
 4491: =item * $username: username of the desired student
 4492: 
 4493: =item * $domain: domain of the desired student
 4494: 
 4495: =item * $course: Course ID
 4496: 
 4497: =item * $getattempt: Leave blank for all attempts, otherwise put
 4498:     something
 4499: 
 4500: =item * $regexp: if string matches this regexp, the string will be
 4501:     sent to $gradesub
 4502: 
 4503: =item * $gradesub: routine that processes the string if it matches $regexp
 4504: 
 4505: =item * $usec: section of the desired student
 4506: 
 4507: =item * $identifier: counter for student (multiple students one problem) or 
 4508:     problem (one student; whole sequence).
 4509: 
 4510: =back
 4511: 
 4512: The output string is a table containing all desired attempts, if any.
 4513: 
 4514: =cut
 4515: 
 4516: sub get_previous_attempt {
 4517:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4518:   my $prevattempts='';
 4519:   no strict 'refs';
 4520:   if ($symb) {
 4521:     my (%returnhash)=
 4522:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4523:     if ($returnhash{'version'}) {
 4524:       my %lasthash=();
 4525:       my $version;
 4526:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4527:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4528:             if ($key =~ /\.rawrndseed$/) {
 4529:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4530:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4531:             } else {
 4532:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4533:             }
 4534:         }
 4535:       }
 4536:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4537:       $prevattempts.='<th>'.&mt('History').'</th>';
 4538:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4539:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4540:       foreach my $key (sort(keys(%lasthash))) {
 4541: 	my ($ign,@parts) = split(/\./,$key);
 4542: 	if ($#parts > 0) {
 4543: 	  my $data=$parts[-1];
 4544:           next if ($data eq 'foilorder');
 4545: 	  pop(@parts);
 4546:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4547:           if ($data eq 'type') {
 4548:               unless ($showsurv) {
 4549:                   my $id = join(',',@parts);
 4550:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4551:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4552:                       $lasthidden{$ign.'.'.$id} = 1;
 4553:                   }
 4554:               }
 4555:               if ($identifier ne '') {
 4556:                   my $id = join(',',@parts);
 4557:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4558:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4559:                       $hidestatus{$ign.'.'.$id} = 1;
 4560:                   }
 4561:               }
 4562:           } elsif ($data eq 'regrader') {
 4563:               if (($identifier ne '') && (@parts)) {
 4564:                   my $id = join(',',@parts);
 4565:                   $regraded{$ign.'.'.$id} = 1;
 4566:               }
 4567:           } 
 4568: 	} else {
 4569: 	  if ($#parts == 0) {
 4570: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4571: 	  } else {
 4572: 	    $prevattempts.='<th>'.$ign.'</th>';
 4573: 	  }
 4574: 	}
 4575:       }
 4576:       $prevattempts.=&end_data_table_header_row();
 4577:       if ($getattempt eq '') {
 4578:         my (%solved,%resets,%probstatus);
 4579:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4580:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4581:                 foreach my $id (keys(%regraded)) {
 4582:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4583:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4584:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4585:                         push(@{$resets{$id}},$version);
 4586:                     }
 4587:                 }
 4588:             }
 4589:         }
 4590: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4591:             my (@hidden,@unsolved);
 4592:             if (%typeparts) {
 4593:                 foreach my $id (keys(%typeparts)) {
 4594:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4595:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4596:                         push(@hidden,$id);
 4597:                     } elsif ($identifier ne '') {
 4598:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4599:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4600:                                 ($hidestatus{$id})) {
 4601:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4602:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4603:                                 push(@{$solved{$id}},$version);
 4604:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4605:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4606:                                 my $skip;
 4607:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4608:                                     foreach my $reset (@{$resets{$id}}) {
 4609:                                         if ($reset > $solved{$id}[-1]) {
 4610:                                             $skip=1;
 4611:                                             last;
 4612:                                         }
 4613:                                     }
 4614:                                 }
 4615:                                 unless ($skip) {
 4616:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4617:                                     push(@unsolved,$partslist);
 4618:                                 }
 4619:                             }
 4620:                         }
 4621:                     }
 4622:                 }
 4623:             }
 4624:             $prevattempts.=&start_data_table_row().
 4625:                            '<td>'.&mt('Transaction [_1]',$version);
 4626:             if (@unsolved) {
 4627:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4628:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4629:                                  &mt('Hide').'</label></span>';
 4630:             }
 4631:             $prevattempts .= '</td>';
 4632:             if (@hidden) {
 4633:                 foreach my $key (sort(keys(%lasthash))) {
 4634:                     next if ($key =~ /\.foilorder$/);
 4635:                     my $hide;
 4636:                     foreach my $id (@hidden) {
 4637:                         if ($key =~ /^\Q$id\E/) {
 4638:                             $hide = 1;
 4639:                             last;
 4640:                         }
 4641:                     }
 4642:                     if ($hide) {
 4643:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4644:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4645:                             my $value = &format_previous_attempt_value($key,
 4646:                                              $returnhash{$version.':'.$key});
 4647:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4648:                         } else {
 4649:                             $prevattempts.='<td>&nbsp;</td>';
 4650:                         }
 4651:                     } else {
 4652:                         if ($key =~ /\./) {
 4653:                             my $value = $returnhash{$version.':'.$key};
 4654:                             if ($key =~ /\.rndseed$/) {
 4655:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4656:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4657:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4658:                                 }
 4659:                             }
 4660:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4661:                                            '&nbsp;</td>';
 4662:                         } else {
 4663:                             $prevattempts.='<td>&nbsp;</td>';
 4664:                         }
 4665:                     }
 4666:                 }
 4667:             } else {
 4668: 	        foreach my $key (sort(keys(%lasthash))) {
 4669:                     next if ($key =~ /\.foilorder$/);
 4670:                     my $value = $returnhash{$version.':'.$key};
 4671:                     if ($key =~ /\.rndseed$/) {
 4672:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4673:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4674:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4675:                         }
 4676:                     }
 4677:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4678:                                    '&nbsp;</td>';
 4679: 	        }
 4680:             }
 4681: 	    $prevattempts.=&end_data_table_row();
 4682: 	 }
 4683:       }
 4684:       my @currhidden = keys(%lasthidden);
 4685:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4686:       foreach my $key (sort(keys(%lasthash))) {
 4687:           next if ($key =~ /\.foilorder$/);
 4688:           if (%typeparts) {
 4689:               my $hidden;
 4690:               foreach my $id (@currhidden) {
 4691:                   if ($key =~ /^\Q$id\E/) {
 4692:                       $hidden = 1;
 4693:                       last;
 4694:                   }
 4695:               }
 4696:               if ($hidden) {
 4697:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4698:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4699:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4700:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4701:                           $value = &$gradesub($value);
 4702:                       }
 4703:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4704:                   } else {
 4705:                       $prevattempts.='<td>&nbsp;</td>';
 4706:                   }
 4707:               } else {
 4708:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4709:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4710:                       $value = &$gradesub($value);
 4711:                   }
 4712:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4713:               }
 4714:           } else {
 4715: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4716: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4717:                   $value = &$gradesub($value);
 4718:               }
 4719: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4720:           }
 4721:       }
 4722:       $prevattempts.= &end_data_table_row().&end_data_table();
 4723:     } else {
 4724:       my $msg;
 4725:       if ($symb =~ /ext\.tool$/) {
 4726:           $msg = &mt('No grade passed back.');
 4727:       } else {
 4728:           $msg = &mt('Nothing submitted - no attempts.');
 4729:       }
 4730:       $prevattempts=
 4731: 	  &start_data_table().&start_data_table_row().
 4732: 	  '<td>'.$msg.'</td>'.
 4733: 	  &end_data_table_row().&end_data_table();
 4734:     }
 4735:   } else {
 4736:     $prevattempts=
 4737: 	  &start_data_table().&start_data_table_row().
 4738: 	  '<td>'.&mt('No data.').'</td>'.
 4739: 	  &end_data_table_row().&end_data_table();
 4740:   }
 4741: }
 4742: 
 4743: sub format_previous_attempt_value {
 4744:     my ($key,$value) = @_;
 4745:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4746:         $value = &Apache::lonlocal::locallocaltime($value);
 4747:     } elsif (ref($value) eq 'ARRAY') {
 4748:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4749:     } elsif ($key =~ /answerstring$/) {
 4750:         my %answers = &Apache::lonnet::str2hash($value);
 4751:         my @answer = %answers;
 4752:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4753:         my @anskeys = sort(keys(%answers));
 4754:         if (@anskeys == 1) {
 4755:             my $answer = $answers{$anskeys[0]};
 4756:             if ($answer =~ m{\0}) {
 4757:                 $answer =~ s{\0}{,}g;
 4758:             }
 4759:             my $tag_internal_answer_name = 'INTERNAL';
 4760:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4761:                 $value = $answer; 
 4762:             } else {
 4763:                 $value = $anskeys[0].'='.$answer;
 4764:             }
 4765:         } else {
 4766:             foreach my $ans (@anskeys) {
 4767:                 my $answer = $answers{$ans};
 4768:                 if ($answer =~ m{\0}) {
 4769:                     $answer =~ s{\0}{,}g;
 4770:                 }
 4771:                 $value .=  $ans.'='.$answer.'<br />';;
 4772:             } 
 4773:         }
 4774:     } else {
 4775:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4776:     }
 4777:     return $value;
 4778: }
 4779: 
 4780: 
 4781: sub relative_to_absolute {
 4782:     my ($url,$output)=@_;
 4783:     my $parser=HTML::TokeParser->new(\$output);
 4784:     my $token;
 4785:     my $thisdir=$url;
 4786:     my @rlinks=();
 4787:     while ($token=$parser->get_token) {
 4788: 	if ($token->[0] eq 'S') {
 4789: 	    if ($token->[1] eq 'a') {
 4790: 		if ($token->[2]->{'href'}) {
 4791: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4792: 		}
 4793: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4794: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4795: 	    } elsif ($token->[1] eq 'base') {
 4796: 		$thisdir=$token->[2]->{'href'};
 4797: 	    }
 4798: 	}
 4799:     }
 4800:     $thisdir=~s-/[^/]*$--;
 4801:     foreach my $link (@rlinks) {
 4802: 	unless (($link=~/^https?\:\/\//i) ||
 4803: 		($link=~/^\//) ||
 4804: 		($link=~/^javascript:/i) ||
 4805: 		($link=~/^mailto:/i) ||
 4806: 		($link=~/^\#/)) {
 4807: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4808: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4809: 	}
 4810:     }
 4811: # -------------------------------------------------- Deal with Applet codebases
 4812:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4813:     return $output;
 4814: }
 4815: 
 4816: =pod
 4817: 
 4818: =item * &get_student_view()
 4819: 
 4820: show a snapshot of what student was looking at
 4821: 
 4822: =cut
 4823: 
 4824: sub get_student_view {
 4825:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4826:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4827:   my (%form);
 4828:   my @elements=('symb','courseid','domain','username');
 4829:   foreach my $element (@elements) {
 4830:       $form{'grade_'.$element}=eval '$'.$element #'
 4831:   }
 4832:   if (defined($moreenv)) {
 4833:       %form=(%form,%{$moreenv});
 4834:   }
 4835:   if (defined($target)) { $form{'grade_target'} = $target; }
 4836:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4837:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 4838:       $feedurl =~ s{^/adm/wrapper}{};
 4839:   }
 4840:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4841:   $userview=~s/\<body[^\>]*\>//gi;
 4842:   $userview=~s/\<\/body\>//gi;
 4843:   $userview=~s/\<html\>//gi;
 4844:   $userview=~s/\<\/html\>//gi;
 4845:   $userview=~s/\<head\>//gi;
 4846:   $userview=~s/\<\/head\>//gi;
 4847:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4848:   $userview=&relative_to_absolute($feedurl,$userview);
 4849:   if (wantarray) {
 4850:      return ($userview,$response);
 4851:   } else {
 4852:      return $userview;
 4853:   }
 4854: }
 4855: 
 4856: sub get_student_view_with_retries {
 4857:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4858: 
 4859:     my $ok = 0;                 # True if we got a good response.
 4860:     my $content;
 4861:     my $response;
 4862: 
 4863:     # Try to get the student_view done. within the retries count:
 4864:     
 4865:     do {
 4866:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4867:          $ok      = $response->is_success;
 4868:          if (!$ok) {
 4869:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4870:          }
 4871:          $retries--;
 4872:     } while (!$ok && ($retries > 0));
 4873:     
 4874:     if (!$ok) {
 4875:        $content = '';          # On error return an empty content.
 4876:     }
 4877:     if (wantarray) {
 4878:        return ($content, $response);
 4879:     } else {
 4880:        return $content;
 4881:     }
 4882: }
 4883: 
 4884: =pod
 4885: 
 4886: =item * &get_student_answers() 
 4887: 
 4888: show a snapshot of how student was answering problem
 4889: 
 4890: =cut
 4891: 
 4892: sub get_student_answers {
 4893:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4894:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4895:   my (%moreenv);
 4896:   my @elements=('symb','courseid','domain','username');
 4897:   foreach my $element (@elements) {
 4898:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4899:   }
 4900:   $moreenv{'grade_target'}='answer';
 4901:   %moreenv=(%form,%moreenv);
 4902:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4903:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4904:   return $userview;
 4905: }
 4906: 
 4907: =pod
 4908: 
 4909: =item * &submlink()
 4910: 
 4911: Inputs: $text $uname $udom $symb $target
 4912: 
 4913: Returns: A link to grades.pm such as to see the SUBM view of a student
 4914: 
 4915: =cut
 4916: 
 4917: ###############################################
 4918: sub submlink {
 4919:     my ($text,$uname,$udom,$symb,$target)=@_;
 4920:     if (!($uname && $udom)) {
 4921: 	(my $cursymb, my $courseid,$udom,$uname)=
 4922: 	    &Apache::lonnet::whichuser($symb);
 4923: 	if (!$symb) { $symb=$cursymb; }
 4924:     }
 4925:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4926:     $symb=&escape($symb);
 4927:     if ($target) { $target=" target=\"$target\""; }
 4928:     return
 4929:         '<a href="/adm/grades?command=submission'.
 4930:         '&amp;symb='.$symb.
 4931:         '&amp;student='.$uname.
 4932:         '&amp;userdom='.$udom.'"'.
 4933:         $target.'>'.$text.'</a>';
 4934: }
 4935: ##############################################
 4936: 
 4937: =pod
 4938: 
 4939: =item * &pgrdlink()
 4940: 
 4941: Inputs: $text $uname $udom $symb $target
 4942: 
 4943: Returns: A link to grades.pm such as to see the PGRD view of a student
 4944: 
 4945: =cut
 4946: 
 4947: ###############################################
 4948: sub pgrdlink {
 4949:     my $link=&submlink(@_);
 4950:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4951:     return $link;
 4952: }
 4953: ##############################################
 4954: 
 4955: =pod
 4956: 
 4957: =item * &pprmlink()
 4958: 
 4959: Inputs: $text $uname $udom $symb $target
 4960: 
 4961: Returns: A link to parmset.pm such as to see the PPRM view of a
 4962: student and a specific resource
 4963: 
 4964: =cut
 4965: 
 4966: ###############################################
 4967: sub pprmlink {
 4968:     my ($text,$uname,$udom,$symb,$target)=@_;
 4969:     if (!($uname && $udom)) {
 4970: 	(my $cursymb, my $courseid,$udom,$uname)=
 4971: 	    &Apache::lonnet::whichuser($symb);
 4972: 	if (!$symb) { $symb=$cursymb; }
 4973:     }
 4974:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4975:     $symb=&escape($symb);
 4976:     if ($target) { $target="target=\"$target\""; }
 4977:     return '<a href="/adm/parmset?command=set&amp;'.
 4978: 	'symb='.$symb.'&amp;uname='.$uname.
 4979: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4980: }
 4981: ##############################################
 4982: 
 4983: =pod
 4984: 
 4985: =back
 4986: 
 4987: =cut
 4988: 
 4989: ###############################################
 4990: 
 4991: 
 4992: sub timehash {
 4993:     my ($thistime) = @_;
 4994:     my $timezone = &Apache::lonlocal::gettimezone();
 4995:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4996:                      ->set_time_zone($timezone);
 4997:     my $wday = $dt->day_of_week();
 4998:     if ($wday == 7) { $wday = 0; }
 4999:     return ( 'second' => $dt->second(),
 5000:              'minute' => $dt->minute(),
 5001:              'hour'   => $dt->hour(),
 5002:              'day'     => $dt->day_of_month(),
 5003:              'month'   => $dt->month(),
 5004:              'year'    => $dt->year(),
 5005:              'weekday' => $wday,
 5006:              'dayyear' => $dt->day_of_year(),
 5007:              'dlsav'   => $dt->is_dst() );
 5008: }
 5009: 
 5010: sub utc_string {
 5011:     my ($date)=@_;
 5012:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5013: }
 5014: 
 5015: sub maketime {
 5016:     my %th=@_;
 5017:     my ($epoch_time,$timezone,$dt);
 5018:     $timezone = &Apache::lonlocal::gettimezone();
 5019:     eval {
 5020:         $dt = DateTime->new( year   => $th{'year'},
 5021:                              month  => $th{'month'},
 5022:                              day    => $th{'day'},
 5023:                              hour   => $th{'hour'},
 5024:                              minute => $th{'minute'},
 5025:                              second => $th{'second'},
 5026:                              time_zone => $timezone,
 5027:                          );
 5028:     };
 5029:     if (!$@) {
 5030:         $epoch_time = $dt->epoch;
 5031:         if ($epoch_time) {
 5032:             return $epoch_time;
 5033:         }
 5034:     }
 5035:     return POSIX::mktime(
 5036:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5037:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5038: }
 5039: 
 5040: #########################################
 5041: 
 5042: sub findallcourses {
 5043:     my ($roles,$uname,$udom) = @_;
 5044:     my %roles;
 5045:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5046:     my %courses;
 5047:     my $now=time;
 5048:     if (!defined($uname)) {
 5049:         $uname = $env{'user.name'};
 5050:     }
 5051:     if (!defined($udom)) {
 5052:         $udom = $env{'user.domain'};
 5053:     }
 5054:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5055:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5056:         if (!%roles) {
 5057:             %roles = (
 5058:                        cc => 1,
 5059:                        co => 1,
 5060:                        in => 1,
 5061:                        ep => 1,
 5062:                        ta => 1,
 5063:                        cr => 1,
 5064:                        st => 1,
 5065:              );
 5066:         }
 5067:         foreach my $entry (keys(%roleshash)) {
 5068:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5069:             if ($trole =~ /^cr/) { 
 5070:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5071:             } else {
 5072:                 next if (!exists($roles{$trole}));
 5073:             }
 5074:             if ($tend) {
 5075:                 next if ($tend < $now);
 5076:             }
 5077:             if ($tstart) {
 5078:                 next if ($tstart > $now);
 5079:             }
 5080:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5081:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5082:             my $value = $trole.'/'.$cdom.'/';
 5083:             if ($secpart eq '') {
 5084:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5085:                 $sec = 'none';
 5086:                 $value .= $cnum.'/';
 5087:             } else {
 5088:                 $cnum = $cnumpart;
 5089:                 ($sec,$role) = split(/_/,$secpart);
 5090:                 $value .= $cnum.'/'.$sec;
 5091:             }
 5092:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5093:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5094:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5095:                 }
 5096:             } else {
 5097:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5098:             }
 5099:         }
 5100:     } else {
 5101:         foreach my $key (keys(%env)) {
 5102: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5103:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5104: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5105: 	        next if ($role eq 'ca' || $role eq 'aa');
 5106: 	        next if (%roles && !exists($roles{$role}));
 5107: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5108:                 my $active=1;
 5109:                 if ($starttime) {
 5110: 		    if ($now<$starttime) { $active=0; }
 5111:                 }
 5112:                 if ($endtime) {
 5113:                     if ($now>$endtime) { $active=0; }
 5114:                 }
 5115:                 if ($active) {
 5116:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5117:                     if ($sec eq '') {
 5118:                         $sec = 'none';
 5119:                     } else {
 5120:                         $value .= $sec;
 5121:                     }
 5122:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5123:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5124:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5125:                         }
 5126:                     } else {
 5127:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5128:                     }
 5129:                 }
 5130:             }
 5131:         }
 5132:     }
 5133:     return %courses;
 5134: }
 5135: 
 5136: ###############################################
 5137: 
 5138: sub blockcheck {
 5139:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 5140: 
 5141:     if (defined($udom) && defined($uname)) {
 5142:         # If uname and udom are for a course, check for blocks in the course.
 5143:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5144:             my ($startblock,$endblock,$triggerblock) =
 5145:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 5146:             return ($startblock,$endblock,$triggerblock);
 5147:         }
 5148:     } else {
 5149:         $udom = $env{'user.domain'};
 5150:         $uname = $env{'user.name'};
 5151:     }
 5152: 
 5153:     my $startblock = 0;
 5154:     my $endblock = 0;
 5155:     my $triggerblock = '';
 5156:     my %live_courses = &findallcourses(undef,$uname,$udom);
 5157: 
 5158:     # If uname is for a user, and activity is course-specific, i.e.,
 5159:     # boards, chat or groups, check for blocking in current course only.
 5160: 
 5161:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5162:          $activity eq 'groups' || $activity eq 'printout' ||
 5163:          $activity eq 'reinit' || $activity eq 'alert') &&
 5164:         ($env{'request.course.id'})) {
 5165:         foreach my $key (keys(%live_courses)) {
 5166:             if ($key ne $env{'request.course.id'}) {
 5167:                 delete($live_courses{$key});
 5168:             }
 5169:         }
 5170:     }
 5171: 
 5172:     my $otheruser = 0;
 5173:     my %own_courses;
 5174:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5175:         # Resource belongs to user other than current user.
 5176:         $otheruser = 1;
 5177:         # Gather courses for current user
 5178:         %own_courses = 
 5179:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5180:     }
 5181: 
 5182:     # Gather active course roles - course coordinator, instructor, 
 5183:     # exam proctor, ta, student, or custom role.
 5184: 
 5185:     foreach my $course (keys(%live_courses)) {
 5186:         my ($cdom,$cnum);
 5187:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5188:             $cdom = $env{'course.'.$course.'.domain'};
 5189:             $cnum = $env{'course.'.$course.'.num'};
 5190:         } else {
 5191:             ($cdom,$cnum) = split(/_/,$course); 
 5192:         }
 5193:         my $no_ownblock = 0;
 5194:         my $no_userblock = 0;
 5195:         if ($otheruser && $activity ne 'com') {
 5196:             # Check if current user has 'evb' priv for this
 5197:             if (defined($own_courses{$course})) {
 5198:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5199:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5200:                     if ($sec ne 'none') {
 5201:                         $checkrole .= '/'.$sec;
 5202:                     }
 5203:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5204:                         $no_ownblock = 1;
 5205:                         last;
 5206:                     }
 5207:                 }
 5208:             }
 5209:             # if they have 'evb' priv and are currently not playing student
 5210:             next if (($no_ownblock) &&
 5211:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5212:         }
 5213:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5214:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5215:             if ($sec ne 'none') {
 5216:                 $checkrole .= '/'.$sec;
 5217:             }
 5218:             if ($otheruser) {
 5219:                 # Resource belongs to user other than current user.
 5220:                 # Assemble privs for that user, and check for 'evb' priv.
 5221:                 my (%allroles,%userroles);
 5222:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5223:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5224:                         my ($trole,$tdom,$tnum,$tsec);
 5225:                         if ($entry =~ /^cr/) {
 5226:                             ($trole,$tdom,$tnum,$tsec) = 
 5227:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5228:                         } else {
 5229:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5230:                         }
 5231:                         my ($spec,$area,$trest);
 5232:                         $area = '/'.$tdom.'/'.$tnum;
 5233:                         $trest = $tnum;
 5234:                         if ($tsec ne '') {
 5235:                             $area .= '/'.$tsec;
 5236:                             $trest .= '/'.$tsec;
 5237:                         }
 5238:                         $spec = $trole.'.'.$area;
 5239:                         if ($trole =~ /^cr/) {
 5240:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5241:                                                               $tdom,$spec,$trest,$area);
 5242:                         } else {
 5243:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5244:                                                                 $tdom,$spec,$trest,$area);
 5245:                         }
 5246:                     }
 5247:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5248:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5249:                         if ($1) {
 5250:                             $no_userblock = 1;
 5251:                             last;
 5252:                         }
 5253:                     }
 5254:                 }
 5255:             } else {
 5256:                 # Resource belongs to current user
 5257:                 # Check for 'evb' priv via lonnet::allowed().
 5258:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5259:                     $no_ownblock = 1;
 5260:                     last;
 5261:                 }
 5262:             }
 5263:         }
 5264:         # if they have the evb priv and are currently not playing student
 5265:         next if (($no_ownblock) &&
 5266:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5267:         next if ($no_userblock);
 5268: 
 5269:         # Retrieve blocking times and identity of blocker for course
 5270:         # of specified user, unless user has 'evb' privilege.
 5271: 
 5272:         my ($start,$end,$trigger) = 
 5273:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5274:         if (($start != 0) && 
 5275:             (($startblock == 0) || ($startblock > $start))) {
 5276:             $startblock = $start;
 5277:             if ($trigger ne '') {
 5278:                 $triggerblock = $trigger;
 5279:             }
 5280:         }
 5281:         if (($end != 0)  &&
 5282:             (($endblock == 0) || ($endblock < $end))) {
 5283:             $endblock = $end;
 5284:             if ($trigger ne '') {
 5285:                 $triggerblock = $trigger;
 5286:             }
 5287:         }
 5288:     }
 5289:     return ($startblock,$endblock,$triggerblock);
 5290: }
 5291: 
 5292: sub get_blocks {
 5293:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5294:     my $startblock = 0;
 5295:     my $endblock = 0;
 5296:     my $triggerblock = '';
 5297:     my $course = $cdom.'_'.$cnum;
 5298:     $setters->{$course} = {};
 5299:     $setters->{$course}{'staff'} = [];
 5300:     $setters->{$course}{'times'} = [];
 5301:     $setters->{$course}{'triggers'} = [];
 5302:     my (@blockers,%triggered);
 5303:     my $now = time;
 5304:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5305:     if ($activity eq 'docs') {
 5306:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5307:         foreach my $block (@blockers) {
 5308:             if ($block =~ /^firstaccess____(.+)$/) {
 5309:                 my $item = $1;
 5310:                 my $type = 'map';
 5311:                 my $timersymb = $item;
 5312:                 if ($item eq 'course') {
 5313:                     $type = 'course';
 5314:                 } elsif ($item =~ /___\d+___/) {
 5315:                     $type = 'resource';
 5316:                 } else {
 5317:                     $timersymb = &Apache::lonnet::symbread($item);
 5318:                 }
 5319:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5320:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5321:                 $triggered{$block} = {
 5322:                                        start => $start,
 5323:                                        end   => $end,
 5324:                                        type  => $type,
 5325:                                      };
 5326:             }
 5327:         }
 5328:     } else {
 5329:         foreach my $block (keys(%commblocks)) {
 5330:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5331:                 my ($start,$end) = ($1,$2);
 5332:                 if ($start <= time && $end >= time) {
 5333:                     if (ref($commblocks{$block}) eq 'HASH') {
 5334:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5335:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5336:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5337:                                     push(@blockers,$block);
 5338:                                 }
 5339:                             }
 5340:                         }
 5341:                     }
 5342:                 }
 5343:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5344:                 my $item = $1;
 5345:                 my $timersymb = $item; 
 5346:                 my $type = 'map';
 5347:                 if ($item eq 'course') {
 5348:                     $type = 'course';
 5349:                 } elsif ($item =~ /___\d+___/) {
 5350:                     $type = 'resource';
 5351:                 } else {
 5352:                     $timersymb = &Apache::lonnet::symbread($item);
 5353:                 }
 5354:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5355:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5356:                 if ($start && $end) {
 5357:                     if (($start <= time) && ($end >= time)) {
 5358:                         if (ref($commblocks{$block}) eq 'HASH') {
 5359:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5360:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5361:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5362:                                         push(@blockers,$block);
 5363:                                         $triggered{$block} = {
 5364:                                                                start => $start,
 5365:                                                                end   => $end,
 5366:                                                                type  => $type,
 5367:                                                              };
 5368:                                     }
 5369:                                 }
 5370:                             }
 5371:                         }
 5372:                     }
 5373:                 }
 5374:             }
 5375:         }
 5376:     }
 5377:     foreach my $blocker (@blockers) {
 5378:         my ($staff_name,$staff_dom,$title,$blocks) =
 5379:             &parse_block_record($commblocks{$blocker});
 5380:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5381:         my ($start,$end,$triggertype);
 5382:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5383:             ($start,$end) = ($1,$2);
 5384:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5385:             $start = $triggered{$blocker}{'start'};
 5386:             $end = $triggered{$blocker}{'end'};
 5387:             $triggertype = $triggered{$blocker}{'type'};
 5388:         }
 5389:         if ($start) {
 5390:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5391:             if ($triggertype) {
 5392:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5393:             } else {
 5394:                 push(@{$$setters{$course}{'triggers'}},0);
 5395:             }
 5396:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5397:                 $startblock = $start;
 5398:                 if ($triggertype) {
 5399:                     $triggerblock = $blocker;
 5400:                 }
 5401:             }
 5402:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5403:                $endblock = $end;
 5404:                if ($triggertype) {
 5405:                    $triggerblock = $blocker;
 5406:                }
 5407:             }
 5408:         }
 5409:     }
 5410:     return ($startblock,$endblock,$triggerblock);
 5411: }
 5412: 
 5413: sub parse_block_record {
 5414:     my ($record) = @_;
 5415:     my ($setuname,$setudom,$title,$blocks);
 5416:     if (ref($record) eq 'HASH') {
 5417:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5418:         $title = &unescape($record->{'event'});
 5419:         $blocks = $record->{'blocks'};
 5420:     } else {
 5421:         my @data = split(/:/,$record,3);
 5422:         if (scalar(@data) eq 2) {
 5423:             $title = $data[1];
 5424:             ($setuname,$setudom) = split(/@/,$data[0]);
 5425:         } else {
 5426:             ($setuname,$setudom,$title) = @data;
 5427:         }
 5428:         $blocks = { 'com' => 'on' };
 5429:     }
 5430:     return ($setuname,$setudom,$title,$blocks);
 5431: }
 5432: 
 5433: sub blocking_status {
 5434:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5435:     my %setters;
 5436: 
 5437: # check for active blocking
 5438:     my ($startblock,$endblock,$triggerblock) = 
 5439:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5440:     my $blocked = 0;
 5441:     if ($startblock && $endblock) {
 5442:         $blocked = 1;
 5443:     }
 5444: 
 5445: # caller just wants to know whether a block is active
 5446:     if (!wantarray) { return $blocked; }
 5447: 
 5448: # build a link to a popup window containing the details
 5449:     my $querystring  = "?activity=$activity";
 5450: # $uname and $udom decide whose portfolio the user is trying to look at
 5451:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5452:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5453:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5454:     } elsif ($activity eq 'docs') {
 5455:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5456:     }
 5457: 
 5458:     my $output .= <<'END_MYBLOCK';
 5459: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5460:     var options = "width=" + w + ",height=" + h + ",";
 5461:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5462:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5463:     var newWin = window.open(url, wdwName, options);
 5464:     newWin.focus();
 5465: }
 5466: END_MYBLOCK
 5467: 
 5468:     $output = Apache::lonhtmlcommon::scripttag($output);
 5469:   
 5470:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5471:     my $text = &mt('Communication Blocked');
 5472:     my $class = 'LC_comblock';
 5473:     if ($activity eq 'docs') {
 5474:         $text = &mt('Content Access Blocked');
 5475:         $class = '';
 5476:     } elsif ($activity eq 'printout') {
 5477:         $text = &mt('Printing Blocked');
 5478:     } elsif ($activity eq 'passwd') {
 5479:         $text = &mt('Password Changing Blocked');
 5480:     } elsif ($activity eq 'alert') {
 5481:         $text = &mt('Checking Critical Messages Blocked');
 5482:     } elsif ($activity eq 'reinit') {
 5483:         $text = &mt('Checking Course Update Blocked');
 5484:     }
 5485:     $output .= <<"END_BLOCK";
 5486: <div class='$class'>
 5487:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5488:   title='$text'>
 5489:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5490:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5491:   title='$text'>$text</a>
 5492: </div>
 5493: 
 5494: END_BLOCK
 5495: 
 5496:     return ($blocked, $output);
 5497: }
 5498: 
 5499: ###############################################
 5500: 
 5501: sub check_ip_acc {
 5502:     my ($acc,$clientip)=@_;
 5503:     &Apache::lonxml::debug("acc is $acc");
 5504:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5505:         return 1;
 5506:     }
 5507:     my $allowed;
 5508:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5509: 
 5510:     my $name;
 5511:     my %access = (
 5512:                      allowfrom => 1,
 5513:                      denyfrom  => 0,
 5514:                  );
 5515:     my @allows;
 5516:     my @denies;
 5517:     foreach my $item (split(',',$acc)) {
 5518:         $item =~ s/^\s*//;
 5519:         $item =~ s/\s*$//;
 5520:         my $pattern;
 5521:         if ($item =~ /^\!(.+)$/) {
 5522:             push(@denies,$1);
 5523:         } else {
 5524:             push(@allows,$item);
 5525:         }
 5526:    }
 5527:    my $numdenies = scalar(@denies);
 5528:    my $numallows = scalar(@allows);
 5529:    my $count = 0;
 5530:    foreach my $pattern (@denies,@allows) {
 5531:         $count ++; 
 5532:         my $acctype = 'allowfrom';
 5533:         if ($count <= $numdenies) {
 5534:             $acctype = 'denyfrom';
 5535:         }
 5536:         if ($pattern =~ /\*$/) {
 5537:             #35.8.*
 5538:             $pattern=~s/\*//;
 5539:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5540:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5541:             #35.8.3.[34-56]
 5542:             my $low=$2;
 5543:             my $high=$3;
 5544:             $pattern=$1;
 5545:             if ($ip =~ /^\Q$pattern\E/) {
 5546:                 my $last=(split(/\./,$ip))[3];
 5547:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5548:             }
 5549:         } elsif ($pattern =~ /^\*/) {
 5550:             #*.msu.edu
 5551:             $pattern=~s/\*//;
 5552:             if (!defined($name)) {
 5553:                 use Socket;
 5554:                 my $netaddr=inet_aton($ip);
 5555:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5556:             }
 5557:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5558:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5559:             #127.0.0.1
 5560:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5561:         } else {
 5562:             #some.name.com
 5563:             if (!defined($name)) {
 5564:                 use Socket;
 5565:                 my $netaddr=inet_aton($ip);
 5566:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5567:             }
 5568:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5569:         }
 5570:         if ($allowed =~ /^(0|1)$/) { last; }
 5571:     }
 5572:     if ($allowed eq '') {
 5573:         if ($numdenies && !$numallows) {
 5574:             $allowed = 1;
 5575:         } else {
 5576:             $allowed = 0;
 5577:         }
 5578:     }
 5579:     return $allowed;
 5580: }
 5581: 
 5582: ###############################################
 5583: 
 5584: =pod
 5585: 
 5586: =head1 Domain Template Functions
 5587: 
 5588: =over 4
 5589: 
 5590: =item * &determinedomain()
 5591: 
 5592: Inputs: $domain (usually will be undef)
 5593: 
 5594: Returns: Determines which domain should be used for designs
 5595: 
 5596: =cut
 5597: 
 5598: ###############################################
 5599: sub determinedomain {
 5600:     my $domain=shift;
 5601:     if (! $domain) {
 5602:         # Determine domain if we have not been given one
 5603:         $domain = &Apache::lonnet::default_login_domain();
 5604:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5605:         if ($env{'request.role.domain'}) { 
 5606:             $domain=$env{'request.role.domain'}; 
 5607:         }
 5608:     }
 5609:     return $domain;
 5610: }
 5611: ###############################################
 5612: 
 5613: sub devalidate_domconfig_cache {
 5614:     my ($udom)=@_;
 5615:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5616: }
 5617: 
 5618: # ---------------------- Get domain configuration for a domain
 5619: sub get_domainconf {
 5620:     my ($udom) = @_;
 5621:     my $cachetime=1800;
 5622:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5623:     if (defined($cached)) { return %{$result}; }
 5624: 
 5625:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5626: 					     ['login','rolecolors','autoenroll'],$udom);
 5627:     my (%designhash,%legacy);
 5628:     if (keys(%domconfig) > 0) {
 5629:         if (ref($domconfig{'login'}) eq 'HASH') {
 5630:             if (keys(%{$domconfig{'login'}})) {
 5631:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5632:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5633:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5634:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5635:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5636:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5637:                                         if ($key eq 'loginvia') {
 5638:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5639:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5640:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5641:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5642: 
 5643:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5644:                                                 } else {
 5645:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5646:                                                 }
 5647:                                             }
 5648:                                         } elsif ($key eq 'headtag') {
 5649:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5650:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5651:                                             }
 5652:                                         }
 5653:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5654:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5655:                                         }
 5656:                                     }
 5657:                                 }
 5658:                             }
 5659:                         } else {
 5660:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5661:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5662:                                     $domconfig{'login'}{$key}{$img};
 5663:                             }
 5664:                         }
 5665:                     } else {
 5666:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5667:                     }
 5668:                 }
 5669:             } else {
 5670:                 $legacy{'login'} = 1;
 5671:             }
 5672:         } else {
 5673:             $legacy{'login'} = 1;
 5674:         }
 5675:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5676:             if (keys(%{$domconfig{'rolecolors'}})) {
 5677:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5678:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5679:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5680:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5681:                         }
 5682:                     }
 5683:                 }
 5684:             } else {
 5685:                 $legacy{'rolecolors'} = 1;
 5686:             }
 5687:         } else {
 5688:             $legacy{'rolecolors'} = 1;
 5689:         }
 5690:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5691:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5692:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5693:             }
 5694:         }
 5695:         if (keys(%legacy) > 0) {
 5696:             my %legacyhash = &get_legacy_domconf($udom);
 5697:             foreach my $item (keys(%legacyhash)) {
 5698:                 if ($item =~ /^\Q$udom\E\.login/) {
 5699:                     if ($legacy{'login'}) { 
 5700:                         $designhash{$item} = $legacyhash{$item};
 5701:                     }
 5702:                 } else {
 5703:                     if ($legacy{'rolecolors'}) {
 5704:                         $designhash{$item} = $legacyhash{$item};
 5705:                     }
 5706:                 }
 5707:             }
 5708:         }
 5709:     } else {
 5710:         %designhash = &get_legacy_domconf($udom); 
 5711:     }
 5712:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5713: 				  $cachetime);
 5714:     return %designhash;
 5715: }
 5716: 
 5717: sub get_legacy_domconf {
 5718:     my ($udom) = @_;
 5719:     my %legacyhash;
 5720:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5721:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5722:     if (-e $designfile) {
 5723:         if ( open (my $fh,'<',$designfile) ) {
 5724:             while (my $line = <$fh>) {
 5725:                 next if ($line =~ /^\#/);
 5726:                 chomp($line);
 5727:                 my ($key,$val)=(split(/\=/,$line));
 5728:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5729:             }
 5730:             close($fh);
 5731:         }
 5732:     }
 5733:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5734:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5735:     }
 5736:     return %legacyhash;
 5737: }
 5738: 
 5739: =pod
 5740: 
 5741: =item * &domainlogo()
 5742: 
 5743: Inputs: $domain (usually will be undef)
 5744: 
 5745: Returns: A link to a domain logo, if the domain logo exists.
 5746: If the domain logo does not exist, a description of the domain.
 5747: 
 5748: =cut
 5749: 
 5750: ###############################################
 5751: sub domainlogo {
 5752:     my $domain = &determinedomain(shift);
 5753:     my %designhash = &get_domainconf($domain);    
 5754:     # See if there is a logo
 5755:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5756:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5757:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5758: 	    if ($imgsrc =~ m{^/res/}) {
 5759: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5760: 		&Apache::lonnet::repcopy($local_name);
 5761: 	    }
 5762: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5763:         } 
 5764:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5765:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5766:         return &Apache::lonnet::domain($domain,'description');
 5767:     } else {
 5768:         return '';
 5769:     }
 5770: }
 5771: ##############################################
 5772: 
 5773: =pod
 5774: 
 5775: =item * &designparm()
 5776: 
 5777: Inputs: $which parameter; $domain (usually will be undef)
 5778: 
 5779: Returns: value of designparamter $which
 5780: 
 5781: =cut
 5782: 
 5783: 
 5784: ##############################################
 5785: sub designparm {
 5786:     my ($which,$domain)=@_;
 5787:     if (exists($env{'environment.color.'.$which})) {
 5788:         return $env{'environment.color.'.$which};
 5789:     }
 5790:     $domain=&determinedomain($domain);
 5791:     my %domdesign;
 5792:     unless ($domain eq 'public') {
 5793:         %domdesign = &get_domainconf($domain);
 5794:     }
 5795:     my $output;
 5796:     if ($domdesign{$domain.'.'.$which} ne '') {
 5797:         $output = $domdesign{$domain.'.'.$which};
 5798:     } else {
 5799:         $output = $defaultdesign{$which};
 5800:     }
 5801:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5802:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5803:         if ($output =~ m{^/(adm|res)/}) {
 5804:             if ($output =~ m{^/res/}) {
 5805:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5806:                 &Apache::lonnet::repcopy($local_name);
 5807:             }
 5808:             $output = &lonhttpdurl($output);
 5809:         }
 5810:     }
 5811:     return $output;
 5812: }
 5813: 
 5814: ##############################################
 5815: =pod
 5816: 
 5817: =item * &authorspace()
 5818: 
 5819: Inputs: $url (usually will be undef).
 5820: 
 5821: Returns: Path to Authoring Space containing the resource or 
 5822:          directory being viewed (or for which action is being taken). 
 5823:          If $url is provided, and begins /priv/<domain>/<uname>
 5824:          the path will be that portion of the $context argument.
 5825:          Otherwise the path will be for the author space of the current
 5826:          user when the current role is author, or for that of the 
 5827:          co-author/assistant co-author space when the current role 
 5828:          is co-author or assistant co-author.
 5829: 
 5830: =cut
 5831: 
 5832: sub authorspace {
 5833:     my ($url) = @_;
 5834:     if ($url ne '') {
 5835:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5836:            return $1;
 5837:         }
 5838:     }
 5839:     my $caname = '';
 5840:     my $cadom = '';
 5841:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5842:         ($cadom,$caname) =
 5843:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5844:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5845:         $caname = $env{'user.name'};
 5846:         $cadom = $env{'user.domain'};
 5847:     }
 5848:     if (($caname ne '') && ($cadom ne '')) {
 5849:         return "/priv/$cadom/$caname/";
 5850:     }
 5851:     return;
 5852: }
 5853: 
 5854: ##############################################
 5855: =pod
 5856: 
 5857: =item * &head_subbox()
 5858: 
 5859: Inputs: $content (contains HTML code with page functions, etc.)
 5860: 
 5861: Returns: HTML div with $content
 5862:          To be included in page header
 5863: 
 5864: =cut
 5865: 
 5866: sub head_subbox {
 5867:     my ($content)=@_;
 5868:     my $output =
 5869:         '<div class="LC_head_subbox">'
 5870:        .$content
 5871:        .'</div>'
 5872: }
 5873: 
 5874: ##############################################
 5875: =pod
 5876: 
 5877: =item * &CSTR_pageheader()
 5878: 
 5879: Input: (optional) filename from which breadcrumb trail is built.
 5880:        In most cases no input as needed, as $env{'request.filename'}
 5881:        is appropriate for use in building the breadcrumb trail.
 5882: 
 5883: Returns: HTML div with CSTR path and recent box
 5884:          To be included on Authoring Space pages
 5885: 
 5886: =cut
 5887: 
 5888: sub CSTR_pageheader {
 5889:     my ($trailfile) = @_;
 5890:     if ($trailfile eq '') {
 5891:         $trailfile = $env{'request.filename'};
 5892:     }
 5893: 
 5894: # this is for resources; directories have customtitle, and crumbs
 5895: # and select recent are created in lonpubdir.pm
 5896: 
 5897:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5898:     my ($udom,$uname,$thisdisfn)=
 5899:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5900:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5901:     $formaction =~ s{/+}{/}g;
 5902: 
 5903:     my $parentpath = '';
 5904:     my $lastitem = '';
 5905:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5906:         $parentpath = $1;
 5907:         $lastitem = $2;
 5908:     } else {
 5909:         $lastitem = $thisdisfn;
 5910:     }
 5911: 
 5912:     my ($crsauthor,$title);
 5913:     if (($env{'request.course.id'}) &&
 5914:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5915:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5916:         $crsauthor = 1;
 5917:         $title = &mt('Course Authoring Space');
 5918:     } else {
 5919:         $title = &mt('Authoring Space');
 5920:     }
 5921: 
 5922:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
 5923:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 5924:         $target = '';
 5925:         $crumbtarget = '';
 5926:     }
 5927: 
 5928:     my $output =
 5929:          '<div>'
 5930:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5931:         .'<b>'.$title.'</b> '
 5932:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5933:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5934: 
 5935:     if ($lastitem) {
 5936:         $output .=
 5937:              '<span class="LC_filename">'
 5938:             .$lastitem
 5939:             .'</span>';
 5940:     }
 5941: 
 5942:     if ($crsauthor) {
 5943:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5944:     } else {
 5945:         $output .=
 5946:              '<br />'
 5947:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5948:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5949:             .'</form>'
 5950:             .&Apache::lonmenu::constspaceform();
 5951:     }
 5952:     $output .= '</div>';
 5953: 
 5954:     return $output;
 5955: }
 5956: 
 5957: ###############################################
 5958: ###############################################
 5959: 
 5960: =pod
 5961: 
 5962: =back
 5963: 
 5964: =head1 HTML Helpers
 5965: 
 5966: =over 4
 5967: 
 5968: =item * &bodytag()
 5969: 
 5970: Returns a uniform header for LON-CAPA web pages.
 5971: 
 5972: Inputs: 
 5973: 
 5974: =over 4
 5975: 
 5976: =item * $title, A title to be displayed on the page.
 5977: 
 5978: =item * $function, the current role (can be undef).
 5979: 
 5980: =item * $addentries, extra parameters for the <body> tag.
 5981: 
 5982: =item * $bodyonly, if defined, only return the <body> tag.
 5983: 
 5984: =item * $domain, if defined, force a given domain.
 5985: 
 5986: =item * $forcereg, if page should register as content page (relevant for 
 5987:             text interface only)
 5988: 
 5989: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5990:                      navigational links
 5991: 
 5992: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5993: 
 5994: =item * $args, optional argument valid values are
 5995:             no_auto_mt_title -> prevents &mt()ing the title arg
 5996:             use_absolute     -> for external resource or syllabus, this will
 5997:                                 contain https://<hostname> if server uses
 5998:                                 https (as per hosts.tab), but request is for http
 5999:             hostname         -> hostname, from $r->hostname().
 6000: 
 6001: =item * $advtoolsref, optional argument, ref to an array containing
 6002:             inlineremote items to be added in "Functions" menu below
 6003:             breadcrumbs.
 6004: 
 6005: =item * $ltiscope, optional argument, will be one of: resource, map or
 6006:             course, if LON-CAPA is in LTI Provider context. Value is
 6007:             the scope of use, i.e., launch was for access to a single, a map
 6008:             or the entire course.
 6009: 
 6010: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6011:             context, this will contain the URL for the landing item in
 6012:             the course, after launch from an LTI Consumer
 6013: 
 6014: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6015:             context, this will contain a reference to hash of items
 6016:             to be included in the page header and/or inline menu.
 6017: 
 6018: =back
 6019: 
 6020: Returns: A uniform header for LON-CAPA web pages.  
 6021: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6022: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6023: other decorations will be returned.
 6024: 
 6025: =cut
 6026: 
 6027: sub bodytag {
 6028:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6029:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
 6030: 
 6031:     my $public;
 6032:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6033:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6034:         $public = 1;
 6035:     }
 6036:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6037:     my $httphost = $args->{'use_absolute'};
 6038:     my $hostname = $args->{'hostname'};
 6039: 
 6040:     $function = &get_users_function() if (!$function);
 6041:     my $img =    &designparm($function.'.img',$domain);
 6042:     my $font =   &designparm($function.'.font',$domain);
 6043:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6044: 
 6045:     my %design = ( 'style'   => 'margin-top: 0',
 6046: 		   'bgcolor' => $pgbg,
 6047: 		   'text'    => $font,
 6048:                    'alink'   => &designparm($function.'.alink',$domain),
 6049: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6050: 		   'link'    => &designparm($function.'.link',$domain),);
 6051:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6052: 
 6053:  # role and realm
 6054:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6055:     if ($realm) {
 6056:         $realm = '/'.$realm;
 6057:     }
 6058:     if ($role  eq 'ca') {
 6059:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6060:         $realm = &plainname($rname,$rdom);
 6061:     } 
 6062: # realm
 6063:     if ($env{'request.course.id'}) {
 6064:         if ($env{'request.role'} !~ /^cr/) {
 6065:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6066:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6067:             if ($env{'request.role.desc'}) {
 6068:                 $role = $env{'request.role.desc'};
 6069:             } else {
 6070:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6071:             }
 6072:         } else {
 6073:             $role = (split(/\//,$role,4))[-1]; 
 6074:         }
 6075:         if ($env{'request.course.sec'}) {
 6076:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 6077:         }   
 6078: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 6079:     } else {
 6080:         $role = &Apache::lonnet::plaintext($role);
 6081:     }
 6082: 
 6083:     if (!$realm) { $realm='&nbsp;'; }
 6084: 
 6085:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6086: 
 6087: # construct main body tag
 6088:     my $bodytag = "<body $extra_body_attr>".
 6089: 	&Apache::lontexconvert::init_math_support();
 6090: 
 6091:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6092: 
 6093:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6094:         return $bodytag;
 6095:     }
 6096: 
 6097:     if ($public) {
 6098: 	undef($role);
 6099:     }
 6100: 
 6101:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 6102:         if (ref($ltimenu) eq 'HASH') {
 6103:             unless ($ltimenu->{'role'}) {
 6104:                 undef($role);
 6105:             }
 6106:             unless ($ltimenu->{'coursetitle'}) {
 6107:                 $realm='&nbsp;';
 6108:             }
 6109:         }
 6110:     }
 6111: 
 6112:     my $titleinfo = '<h1>'.$title.'</h1>';
 6113:     #
 6114:     # Extra info if you are the DC
 6115:     my $dc_info = '';
 6116:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 6117:                         $env{'course.'.$env{'request.course.id'}.
 6118:                                  '.domain'}.'/'})) {
 6119:         my $cid = $env{'request.course.id'};
 6120:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6121:         $dc_info =~ s/\s+$//;
 6122:     }
 6123: 
 6124:     my $crstype;
 6125:     if ($env{'request.course.id'}) {
 6126:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 6127:     } elsif ($args->{'crstype'}) {
 6128:         $crstype = $args->{'crstype'};
 6129:     }
 6130:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6131:         undef($role);
 6132:     } else {
 6133:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6134:     }
 6135: 
 6136:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6137: 
 6138:         #    if ($env{'request.state'} eq 'construct') {
 6139:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6140:         #    }
 6141: 
 6142:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6143:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6144: 
 6145:         unless ($args->{'no_primary_menu'}) {
 6146:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
 6147: 
 6148:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6149:                 if ($dc_info) {
 6150:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6151:                 }
 6152:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6153:                                <em>$realm</em> $dc_info</div>|;
 6154:                 return $bodytag;
 6155:             }
 6156: 
 6157:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6158:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6159:             }
 6160: 
 6161:             $bodytag .= $right;
 6162: 
 6163:             if ($dc_info) {
 6164:                 $dc_info = &dc_courseid_toggle($dc_info);
 6165:             }
 6166:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6167:         }
 6168: 
 6169:         #if directed to not display the secondary menu, don't.  
 6170:         if ($args->{'no_secondary_menu'}) {
 6171:             return $bodytag;
 6172:         }
 6173:         #don't show menus for public users
 6174:         if (!$public){
 6175:             unless ($args->{'no_inline_menu'}) {
 6176:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6177:                                                             $args->{'no_primary_menu'});
 6178:             }
 6179:             $bodytag .= Apache::lonmenu::serverform();
 6180:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6181:             if ($env{'request.state'} eq 'construct') {
 6182:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6183:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
 6184:             } elsif ($forcereg) {
 6185:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6186:                                                             $args->{'group'},
 6187:                                                             $args->{'hide_buttons'},
 6188:                                                             $hostname,$ltiscope,$ltiuri);
 6189:             } else {
 6190:                 $bodytag .= 
 6191:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6192:                                                         $forcereg,$args->{'group'},
 6193:                                                         $args->{'bread_crumbs'},
 6194:                                                         $advtoolsref,'',$hostname);
 6195:             }
 6196:         }else{
 6197:             # this is to seperate menu from content when there's no secondary
 6198:             # menu. Especially needed for public accessible ressources.
 6199:             $bodytag .= '<hr style="clear:both" />';
 6200:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6201:         }
 6202: 
 6203:         return $bodytag;
 6204: }
 6205: 
 6206: sub dc_courseid_toggle {
 6207:     my ($dc_info) = @_;
 6208:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6209:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6210:            &mt('(More ...)').'</a></span>'.
 6211:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6212: }
 6213: 
 6214: sub make_attr_string {
 6215:     my ($register,$attr_ref) = @_;
 6216: 
 6217:     if ($attr_ref && !ref($attr_ref)) {
 6218: 	die("addentries Must be a hash ref ".
 6219: 	    join(':',caller(1))." ".
 6220: 	    join(':',caller(0))." ");
 6221:     }
 6222: 
 6223:     if ($register) {
 6224: 	my ($on_load,$on_unload);
 6225: 	foreach my $key (keys(%{$attr_ref})) {
 6226: 	    if      (lc($key) eq 'onload') {
 6227: 		$on_load.=$attr_ref->{$key}.';';
 6228: 		delete($attr_ref->{$key});
 6229: 
 6230: 	    } elsif (lc($key) eq 'onunload') {
 6231: 		$on_unload.=$attr_ref->{$key}.';';
 6232: 		delete($attr_ref->{$key});
 6233: 	    }
 6234: 	}
 6235: 	$attr_ref->{'onload'}  = $on_load;
 6236: 	$attr_ref->{'onunload'}= $on_unload;
 6237:     }
 6238: 
 6239:     my $attr_string;
 6240:     foreach my $attr (sort(keys(%$attr_ref))) {
 6241: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6242:     }
 6243:     return $attr_string;
 6244: }
 6245: 
 6246: 
 6247: ###############################################
 6248: ###############################################
 6249: 
 6250: =pod
 6251: 
 6252: =item * &endbodytag()
 6253: 
 6254: Returns a uniform footer for LON-CAPA web pages.
 6255: 
 6256: Inputs: 1 - optional reference to an args hash
 6257: If in the hash, key for noredirectlink has a value which evaluates to true,
 6258: a 'Continue' link is not displayed if the page contains an
 6259: internal redirect in the <head></head> section,
 6260: i.e., $env{'internal.head.redirect'} exists   
 6261: 
 6262: =cut
 6263: 
 6264: sub endbodytag {
 6265:     my ($args) = @_;
 6266:     my $endbodytag;
 6267:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6268:         $endbodytag='</body>';
 6269:     }
 6270:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6271:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6272: 	    $endbodytag=
 6273: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6274: 	        &mt('Continue').'</a>'.
 6275: 	        $endbodytag;
 6276:         }
 6277:     }
 6278:     return $endbodytag;
 6279: }
 6280: 
 6281: =pod
 6282: 
 6283: =item * &standard_css()
 6284: 
 6285: Returns a style sheet
 6286: 
 6287: Inputs: (all optional)
 6288:             domain         -> force to color decorate a page for a specific
 6289:                                domain
 6290:             function       -> force usage of a specific rolish color scheme
 6291:             bgcolor        -> override the default page bgcolor
 6292: 
 6293: =cut
 6294: 
 6295: sub standard_css {
 6296:     my ($function,$domain,$bgcolor) = @_;
 6297:     $function  = &get_users_function() if (!$function);
 6298:     my $img    = &designparm($function.'.img',   $domain);
 6299:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6300:     my $font   = &designparm($function.'.font',  $domain);
 6301:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6302: #second colour for later usage
 6303:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6304:     my $pgbg_or_bgcolor =
 6305: 	         $bgcolor ||
 6306: 	         &designparm($function.'.pgbg',  $domain);
 6307:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6308:     my $alink  = &designparm($function.'.alink', $domain);
 6309:     my $vlink  = &designparm($function.'.vlink', $domain);
 6310:     my $link   = &designparm($function.'.link',  $domain);
 6311: 
 6312:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6313:     my $mono                 = 'monospace';
 6314:     my $data_table_head      = $sidebg;
 6315:     my $data_table_light     = '#FAFAFA';
 6316:     my $data_table_dark      = '#E0E0E0';
 6317:     my $data_table_darker    = '#CCCCCC';
 6318:     my $data_table_highlight = '#FFFF00';
 6319:     my $mail_new             = '#FFBB77';
 6320:     my $mail_new_hover       = '#DD9955';
 6321:     my $mail_read            = '#BBBB77';
 6322:     my $mail_read_hover      = '#999944';
 6323:     my $mail_replied         = '#AAAA88';
 6324:     my $mail_replied_hover   = '#888855';
 6325:     my $mail_other           = '#99BBBB';
 6326:     my $mail_other_hover     = '#669999';
 6327:     my $table_header         = '#DDDDDD';
 6328:     my $feedback_link_bg     = '#BBBBBB';
 6329:     my $lg_border_color      = '#C8C8C8';
 6330:     my $button_hover         = '#BF2317';
 6331: 
 6332:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6333:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6334:                                              : '0 3px 0 4px';
 6335: 
 6336: 
 6337:     return <<END;
 6338: 
 6339: /* needed for iframe to allow 100% height in FF */
 6340: body, html { 
 6341:     margin: 0;
 6342:     padding: 0 0.5%;
 6343:     height: 99%; /* to avoid scrollbars */
 6344: }
 6345: 
 6346: body {
 6347:   font-family: $sans;
 6348:   line-height:130%;
 6349:   font-size:0.83em;
 6350:   color:$font;
 6351: }
 6352: 
 6353: a:focus,
 6354: a:focus img {
 6355:   color: red;
 6356: }
 6357: 
 6358: form, .inline {
 6359:   display: inline;
 6360: }
 6361: 
 6362: .LC_right {
 6363:   text-align:right;
 6364: }
 6365: 
 6366: .LC_middle {
 6367:   vertical-align:middle;
 6368: }
 6369: 
 6370: .LC_floatleft {
 6371:   float: left;
 6372: }
 6373: 
 6374: .LC_floatright {
 6375:   float: right;
 6376: }
 6377: 
 6378: .LC_400Box {
 6379:   width:400px;
 6380: }
 6381: 
 6382: .LC_iframecontainer {
 6383:     width: 98%;
 6384:     margin: 0;
 6385:     position: fixed;
 6386:     top: 8.5em;
 6387:     bottom: 0;
 6388: }
 6389: 
 6390: .LC_iframecontainer iframe{
 6391:     border: none;
 6392:     width: 100%;
 6393:     height: 100%;
 6394: }
 6395: 
 6396: .LC_filename {
 6397:   font-family: $mono;
 6398:   white-space:pre;
 6399:   font-size: 120%;
 6400: }
 6401: 
 6402: .LC_fileicon {
 6403:   border: none;
 6404:   height: 1.3em;
 6405:   vertical-align: text-bottom;
 6406:   margin-right: 0.3em;
 6407:   text-decoration:none;
 6408: }
 6409: 
 6410: .LC_setting {
 6411:   text-decoration:underline;
 6412: }
 6413: 
 6414: .LC_error {
 6415:   color: red;
 6416: }
 6417: 
 6418: .LC_warning {
 6419:   color: darkorange;
 6420: }
 6421: 
 6422: .LC_diff_removed {
 6423:   color: red;
 6424: }
 6425: 
 6426: .LC_info,
 6427: .LC_success,
 6428: .LC_diff_added {
 6429:   color: green;
 6430: }
 6431: 
 6432: div.LC_confirm_box {
 6433:   background-color: #FAFAFA;
 6434:   border: 1px solid $lg_border_color;
 6435:   margin-right: 0;
 6436:   padding: 5px;
 6437: }
 6438: 
 6439: div.LC_confirm_box .LC_error img,
 6440: div.LC_confirm_box .LC_success img {
 6441:   vertical-align: middle;
 6442: }
 6443: 
 6444: .LC_maxwidth {
 6445:   max-width: 100%;
 6446:   height: auto;
 6447: }
 6448: 
 6449: .LC_textsize_mobile {
 6450:   \@media only screen and (max-device-width: 480px) {
 6451:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6452:   }
 6453: }
 6454: 
 6455: .LC_icon {
 6456:   border: none;
 6457:   vertical-align: middle;
 6458: }
 6459: 
 6460: .LC_docs_spacer {
 6461:   width: 25px;
 6462:   height: 1px;
 6463:   border: none;
 6464: }
 6465: 
 6466: .LC_internal_info {
 6467:   color: #999999;
 6468: }
 6469: 
 6470: .LC_discussion {
 6471:   background: $data_table_dark;
 6472:   border: 1px solid black;
 6473:   margin: 2px;
 6474: }
 6475: 
 6476: .LC_disc_action_left {
 6477:   background: $sidebg;
 6478:   text-align: left;
 6479:   padding: 4px;
 6480:   margin: 2px;
 6481: }
 6482: 
 6483: .LC_disc_action_right {
 6484:   background: $sidebg;
 6485:   text-align: right;
 6486:   padding: 4px;
 6487:   margin: 2px;
 6488: }
 6489: 
 6490: .LC_disc_new_item {
 6491:   background: white;
 6492:   border: 2px solid red;
 6493:   margin: 4px;
 6494:   padding: 4px;
 6495: }
 6496: 
 6497: .LC_disc_old_item {
 6498:   background: white;
 6499:   margin: 4px;
 6500:   padding: 4px;
 6501: }
 6502: 
 6503: table.LC_pastsubmission {
 6504:   border: 1px solid black;
 6505:   margin: 2px;
 6506: }
 6507: 
 6508: table#LC_menubuttons {
 6509:   width: 100%;
 6510:   background: $pgbg;
 6511:   border: 2px;
 6512:   border-collapse: separate;
 6513:   padding: 0;
 6514: }
 6515: 
 6516: table#LC_title_bar a {
 6517:   color: $fontmenu;
 6518: }
 6519: 
 6520: table#LC_title_bar {
 6521:   clear: both;
 6522:   display: none;
 6523: }
 6524: 
 6525: table#LC_title_bar,
 6526: table.LC_breadcrumbs, /* obsolete? */
 6527: table#LC_title_bar.LC_with_remote {
 6528:   width: 100%;
 6529:   border-color: $pgbg;
 6530:   border-style: solid;
 6531:   border-width: $border;
 6532:   background: $pgbg;
 6533:   color: $fontmenu;
 6534:   border-collapse: collapse;
 6535:   padding: 0;
 6536:   margin: 0;
 6537: }
 6538: 
 6539: ul.LC_breadcrumb_tools_outerlist {
 6540:     margin: 0;
 6541:     padding: 0;
 6542:     position: relative;
 6543:     list-style: none;
 6544: }
 6545: ul.LC_breadcrumb_tools_outerlist li {
 6546:     display: inline;
 6547: }
 6548: 
 6549: .LC_breadcrumb_tools_navigation {
 6550:     padding: 0;
 6551:     margin: 0;
 6552:     float: left;
 6553: }
 6554: .LC_breadcrumb_tools_tools {
 6555:     padding: 0;
 6556:     margin: 0;
 6557:     float: right;
 6558: }
 6559: 
 6560: .LC_placement_prog {
 6561:     padding-right: 20px;
 6562:     font-weight: bold;
 6563:     font-size: 90%;
 6564: }
 6565: 
 6566: table#LC_title_bar td {
 6567:   background: $tabbg;
 6568: }
 6569: 
 6570: table#LC_menubuttons img {
 6571:   border: none;
 6572: }
 6573: 
 6574: .LC_breadcrumbs_component {
 6575:   float: right;
 6576:   margin: 0 1em;
 6577: }
 6578: .LC_breadcrumbs_component img {
 6579:   vertical-align: middle;
 6580: }
 6581: 
 6582: .LC_breadcrumbs_hoverable {
 6583:   background: $sidebg;
 6584: }
 6585: 
 6586: td.LC_table_cell_checkbox {
 6587:   text-align: center;
 6588: }
 6589: 
 6590: .LC_fontsize_small {
 6591:   font-size: 70%;
 6592: }
 6593: 
 6594: #LC_breadcrumbs {
 6595:   clear:both;
 6596:   background: $sidebg;
 6597:   border-bottom: 1px solid $lg_border_color;
 6598:   line-height: 2.5em;
 6599:   overflow: hidden;
 6600:   margin: 0;
 6601:   padding: 0;
 6602:   text-align: left;
 6603: }
 6604: 
 6605: .LC_head_subbox, .LC_actionbox {
 6606:   clear:both;
 6607:   background: #F8F8F8; /* $sidebg; */
 6608:   border: 1px solid $sidebg;
 6609:   margin: 0 0 10px 0;
 6610:   padding: 3px;
 6611:   text-align: left;
 6612: }
 6613: 
 6614: .LC_fontsize_medium {
 6615:   font-size: 85%;
 6616: }
 6617: 
 6618: .LC_fontsize_large {
 6619:   font-size: 120%;
 6620: }
 6621: 
 6622: .LC_menubuttons_inline_text {
 6623:   color: $font;
 6624:   font-size: 90%;
 6625:   padding-left:3px;
 6626: }
 6627: 
 6628: .LC_menubuttons_inline_text img{
 6629:   vertical-align: middle;
 6630: }
 6631: 
 6632: li.LC_menubuttons_inline_text img {
 6633:   cursor:pointer;
 6634:   text-decoration: none;
 6635: }
 6636: 
 6637: .LC_menubuttons_link {
 6638:   text-decoration: none;
 6639: }
 6640: 
 6641: .LC_menubuttons_category {
 6642:   color: $font;
 6643:   background: $pgbg;
 6644:   font-size: larger;
 6645:   font-weight: bold;
 6646: }
 6647: 
 6648: td.LC_menubuttons_text {
 6649:   color: $font;
 6650: }
 6651: 
 6652: .LC_current_location {
 6653:   background: $tabbg;
 6654: }
 6655: 
 6656: td.LC_zero_height {
 6657:   line-height: 0; 
 6658:   cellpadding: 0;
 6659: }
 6660: 
 6661: table.LC_data_table {
 6662:   border: 1px solid #000000;
 6663:   border-collapse: separate;
 6664:   border-spacing: 1px;
 6665:   background: $pgbg;
 6666: }
 6667: 
 6668: .LC_data_table_dense {
 6669:   font-size: small;
 6670: }
 6671: 
 6672: table.LC_nested_outer {
 6673:   border: 1px solid #000000;
 6674:   border-collapse: collapse;
 6675:   border-spacing: 0;
 6676:   width: 100%;
 6677: }
 6678: 
 6679: table.LC_innerpickbox,
 6680: table.LC_nested {
 6681:   border: none;
 6682:   border-collapse: collapse;
 6683:   border-spacing: 0;
 6684:   width: 100%;
 6685: }
 6686: 
 6687: table.LC_data_table tr th,
 6688: table.LC_calendar tr th,
 6689: table.LC_prior_tries tr th,
 6690: table.LC_innerpickbox tr th {
 6691:   font-weight: bold;
 6692:   background-color: $data_table_head;
 6693:   color:$fontmenu;
 6694:   font-size:90%;
 6695: }
 6696: 
 6697: table.LC_innerpickbox tr th,
 6698: table.LC_innerpickbox tr td {
 6699:   vertical-align: top;
 6700: }
 6701: 
 6702: table.LC_data_table tr.LC_info_row > td {
 6703:   background-color: #CCCCCC;
 6704:   font-weight: bold;
 6705:   text-align: left;
 6706: }
 6707: 
 6708: table.LC_data_table tr.LC_odd_row > td {
 6709:   background-color: $data_table_light;
 6710:   padding: 2px;
 6711:   vertical-align: top;
 6712: }
 6713: 
 6714: table.LC_pick_box tr > td.LC_odd_row {
 6715:   background-color: $data_table_light;
 6716:   vertical-align: top;
 6717: }
 6718: 
 6719: table.LC_data_table tr.LC_even_row > td {
 6720:   background-color: $data_table_dark;
 6721:   padding: 2px;
 6722:   vertical-align: top;
 6723: }
 6724: 
 6725: table.LC_pick_box tr > td.LC_even_row {
 6726:   background-color: $data_table_dark;
 6727:   vertical-align: top;
 6728: }
 6729: 
 6730: table.LC_data_table tr.LC_data_table_highlight td {
 6731:   background-color: $data_table_darker;
 6732: }
 6733: 
 6734: table.LC_data_table tr td.LC_leftcol_header {
 6735:   background-color: $data_table_head;
 6736:   font-weight: bold;
 6737: }
 6738: 
 6739: table.LC_data_table tr.LC_empty_row td,
 6740: table.LC_nested tr.LC_empty_row td {
 6741:   font-weight: bold;
 6742:   font-style: italic;
 6743:   text-align: center;
 6744:   padding: 8px;
 6745: }
 6746: 
 6747: table.LC_data_table tr.LC_empty_row td,
 6748: table.LC_data_table tr.LC_footer_row td {
 6749:   background-color: $sidebg;
 6750: }
 6751: 
 6752: table.LC_nested tr.LC_empty_row td {
 6753:   background-color: #FFFFFF;
 6754: }
 6755: 
 6756: table.LC_caption {
 6757: }
 6758: 
 6759: table.LC_nested tr.LC_empty_row td {
 6760:   padding: 4ex
 6761: }
 6762: 
 6763: table.LC_nested_outer tr th {
 6764:   font-weight: bold;
 6765:   color:$fontmenu;
 6766:   background-color: $data_table_head;
 6767:   font-size: small;
 6768:   border-bottom: 1px solid #000000;
 6769: }
 6770: 
 6771: table.LC_nested_outer tr td.LC_subheader {
 6772:   background-color: $data_table_head;
 6773:   font-weight: bold;
 6774:   font-size: small;
 6775:   border-bottom: 1px solid #000000;
 6776:   text-align: right;
 6777: }
 6778: 
 6779: table.LC_nested tr.LC_info_row td {
 6780:   background-color: #CCCCCC;
 6781:   font-weight: bold;
 6782:   font-size: small;
 6783:   text-align: center;
 6784: }
 6785: 
 6786: table.LC_nested tr.LC_info_row td.LC_left_item,
 6787: table.LC_nested_outer tr th.LC_left_item {
 6788:   text-align: left;
 6789: }
 6790: 
 6791: table.LC_nested td {
 6792:   background-color: #FFFFFF;
 6793:   font-size: small;
 6794: }
 6795: 
 6796: table.LC_nested_outer tr th.LC_right_item,
 6797: table.LC_nested tr.LC_info_row td.LC_right_item,
 6798: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6799: table.LC_nested tr td.LC_right_item {
 6800:   text-align: right;
 6801: }
 6802: 
 6803: table.LC_nested tr.LC_odd_row td {
 6804:   background-color: #EEEEEE;
 6805: }
 6806: 
 6807: table.LC_createuser {
 6808: }
 6809: 
 6810: table.LC_createuser tr.LC_section_row td {
 6811:   font-size: small;
 6812: }
 6813: 
 6814: table.LC_createuser tr.LC_info_row td  {
 6815:   background-color: #CCCCCC;
 6816:   font-weight: bold;
 6817:   text-align: center;
 6818: }
 6819: 
 6820: table.LC_calendar {
 6821:   border: 1px solid #000000;
 6822:   border-collapse: collapse;
 6823:   width: 98%;
 6824: }
 6825: 
 6826: table.LC_calendar_pickdate {
 6827:   font-size: xx-small;
 6828: }
 6829: 
 6830: table.LC_calendar tr td {
 6831:   border: 1px solid #000000;
 6832:   vertical-align: top;
 6833:   width: 14%;
 6834: }
 6835: 
 6836: table.LC_calendar tr td.LC_calendar_day_empty {
 6837:   background-color: $data_table_dark;
 6838: }
 6839: 
 6840: table.LC_calendar tr td.LC_calendar_day_current {
 6841:   background-color: $data_table_highlight;
 6842: }
 6843: 
 6844: table.LC_data_table tr td.LC_mail_new {
 6845:   background-color: $mail_new;
 6846: }
 6847: 
 6848: table.LC_data_table tr.LC_mail_new:hover {
 6849:   background-color: $mail_new_hover;
 6850: }
 6851: 
 6852: table.LC_data_table tr td.LC_mail_read {
 6853:   background-color: $mail_read;
 6854: }
 6855: 
 6856: /*
 6857: table.LC_data_table tr.LC_mail_read:hover {
 6858:   background-color: $mail_read_hover;
 6859: }
 6860: */
 6861: 
 6862: table.LC_data_table tr td.LC_mail_replied {
 6863:   background-color: $mail_replied;
 6864: }
 6865: 
 6866: /*
 6867: table.LC_data_table tr.LC_mail_replied:hover {
 6868:   background-color: $mail_replied_hover;
 6869: }
 6870: */
 6871: 
 6872: table.LC_data_table tr td.LC_mail_other {
 6873:   background-color: $mail_other;
 6874: }
 6875: 
 6876: /*
 6877: table.LC_data_table tr.LC_mail_other:hover {
 6878:   background-color: $mail_other_hover;
 6879: }
 6880: */
 6881: 
 6882: table.LC_data_table tr > td.LC_browser_file,
 6883: table.LC_data_table tr > td.LC_browser_file_published {
 6884:   background: #AAEE77;
 6885: }
 6886: 
 6887: table.LC_data_table tr > td.LC_browser_file_locked,
 6888: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6889:   background: #FFAA99;
 6890: }
 6891: 
 6892: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6893:   background: #888888;
 6894: }
 6895: 
 6896: table.LC_data_table tr > td.LC_browser_file_modified,
 6897: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6898:   background: #F8F866;
 6899: }
 6900: 
 6901: table.LC_data_table tr.LC_browser_folder > td {
 6902:   background: #E0E8FF;
 6903: }
 6904: 
 6905: table.LC_data_table tr > td.LC_roles_is {
 6906:   /* background: #77FF77; */
 6907: }
 6908: 
 6909: table.LC_data_table tr > td.LC_roles_future {
 6910:   border-right: 8px solid #FFFF77;
 6911: }
 6912: 
 6913: table.LC_data_table tr > td.LC_roles_will {
 6914:   border-right: 8px solid #FFAA77;
 6915: }
 6916: 
 6917: table.LC_data_table tr > td.LC_roles_expired {
 6918:   border-right: 8px solid #FF7777;
 6919: }
 6920: 
 6921: table.LC_data_table tr > td.LC_roles_will_not {
 6922:   border-right: 8px solid #AAFF77;
 6923: }
 6924: 
 6925: table.LC_data_table tr > td.LC_roles_selected {
 6926:   border-right: 8px solid #11CC55;
 6927: }
 6928: 
 6929: span.LC_current_location {
 6930:   font-size:larger;
 6931:   background: $pgbg;
 6932: }
 6933: 
 6934: span.LC_current_nav_location {
 6935:   font-weight:bold;
 6936:   background: $sidebg;
 6937: }
 6938: 
 6939: span.LC_parm_menu_item {
 6940:   font-size: larger;
 6941: }
 6942: 
 6943: span.LC_parm_scope_all {
 6944:   color: red;
 6945: }
 6946: 
 6947: span.LC_parm_scope_folder {
 6948:   color: green;
 6949: }
 6950: 
 6951: span.LC_parm_scope_resource {
 6952:   color: orange;
 6953: }
 6954: 
 6955: span.LC_parm_part {
 6956:   color: blue;
 6957: }
 6958: 
 6959: span.LC_parm_folder,
 6960: span.LC_parm_symb {
 6961:   font-size: x-small;
 6962:   font-family: $mono;
 6963:   color: #AAAAAA;
 6964: }
 6965: 
 6966: ul.LC_parm_parmlist li {
 6967:   display: inline-block;
 6968:   padding: 0.3em 0.8em;
 6969:   vertical-align: top;
 6970:   width: 150px;
 6971:   border-top:1px solid $lg_border_color;
 6972: }
 6973: 
 6974: td.LC_parm_overview_level_menu,
 6975: td.LC_parm_overview_map_menu,
 6976: td.LC_parm_overview_parm_selectors,
 6977: td.LC_parm_overview_restrictions  {
 6978:   border: 1px solid black;
 6979:   border-collapse: collapse;
 6980: }
 6981: 
 6982: span.LC_parm_recursive,
 6983: td.LC_parm_recursive {
 6984:   font-weight: bold;
 6985:   font-size: smaller;
 6986: }
 6987: 
 6988: table.LC_parm_overview_restrictions td {
 6989:   border-width: 1px 4px 1px 4px;
 6990:   border-style: solid;
 6991:   border-color: $pgbg;
 6992:   text-align: center;
 6993: }
 6994: 
 6995: table.LC_parm_overview_restrictions th {
 6996:   background: $tabbg;
 6997:   border-width: 1px 4px 1px 4px;
 6998:   border-style: solid;
 6999:   border-color: $pgbg;
 7000: }
 7001: 
 7002: table#LC_helpmenu {
 7003:   border: none;
 7004:   height: 55px;
 7005:   border-spacing: 0;
 7006: }
 7007: 
 7008: table#LC_helpmenu fieldset legend {
 7009:   font-size: larger;
 7010: }
 7011: 
 7012: table#LC_helpmenu_links {
 7013:   width: 100%;
 7014:   border: 1px solid black;
 7015:   background: $pgbg;
 7016:   padding: 0;
 7017:   border-spacing: 1px;
 7018: }
 7019: 
 7020: table#LC_helpmenu_links tr td {
 7021:   padding: 1px;
 7022:   background: $tabbg;
 7023:   text-align: center;
 7024:   font-weight: bold;
 7025: }
 7026: 
 7027: table#LC_helpmenu_links a:link,
 7028: table#LC_helpmenu_links a:visited,
 7029: table#LC_helpmenu_links a:active {
 7030:   text-decoration: none;
 7031:   color: $font;
 7032: }
 7033: 
 7034: table#LC_helpmenu_links a:hover {
 7035:   text-decoration: underline;
 7036:   color: $vlink;
 7037: }
 7038: 
 7039: .LC_chrt_popup_exists {
 7040:   border: 1px solid #339933;
 7041:   margin: -1px;
 7042: }
 7043: 
 7044: .LC_chrt_popup_up {
 7045:   border: 1px solid yellow;
 7046:   margin: -1px;
 7047: }
 7048: 
 7049: .LC_chrt_popup {
 7050:   border: 1px solid #8888FF;
 7051:   background: #CCCCFF;
 7052: }
 7053: 
 7054: table.LC_pick_box {
 7055:   border-collapse: separate;
 7056:   background: white;
 7057:   border: 1px solid black;
 7058:   border-spacing: 1px;
 7059: }
 7060: 
 7061: table.LC_pick_box td.LC_pick_box_title {
 7062:   background: $sidebg;
 7063:   font-weight: bold;
 7064:   text-align: left;
 7065:   vertical-align: top;
 7066:   width: 184px;
 7067:   padding: 8px;
 7068: }
 7069: 
 7070: table.LC_pick_box td.LC_pick_box_value {
 7071:   text-align: left;
 7072:   padding: 8px;
 7073: }
 7074: 
 7075: table.LC_pick_box td.LC_pick_box_select {
 7076:   text-align: left;
 7077:   padding: 8px;
 7078: }
 7079: 
 7080: table.LC_pick_box td.LC_pick_box_separator {
 7081:   padding: 0;
 7082:   height: 1px;
 7083:   background: black;
 7084: }
 7085: 
 7086: table.LC_pick_box td.LC_pick_box_submit {
 7087:   text-align: right;
 7088: }
 7089: 
 7090: table.LC_pick_box td.LC_evenrow_value {
 7091:   text-align: left;
 7092:   padding: 8px;
 7093:   background-color: $data_table_light;
 7094: }
 7095: 
 7096: table.LC_pick_box td.LC_oddrow_value {
 7097:   text-align: left;
 7098:   padding: 8px;
 7099:   background-color: $data_table_light;
 7100: }
 7101: 
 7102: span.LC_helpform_receipt_cat {
 7103:   font-weight: bold;
 7104: }
 7105: 
 7106: table.LC_group_priv_box {
 7107:   background: white;
 7108:   border: 1px solid black;
 7109:   border-spacing: 1px;
 7110: }
 7111: 
 7112: table.LC_group_priv_box td.LC_pick_box_title {
 7113:   background: $tabbg;
 7114:   font-weight: bold;
 7115:   text-align: right;
 7116:   width: 184px;
 7117: }
 7118: 
 7119: table.LC_group_priv_box td.LC_groups_fixed {
 7120:   background: $data_table_light;
 7121:   text-align: center;
 7122: }
 7123: 
 7124: table.LC_group_priv_box td.LC_groups_optional {
 7125:   background: $data_table_dark;
 7126:   text-align: center;
 7127: }
 7128: 
 7129: table.LC_group_priv_box td.LC_groups_functionality {
 7130:   background: $data_table_darker;
 7131:   text-align: center;
 7132:   font-weight: bold;
 7133: }
 7134: 
 7135: table.LC_group_priv td {
 7136:   text-align: left;
 7137:   padding: 0;
 7138: }
 7139: 
 7140: .LC_navbuttons {
 7141:   margin: 2ex 0ex 2ex 0ex;
 7142: }
 7143: 
 7144: .LC_topic_bar {
 7145:   font-weight: bold;
 7146:   background: $tabbg;
 7147:   margin: 1em 0em 1em 2em;
 7148:   padding: 3px;
 7149:   font-size: 1.2em;
 7150: }
 7151: 
 7152: .LC_topic_bar span {
 7153:   left: 0.5em;
 7154:   position: absolute;
 7155:   vertical-align: middle;
 7156:   font-size: 1.2em;
 7157: }
 7158: 
 7159: table.LC_course_group_status {
 7160:   margin: 20px;
 7161: }
 7162: 
 7163: table.LC_status_selector td {
 7164:   vertical-align: top;
 7165:   text-align: center;
 7166:   padding: 4px;
 7167: }
 7168: 
 7169: div.LC_feedback_link {
 7170:   clear: both;
 7171:   background: $sidebg;
 7172:   width: 100%;
 7173:   padding-bottom: 10px;
 7174:   border: 1px $tabbg solid;
 7175:   height: 22px;
 7176:   line-height: 22px;
 7177:   padding-top: 5px;
 7178: }
 7179: 
 7180: div.LC_feedback_link img {
 7181:   height: 22px;
 7182:   vertical-align:middle;
 7183: }
 7184: 
 7185: div.LC_feedback_link a {
 7186:   text-decoration: none;
 7187: }
 7188: 
 7189: div.LC_comblock {
 7190:   display:inline;
 7191:   color:$font;
 7192:   font-size:90%;
 7193: }
 7194: 
 7195: div.LC_feedback_link div.LC_comblock {
 7196:   padding-left:5px;
 7197: }
 7198: 
 7199: div.LC_feedback_link div.LC_comblock a {
 7200:   color:$font;
 7201: }
 7202: 
 7203: span.LC_feedback_link {
 7204:   /* background: $feedback_link_bg; */
 7205:   font-size: larger;
 7206: }
 7207: 
 7208: span.LC_message_link {
 7209:   /* background: $feedback_link_bg; */
 7210:   font-size: larger;
 7211:   position: absolute;
 7212:   right: 1em;
 7213: }
 7214: 
 7215: table.LC_prior_tries {
 7216:   border: 1px solid #000000;
 7217:   border-collapse: separate;
 7218:   border-spacing: 1px;
 7219: }
 7220: 
 7221: table.LC_prior_tries td {
 7222:   padding: 2px;
 7223: }
 7224: 
 7225: .LC_answer_correct {
 7226:   background: lightgreen;
 7227:   color: darkgreen;
 7228:   padding: 6px;
 7229: }
 7230: 
 7231: .LC_answer_charged_try {
 7232:   background: #FFAAAA;
 7233:   color: darkred;
 7234:   padding: 6px;
 7235: }
 7236: 
 7237: .LC_answer_not_charged_try,
 7238: .LC_answer_no_grade,
 7239: .LC_answer_late {
 7240:   background: lightyellow;
 7241:   color: black;
 7242:   padding: 6px;
 7243: }
 7244: 
 7245: .LC_answer_previous {
 7246:   background: lightblue;
 7247:   color: darkblue;
 7248:   padding: 6px;
 7249: }
 7250: 
 7251: .LC_answer_no_message {
 7252:   background: #FFFFFF;
 7253:   color: black;
 7254:   padding: 6px;
 7255: }
 7256: 
 7257: .LC_answer_unknown {
 7258:   background: orange;
 7259:   color: black;
 7260:   padding: 6px;
 7261: }
 7262: 
 7263: span.LC_prior_numerical,
 7264: span.LC_prior_string,
 7265: span.LC_prior_custom,
 7266: span.LC_prior_reaction,
 7267: span.LC_prior_math {
 7268:   font-family: $mono;
 7269:   white-space: pre;
 7270: }
 7271: 
 7272: span.LC_prior_string {
 7273:   font-family: $mono;
 7274:   white-space: pre;
 7275: }
 7276: 
 7277: table.LC_prior_option {
 7278:   width: 100%;
 7279:   border-collapse: collapse;
 7280: }
 7281: 
 7282: table.LC_prior_rank,
 7283: table.LC_prior_match {
 7284:   border-collapse: collapse;
 7285: }
 7286: 
 7287: table.LC_prior_option tr td,
 7288: table.LC_prior_rank tr td,
 7289: table.LC_prior_match tr td {
 7290:   border: 1px solid #000000;
 7291: }
 7292: 
 7293: .LC_nobreak {
 7294:   white-space: nowrap;
 7295: }
 7296: 
 7297: span.LC_cusr_emph {
 7298:   font-style: italic;
 7299: }
 7300: 
 7301: span.LC_cusr_subheading {
 7302:   font-weight: normal;
 7303:   font-size: 85%;
 7304: }
 7305: 
 7306: div.LC_docs_entry_move {
 7307:   border: 1px solid #BBBBBB;
 7308:   background: #DDDDDD;
 7309:   width: 22px;
 7310:   padding: 1px;
 7311:   margin: 0;
 7312: }
 7313: 
 7314: table.LC_data_table tr > td.LC_docs_entry_commands,
 7315: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7316:   font-size: x-small;
 7317: }
 7318: 
 7319: .LC_docs_entry_parameter {
 7320:   white-space: nowrap;
 7321: }
 7322: 
 7323: .LC_docs_copy {
 7324:   color: #000099;
 7325: }
 7326: 
 7327: .LC_docs_cut {
 7328:   color: #550044;
 7329: }
 7330: 
 7331: .LC_docs_rename {
 7332:   color: #009900;
 7333: }
 7334: 
 7335: .LC_docs_remove {
 7336:   color: #990000;
 7337: }
 7338: 
 7339: .LC_docs_alias {
 7340:   color: #440055;  
 7341: }
 7342: 
 7343: .LC_domprefs_email,
 7344: .LC_docs_alias_name,
 7345: .LC_docs_reinit_warn,
 7346: .LC_docs_ext_edit {
 7347:   font-size: x-small;
 7348: }
 7349: 
 7350: table.LC_docs_adddocs td,
 7351: table.LC_docs_adddocs th {
 7352:   border: 1px solid #BBBBBB;
 7353:   padding: 4px;
 7354:   background: #DDDDDD;
 7355: }
 7356: 
 7357: table.LC_sty_begin {
 7358:   background: #BBFFBB;
 7359: }
 7360: 
 7361: table.LC_sty_end {
 7362:   background: #FFBBBB;
 7363: }
 7364: 
 7365: table.LC_double_column {
 7366:   border-width: 0;
 7367:   border-collapse: collapse;
 7368:   width: 100%;
 7369:   padding: 2px;
 7370: }
 7371: 
 7372: table.LC_double_column tr td.LC_left_col {
 7373:   top: 2px;
 7374:   left: 2px;
 7375:   width: 47%;
 7376:   vertical-align: top;
 7377: }
 7378: 
 7379: table.LC_double_column tr td.LC_right_col {
 7380:   top: 2px;
 7381:   right: 2px;
 7382:   width: 47%;
 7383:   vertical-align: top;
 7384: }
 7385: 
 7386: div.LC_left_float {
 7387:   float: left;
 7388:   padding-right: 5%;
 7389:   padding-bottom: 4px;
 7390: }
 7391: 
 7392: div.LC_clear_float_header {
 7393:   padding-bottom: 2px;
 7394: }
 7395: 
 7396: div.LC_clear_float_footer {
 7397:   padding-top: 10px;
 7398:   clear: both;
 7399: }
 7400: 
 7401: div.LC_grade_show_user {
 7402: /*  border-left: 5px solid $sidebg; */
 7403:   border-top: 5px solid #000000;
 7404:   margin: 50px 0 0 0;
 7405:   padding: 15px 0 5px 10px;
 7406: }
 7407: 
 7408: div.LC_grade_show_user_odd_row {
 7409: /*  border-left: 5px solid #000000; */
 7410: }
 7411: 
 7412: div.LC_grade_show_user div.LC_Box {
 7413:   margin-right: 50px;
 7414: }
 7415: 
 7416: div.LC_grade_submissions,
 7417: div.LC_grade_message_center,
 7418: div.LC_grade_info_links {
 7419:   margin: 5px;
 7420:   width: 99%;
 7421:   background: #FFFFFF;
 7422: }
 7423: 
 7424: div.LC_grade_submissions_header,
 7425: div.LC_grade_message_center_header {
 7426:   font-weight: bold;
 7427:   font-size: large;
 7428: }
 7429: 
 7430: div.LC_grade_submissions_body,
 7431: div.LC_grade_message_center_body {
 7432:   border: 1px solid black;
 7433:   width: 99%;
 7434:   background: #FFFFFF;
 7435: }
 7436: 
 7437: table.LC_scantron_action {
 7438:   width: 100%;
 7439: }
 7440: 
 7441: table.LC_scantron_action tr th {
 7442:   font-weight:bold;
 7443:   font-style:normal;
 7444: }
 7445: 
 7446: .LC_edit_problem_header,
 7447: div.LC_edit_problem_footer {
 7448:   font-weight: normal;
 7449:   font-size:  medium;
 7450:   margin: 2px;
 7451:   background-color: $sidebg;
 7452: }
 7453: 
 7454: div.LC_edit_problem_header,
 7455: div.LC_edit_problem_header div,
 7456: div.LC_edit_problem_footer,
 7457: div.LC_edit_problem_footer div,
 7458: div.LC_edit_problem_editxml_header,
 7459: div.LC_edit_problem_editxml_header div {
 7460:   z-index: 100;
 7461: }
 7462: 
 7463: div.LC_edit_problem_header_title {
 7464:   font-weight: bold;
 7465:   font-size: larger;
 7466:   background: $tabbg;
 7467:   padding: 3px;
 7468:   margin: 0 0 5px 0;
 7469: }
 7470: 
 7471: table.LC_edit_problem_header_title {
 7472:   width: 100%;
 7473:   background: $tabbg;
 7474: }
 7475: 
 7476: div.LC_edit_actionbar {
 7477:     background-color: $sidebg;
 7478:     margin: 0;
 7479:     padding: 0;
 7480:     line-height: 200%;
 7481: }
 7482: 
 7483: div.LC_edit_actionbar div{
 7484:     padding: 0;
 7485:     margin: 0;
 7486:     display: inline-block;
 7487: }
 7488: 
 7489: .LC_edit_opt {
 7490:   padding-left: 1em;
 7491:   white-space: nowrap;
 7492: }
 7493: 
 7494: .LC_edit_problem_latexhelper{
 7495:     text-align: right;
 7496: }
 7497: 
 7498: #LC_edit_problem_colorful div{
 7499:     margin-left: 40px;
 7500: }
 7501: 
 7502: #LC_edit_problem_codemirror div{
 7503:     margin-left: 0px;
 7504: }
 7505: 
 7506: img.stift {
 7507:   border-width: 0;
 7508:   vertical-align: middle;
 7509: }
 7510: 
 7511: table td.LC_mainmenu_col_fieldset {
 7512:   vertical-align: top;
 7513: }
 7514: 
 7515: div.LC_createcourse {
 7516:   margin: 10px 10px 10px 10px;
 7517: }
 7518: 
 7519: .LC_dccid {
 7520:   float: right;
 7521:   margin: 0.2em 0 0 0;
 7522:   padding: 0;
 7523:   font-size: 90%;
 7524:   display:none;
 7525: }
 7526: 
 7527: ol.LC_primary_menu a:hover,
 7528: ol#LC_MenuBreadcrumbs a:hover,
 7529: ol#LC_PathBreadcrumbs a:hover,
 7530: ul#LC_secondary_menu a:hover,
 7531: .LC_FormSectionClearButton input:hover
 7532: ul.LC_TabContent   li:hover a {
 7533:   color:$button_hover;
 7534:   text-decoration:none;
 7535: }
 7536: 
 7537: h1 {
 7538:   padding: 0;
 7539:   line-height:130%;
 7540: }
 7541: 
 7542: h2,
 7543: h3,
 7544: h4,
 7545: h5,
 7546: h6 {
 7547:   margin: 5px 0 5px 0;
 7548:   padding: 0;
 7549:   line-height:130%;
 7550: }
 7551: 
 7552: .LC_hcell {
 7553:   padding:3px 15px 3px 15px;
 7554:   margin: 0;
 7555:   background-color:$tabbg;
 7556:   color:$fontmenu;
 7557:   border-bottom:solid 1px $lg_border_color;
 7558: }
 7559: 
 7560: .LC_Box > .LC_hcell {
 7561:   margin: 0 -10px 10px -10px;
 7562: }
 7563: 
 7564: .LC_noBorder {
 7565:   border: 0;
 7566: }
 7567: 
 7568: .LC_FormSectionClearButton input {
 7569:   background-color:transparent;
 7570:   border: none;
 7571:   cursor:pointer;
 7572:   text-decoration:underline;
 7573: }
 7574: 
 7575: .LC_help_open_topic {
 7576:   color: #FFFFFF;
 7577:   background-color: #EEEEFF;
 7578:   margin: 1px;
 7579:   padding: 4px;
 7580:   border: 1px solid #000033;
 7581:   white-space: nowrap;
 7582:   /* vertical-align: middle; */
 7583: }
 7584: 
 7585: dl,
 7586: ul,
 7587: div,
 7588: fieldset {
 7589:   margin: 10px 10px 10px 0;
 7590:   /* overflow: hidden; */
 7591: }
 7592: 
 7593: article.geogebraweb div {
 7594:     margin: 0;
 7595: }
 7596: 
 7597: fieldset > legend {
 7598:   font-weight: bold;
 7599:   padding: 0 5px 0 5px;
 7600: }
 7601: 
 7602: #LC_nav_bar {
 7603:   float: left;
 7604:   background-color: $pgbg_or_bgcolor;
 7605:   margin: 0 0 2px 0;
 7606: }
 7607: 
 7608: #LC_realm {
 7609:   margin: 0.2em 0 0 0;
 7610:   padding: 0;
 7611:   font-weight: bold;
 7612:   text-align: center;
 7613:   background-color: $pgbg_or_bgcolor;
 7614: }
 7615: 
 7616: #LC_nav_bar em {
 7617:   font-weight: bold;
 7618:   font-style: normal;
 7619: }
 7620: 
 7621: ol.LC_primary_menu {
 7622:   margin: 0;
 7623:   padding: 0;
 7624: }
 7625: 
 7626: ol#LC_PathBreadcrumbs {
 7627:   margin: 0;
 7628: }
 7629: 
 7630: ol.LC_primary_menu li {
 7631:   color: RGB(80, 80, 80);
 7632:   vertical-align: middle;
 7633:   text-align: left;
 7634:   list-style: none;
 7635:   position: relative;
 7636:   float: left;
 7637:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7638:   line-height: 1.5em;
 7639: }
 7640: 
 7641: ol.LC_primary_menu li a,
 7642: ol.LC_primary_menu li p {
 7643:   display: block;
 7644:   margin: 0;
 7645:   padding: 0 5px 0 10px;
 7646:   text-decoration: none;
 7647: }
 7648: 
 7649: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7650:   display: inline-block;
 7651:   width: 95%;
 7652:   text-align: left;
 7653: }
 7654: 
 7655: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7656:   display: inline-block;	
 7657:   width: 5%;
 7658:   float: right;
 7659:   text-align: right;
 7660:   font-size: 70%;
 7661: }
 7662: 
 7663: ol.LC_primary_menu ul {
 7664:   display: none;
 7665:   width: 15em;
 7666:   background-color: $data_table_light;
 7667:   position: absolute;
 7668:   top: 100%;
 7669: }
 7670: 
 7671: ol.LC_primary_menu ul ul {
 7672:   left: 100%;
 7673:   top: 0;
 7674: }
 7675: 
 7676: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7677:   display: block;
 7678:   position: absolute;
 7679:   margin: 0;
 7680:   padding: 0;
 7681:   z-index: 2;
 7682: }
 7683: 
 7684: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7685: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7686:   font-size: 90%;
 7687:   vertical-align: top;
 7688:   float: none;
 7689:   border-left: 1px solid black;
 7690:   border-right: 1px solid black;
 7691: /* A dark bottom border to visualize different menu options; 
 7692: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7693:   border-bottom: 1px solid $data_table_dark; 
 7694: }
 7695: 
 7696: ol.LC_primary_menu li li p:hover {
 7697:   color:$button_hover;
 7698:   text-decoration:none;
 7699:   background-color:$data_table_dark;
 7700: }
 7701: 
 7702: ol.LC_primary_menu li li a:hover {
 7703:    color:$button_hover;
 7704:    background-color:$data_table_dark;
 7705: }
 7706: 
 7707: /* Font-size equal to the size of the predecessors*/
 7708: ol.LC_primary_menu li:hover li li {
 7709:   font-size: 100%;
 7710: }
 7711: 
 7712: ol.LC_primary_menu li img {
 7713:   vertical-align: bottom;
 7714:   height: 1.1em;
 7715:   margin: 0.2em 0 0 0;
 7716: }
 7717: 
 7718: ol.LC_primary_menu a {
 7719:   color: RGB(80, 80, 80);
 7720:   text-decoration: none;
 7721: }
 7722: 
 7723: ol.LC_primary_menu a.LC_new_message {
 7724:   font-weight:bold;
 7725:   color: darkred;
 7726: }
 7727: 
 7728: ol.LC_docs_parameters {
 7729:   margin-left: 0;
 7730:   padding: 0;
 7731:   list-style: none;
 7732: }
 7733: 
 7734: ol.LC_docs_parameters li {
 7735:   margin: 0;
 7736:   padding-right: 20px;
 7737:   display: inline;
 7738: }
 7739: 
 7740: ol.LC_docs_parameters li:before {
 7741:   content: "\\002022 \\0020";
 7742: }
 7743: 
 7744: li.LC_docs_parameters_title {
 7745:   font-weight: bold;
 7746: }
 7747: 
 7748: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7749:   content: "";
 7750: }
 7751: 
 7752: ul#LC_secondary_menu {
 7753:   clear: right;
 7754:   color: $fontmenu;
 7755:   background: $tabbg;
 7756:   list-style: none;
 7757:   padding: 0;
 7758:   margin: 0;
 7759:   width: 100%;
 7760:   text-align: left;
 7761:   float: left;
 7762: }
 7763: 
 7764: ul#LC_secondary_menu li {
 7765:   font-weight: bold;
 7766:   line-height: 1.8em;
 7767:   border-right: 1px solid black;
 7768:   float: left;
 7769: }
 7770: 
 7771: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7772:   background-color: $data_table_light;
 7773: }
 7774: 
 7775: ul#LC_secondary_menu li a {
 7776:   padding: 0 0.8em;
 7777: }
 7778: 
 7779: ul#LC_secondary_menu li ul {
 7780:   display: none;
 7781: }
 7782: 
 7783: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7784:   display: block;
 7785:   position: absolute;
 7786:   margin: 0;
 7787:   padding: 0;
 7788:   list-style:none;
 7789:   float: none;
 7790:   background-color: $data_table_light;
 7791:   z-index: 2;
 7792:   margin-left: -1px;
 7793: }
 7794: 
 7795: ul#LC_secondary_menu li ul li {
 7796:   font-size: 90%;
 7797:   vertical-align: top;
 7798:   border-left: 1px solid black;
 7799:   border-right: 1px solid black;
 7800:   background-color: $data_table_light;
 7801:   list-style:none;
 7802:   float: none;
 7803: }
 7804: 
 7805: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7806:   background-color: $data_table_dark;
 7807: }
 7808: 
 7809: ul.LC_TabContent {
 7810:   display:block;
 7811:   background: $sidebg;
 7812:   border-bottom: solid 1px $lg_border_color;
 7813:   list-style:none;
 7814:   margin: -1px -10px 0 -10px;
 7815:   padding: 0;
 7816: }
 7817: 
 7818: ul.LC_TabContent li,
 7819: ul.LC_TabContentBigger li {
 7820:   float:left;
 7821: }
 7822: 
 7823: ul#LC_secondary_menu li a {
 7824:   color: $fontmenu;
 7825:   text-decoration: none;
 7826: }
 7827: 
 7828: ul.LC_TabContent {
 7829:   min-height:20px;
 7830: }
 7831: 
 7832: ul.LC_TabContent li {
 7833:   vertical-align:middle;
 7834:   padding: 0 16px 0 10px;
 7835:   background-color:$tabbg;
 7836:   border-bottom:solid 1px $lg_border_color;
 7837:   border-left: solid 1px $font;
 7838: }
 7839: 
 7840: ul.LC_TabContent .right {
 7841:   float:right;
 7842: }
 7843: 
 7844: ul.LC_TabContent li a,
 7845: ul.LC_TabContent li {
 7846:   color:rgb(47,47,47);
 7847:   text-decoration:none;
 7848:   font-size:95%;
 7849:   font-weight:bold;
 7850:   min-height:20px;
 7851: }
 7852: 
 7853: ul.LC_TabContent li a:hover,
 7854: ul.LC_TabContent li a:focus {
 7855:   color: $button_hover;
 7856:   background:none;
 7857:   outline:none;
 7858: }
 7859: 
 7860: ul.LC_TabContent li:hover {
 7861:   color: $button_hover;
 7862:   cursor:pointer;
 7863: }
 7864: 
 7865: ul.LC_TabContent li.active {
 7866:   color: $font;
 7867:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7868:   border-bottom:solid 1px #FFFFFF;
 7869:   cursor: default;
 7870: }
 7871: 
 7872: ul.LC_TabContent li.active a {
 7873:   color:$font;
 7874:   background:#FFFFFF;
 7875:   outline: none;
 7876: }
 7877: 
 7878: ul.LC_TabContent li.goback {
 7879:   float: left;
 7880:   border-left: none;
 7881: }
 7882: 
 7883: #maincoursedoc {
 7884:   clear:both;
 7885: }
 7886: 
 7887: ul.LC_TabContentBigger {
 7888:   display:block;
 7889:   list-style:none;
 7890:   padding: 0;
 7891: }
 7892: 
 7893: ul.LC_TabContentBigger li {
 7894:   vertical-align:bottom;
 7895:   height: 30px;
 7896:   font-size:110%;
 7897:   font-weight:bold;
 7898:   color: #737373;
 7899: }
 7900: 
 7901: ul.LC_TabContentBigger li.active {
 7902:   position: relative;
 7903:   top: 1px;
 7904: }
 7905: 
 7906: ul.LC_TabContentBigger li a {
 7907:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7908:   height: 30px;
 7909:   line-height: 30px;
 7910:   text-align: center;
 7911:   display: block;
 7912:   text-decoration: none;
 7913:   outline: none;  
 7914: }
 7915: 
 7916: ul.LC_TabContentBigger li.active a {
 7917:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7918:   color:$font;
 7919: }
 7920: 
 7921: ul.LC_TabContentBigger li b {
 7922:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7923:   display: block;
 7924:   float: left;
 7925:   padding: 0 30px;
 7926:   border-bottom: 1px solid $lg_border_color;
 7927: }
 7928: 
 7929: ul.LC_TabContentBigger li:hover b {
 7930:   color:$button_hover;
 7931: }
 7932: 
 7933: ul.LC_TabContentBigger li.active b {
 7934:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7935:   color:$font;
 7936:   border: 0;
 7937: }
 7938: 
 7939: 
 7940: ul.LC_CourseBreadcrumbs {
 7941:   background: $sidebg;
 7942:   height: 2em;
 7943:   padding-left: 10px;
 7944:   margin: 0;
 7945:   list-style-position: inside;
 7946: }
 7947: 
 7948: ol#LC_MenuBreadcrumbs,
 7949: ol#LC_PathBreadcrumbs {
 7950:   padding-left: 10px;
 7951:   margin: 0;
 7952:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7953: }
 7954: 
 7955: ol#LC_MenuBreadcrumbs li,
 7956: ol#LC_PathBreadcrumbs li,
 7957: ul.LC_CourseBreadcrumbs li {
 7958:   display: inline;
 7959:   white-space: normal;  
 7960: }
 7961: 
 7962: ol#LC_MenuBreadcrumbs li a,
 7963: ul.LC_CourseBreadcrumbs li a {
 7964:   text-decoration: none;
 7965:   font-size:90%;
 7966: }
 7967: 
 7968: ol#LC_MenuBreadcrumbs h1 {
 7969:   display: inline;
 7970:   font-size: 90%;
 7971:   line-height: 2.5em;
 7972:   margin: 0;
 7973:   padding: 0;
 7974: }
 7975: 
 7976: ol#LC_PathBreadcrumbs li a {
 7977:   text-decoration:none;
 7978:   font-size:100%;
 7979:   font-weight:bold;
 7980: }
 7981: 
 7982: .LC_Box {
 7983:   border: solid 1px $lg_border_color;
 7984:   padding: 0 10px 10px 10px;
 7985: }
 7986: 
 7987: .LC_DocsBox {
 7988:   border: solid 1px $lg_border_color;
 7989:   padding: 0 0 10px 10px;
 7990: }
 7991: 
 7992: .LC_AboutMe_Image {
 7993:   float:left;
 7994:   margin-right:10px;
 7995: }
 7996: 
 7997: .LC_Clear_AboutMe_Image {
 7998:   clear:left;
 7999: }
 8000: 
 8001: dl.LC_ListStyleClean dt {
 8002:   padding-right: 5px;
 8003:   display: table-header-group;
 8004: }
 8005: 
 8006: dl.LC_ListStyleClean dd {
 8007:   display: table-row;
 8008: }
 8009: 
 8010: .LC_ListStyleClean,
 8011: .LC_ListStyleSimple,
 8012: .LC_ListStyleNormal,
 8013: .LC_ListStyleSpecial {
 8014:   /* display:block; */
 8015:   list-style-position: inside;
 8016:   list-style-type: none;
 8017:   overflow: hidden;
 8018:   padding: 0;
 8019: }
 8020: 
 8021: .LC_ListStyleSimple li,
 8022: .LC_ListStyleSimple dd,
 8023: .LC_ListStyleNormal li,
 8024: .LC_ListStyleNormal dd,
 8025: .LC_ListStyleSpecial li,
 8026: .LC_ListStyleSpecial dd {
 8027:   margin: 0;
 8028:   padding: 5px 5px 5px 10px;
 8029:   clear: both;
 8030: }
 8031: 
 8032: .LC_ListStyleClean li,
 8033: .LC_ListStyleClean dd {
 8034:   padding-top: 0;
 8035:   padding-bottom: 0;
 8036: }
 8037: 
 8038: .LC_ListStyleSimple dd,
 8039: .LC_ListStyleSimple li {
 8040:   border-bottom: solid 1px $lg_border_color;
 8041: }
 8042: 
 8043: .LC_ListStyleSpecial li,
 8044: .LC_ListStyleSpecial dd {
 8045:   list-style-type: none;
 8046:   background-color: RGB(220, 220, 220);
 8047:   margin-bottom: 4px;
 8048: }
 8049: 
 8050: table.LC_SimpleTable {
 8051:   margin:5px;
 8052:   border:solid 1px $lg_border_color;
 8053: }
 8054: 
 8055: table.LC_SimpleTable tr {
 8056:   padding: 0;
 8057:   border:solid 1px $lg_border_color;
 8058: }
 8059: 
 8060: table.LC_SimpleTable thead {
 8061:   background:rgb(220,220,220);
 8062: }
 8063: 
 8064: div.LC_columnSection {
 8065:   display: block;
 8066:   clear: both;
 8067:   overflow: hidden;
 8068:   margin: 0;
 8069: }
 8070: 
 8071: div.LC_columnSection>* {
 8072:   float: left;
 8073:   margin: 10px 20px 10px 0;
 8074:   overflow:hidden;
 8075: }
 8076: 
 8077: table em {
 8078:   font-weight: bold;
 8079:   font-style: normal;
 8080: }
 8081: 
 8082: table.LC_tableBrowseRes,
 8083: table.LC_tableOfContent {
 8084:   border:none;
 8085:   border-spacing: 1px;
 8086:   padding: 3px;
 8087:   background-color: #FFFFFF;
 8088:   font-size: 90%;
 8089: }
 8090: 
 8091: table.LC_tableOfContent {
 8092:   border-collapse: collapse;
 8093: }
 8094: 
 8095: table.LC_tableBrowseRes a,
 8096: table.LC_tableOfContent a {
 8097:   background-color: transparent;
 8098:   text-decoration: none;
 8099: }
 8100: 
 8101: table.LC_tableOfContent img {
 8102:   border: none;
 8103:   height: 1.3em;
 8104:   vertical-align: text-bottom;
 8105:   margin-right: 0.3em;
 8106: }
 8107: 
 8108: a#LC_content_toolbar_firsthomework {
 8109:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8110: }
 8111: 
 8112: a#LC_content_toolbar_everything {
 8113:   background-image:url(/res/adm/pages/show-all.gif);
 8114: }
 8115: 
 8116: a#LC_content_toolbar_uncompleted {
 8117:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8118: }
 8119: 
 8120: #LC_content_toolbar_clearbubbles {
 8121:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8122: }
 8123: 
 8124: a#LC_content_toolbar_changefolder {
 8125:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8126: }
 8127: 
 8128: a#LC_content_toolbar_changefolder_toggled {
 8129:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8130: }
 8131: 
 8132: a#LC_content_toolbar_edittoplevel {
 8133:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8134: }
 8135: 
 8136: ul#LC_toolbar li a:hover {
 8137:   background-position: bottom center;
 8138: }
 8139: 
 8140: ul#LC_toolbar {
 8141:   padding: 0;
 8142:   margin: 2px;
 8143:   list-style:none;
 8144:   position:relative;
 8145:   background-color:white;
 8146:   overflow: auto;
 8147: }
 8148: 
 8149: ul#LC_toolbar li {
 8150:   border:1px solid white;
 8151:   padding: 0;
 8152:   margin: 0;
 8153:   float: left;
 8154:   display:inline;
 8155:   vertical-align:middle;
 8156:   white-space: nowrap;
 8157: }
 8158: 
 8159: 
 8160: a.LC_toolbarItem {
 8161:   display:block;
 8162:   padding: 0;
 8163:   margin: 0;
 8164:   height: 32px;
 8165:   width: 32px;
 8166:   color:white;
 8167:   border: none;
 8168:   background-repeat:no-repeat;
 8169:   background-color:transparent;
 8170: }
 8171: 
 8172: ul.LC_funclist {
 8173:     margin: 0;
 8174:     padding: 0.5em 1em 0.5em 0;
 8175: }
 8176: 
 8177: ul.LC_funclist > li:first-child {
 8178:     font-weight:bold; 
 8179:     margin-left:0.8em;
 8180: }
 8181: 
 8182: ul.LC_funclist + ul.LC_funclist {
 8183:     /* 
 8184:        left border as a seperator if we have more than
 8185:        one list 
 8186:     */
 8187:     border-left: 1px solid $sidebg;
 8188:     /* 
 8189:        this hides the left border behind the border of the 
 8190:        outer box if element is wrapped to the next 'line' 
 8191:     */
 8192:     margin-left: -1px;
 8193: }
 8194: 
 8195: ul.LC_funclist li {
 8196:   display: inline;
 8197:   white-space: nowrap;
 8198:   margin: 0 0 0 25px;
 8199:   line-height: 150%;
 8200: }
 8201: 
 8202: .LC_hidden {
 8203:   display: none;
 8204: }
 8205: 
 8206: .LCmodal-overlay {
 8207: 		position:fixed;
 8208: 		top:0;
 8209: 		right:0;
 8210: 		bottom:0;
 8211: 		left:0;
 8212: 		height:100%;
 8213: 		width:100%;
 8214: 		margin:0;
 8215: 		padding:0;
 8216: 		background:#999;
 8217: 		opacity:.75;
 8218: 		filter: alpha(opacity=75);
 8219: 		-moz-opacity: 0.75;
 8220: 		z-index:101;
 8221: }
 8222: 
 8223: * html .LCmodal-overlay {   
 8224: 		position: absolute;
 8225: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8226: }
 8227: 
 8228: .LCmodal-window {
 8229: 		position:fixed;
 8230: 		top:50%;
 8231: 		left:50%;
 8232: 		margin:0;
 8233: 		padding:0;
 8234: 		z-index:102;
 8235: 	}
 8236: 
 8237: * html .LCmodal-window {
 8238: 		position:absolute;
 8239: }
 8240: 
 8241: .LCclose-window {
 8242: 		position:absolute;
 8243: 		width:32px;
 8244: 		height:32px;
 8245: 		right:8px;
 8246: 		top:8px;
 8247: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8248: 		text-indent:-99999px;
 8249: 		overflow:hidden;
 8250: 		cursor:pointer;
 8251: }
 8252: 
 8253: /*
 8254:   styles used for response display
 8255: */
 8256: div.LC_radiofoil, div.LC_rankfoil {
 8257:   margin: .5em 0em .5em 0em;
 8258: }
 8259: table.LC_itemgroup {
 8260:   margin-top: 1em;
 8261: }
 8262: 
 8263: /*
 8264:   styles used by TTH when "Default set of options to pass to tth/m
 8265:   when converting TeX" in course settings has been set
 8266: 
 8267:   option passed: -t
 8268: 
 8269: */
 8270: 
 8271: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8272: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8273: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8274: td div.norm {line-height:normal;}
 8275: 
 8276: /*
 8277:   option passed -y3
 8278: */
 8279: 
 8280: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8281: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8282: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8283: 
 8284: /*
 8285:   sections with roles, for content only
 8286: */
 8287: section[class^="role-"] {
 8288:   padding-left: 10px;
 8289:   padding-right: 5px;
 8290:   margin-top: 8px;
 8291:   margin-bottom: 8px;
 8292:   border: 1px solid #2A4;
 8293:   border-radius: 5px;
 8294:   box-shadow: 0px 1px 1px #BBB;
 8295: }
 8296: section[class^="role-"]>h1 {
 8297:   position: relative;
 8298:   margin: 0px;
 8299:   padding-top: 10px;
 8300:   padding-left: 40px;
 8301: }
 8302: section[class^="role-"]>h1:before {
 8303:   position: absolute;
 8304:   left: -5px;
 8305:   top: 5px;
 8306: }
 8307: section.role-activity>h1:before {
 8308:   content:url('/adm/daxe/images/section_icons/activity.png');
 8309: }
 8310: section.role-advice>h1:before {
 8311:   content:url('/adm/daxe/images/section_icons/advice.png');
 8312: }
 8313: section.role-bibliography>h1:before {
 8314:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8315: }
 8316: section.role-citation>h1:before {
 8317:   content:url('/adm/daxe/images/section_icons/citation.png');
 8318: }
 8319: section.role-conclusion>h1:before {
 8320:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8321: }
 8322: section.role-definition>h1:before {
 8323:   content:url('/adm/daxe/images/section_icons/definition.png');
 8324: }
 8325: section.role-demonstration>h1:before {
 8326:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8327: }
 8328: section.role-example>h1:before {
 8329:   content:url('/adm/daxe/images/section_icons/example.png');
 8330: }
 8331: section.role-explanation>h1:before {
 8332:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8333: }
 8334: section.role-introduction>h1:before {
 8335:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8336: }
 8337: section.role-method>h1:before {
 8338:   content:url('/adm/daxe/images/section_icons/method.png');
 8339: }
 8340: section.role-more_information>h1:before {
 8341:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8342: }
 8343: section.role-objectives>h1:before {
 8344:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8345: }
 8346: section.role-prerequisites>h1:before {
 8347:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8348: }
 8349: section.role-remark>h1:before {
 8350:   content:url('/adm/daxe/images/section_icons/remark.png');
 8351: }
 8352: section.role-reminder>h1:before {
 8353:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8354: }
 8355: section.role-summary>h1:before {
 8356:   content:url('/adm/daxe/images/section_icons/summary.png');
 8357: }
 8358: section.role-syntax>h1:before {
 8359:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8360: }
 8361: section.role-warning>h1:before {
 8362:   content:url('/adm/daxe/images/section_icons/warning.png');
 8363: }
 8364: 
 8365: #LC_minitab_header {
 8366:   float:left;
 8367:   width:100%;
 8368:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8369:   font-size:93%;
 8370:   line-height:normal;
 8371:   margin: 0.5em 0 0.5em 0;
 8372: }
 8373: #LC_minitab_header ul {
 8374:   margin:0;
 8375:   padding:10px 10px 0;
 8376:   list-style:none;
 8377: }
 8378: #LC_minitab_header li {
 8379:   float:left;
 8380:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8381:   margin:0;
 8382:   padding:0 0 0 9px;
 8383: }
 8384: #LC_minitab_header a {
 8385:   display:block;
 8386:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8387:   padding:5px 15px 4px 6px;
 8388: }
 8389: #LC_minitab_header #LC_current_minitab {
 8390:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8391: }
 8392: #LC_minitab_header #LC_current_minitab a {
 8393:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8394:   padding-bottom:5px;
 8395: }
 8396: 
 8397: 
 8398: END
 8399: }
 8400: 
 8401: =pod
 8402: 
 8403: =item * &headtag()
 8404: 
 8405: Returns a uniform footer for LON-CAPA web pages.
 8406: 
 8407: Inputs: $title - optional title for the head
 8408:         $head_extra - optional extra HTML to put inside the <head>
 8409:         $args - optional arguments
 8410:             force_register - if is true call registerurl so the remote is 
 8411:                              informed
 8412:             redirect       -> array ref of
 8413:                                    1- seconds before redirect occurs
 8414:                                    2- url to redirect to
 8415:                                    3- whether the side effect should occur
 8416:                            (side effect of setting 
 8417:                                $env{'internal.head.redirect'} to the url 
 8418:                                redirected too)
 8419:             domain         -> force to color decorate a page for a specific
 8420:                                domain
 8421:             function       -> force usage of a specific rolish color scheme
 8422:             bgcolor        -> override the default page bgcolor
 8423:             no_auto_mt_title
 8424:                            -> prevent &mt()ing the title arg
 8425: 
 8426: =cut
 8427: 
 8428: sub headtag {
 8429:     my ($title,$head_extra,$args) = @_;
 8430:     
 8431:     my $function = $args->{'function'} || &get_users_function();
 8432:     my $domain   = $args->{'domain'}   || &determinedomain();
 8433:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8434:     my $httphost = $args->{'use_absolute'};
 8435:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8436: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8437: 		   #time(),
 8438: 		   $env{'environment.color.timestamp'},
 8439: 		   $function,$domain,$bgcolor);
 8440: 
 8441:     $url = '/adm/css/'.&escape($url).'.css';
 8442: 
 8443:     my $result =
 8444: 	'<head>'.
 8445: 	&font_settings($args);
 8446: 
 8447:     my $inhibitprint;
 8448:     if ($args->{'print_suppress'}) {
 8449:         $inhibitprint = &print_suppression();
 8450:     }
 8451: 
 8452:     if (!$args->{'frameset'}) {
 8453: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8454:     }
 8455:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8456:         $result .= Apache::lonxml::display_title();
 8457:     }
 8458:     if (!$args->{'no_nav_bar'} 
 8459: 	&& !$args->{'only_body'}
 8460: 	&& !$args->{'frameset'}) {
 8461: 	$result .= &help_menu_js($httphost);
 8462:         $result.=&modal_window();
 8463:         $result.=&togglebox_script();
 8464:         $result.=&wishlist_window();
 8465:         $result.=&LCprogressbarUpdate_script();
 8466:     } else {
 8467:         if ($args->{'add_modal'}) {
 8468:            $result.=&modal_window();
 8469:         }
 8470:         if ($args->{'add_wishlist'}) {
 8471:            $result.=&wishlist_window();
 8472:         }
 8473:         if ($args->{'add_togglebox'}) {
 8474:            $result.=&togglebox_script();
 8475:         }
 8476:         if ($args->{'add_progressbar'}) {
 8477:            $result.=&LCprogressbarUpdate_script();
 8478:         }
 8479:     }
 8480:     if (ref($args->{'redirect'})) {
 8481: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8482: 	$url = &Apache::lonenc::check_encrypt($url);
 8483: 	if (!$inhibit_continue) {
 8484: 	    $env{'internal.head.redirect'} = $url;
 8485: 	}
 8486: 	$result.=<<ADDMETA
 8487: <meta http-equiv="pragma" content="no-cache" />
 8488: <meta http-equiv="Refresh" content="$time; url=$url" />
 8489: ADDMETA
 8490:     } else {
 8491:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8492:             my $requrl = $env{'request.uri'};
 8493:             if ($requrl eq '') {
 8494:                 $requrl = $ENV{'REQUEST_URI'};
 8495:                 $requrl =~ s/\?.+$//;
 8496:             }
 8497:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8498:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8499:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8500:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8501:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8502:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8503:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8504:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8505:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8506:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8507:                             if (($newserver) && ($newserver ne $lonhost)) {
 8508:                                 my $numsec = 5;
 8509:                                 my $timeout = $numsec * 1000;
 8510:                                 my ($newurl,$locknum,%locks,$msg);
 8511:                                 if ($env{'request.role.adv'}) {
 8512:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8513:                                 }
 8514:                                 my $disable_submit = 0;
 8515:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8516:                                     $disable_submit = 1;
 8517:                                 }
 8518:                                 if ($locknum) {
 8519:                                     my @lockinfo = sort(values(%locks));
 8520:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8521:                                            join(", ",sort(values(%locks)))."\\n".
 8522:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8523:                                 } else {
 8524:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8525:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8526:                                     }
 8527:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8528:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8529:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8530:                                         $newurl .= '&role='.$env{'request.role'};
 8531:                                     }
 8532:                                     if ($env{'request.symb'}) {
 8533:                                         $newurl .= '&symb='.$env{'request.symb'};
 8534:                                     } else {
 8535:                                         $newurl .= '&origurl='.$requrl;
 8536:                                     }
 8537:                                 }
 8538:                                 &js_escape(\$msg);
 8539:                                 $result.=<<OFFLOAD
 8540: <meta http-equiv="pragma" content="no-cache" />
 8541: <script type="text/javascript">
 8542: // <![CDATA[
 8543: function LC_Offload_Now() {
 8544:     var dest = "$newurl";
 8545:     if (dest != '') {
 8546:         window.location.href="$newurl";
 8547:     }
 8548: }
 8549: \$(document).ready(function () {
 8550:     window.alert('$msg');
 8551:     if ($disable_submit) {
 8552:         \$(".LC_hwk_submit").prop("disabled", true);
 8553:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8554:     }
 8555:     setTimeout('LC_Offload_Now()', $timeout);
 8556: });
 8557: // ]]>
 8558: </script>
 8559: OFFLOAD
 8560:                             }
 8561:                         }
 8562:                     }
 8563:                 }
 8564:             }
 8565:         }
 8566:     }
 8567:     if (!defined($title)) {
 8568: 	$title = 'The LearningOnline Network with CAPA';
 8569:     }
 8570:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8571:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8572: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8573:     if (!$args->{'frameset'}) {
 8574:         $result .= ' /';
 8575:     }
 8576:     $result .= '>' 
 8577:         .$inhibitprint
 8578: 	.$head_extra;
 8579:     my $clientmobile;
 8580:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8581:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8582:     } else {
 8583:         $clientmobile = $env{'browser.mobile'};
 8584:     }
 8585:     if ($clientmobile) {
 8586:         $result .= '
 8587: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8588: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8589:     }
 8590:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8591:     return $result.'</head>';
 8592: }
 8593: 
 8594: =pod
 8595: 
 8596: =item * &font_settings()
 8597: 
 8598: Returns neccessary <meta> to set the proper encoding
 8599: 
 8600: Inputs: optional reference to HASH -- $args passed to &headtag()
 8601: 
 8602: =cut
 8603: 
 8604: sub font_settings {
 8605:     my ($args) = @_;
 8606:     my $headerstring='';
 8607:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8608:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8609:         $headerstring.=
 8610:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8611:         if (!$args->{'frameset'}) {
 8612: 	    $headerstring.= ' /';
 8613:         }
 8614: 	$headerstring .= '>'."\n";
 8615:     }
 8616:     return $headerstring;
 8617: }
 8618: 
 8619: =pod
 8620: 
 8621: =item * &print_suppression()
 8622: 
 8623: In course context returns css which causes the body to be blank when media="print",
 8624: if printout generation is unavailable for the current resource.
 8625: 
 8626: This could be because:
 8627: 
 8628: (a) printstartdate is in the future
 8629: 
 8630: (b) printenddate is in the past
 8631: 
 8632: (c) there is an active exam block with "printout"
 8633: functionality blocked
 8634: 
 8635: Users with pav, pfo or evb privileges are exempt.
 8636: 
 8637: Inputs: none
 8638: 
 8639: =cut
 8640: 
 8641: 
 8642: sub print_suppression {
 8643:     my $noprint;
 8644:     if ($env{'request.course.id'}) {
 8645:         my $scope = $env{'request.course.id'};
 8646:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8647:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8648:             return;
 8649:         }
 8650:         if ($env{'request.course.sec'} ne '') {
 8651:             $scope .= "/$env{'request.course.sec'}";
 8652:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8653:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8654:                 return;
 8655:             }
 8656:         }
 8657:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8658:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8659:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8660:         if ($blocked) {
 8661:             my $checkrole = "cm./$cdom/$cnum";
 8662:             if ($env{'request.course.sec'} ne '') {
 8663:                 $checkrole .= "/$env{'request.course.sec'}";
 8664:             }
 8665:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8666:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8667:                 $noprint = 1;
 8668:             }
 8669:         }
 8670:         unless ($noprint) {
 8671:             my $symb = &Apache::lonnet::symbread();
 8672:             if ($symb ne '') {
 8673:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8674:                 if (ref($navmap)) {
 8675:                     my $res = $navmap->getBySymb($symb);
 8676:                     if (ref($res)) {
 8677:                         if (!$res->resprintable()) {
 8678:                             $noprint = 1;
 8679:                         }
 8680:                     }
 8681:                 }
 8682:             }
 8683:         }
 8684:         if ($noprint) {
 8685:             return <<"ENDSTYLE";
 8686: <style type="text/css" media="print">
 8687:     body { display:none }
 8688: </style>
 8689: ENDSTYLE
 8690:         }
 8691:     }
 8692:     return;
 8693: }
 8694: 
 8695: =pod
 8696: 
 8697: =item * &xml_begin()
 8698: 
 8699: Returns the needed doctype and <html>
 8700: 
 8701: Inputs: none
 8702: 
 8703: =cut
 8704: 
 8705: sub xml_begin {
 8706:     my ($is_frameset) = @_;
 8707:     my $output='';
 8708: 
 8709:     if ($env{'browser.mathml'}) {
 8710: 	$output='<?xml version="1.0"?>'
 8711:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8712: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8713:             
 8714: #	    .'<!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">] >'
 8715: 	    .'<!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">'
 8716:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8717: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8718:     } elsif ($is_frameset) {
 8719:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8720:                 '<html>'."\n";
 8721:     } else {
 8722: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8723:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8724:     }
 8725:     return $output;
 8726: }
 8727: 
 8728: =pod
 8729: 
 8730: =item * &start_page()
 8731: 
 8732: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8733: 
 8734: Inputs:
 8735: 
 8736: =over 4
 8737: 
 8738: $title - optional title for the page
 8739: 
 8740: $head_extra - optional extra HTML to incude inside the <head>
 8741: 
 8742: $args - additional optional args supported are:
 8743: 
 8744: =over 8
 8745: 
 8746:              only_body      -> is true will set &bodytag() onlybodytag
 8747:                                     arg on
 8748:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8749:              add_entries    -> additional attributes to add to the  <body>
 8750:              domain         -> force to color decorate a page for a 
 8751:                                     specific domain
 8752:              function       -> force usage of a specific rolish color
 8753:                                     scheme
 8754:              redirect       -> see &headtag()
 8755:              bgcolor        -> override the default page bg color
 8756:              js_ready       -> return a string ready for being used in 
 8757:                                     a javascript writeln
 8758:              html_encode    -> return a string ready for being used in 
 8759:                                     a html attribute
 8760:              force_register -> if is true will turn on the &bodytag()
 8761:                                     $forcereg arg
 8762:              frameset       -> if true will start with a <frameset>
 8763:                                     rather than <body>
 8764:              skip_phases    -> hash ref of 
 8765:                                     head -> skip the <html><head> generation
 8766:                                     body -> skip all <body> generation
 8767:              no_auto_mt_title -> prevent &mt()ing the title arg
 8768:              bread_crumbs ->             Array containing breadcrumbs
 8769:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8770:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8771:                                     to lonhtmlcommon::breadcrumbs
 8772:              group          -> includes the current group, if page is for a 
 8773:                                specific group
 8774:              use_absolute   -> for request for external resource or syllabus, this
 8775:                                will contain https://<hostname> if server uses
 8776:                                https (as per hosts.tab), but request is for http
 8777:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8778: 
 8779: =back
 8780: 
 8781: =back
 8782: 
 8783: =cut
 8784: 
 8785: sub start_page {
 8786:     my ($title,$head_extra,$args) = @_;
 8787:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8788: 
 8789:     $env{'internal.start_page'}++;
 8790:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
 8791: 
 8792:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8793:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8794:     }
 8795: 
 8796:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8797:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8798:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8799:                 $args->{'no_primary_menu'} = 1;
 8800:             }
 8801:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8802:                 $args->{'no_inline_menu'} = 1;
 8803:             }
 8804:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8805:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8806:             }
 8807:         } else {
 8808:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8809:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8810:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8811:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8812:                     $args->{'no_primary_menu'} = 1;
 8813:                 }
 8814:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8815:                     $args->{'no_inline_menu'} = 1;
 8816:                 }
 8817:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8818:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8819:                 }
 8820:             }
 8821:         }
 8822:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8823:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8824:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8825:     }
 8826:     
 8827:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8828: 	if ($args->{'frameset'}) {
 8829: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8830: 						$args->{'add_entries'});
 8831: 	    $result .= "\n<frameset $attr_string>\n";
 8832:         } else {
 8833:             $result .=
 8834:                 &bodytag($title, 
 8835:                          $args->{'function'},       $args->{'add_entries'},
 8836:                          $args->{'only_body'},      $args->{'domain'},
 8837:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8838:                          $args->{'bgcolor'},        $args,
 8839:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
 8840:         }
 8841:     }
 8842: 
 8843:     if ($args->{'js_ready'}) {
 8844: 		$result = &js_ready($result);
 8845:     }
 8846:     if ($args->{'html_encode'}) {
 8847: 		$result = &html_encode($result);
 8848:     }
 8849: 
 8850:     # Preparation for new and consistent functionlist at top of screen
 8851:     # if ($args->{'functionlist'}) {
 8852:     #            $result .= &build_functionlist();
 8853:     #}
 8854: 
 8855:     # Don't add anything more if only_body wanted or in const space
 8856:     return $result if    $args->{'only_body'} 
 8857:                       || $env{'request.state'} eq 'construct';
 8858: 
 8859:     #Breadcrumbs
 8860:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8861: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8862: 		#if any br links exists, add them to the breadcrumbs
 8863: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8864: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8865: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8866: 			}
 8867: 		}
 8868:                 # if @advtools array contains items add then to the breadcrumbs
 8869:                 if (@advtools > 0) {
 8870:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8871:                 }
 8872:                 my $menulink;
 8873:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8874:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8875:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 8876:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 8877:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 8878:                      (!$env{'request.role.adv'}))) {
 8879:                     $menulink = 0;
 8880:                 } else {
 8881:                     undef($menulink);
 8882:                 }
 8883: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8884: 		if(exists($args->{'bread_crumbs_component'})){
 8885: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8886:                 } else {
 8887: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8888: 		}
 8889:     }
 8890:     return $result;
 8891: }
 8892: 
 8893: sub end_page {
 8894:     my ($args) = @_;
 8895:     $env{'internal.end_page'}++;
 8896:     my $result;
 8897:     if ($args->{'discussion'}) {
 8898: 	my ($target,$parser);
 8899: 	if (ref($args->{'discussion'})) {
 8900: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8901: 				$args->{'discussion'}{'parser'});
 8902: 	}
 8903: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8904:     }
 8905:     if ($args->{'frameset'}) {
 8906: 	$result .= '</frameset>';
 8907:     } else {
 8908: 	$result .= &endbodytag($args);
 8909:     }
 8910:     unless ($args->{'notbody'}) {
 8911:         $result .= "\n</html>";
 8912:     }
 8913: 
 8914:     if ($args->{'js_ready'}) {
 8915: 	$result = &js_ready($result);
 8916:     }
 8917: 
 8918:     if ($args->{'html_encode'}) {
 8919: 	$result = &html_encode($result);
 8920:     }
 8921: 
 8922:     return $result;
 8923: }
 8924: 
 8925: sub wishlist_window {
 8926:     return(<<'ENDWISHLIST');
 8927: <script type="text/javascript">
 8928: // <![CDATA[
 8929: // <!-- BEGIN LON-CAPA Internal
 8930: function set_wishlistlink(title, path) {
 8931:     if (!title) {
 8932:         title = document.title;
 8933:         title = title.replace(/^LON-CAPA /,'');
 8934:     }
 8935:     title = encodeURIComponent(title);
 8936:     title = title.replace("'","\\\'");
 8937:     if (!path) {
 8938:         path = location.pathname;
 8939:     }
 8940:     path = encodeURIComponent(path);
 8941:     path = path.replace("'","\\\'");
 8942:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8943:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8944: }
 8945: // END LON-CAPA Internal -->
 8946: // ]]>
 8947: </script>
 8948: ENDWISHLIST
 8949: }
 8950: 
 8951: sub modal_window {
 8952:     return(<<'ENDMODAL');
 8953: <script type="text/javascript">
 8954: // <![CDATA[
 8955: // <!-- BEGIN LON-CAPA Internal
 8956: var modalWindow = {
 8957: 	parent:"body",
 8958: 	windowId:null,
 8959: 	content:null,
 8960: 	width:null,
 8961: 	height:null,
 8962: 	close:function()
 8963: 	{
 8964: 	        $(".LCmodal-window").remove();
 8965: 	        $(".LCmodal-overlay").remove();
 8966: 	},
 8967: 	open:function()
 8968: 	{
 8969: 		var modal = "";
 8970: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8971: 		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;\">";
 8972: 		modal += this.content;
 8973: 		modal += "</div>";	
 8974: 
 8975: 		$(this.parent).append(modal);
 8976: 
 8977: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8978: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8979: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8980: 	}
 8981: };
 8982: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8983: 	{
 8984:                 source = source.replace(/'/g,"&#39;");
 8985: 		modalWindow.windowId = "myModal";
 8986: 		modalWindow.width = width;
 8987: 		modalWindow.height = height;
 8988: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8989: 		modalWindow.open();
 8990: 	};
 8991: // END LON-CAPA Internal -->
 8992: // ]]>
 8993: </script>
 8994: ENDMODAL
 8995: }
 8996: 
 8997: sub modal_link {
 8998:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8999:     unless ($width) { $width=480; }
 9000:     unless ($height) { $height=400; }
 9001:     unless ($scrolling) { $scrolling='yes'; }
 9002:     unless ($transparency) { $transparency='true'; }
 9003: 
 9004:     my $target_attr;
 9005:     if (defined($target)) {
 9006:         $target_attr = 'target="'.$target.'"';
 9007:     }
 9008:     return <<"ENDLINK";
 9009: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 9010:            $linktext</a>
 9011: ENDLINK
 9012: }
 9013: 
 9014: sub modal_adhoc_script {
 9015:     my ($funcname,$width,$height,$content)=@_;
 9016:     return (<<ENDADHOC);
 9017: <script type="text/javascript">
 9018: // <![CDATA[
 9019:         var $funcname = function()
 9020:         {
 9021:                 modalWindow.windowId = "myModal";
 9022:                 modalWindow.width = $width;
 9023:                 modalWindow.height = $height;
 9024:                 modalWindow.content = '$content';
 9025:                 modalWindow.open();
 9026:         };  
 9027: // ]]>
 9028: </script>
 9029: ENDADHOC
 9030: }
 9031: 
 9032: sub modal_adhoc_inner {
 9033:     my ($funcname,$width,$height,$content)=@_;
 9034:     my $innerwidth=$width-20;
 9035:     $content=&js_ready(
 9036:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9037:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9038:                  $content.
 9039:                  &end_scrollbox().
 9040:                  &end_page()
 9041:              );
 9042:     return &modal_adhoc_script($funcname,$width,$height,$content);
 9043: }
 9044: 
 9045: sub modal_adhoc_window {
 9046:     my ($funcname,$width,$height,$content,$linktext)=@_;
 9047:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 9048:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9049: }
 9050: 
 9051: sub modal_adhoc_launch {
 9052:     my ($funcname,$width,$height,$content)=@_;
 9053:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9054: <script type="text/javascript">
 9055: // <![CDATA[
 9056: $funcname();
 9057: // ]]>
 9058: </script>
 9059: ENDLAUNCH
 9060: }
 9061: 
 9062: sub modal_adhoc_close {
 9063:     return (<<ENDCLOSE);
 9064: <script type="text/javascript">
 9065: // <![CDATA[
 9066: modalWindow.close();
 9067: // ]]>
 9068: </script>
 9069: ENDCLOSE
 9070: }
 9071: 
 9072: sub togglebox_script {
 9073:    return(<<ENDTOGGLE);
 9074: <script type="text/javascript"> 
 9075: // <![CDATA[
 9076: function LCtoggleDisplay(id,hidetext,showtext) {
 9077:    link = document.getElementById(id + "link").childNodes[0];
 9078:    with (document.getElementById(id).style) {
 9079:       if (display == "none" ) {
 9080:           display = "inline";
 9081:           link.nodeValue = hidetext;
 9082:         } else {
 9083:           display = "none";
 9084:           link.nodeValue = showtext;
 9085:        }
 9086:    }
 9087: }
 9088: // ]]>
 9089: </script>
 9090: ENDTOGGLE
 9091: }
 9092: 
 9093: sub start_togglebox {
 9094:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9095:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9096:     unless ($showtext) { $showtext=&mt('show'); }
 9097:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9098:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9099:     return &start_data_table().
 9100:            &start_data_table_header_row().
 9101:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9102:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9103:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9104:            &end_data_table_header_row().
 9105:            '<tr id="'.$id.'" style="display:none""><td>';
 9106: }
 9107: 
 9108: sub end_togglebox {
 9109:     return '</td></tr>'.&end_data_table();
 9110: }
 9111: 
 9112: sub LCprogressbar_script {
 9113:    my ($id,$number_to_do)=@_;
 9114:    if ($number_to_do) {
 9115:        return(<<ENDPROGRESS);
 9116: <script type="text/javascript">
 9117: // <![CDATA[
 9118: \$('#progressbar$id').progressbar({
 9119:   value: 0,
 9120:   change: function(event, ui) {
 9121:     var newVal = \$(this).progressbar('option', 'value');
 9122:     \$('.pblabel', this).text(LCprogressTxt);
 9123:   }
 9124: });
 9125: // ]]>
 9126: </script>
 9127: ENDPROGRESS
 9128:    } else {
 9129:        return(<<ENDPROGRESS);
 9130: <script type="text/javascript">
 9131: // <![CDATA[
 9132: \$('#progressbar$id').progressbar({
 9133:   value: false,
 9134:   create: function(event, ui) {
 9135:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9136:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9137:   }
 9138: });
 9139: // ]]>
 9140: </script>
 9141: ENDPROGRESS
 9142:    }
 9143: }
 9144: 
 9145: sub LCprogressbarUpdate_script {
 9146:    return(<<ENDPROGRESSUPDATE);
 9147: <style type="text/css">
 9148: .ui-progressbar { position:relative; }
 9149: .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%; }
 9150: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9151: </style>
 9152: <script type="text/javascript">
 9153: // <![CDATA[
 9154: var LCprogressTxt='---';
 9155: 
 9156: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9157:    LCprogressTxt=progresstext;
 9158:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9159:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9160:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9161:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9162:    } else {
 9163:        \$('#progressbar'+id).progressbar('value',percent);
 9164:    }
 9165: }
 9166: // ]]>
 9167: </script>
 9168: ENDPROGRESSUPDATE
 9169: }
 9170: 
 9171: my $LClastpercent;
 9172: my $LCidcnt;
 9173: my $LCcurrentid;
 9174: 
 9175: sub LCprogressbar {
 9176:     my ($r,$number_to_do,$preamble)=@_;
 9177:     $LClastpercent=0;
 9178:     $LCidcnt++;
 9179:     $LCcurrentid=$$.'_'.$LCidcnt;
 9180:     my ($starting,$content);
 9181:     if ($number_to_do) {
 9182:         $starting=&mt('Starting');
 9183:         $content=(<<ENDPROGBAR);
 9184: $preamble
 9185:   <div id="progressbar$LCcurrentid">
 9186:     <span class="pblabel">$starting</span>
 9187:   </div>
 9188: ENDPROGBAR
 9189:     } else {
 9190:         $starting=&mt('Loading...');
 9191:         $LClastpercent='false';
 9192:         $content=(<<ENDPROGBAR);
 9193: $preamble
 9194:   <div id="progressbar$LCcurrentid">
 9195:       <div class="progress-label">$starting</div>
 9196:   </div>
 9197: ENDPROGBAR
 9198:     }
 9199:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9200: }
 9201: 
 9202: sub LCprogressbarUpdate {
 9203:     my ($r,$val,$text,$number_to_do)=@_;
 9204:     if ($number_to_do) {
 9205:         unless ($val) { 
 9206:             if ($LClastpercent) {
 9207:                 $val=$LClastpercent;
 9208:             } else {
 9209:                 $val=0;
 9210:             }
 9211:         }
 9212:         if ($val<0) { $val=0; }
 9213:         if ($val>100) { $val=0; }
 9214:         $LClastpercent=$val;
 9215:         unless ($text) { $text=$val.'%'; }
 9216:     } else {
 9217:         $val = 'false';
 9218:     }
 9219:     $text=&js_ready($text);
 9220:     &r_print($r,<<ENDUPDATE);
 9221: <script type="text/javascript">
 9222: // <![CDATA[
 9223: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9224: // ]]>
 9225: </script>
 9226: ENDUPDATE
 9227: }
 9228: 
 9229: sub LCprogressbarClose {
 9230:     my ($r)=@_;
 9231:     $LClastpercent=0;
 9232:     &r_print($r,<<ENDCLOSE);
 9233: <script type="text/javascript">
 9234: // <![CDATA[
 9235: \$("#progressbar$LCcurrentid").hide('slow'); 
 9236: // ]]>
 9237: </script>
 9238: ENDCLOSE
 9239: }
 9240: 
 9241: sub r_print {
 9242:     my ($r,$to_print)=@_;
 9243:     if ($r) {
 9244:       $r->print($to_print);
 9245:       $r->rflush();
 9246:     } else {
 9247:       print($to_print);
 9248:     }
 9249: }
 9250: 
 9251: sub html_encode {
 9252:     my ($result) = @_;
 9253: 
 9254:     $result = &HTML::Entities::encode($result,'<>&"');
 9255:     
 9256:     return $result;
 9257: }
 9258: 
 9259: sub js_ready {
 9260:     my ($result) = @_;
 9261: 
 9262:     $result =~ s/[\n\r]/ /xmsg;
 9263:     $result =~ s/\\/\\\\/xmsg;
 9264:     $result =~ s/'/\\'/xmsg;
 9265:     $result =~ s{</}{<\\/}xmsg;
 9266:     
 9267:     return $result;
 9268: }
 9269: 
 9270: sub validate_page {
 9271:     if (  exists($env{'internal.start_page'})
 9272: 	  &&     $env{'internal.start_page'} > 1) {
 9273: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9274: 				 $env{'internal.start_page'}.' '.
 9275: 				 $ENV{'request.filename'});
 9276:     }
 9277:     if (  exists($env{'internal.end_page'})
 9278: 	  &&     $env{'internal.end_page'} > 1) {
 9279: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9280: 				 $env{'internal.end_page'}.' '.
 9281: 				 $env{'request.filename'});
 9282:     }
 9283:     if (     exists($env{'internal.start_page'})
 9284: 	&& ! exists($env{'internal.end_page'})) {
 9285: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9286: 				 $env{'request.filename'});
 9287:     }
 9288:     if (   ! exists($env{'internal.start_page'})
 9289: 	&&   exists($env{'internal.end_page'})) {
 9290: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9291: 				 $env{'request.filename'});
 9292:     }
 9293: }
 9294: 
 9295: 
 9296: sub start_scrollbox {
 9297:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9298:     unless ($outerwidth) { $outerwidth='520px'; }
 9299:     unless ($width) { $width='500px'; }
 9300:     unless ($height) { $height='200px'; }
 9301:     my ($table_id,$div_id,$tdcol);
 9302:     if ($id ne '') {
 9303:         $table_id = ' id="table_'.$id.'"';
 9304:         $div_id = ' id="div_'.$id.'"';
 9305:     }
 9306:     if ($bgcolor ne '') {
 9307:         $tdcol = "background-color: $bgcolor;";
 9308:     }
 9309:     my $nicescroll_js;
 9310:     if ($env{'browser.mobile'}) {
 9311:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9312:     }
 9313:     return <<"END";
 9314: $nicescroll_js
 9315: 
 9316: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9317: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9318: END
 9319: }
 9320: 
 9321: sub end_scrollbox {
 9322:     return '</div></td></tr></table>';
 9323: }
 9324: 
 9325: sub nicescroll_javascript {
 9326:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9327:     my %options;
 9328:     if (ref($cursor) eq 'HASH') {
 9329:         %options = %{$cursor};
 9330:     }
 9331:     unless ($options{'railalign'} =~ /^left|right$/) {
 9332:         $options{'railalign'} = 'left';
 9333:     }
 9334:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9335:         my $function  = &get_users_function();
 9336:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9337:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9338:             $options{'cursorcolor'} = '#00F';
 9339:         }
 9340:     }
 9341:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9342:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9343:             $options{'cursoropacity'}='1.0';
 9344:         }
 9345:     } else {
 9346:         $options{'cursoropacity'}='1.0';
 9347:     }
 9348:     if ($options{'cursorfixedheight'} eq 'none') {
 9349:         delete($options{'cursorfixedheight'});
 9350:     } else {
 9351:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9352:     }
 9353:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9354:         delete($options{'railoffset'});
 9355:     }
 9356:     my @niceoptions;
 9357:     while (my($key,$value) = each(%options)) {
 9358:         if ($value =~ /^\{.+\}$/) {
 9359:             push(@niceoptions,$key.':'.$value);
 9360:         } else {
 9361:             push(@niceoptions,$key.':"'.$value.'"');
 9362:         }
 9363:     }
 9364:     my $nicescroll_js = '
 9365: $(document).ready(
 9366:       function() {
 9367:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9368:       }
 9369: );
 9370: ';
 9371:     if ($framecheck) {
 9372:         $nicescroll_js .= '
 9373: function expand_div(caller) {
 9374:     if (top === self) {
 9375:         document.getElementById("'.$id.'").style.width = "auto";
 9376:         document.getElementById("'.$id.'").style.height = "auto";
 9377:     } else {
 9378:         try {
 9379:             if (parent.frames) {
 9380:                 if (parent.frames.length > 1) {
 9381:                     var framesrc = parent.frames[1].location.href;
 9382:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9383:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9384:                         document.getElementById("'.$id.'").style.width = "auto";
 9385:                         document.getElementById("'.$id.'").style.height = "auto";
 9386:                     }
 9387:                 }
 9388:             }
 9389:         } catch (e) {
 9390:             return;
 9391:         }
 9392:     }
 9393:     return;
 9394: }
 9395: ';
 9396:     }
 9397:     if ($needjsready) {
 9398:         $nicescroll_js = '
 9399: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9400:     } else {
 9401:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9402:     }
 9403:     return $nicescroll_js;
 9404: }
 9405: 
 9406: sub simple_error_page {
 9407:     my ($r,$title,$msg,$args) = @_;
 9408:     my %displayargs;
 9409:     if (ref($args) eq 'HASH') {
 9410:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9411:         if ($args->{'only_body'}) {
 9412:             $displayargs{'only_body'} = 1;
 9413:         }
 9414:         if ($args->{'no_nav_bar'}) {
 9415:             $displayargs{'no_nav_bar'} = 1;
 9416:         }
 9417:     } else {
 9418:         $msg = &mt($msg);
 9419:     }
 9420: 
 9421:     my $page =
 9422: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9423: 	'<p class="LC_error">'.$msg.'</p>'.
 9424: 	&Apache::loncommon::end_page();
 9425:     if (ref($r)) {
 9426: 	$r->print($page);
 9427: 	return;
 9428:     }
 9429:     return $page;
 9430: }
 9431: 
 9432: {
 9433:     my @row_count;
 9434: 
 9435:     sub start_data_table_count {
 9436:         unshift(@row_count, 0);
 9437:         return;
 9438:     }
 9439: 
 9440:     sub end_data_table_count {
 9441:         shift(@row_count);
 9442:         return;
 9443:     }
 9444: 
 9445:     sub start_data_table {
 9446: 	my ($add_class,$id) = @_;
 9447: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9448:         my $table_id;
 9449:         if (defined($id)) {
 9450:             $table_id = ' id="'.$id.'"';
 9451:         }
 9452: 	&start_data_table_count();
 9453: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9454:     }
 9455: 
 9456:     sub end_data_table {
 9457: 	&end_data_table_count();
 9458: 	return '</table>'."\n";;
 9459:     }
 9460: 
 9461:     sub start_data_table_row {
 9462: 	my ($add_class, $id) = @_;
 9463: 	$row_count[0]++;
 9464: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9465: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9466:         $id = (' id="'.$id.'"') unless ($id eq '');
 9467:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9468:     }
 9469:     
 9470:     sub continue_data_table_row {
 9471: 	my ($add_class, $id) = @_;
 9472: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9473: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9474:         $id = (' id="'.$id.'"') unless ($id eq '');
 9475:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9476:     }
 9477: 
 9478:     sub end_data_table_row {
 9479: 	return '</tr>'."\n";;
 9480:     }
 9481: 
 9482:     sub start_data_table_empty_row {
 9483: #	$row_count[0]++;
 9484: 	return  '<tr class="LC_empty_row" >'."\n";;
 9485:     }
 9486: 
 9487:     sub end_data_table_empty_row {
 9488: 	return '</tr>'."\n";;
 9489:     }
 9490: 
 9491:     sub start_data_table_header_row {
 9492: 	return  '<tr class="LC_header_row">'."\n";;
 9493:     }
 9494: 
 9495:     sub end_data_table_header_row {
 9496: 	return '</tr>'."\n";;
 9497:     }
 9498: 
 9499:     sub data_table_caption {
 9500:         my $caption = shift;
 9501:         return "<caption class=\"LC_caption\">$caption</caption>";
 9502:     }
 9503: }
 9504: 
 9505: =pod
 9506: 
 9507: =item * &inhibit_menu_check($arg)
 9508: 
 9509: Checks for a inhibitmenu state and generates output to preserve it
 9510: 
 9511: Inputs:         $arg - can be any of
 9512:                      - undef - in which case the return value is a string 
 9513:                                to add  into arguments list of a uri
 9514:                      - 'input' - in which case the return value is a HTML
 9515:                                  <form> <input> field of type hidden to
 9516:                                  preserve the value
 9517:                      - a url - in which case the return value is the url with
 9518:                                the neccesary cgi args added to preserve the
 9519:                                inhibitmenu state
 9520:                      - a ref to a url - no return value, but the string is
 9521:                                         updated to include the neccessary cgi
 9522:                                         args to preserve the inhibitmenu state
 9523: 
 9524: =cut
 9525: 
 9526: sub inhibit_menu_check {
 9527:     my ($arg) = @_;
 9528:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9529:     if ($arg eq 'input') {
 9530: 	if ($env{'form.inhibitmenu'}) {
 9531: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9532: 	} else {
 9533: 	    return
 9534: 	}
 9535:     }
 9536:     if ($env{'form.inhibitmenu'}) {
 9537: 	if (ref($arg)) {
 9538: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9539: 	} elsif ($arg eq '') {
 9540: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9541: 	} else {
 9542: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9543: 	}
 9544:     }
 9545:     if (!ref($arg)) {
 9546: 	return $arg;
 9547:     }
 9548: }
 9549: 
 9550: ###############################################
 9551: 
 9552: =pod
 9553: 
 9554: =back
 9555: 
 9556: =head1 User Information Routines
 9557: 
 9558: =over 4
 9559: 
 9560: =item * &get_users_function()
 9561: 
 9562: Used by &bodytag to determine the current users primary role.
 9563: Returns either 'student','coordinator','admin', or 'author'.
 9564: 
 9565: =cut
 9566: 
 9567: ###############################################
 9568: sub get_users_function {
 9569:     my $function = 'norole';
 9570:     if ($env{'request.role'}=~/^(st)/) {
 9571:         $function='student';
 9572:     }
 9573:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9574:         $function='coordinator';
 9575:     }
 9576:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9577:         $function='admin';
 9578:     }
 9579:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9580:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9581:         $function='author';
 9582:     }
 9583:     return $function;
 9584: }
 9585: 
 9586: ###############################################
 9587: 
 9588: =pod
 9589: 
 9590: =item * &show_course()
 9591: 
 9592: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9593: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9594: 
 9595: Inputs:
 9596: None
 9597: 
 9598: Outputs:
 9599: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9600: 
 9601: =cut
 9602: 
 9603: ###############################################
 9604: sub show_course {
 9605:     my $course = !$env{'user.adv'};
 9606:     if (!$env{'user.adv'}) {
 9607:         foreach my $env (keys(%env)) {
 9608:             next if ($env !~ m/^user\.priv\./);
 9609:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9610:                 $course = 0;
 9611:                 last;
 9612:             }
 9613:         }
 9614:     }
 9615:     return $course;
 9616: }
 9617: 
 9618: ###############################################
 9619: 
 9620: =pod
 9621: 
 9622: =item * &check_user_status()
 9623: 
 9624: Determines current status of supplied role for a
 9625: specific user. Roles can be active, previous or future.
 9626: 
 9627: Inputs: 
 9628: user's domain, user's username, course's domain,
 9629: course's number, optional section ID.
 9630: 
 9631: Outputs:
 9632: role status: active, previous or future. 
 9633: 
 9634: =cut
 9635: 
 9636: sub check_user_status {
 9637:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9638:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9639:     my @uroles = keys(%userinfo);
 9640:     my $srchstr;
 9641:     my $active_chk = 'none';
 9642:     my $now = time;
 9643:     if (@uroles > 0) {
 9644:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9645:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9646:         } else {
 9647:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9648:         }
 9649:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9650:             my $role_end = 0;
 9651:             my $role_start = 0;
 9652:             $active_chk = 'active';
 9653:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9654:                 $role_end = $1;
 9655:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9656:                     $role_start = $1;
 9657:                 }
 9658:             }
 9659:             if ($role_start > 0) {
 9660:                 if ($now < $role_start) {
 9661:                     $active_chk = 'future';
 9662:                 }
 9663:             }
 9664:             if ($role_end > 0) {
 9665:                 if ($now > $role_end) {
 9666:                     $active_chk = 'previous';
 9667:                 }
 9668:             }
 9669:         }
 9670:     }
 9671:     return $active_chk;
 9672: }
 9673: 
 9674: ###############################################
 9675: 
 9676: =pod
 9677: 
 9678: =item * &get_sections()
 9679: 
 9680: Determines all the sections for a course including
 9681: sections with students and sections containing other roles.
 9682: Incoming parameters: 
 9683: 
 9684: 1. domain
 9685: 2. course number 
 9686: 3. reference to array containing roles for which sections should 
 9687: be gathered (optional).
 9688: 4. reference to array containing status types for which sections 
 9689: should be gathered (optional).
 9690: 
 9691: If the third argument is undefined, sections are gathered for any role. 
 9692: If the fourth argument is undefined, sections are gathered for any status.
 9693: Permissible values are 'active' or 'future' or 'previous'.
 9694:  
 9695: Returns section hash (keys are section IDs, values are
 9696: number of users in each section), subject to the
 9697: optional roles filter, optional status filter 
 9698: 
 9699: =cut
 9700: 
 9701: ###############################################
 9702: sub get_sections {
 9703:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9704:     if (!defined($cdom) || !defined($cnum)) {
 9705:         my $cid =  $env{'request.course.id'};
 9706: 
 9707: 	return if (!defined($cid));
 9708: 
 9709:         $cdom = $env{'course.'.$cid.'.domain'};
 9710:         $cnum = $env{'course.'.$cid.'.num'};
 9711:     }
 9712: 
 9713:     my %sectioncount;
 9714:     my $now = time;
 9715: 
 9716:     my $check_students = 1;
 9717:     my $only_students = 0;
 9718:     if (ref($possible_roles) eq 'ARRAY') {
 9719:         if (grep(/^st$/,@{$possible_roles})) {
 9720:             if (@{$possible_roles} == 1) {
 9721:                 $only_students = 1;
 9722:             }
 9723:         } else {
 9724:             $check_students = 0;
 9725:         }
 9726:     }
 9727: 
 9728:     if ($check_students) { 
 9729: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9730: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9731: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9732:         my $start_index = &Apache::loncoursedata::CL_START();
 9733:         my $end_index = &Apache::loncoursedata::CL_END();
 9734:         my $status;
 9735: 	while (my ($student,$data) = each(%$classlist)) {
 9736: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9737: 				                     $data->[$status_index],
 9738:                                                      $data->[$start_index],
 9739:                                                      $data->[$end_index]);
 9740:             if ($stu_status eq 'Active') {
 9741:                 $status = 'active';
 9742:             } elsif ($end < $now) {
 9743:                 $status = 'previous';
 9744:             } elsif ($start > $now) {
 9745:                 $status = 'future';
 9746:             } 
 9747: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9748:                 if ((!defined($possible_status)) || (($status ne '') && 
 9749:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9750: 		    $sectioncount{$section}++;
 9751:                 }
 9752: 	    }
 9753: 	}
 9754:     }
 9755:     if ($only_students) {
 9756:         return %sectioncount;
 9757:     }
 9758:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9759:     foreach my $user (sort(keys(%courseroles))) {
 9760: 	if ($user !~ /^(\w{2})/) { next; }
 9761: 	my ($role) = ($user =~ /^(\w{2})/);
 9762: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9763: 	my ($section,$status);
 9764: 	if ($role eq 'cr' &&
 9765: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9766: 	    $section=$1;
 9767: 	}
 9768: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9769: 	if (!defined($section) || $section eq '-1') { next; }
 9770:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9771:         if ($end == -1 && $start == -1) {
 9772:             next; #deleted role
 9773:         }
 9774:         if (!defined($possible_status)) { 
 9775:             $sectioncount{$section}++;
 9776:         } else {
 9777:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9778:                 $status = 'active';
 9779:             } elsif ($end < $now) {
 9780:                 $status = 'future';
 9781:             } elsif ($start > $now) {
 9782:                 $status = 'previous';
 9783:             }
 9784:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9785:                 $sectioncount{$section}++;
 9786:             }
 9787:         }
 9788:     }
 9789:     return %sectioncount;
 9790: }
 9791: 
 9792: ###############################################
 9793: 
 9794: =pod
 9795: 
 9796: =item * &get_course_users()
 9797: 
 9798: Retrieves usernames:domains for users in the specified course
 9799: with specific role(s), and access status. 
 9800: 
 9801: Incoming parameters:
 9802: 1. course domain
 9803: 2. course number
 9804: 3. access status: users must have - either active, 
 9805: previous, future, or all.
 9806: 4. reference to array of permissible roles
 9807: 5. reference to array of section restrictions (optional)
 9808: 6. reference to results object (hash of hashes).
 9809: 7. reference to optional userdata hash
 9810: 8. reference to optional statushash
 9811: 9. flag if privileged users (except those set to unhide in
 9812:    course settings) should be excluded    
 9813: Keys of top level results hash are roles.
 9814: Keys of inner hashes are username:domain, with 
 9815: values set to access type.
 9816: Optional userdata hash returns an array with arguments in the 
 9817: same order as loncoursedata::get_classlist() for student data.
 9818: 
 9819: Optional statushash returns
 9820: 
 9821: Entries for end, start, section and status are blank because
 9822: of the possibility of multiple values for non-student roles.
 9823: 
 9824: =cut
 9825: 
 9826: ###############################################
 9827: 
 9828: sub get_course_users {
 9829:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9830:     my %idx = ();
 9831:     my %seclists;
 9832: 
 9833:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9834:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9835:     $idx{end} = &Apache::loncoursedata::CL_END();
 9836:     $idx{start} = &Apache::loncoursedata::CL_START();
 9837:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9838:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9839:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9840:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9841: 
 9842:     if (grep(/^st$/,@{$roles})) {
 9843:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9844:         my $now = time;
 9845:         foreach my $student (keys(%{$classlist})) {
 9846:             my $match = 0;
 9847:             my $secmatch = 0;
 9848:             my $section = $$classlist{$student}[$idx{section}];
 9849:             my $status = $$classlist{$student}[$idx{status}];
 9850:             if ($section eq '') {
 9851:                 $section = 'none';
 9852:             }
 9853:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9854:                 if (grep(/^all$/,@{$sections})) {
 9855:                     $secmatch = 1;
 9856:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9857:                     if (grep(/^none$/,@{$sections})) {
 9858:                         $secmatch = 1;
 9859:                     }
 9860:                 } else {  
 9861: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9862: 		        $secmatch = 1;
 9863:                     }
 9864: 		}
 9865:                 if (!$secmatch) {
 9866:                     next;
 9867:                 }
 9868:             }
 9869:             if (defined($$types{'active'})) {
 9870:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9871:                     push(@{$$users{st}{$student}},'active');
 9872:                     $match = 1;
 9873:                 }
 9874:             }
 9875:             if (defined($$types{'previous'})) {
 9876:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9877:                     push(@{$$users{st}{$student}},'previous');
 9878:                     $match = 1;
 9879:                 }
 9880:             }
 9881:             if (defined($$types{'future'})) {
 9882:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9883:                     push(@{$$users{st}{$student}},'future');
 9884:                     $match = 1;
 9885:                 }
 9886:             }
 9887:             if ($match) {
 9888:                 push(@{$seclists{$student}},$section);
 9889:                 if (ref($userdata) eq 'HASH') {
 9890:                     $$userdata{$student} = $$classlist{$student};
 9891:                 }
 9892:                 if (ref($statushash) eq 'HASH') {
 9893:                     $statushash->{$student}{'st'}{$section} = $status;
 9894:                 }
 9895:             }
 9896:         }
 9897:     }
 9898:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9899:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9900:         my $now = time;
 9901:         my %displaystatus = ( previous => 'Expired',
 9902:                               active   => 'Active',
 9903:                               future   => 'Future',
 9904:                             );
 9905:         my (%nothide,@possdoms);
 9906:         if ($hidepriv) {
 9907:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9908:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9909:                 if ($user !~ /:/) {
 9910:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9911:                 } else {
 9912:                     $nothide{$user} = 1;
 9913:                 }
 9914:             }
 9915:             my @possdoms = ($cdom);
 9916:             if ($coursehash{'checkforpriv'}) {
 9917:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9918:             }
 9919:         }
 9920:         foreach my $person (sort(keys(%coursepersonnel))) {
 9921:             my $match = 0;
 9922:             my $secmatch = 0;
 9923:             my $status;
 9924:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9925:             $user =~ s/:$//;
 9926:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9927:             if ($end == -1 || $start == -1) {
 9928:                 next;
 9929:             }
 9930:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9931:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9932:                 my ($uname,$udom) = split(/:/,$user);
 9933:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9934:                     if (grep(/^all$/,@{$sections})) {
 9935:                         $secmatch = 1;
 9936:                     } elsif ($usec eq '') {
 9937:                         if (grep(/^none$/,@{$sections})) {
 9938:                             $secmatch = 1;
 9939:                         }
 9940:                     } else {
 9941:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9942:                             $secmatch = 1;
 9943:                         }
 9944:                     }
 9945:                     if (!$secmatch) {
 9946:                         next;
 9947:                     }
 9948:                 }
 9949:                 if ($usec eq '') {
 9950:                     $usec = 'none';
 9951:                 }
 9952:                 if ($uname ne '' && $udom ne '') {
 9953:                     if ($hidepriv) {
 9954:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9955:                             (!$nothide{$uname.':'.$udom})) {
 9956:                             next;
 9957:                         }
 9958:                     }
 9959:                     if ($end > 0 && $end < $now) {
 9960:                         $status = 'previous';
 9961:                     } elsif ($start > $now) {
 9962:                         $status = 'future';
 9963:                     } else {
 9964:                         $status = 'active';
 9965:                     }
 9966:                     foreach my $type (keys(%{$types})) { 
 9967:                         if ($status eq $type) {
 9968:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9969:                                 push(@{$$users{$role}{$user}},$type);
 9970:                             }
 9971:                             $match = 1;
 9972:                         }
 9973:                     }
 9974:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9975:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9976: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9977:                         }
 9978:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9979:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9980:                         }
 9981:                         if (ref($statushash) eq 'HASH') {
 9982:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9983:                         }
 9984:                     }
 9985:                 }
 9986:             }
 9987:         }
 9988:         if (grep(/^ow$/,@{$roles})) {
 9989:             if ((defined($cdom)) && (defined($cnum))) {
 9990:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9991:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9992:                     my $owner = $csettings{'internal.courseowner'};
 9993:                     next if ($owner eq '');
 9994:                     my ($ownername,$ownerdom);
 9995:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9996:                         $ownername = $1;
 9997:                         $ownerdom = $2;
 9998:                     } else {
 9999:                         $ownername = $owner;
10000:                         $ownerdom = $cdom;
10001:                         $owner = $ownername.':'.$ownerdom;
10002:                     }
10003:                     @{$$users{'ow'}{$owner}} = 'any';
10004:                     if (defined($userdata) && 
10005: 			!exists($$userdata{$owner})) {
10006: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10007:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10008:                             push(@{$seclists{$owner}},'none');
10009:                         }
10010:                         if (ref($statushash) eq 'HASH') {
10011:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10012:                         }
10013: 		    }
10014:                 }
10015:             }
10016:         }
10017:         foreach my $user (keys(%seclists)) {
10018:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10019:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10020:         }
10021:     }
10022:     return;
10023: }
10024: 
10025: sub get_user_info {
10026:     my ($udom,$uname,$idx,$userdata) = @_;
10027:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10028: 	&plainname($uname,$udom,'lastname');
10029:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10030:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10031:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10032:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10033:     return;
10034: }
10035: 
10036: ###############################################
10037: 
10038: =pod
10039: 
10040: =item * &get_user_quota()
10041: 
10042: Retrieves quota assigned for storage of user files.
10043: Default is to report quota for portfolio files.
10044: 
10045: Incoming parameters:
10046: 1. user's username
10047: 2. user's domain
10048: 3. quota name - portfolio, author, or course
10049:    (if no quota name provided, defaults to portfolio).
10050: 4. crstype - official, unofficial, textbook, placement or community, 
10051:    if quota name is course
10052: 
10053: Returns:
10054: 1. Disk quota (in MB) assigned to student.
10055: 2. (Optional) Type of setting: custom or default
10056:    (individually assigned or default for user's 
10057:    institutional status).
10058: 3. (Optional) - User's institutional status (e.g., faculty, staff
10059:    or student - types as defined in localenroll::inst_usertypes 
10060:    for user's domain, which determines default quota for user.
10061: 4. (Optional) - Default quota which would apply to the user.
10062: 
10063: If a value has been stored in the user's environment, 
10064: it will return that, otherwise it returns the maximal default
10065: defined for the user's institutional status(es) in the domain.
10066: 
10067: =cut
10068: 
10069: ###############################################
10070: 
10071: 
10072: sub get_user_quota {
10073:     my ($uname,$udom,$quotaname,$crstype) = @_;
10074:     my ($quota,$quotatype,$settingstatus,$defquota);
10075:     if (!defined($udom)) {
10076:         $udom = $env{'user.domain'};
10077:     }
10078:     if (!defined($uname)) {
10079:         $uname = $env{'user.name'};
10080:     }
10081:     if (($udom eq '' || $uname eq '') ||
10082:         ($udom eq 'public') && ($uname eq 'public')) {
10083:         $quota = 0;
10084:         $quotatype = 'default';
10085:         $defquota = 0; 
10086:     } else {
10087:         my $inststatus;
10088:         if ($quotaname eq 'course') {
10089:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10090:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10091:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10092:             } else {
10093:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10094:                 $quota = $cenv{'internal.uploadquota'};
10095:             }
10096:         } else {
10097:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10098:                 if ($quotaname eq 'author') {
10099:                     $quota = $env{'environment.authorquota'};
10100:                 } else {
10101:                     $quota = $env{'environment.portfolioquota'};
10102:                 }
10103:                 $inststatus = $env{'environment.inststatus'};
10104:             } else {
10105:                 my %userenv = 
10106:                     &Apache::lonnet::get('environment',['portfolioquota',
10107:                                          'authorquota','inststatus'],$udom,$uname);
10108:                 my ($tmp) = keys(%userenv);
10109:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10110:                     if ($quotaname eq 'author') {
10111:                         $quota = $userenv{'authorquota'};
10112:                     } else {
10113:                         $quota = $userenv{'portfolioquota'};
10114:                     }
10115:                     $inststatus = $userenv{'inststatus'};
10116:                 } else {
10117:                     undef(%userenv);
10118:                 }
10119:             }
10120:         }
10121:         if ($quota eq '' || wantarray) {
10122:             if ($quotaname eq 'course') {
10123:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10124:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10125:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10126:                     ($crstype eq 'placement')) { 
10127:                     $defquota = $domdefs{$crstype.'quota'};
10128:                 }
10129:                 if ($defquota eq '') {
10130:                     $defquota = 500;
10131:                 }
10132:             } else {
10133:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10134:             }
10135:             if ($quota eq '') {
10136:                 $quota = $defquota;
10137:                 $quotatype = 'default';
10138:             } else {
10139:                 $quotatype = 'custom';
10140:             }
10141:         }
10142:     }
10143:     if (wantarray) {
10144:         return ($quota,$quotatype,$settingstatus,$defquota);
10145:     } else {
10146:         return $quota;
10147:     }
10148: }
10149: 
10150: ###############################################
10151: 
10152: =pod
10153: 
10154: =item * &default_quota()
10155: 
10156: Retrieves default quota assigned for storage of user portfolio files,
10157: given an (optional) user's institutional status.
10158: 
10159: Incoming parameters:
10160: 
10161: 1. domain
10162: 2. (Optional) institutional status(es).  This is a : separated list of 
10163:    status types (e.g., faculty, staff, student etc.)
10164:    which apply to the user for whom the default is being retrieved.
10165:    If the institutional status string in undefined, the domain
10166:    default quota will be returned.
10167: 3.  quota name - portfolio, author, or course
10168:    (if no quota name provided, defaults to portfolio).
10169: 
10170: Returns:
10171: 
10172: 1. Default disk quota (in MB) for user portfolios in the domain.
10173: 2. (Optional) institutional type which determined the value of the
10174:    default quota.
10175: 
10176: If a value has been stored in the domain's configuration db,
10177: it will return that, otherwise it returns 20 (for backwards 
10178: compatibility with domains which have not set up a configuration
10179: db file; the original statically defined portfolio quota was 20 MB). 
10180: 
10181: If the user's status includes multiple types (e.g., staff and student),
10182: the largest default quota which applies to the user determines the
10183: default quota returned.
10184: 
10185: =cut
10186: 
10187: ###############################################
10188: 
10189: 
10190: sub default_quota {
10191:     my ($udom,$inststatus,$quotaname) = @_;
10192:     my ($defquota,$settingstatus);
10193:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10194:                                             ['quotas'],$udom);
10195:     my $key = 'defaultquota';
10196:     if ($quotaname eq 'author') {
10197:         $key = 'authorquota';
10198:     }
10199:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10200:         if ($inststatus ne '') {
10201:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10202:             foreach my $item (@statuses) {
10203:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10204:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10205:                         if ($defquota eq '') {
10206:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10207:                             $settingstatus = $item;
10208:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10209:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10210:                             $settingstatus = $item;
10211:                         }
10212:                     }
10213:                 } elsif ($key eq 'defaultquota') {
10214:                     if ($quotahash{'quotas'}{$item} ne '') {
10215:                         if ($defquota eq '') {
10216:                             $defquota = $quotahash{'quotas'}{$item};
10217:                             $settingstatus = $item;
10218:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10219:                             $defquota = $quotahash{'quotas'}{$item};
10220:                             $settingstatus = $item;
10221:                         }
10222:                     }
10223:                 }
10224:             }
10225:         }
10226:         if ($defquota eq '') {
10227:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10228:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10229:             } elsif ($key eq 'defaultquota') {
10230:                 $defquota = $quotahash{'quotas'}{'default'};
10231:             }
10232:             $settingstatus = 'default';
10233:             if ($defquota eq '') {
10234:                 if ($quotaname eq 'author') {
10235:                     $defquota = 500;
10236:                 }
10237:             }
10238:         }
10239:     } else {
10240:         $settingstatus = 'default';
10241:         if ($quotaname eq 'author') {
10242:             $defquota = 500;
10243:         } else {
10244:             $defquota = 20;
10245:         }
10246:     }
10247:     if (wantarray) {
10248:         return ($defquota,$settingstatus);
10249:     } else {
10250:         return $defquota;
10251:     }
10252: }
10253: 
10254: ###############################################
10255: 
10256: =pod
10257: 
10258: =item * &excess_filesize_warning()
10259: 
10260: Returns warning message if upload of file to authoring space, or copying
10261: of existing file within authoring space will cause quota for the authoring
10262: space to be exceeded.
10263: 
10264: Same, if upload of a file directly to a course/community via Course Editor
10265: will cause quota for uploaded content for the course to be exceeded.
10266: 
10267: Inputs: 7 
10268: 1. username or coursenum
10269: 2. domain
10270: 3. context ('author' or 'course')
10271: 4. filename of file for which action is being requested
10272: 5. filesize (kB) of file
10273: 6. action being taken: copy or upload.
10274: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10275: 
10276: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10277:          otherwise return null.
10278: 
10279: =back
10280: 
10281: =cut
10282: 
10283: sub excess_filesize_warning {
10284:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10285:     my $current_disk_usage = 0;
10286:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10287:     if ($context eq 'author') {
10288:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10289:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10290:     } else {
10291:         foreach my $subdir ('docs','supplemental') {
10292:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10293:         }
10294:     }
10295:     $disk_quota = int($disk_quota * 1000);
10296:     if (($current_disk_usage + $filesize) > $disk_quota) {
10297:         return '<p class="LC_warning">'.
10298:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10299:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10300:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10301:                             $disk_quota,$current_disk_usage).
10302:                '</p>';
10303:     }
10304:     return;
10305: }
10306: 
10307: ###############################################
10308: 
10309: 
10310: 
10311: 
10312: sub get_secgrprole_info {
10313:     my ($cdom,$cnum,$needroles,$type)  = @_;
10314:     my %sections_count = &get_sections($cdom,$cnum);
10315:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10316:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10317:     my @groups = sort(keys(%curr_groups));
10318:     my $allroles = [];
10319:     my $rolehash;
10320:     my $accesshash = {
10321:                      active => 'Currently has access',
10322:                      future => 'Will have future access',
10323:                      previous => 'Previously had access',
10324:                   };
10325:     if ($needroles) {
10326:         $rolehash = {'all' => 'all'};
10327:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10328: 	if (&Apache::lonnet::error(%user_roles)) {
10329: 	    undef(%user_roles);
10330: 	}
10331:         foreach my $item (keys(%user_roles)) {
10332:             my ($role)=split(/\:/,$item,2);
10333:             if ($role eq 'cr') { next; }
10334:             if ($role =~ /^cr/) {
10335:                 $$rolehash{$role} = (split('/',$role))[3];
10336:             } else {
10337:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10338:             }
10339:         }
10340:         foreach my $key (sort(keys(%{$rolehash}))) {
10341:             push(@{$allroles},$key);
10342:         }
10343:         push (@{$allroles},'st');
10344:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10345:     }
10346:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10347: }
10348: 
10349: sub user_picker {
10350:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10351:     my $currdom = $dom;
10352:     my @alldoms = &Apache::lonnet::all_domains();
10353:     if (@alldoms == 1) {
10354:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10355:                                                ['directorysrch'],$alldoms[0]);
10356:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10357:         my $showdom = $domdesc;
10358:         if ($showdom eq '') {
10359:             $showdom = $dom;
10360:         }
10361:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10362:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10363:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10364:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10365:             }
10366:         }
10367:     }
10368:     my %curr_selected = (
10369:                         srchin => 'dom',
10370:                         srchby => 'lastname',
10371:                       );
10372:     my $srchterm;
10373:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10374:         if ($srch->{'srchby'} ne '') {
10375:             $curr_selected{'srchby'} = $srch->{'srchby'};
10376:         }
10377:         if ($srch->{'srchin'} ne '') {
10378:             $curr_selected{'srchin'} = $srch->{'srchin'};
10379:         }
10380:         if ($srch->{'srchtype'} ne '') {
10381:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10382:         }
10383:         if ($srch->{'srchdomain'} ne '') {
10384:             $currdom = $srch->{'srchdomain'};
10385:         }
10386:         $srchterm = $srch->{'srchterm'};
10387:     }
10388:     my %html_lt=&Apache::lonlocal::texthash(
10389:                     'usr'       => 'Search criteria',
10390:                     'doma'      => 'Domain/institution to search',
10391:                     'uname'     => 'username',
10392:                     'lastname'  => 'last name',
10393:                     'lastfirst' => 'last name, first name',
10394:                     'crs'       => 'in this course',
10395:                     'dom'       => 'in selected LON-CAPA domain', 
10396:                     'alc'       => 'all LON-CAPA',
10397:                     'instd'     => 'in institutional directory for selected domain',
10398:                     'exact'     => 'is',
10399:                     'contains'  => 'contains',
10400:                     'begins'    => 'begins with',
10401:                                        );
10402:     my %js_lt=&Apache::lonlocal::texthash(
10403:                     'youm'      => "You must include some text to search for.",
10404:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10405:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10406:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10407:                     'ymcd'      => "You must choose a domain when using a domain search.",
10408:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10409:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10410:                      'thfo'     => "The following need to be corrected before the search can be run:",
10411:                                        );
10412:     &html_escape(\%html_lt);
10413:     &js_escape(\%js_lt);
10414:     my $domform;
10415:     my $allow_blank = 1;
10416:     if ($fixeddom) {
10417:         $allow_blank = 0;
10418:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10419:     } else {
10420:         my $defdom = $env{'request.role.domain'};
10421:         my ($trusted,$untrusted);
10422:         if (($context eq 'requestcrs') || ($context eq 'course')) {
10423:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10424:         } elsif ($context eq 'author') {
10425:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10426:         } elsif ($context eq 'domain') {
10427:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10428:         }
10429:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10430:     }
10431:     my $srchinsel = ' <select name="srchin">';
10432: 
10433:     my @srchins = ('crs','dom','alc','instd');
10434: 
10435:     foreach my $option (@srchins) {
10436:         # FIXME 'alc' option unavailable until 
10437:         #       loncreateuser::print_user_query_page()
10438:         #       has been completed.
10439:         next if ($option eq 'alc');
10440:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10441:         next if ($option eq 'crs' && !$env{'request.course.id'});
10442:         next if (($option eq 'instd') && ($noinstd));
10443:         if ($curr_selected{'srchin'} eq $option) {
10444:             $srchinsel .= ' 
10445:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10446:         } else {
10447:             $srchinsel .= '
10448:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10449:         }
10450:     }
10451:     $srchinsel .= "\n  </select>\n";
10452: 
10453:     my $srchbysel =  ' <select name="srchby">';
10454:     foreach my $option ('lastname','lastfirst','uname') {
10455:         if ($curr_selected{'srchby'} eq $option) {
10456:             $srchbysel .= '
10457:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10458:         } else {
10459:             $srchbysel .= '
10460:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10461:          }
10462:     }
10463:     $srchbysel .= "\n  </select>\n";
10464: 
10465:     my $srchtypesel = ' <select name="srchtype">';
10466:     foreach my $option ('begins','contains','exact') {
10467:         if ($curr_selected{'srchtype'} eq $option) {
10468:             $srchtypesel .= '
10469:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10470:         } else {
10471:             $srchtypesel .= '
10472:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10473:         }
10474:     }
10475:     $srchtypesel .= "\n  </select>\n";
10476: 
10477:     my ($newuserscript,$new_user_create);
10478:     my $context_dom = $env{'request.role.domain'};
10479:     if ($context eq 'requestcrs') {
10480:         if ($env{'form.coursedom'} ne '') { 
10481:             $context_dom = $env{'form.coursedom'};
10482:         }
10483:     }
10484:     if ($forcenewuser) {
10485:         if (ref($srch) eq 'HASH') {
10486:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10487:                 if ($cancreate) {
10488:                     $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>';
10489:                 } else {
10490:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10491:                     my %usertypetext = (
10492:                         official   => 'institutional',
10493:                         unofficial => 'non-institutional',
10494:                     );
10495:                     $new_user_create = '<p class="LC_warning">'
10496:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10497:                                       .' '
10498:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10499:                                           ,'<a href="'.$helplink.'">','</a>')
10500:                                       .'</p><br />';
10501:                 }
10502:             }
10503:         }
10504: 
10505:         $newuserscript = <<"ENDSCRIPT";
10506: 
10507: function setSearch(createnew,callingForm) {
10508:     if (createnew == 1) {
10509:         for (var i=0; i<callingForm.srchby.length; i++) {
10510:             if (callingForm.srchby.options[i].value == 'uname') {
10511:                 callingForm.srchby.selectedIndex = i;
10512:             }
10513:         }
10514:         for (var i=0; i<callingForm.srchin.length; i++) {
10515:             if ( callingForm.srchin.options[i].value == 'dom') {
10516: 		callingForm.srchin.selectedIndex = i;
10517:             }
10518:         }
10519:         for (var i=0; i<callingForm.srchtype.length; i++) {
10520:             if (callingForm.srchtype.options[i].value == 'exact') {
10521:                 callingForm.srchtype.selectedIndex = i;
10522:             }
10523:         }
10524:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10525:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10526:                 callingForm.srchdomain.selectedIndex = i;
10527:             }
10528:         }
10529:     }
10530: }
10531: ENDSCRIPT
10532: 
10533:     }
10534: 
10535:     my $output = <<"END_BLOCK";
10536: <script type="text/javascript">
10537: // <![CDATA[
10538: function validateEntry(callingForm) {
10539: 
10540:     var checkok = 1;
10541:     var srchin;
10542:     for (var i=0; i<callingForm.srchin.length; i++) {
10543: 	if ( callingForm.srchin[i].checked ) {
10544: 	    srchin = callingForm.srchin[i].value;
10545: 	}
10546:     }
10547: 
10548:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10549:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10550:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10551:     var srchterm =  callingForm.srchterm.value;
10552:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10553:     var msg = "";
10554: 
10555:     if (srchterm == "") {
10556:         checkok = 0;
10557:         msg += "$js_lt{'youm'}\\n";
10558:     }
10559: 
10560:     if (srchtype== 'begins') {
10561:         if (srchterm.length < 2) {
10562:             checkok = 0;
10563:             msg += "$js_lt{'thte'}\\n";
10564:         }
10565:     }
10566: 
10567:     if (srchtype== 'contains') {
10568:         if (srchterm.length < 3) {
10569:             checkok = 0;
10570:             msg += "$js_lt{'thet'}\\n";
10571:         }
10572:     }
10573:     if (srchin == 'instd') {
10574:         if (srchdomain == '') {
10575:             checkok = 0;
10576:             msg += "$js_lt{'yomc'}\\n";
10577:         }
10578:     }
10579:     if (srchin == 'dom') {
10580:         if (srchdomain == '') {
10581:             checkok = 0;
10582:             msg += "$js_lt{'ymcd'}\\n";
10583:         }
10584:     }
10585:     if (srchby == 'lastfirst') {
10586:         if (srchterm.indexOf(",") == -1) {
10587:             checkok = 0;
10588:             msg += "$js_lt{'whus'}\\n";
10589:         }
10590:         if (srchterm.indexOf(",") == srchterm.length -1) {
10591:             checkok = 0;
10592:             msg += "$js_lt{'whse'}\\n";
10593:         }
10594:     }
10595:     if (checkok == 0) {
10596:         alert("$js_lt{'thfo'}\\n"+msg);
10597:         return;
10598:     }
10599:     if (checkok == 1) {
10600:         callingForm.submit();
10601:     }
10602: }
10603: 
10604: $newuserscript
10605: 
10606: // ]]>
10607: </script>
10608: 
10609: $new_user_create
10610: 
10611: END_BLOCK
10612: 
10613:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10614:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10615:                $domform.
10616:                &Apache::lonhtmlcommon::row_closure().
10617:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10618:                $srchbysel.
10619:                $srchtypesel. 
10620:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10621:                $srchinsel.
10622:                &Apache::lonhtmlcommon::row_closure(1). 
10623:                &Apache::lonhtmlcommon::end_pick_box().
10624:                '<br />';
10625:     return ($output,1);
10626: }
10627: 
10628: sub user_rule_check {
10629:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10630:     my ($response,%inst_response);
10631:     if (ref($usershash) eq 'HASH') {
10632:         if (keys(%{$usershash}) > 1) {
10633:             my (%by_username,%by_id,%userdoms);
10634:             my $checkid; 
10635:             if (ref($checks) eq 'HASH') {
10636:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10637:                     $checkid = 1;
10638:                 }
10639:             }
10640:             foreach my $user (keys(%{$usershash})) {
10641:                 my ($uname,$udom) = split(/:/,$user);
10642:                 if ($checkid) {
10643:                     if (ref($usershash->{$user}) eq 'HASH') {
10644:                         if ($usershash->{$user}->{'id'} ne '') {
10645:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10646:                             $userdoms{$udom} = 1;
10647:                             if (ref($inst_results) eq 'HASH') {
10648:                                 $inst_results->{$uname.':'.$udom} = {};
10649:                             }
10650:                         }
10651:                     }
10652:                 } else {
10653:                     $by_username{$udom}{$uname} = 1;
10654:                     $userdoms{$udom} = 1;
10655:                     if (ref($inst_results) eq 'HASH') {
10656:                         $inst_results->{$uname.':'.$udom} = {};
10657:                     }
10658:                 }
10659:             }
10660:             foreach my $udom (keys(%userdoms)) {
10661:                 if (!$got_rules->{$udom}) {
10662:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10663:                                                              ['usercreation'],$udom);
10664:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10665:                         foreach my $item ('username','id') {
10666:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10667:                                 $$curr_rules{$udom}{$item} =
10668:                                     $domconfig{'usercreation'}{$item.'_rule'};
10669:                             }
10670:                         }
10671:                     }
10672:                     $got_rules->{$udom} = 1;
10673:                 }
10674:             }
10675:             if ($checkid) {
10676:                 foreach my $udom (keys(%by_id)) {
10677:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10678:                     if ($outcome eq 'ok') {
10679:                         foreach my $id (keys(%{$by_id{$udom}})) {
10680:                             my $uname = $by_id{$udom}{$id};
10681:                             $inst_response{$uname.':'.$udom} = $outcome;
10682:                         }
10683:                         if (ref($results) eq 'HASH') {
10684:                             foreach my $uname (keys(%{$results})) {
10685:                                 if (exists($inst_response{$uname.':'.$udom})) {
10686:                                     $inst_response{$uname.':'.$udom} = $outcome;
10687:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10688:                                 }
10689:                             }
10690:                         }
10691:                     }
10692:                 }
10693:             } else {
10694:                 foreach my $udom (keys(%by_username)) {
10695:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10696:                     if ($outcome eq 'ok') {
10697:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10698:                             $inst_response{$uname.':'.$udom} = $outcome;
10699:                         }
10700:                         if (ref($results) eq 'HASH') {
10701:                             foreach my $uname (keys(%{$results})) {
10702:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10703:                             }
10704:                         }
10705:                     }
10706:                 }
10707:             }
10708:         } elsif (keys(%{$usershash}) == 1) {
10709:             my $user = (keys(%{$usershash}))[0];
10710:             my ($uname,$udom) = split(/:/,$user);
10711:             if (($udom ne '') && ($uname ne '')) {
10712:                 if (ref($usershash->{$user}) eq 'HASH') {
10713:                     if (ref($checks) eq 'HASH') {
10714:                         if (defined($checks->{'username'})) {
10715:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10716:                                 &Apache::lonnet::get_instuser($udom,$uname);
10717:                         } elsif (defined($checks->{'id'})) {
10718:                             if ($usershash->{$user}->{'id'} ne '') {
10719:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10720:                                     &Apache::lonnet::get_instuser($udom,undef,
10721:                                                                   $usershash->{$user}->{'id'});
10722:                             } else {
10723:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10724:                                     &Apache::lonnet::get_instuser($udom,$uname);
10725:                             }
10726:                         }
10727:                     } else {
10728:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10729:                             &Apache::lonnet::get_instuser($udom,$uname);
10730:                        return;
10731:                     }
10732:                     if (!$got_rules->{$udom}) {
10733:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10734:                                                                  ['usercreation'],$udom);
10735:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10736:                             foreach my $item ('username','id') {
10737:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10738:                                    $$curr_rules{$udom}{$item} = 
10739:                                        $domconfig{'usercreation'}{$item.'_rule'};
10740:                                 }
10741:                             }
10742:                         }
10743:                         $got_rules->{$udom} = 1;
10744:                     }
10745:                 }
10746:             } else {
10747:                 return;
10748:             }
10749:         } else {
10750:             return;
10751:         }
10752:         foreach my $user (keys(%{$usershash})) {
10753:             my ($uname,$udom) = split(/:/,$user);
10754:             next if (($udom eq '') || ($uname eq ''));
10755:             my $id;
10756:             if (ref($inst_results) eq 'HASH') {
10757:                 if (ref($inst_results->{$user}) eq 'HASH') {
10758:                     $id = $inst_results->{$user}->{'id'};
10759:                 }
10760:             }
10761:             if ($id eq '') { 
10762:                 if (ref($usershash->{$user})) {
10763:                     $id = $usershash->{$user}->{'id'};
10764:                 }
10765:             }
10766:             foreach my $item (keys(%{$checks})) {
10767:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10768:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10769:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10770:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10771:                                                                              $$curr_rules{$udom}{$item});
10772:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10773:                                 if ($rule_check{$rule}) {
10774:                                     $$rulematch{$user}{$item} = $rule;
10775:                                     if ($inst_response{$user} eq 'ok') {
10776:                                         if (ref($inst_results) eq 'HASH') {
10777:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10778:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10779:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10780:                                                 } elsif ($item eq 'id') {
10781:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10782:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10783:                                                     }
10784:                                                 }
10785:                                             }
10786:                                         }
10787:                                     }
10788:                                     last;
10789:                                 }
10790:                             }
10791:                         }
10792:                     }
10793:                 }
10794:             }
10795:         }
10796:     }
10797:     return;
10798: }
10799: 
10800: sub user_rule_formats {
10801:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10802:     my %text = ( 
10803:                  'username' => 'Usernames',
10804:                  'id'       => 'IDs',
10805:                );
10806:     my $output;
10807:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10808:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10809:         if (@{$ruleorder} > 0) {
10810:             $output = '<br />'.
10811:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10812:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10813:                       ' <ul>';
10814:             foreach my $rule (@{$ruleorder}) {
10815:                 if (ref($curr_rules) eq 'ARRAY') {
10816:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10817:                         if (ref($rules->{$rule}) eq 'HASH') {
10818:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10819:                                         $rules->{$rule}{'desc'}.'</li>';
10820:                         }
10821:                     }
10822:                 }
10823:             }
10824:             $output .= '</ul>';
10825:         }
10826:     }
10827:     return $output;
10828: }
10829: 
10830: sub instrule_disallow_msg {
10831:     my ($checkitem,$domdesc,$count,$mode) = @_;
10832:     my $response;
10833:     my %text = (
10834:                   item   => 'username',
10835:                   items  => 'usernames',
10836:                   match  => 'matches',
10837:                   do     => 'does',
10838:                   action => 'a username',
10839:                   one    => 'one',
10840:                );
10841:     if ($count > 1) {
10842:         $text{'item'} = 'usernames';
10843:         $text{'match'} ='match';
10844:         $text{'do'} = 'do';
10845:         $text{'action'} = 'usernames',
10846:         $text{'one'} = 'ones';
10847:     }
10848:     if ($checkitem eq 'id') {
10849:         $text{'items'} = 'IDs';
10850:         $text{'item'} = 'ID';
10851:         $text{'action'} = 'an ID';
10852:         if ($count > 1) {
10853:             $text{'item'} = 'IDs';
10854:             $text{'action'} = 'IDs';
10855:         }
10856:     }
10857:     $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 />';
10858:     if ($mode eq 'upload') {
10859:         if ($checkitem eq 'username') {
10860:             $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'}.");
10861:         } elsif ($checkitem eq 'id') {
10862:             $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.");
10863:         }
10864:     } elsif ($mode eq 'selfcreate') {
10865:         if ($checkitem eq 'id') {
10866:             $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.");
10867:         }
10868:     } else {
10869:         if ($checkitem eq 'username') {
10870:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10871:         } elsif ($checkitem eq 'id') {
10872:             $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.");
10873:         }
10874:     }
10875:     return $response;
10876: }
10877: 
10878: sub personal_data_fieldtitles {
10879:     my %fieldtitles = &Apache::lonlocal::texthash (
10880:                         id => 'Student/Employee ID',
10881:                         permanentemail => 'E-mail address',
10882:                         lastname => 'Last Name',
10883:                         firstname => 'First Name',
10884:                         middlename => 'Middle Name',
10885:                         generation => 'Generation',
10886:                         gen => 'Generation',
10887:                         inststatus => 'Affiliation',
10888:                    );
10889:     return %fieldtitles;
10890: }
10891: 
10892: sub sorted_inst_types {
10893:     my ($dom) = @_;
10894:     my ($usertypes,$order);
10895:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10896:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10897:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10898:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10899:     } else {
10900:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10901:     }
10902:     my $othertitle = &mt('All users');
10903:     if ($env{'request.course.id'}) {
10904:         $othertitle  = &mt('Any users');
10905:     }
10906:     my @types;
10907:     if (ref($order) eq 'ARRAY') {
10908:         @types = @{$order};
10909:     }
10910:     if (@types == 0) {
10911:         if (ref($usertypes) eq 'HASH') {
10912:             @types = sort(keys(%{$usertypes}));
10913:         }
10914:     }
10915:     if (keys(%{$usertypes}) > 0) {
10916:         $othertitle = &mt('Other users');
10917:     }
10918:     return ($othertitle,$usertypes,\@types);
10919: }
10920: 
10921: sub get_institutional_codes {
10922:     my ($settings,$allcourses,$LC_code) = @_;
10923: # Get complete list of course sections to update
10924:     my @currsections = ();
10925:     my @currxlists = ();
10926:     my $coursecode = $$settings{'internal.coursecode'};
10927: 
10928:     if ($$settings{'internal.sectionnums'} ne '') {
10929:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10930:     }
10931: 
10932:     if ($$settings{'internal.crosslistings'} ne '') {
10933:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10934:     }
10935: 
10936:     if (@currxlists > 0) {
10937:         foreach (@currxlists) {
10938:             if (m/^([^:]+):(\w*)$/) {
10939:                 unless (grep/^$1$/,@{$allcourses}) {
10940:                     push(@{$allcourses},$1);
10941:                     $$LC_code{$1} = $2;
10942:                 }
10943:             }
10944:         }
10945:     }
10946:  
10947:     if (@currsections > 0) {
10948:         foreach (@currsections) {
10949:             if (m/^(\w+):(\w*)$/) {
10950:                 my $sec = $coursecode.$1;
10951:                 my $lc_sec = $2;
10952:                 unless (grep/^$sec$/,@{$allcourses}) {
10953:                     push(@{$allcourses},$sec);
10954:                     $$LC_code{$sec} = $lc_sec;
10955:                 }
10956:             }
10957:         }
10958:     }
10959:     return;
10960: }
10961: 
10962: sub get_standard_codeitems {
10963:     return ('Year','Semester','Department','Number','Section');
10964: }
10965: 
10966: =pod
10967: 
10968: =head1 Slot Helpers
10969: 
10970: =over 4
10971: 
10972: =item * sorted_slots()
10973: 
10974: Sorts an array of slot names in order of an optional sort key,
10975: default sort is by slot start time (earliest first). 
10976: 
10977: Inputs:
10978: 
10979: =over 4
10980: 
10981: slotsarr  - Reference to array of unsorted slot names.
10982: 
10983: slots     - Reference to hash of hash, where outer hash keys are slot names.
10984: 
10985: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10986: 
10987: =back
10988: 
10989: Returns:
10990: 
10991: =over 4
10992: 
10993: sorted   - An array of slot names sorted by a specified sort key 
10994:            (default sort key is start time of the slot).
10995: 
10996: =back
10997: 
10998: =cut
10999: 
11000: 
11001: sub sorted_slots {
11002:     my ($slotsarr,$slots,$sortkey) = @_;
11003:     if ($sortkey eq '') {
11004:         $sortkey = 'starttime';
11005:     }
11006:     my @sorted;
11007:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11008:         @sorted =
11009:             sort {
11010:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11011:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11012:                      }
11013:                      if (ref($slots->{$a})) { return -1;}
11014:                      if (ref($slots->{$b})) { return 1;}
11015:                      return 0;
11016:                  } @{$slotsarr};
11017:     }
11018:     return @sorted;
11019: }
11020: 
11021: =pod
11022: 
11023: =item * get_future_slots()
11024: 
11025: Inputs:
11026: 
11027: =over 4
11028: 
11029: cnum - course number
11030: 
11031: cdom - course domain
11032: 
11033: now - current UNIX time
11034: 
11035: symb - optional symb
11036: 
11037: =back
11038: 
11039: Returns:
11040: 
11041: =over 4
11042: 
11043: sorted_reservable - ref to array of student_schedulable slots currently 
11044:                     reservable, ordered by end date of reservation period.
11045: 
11046: reservable_now - ref to hash of student_schedulable slots currently
11047:                  reservable.
11048: 
11049:     Keys in inner hash are:
11050:     (a) symb: either blank or symb to which slot use is restricted.
11051:     (b) endreserve: end date of reservation period.
11052:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11053:         selected.
11054: 
11055: sorted_future - ref to array of student_schedulable slots reservable in
11056:                 the future, ordered by start date of reservation period.
11057: 
11058: future_reservable - ref to hash of student_schedulable slots reservable
11059:                     in the future.
11060: 
11061:     Keys in inner hash are:
11062:     (a) symb: either blank or symb to which slot use is restricted.
11063:     (b) startreserve: start date of reservation period.
11064:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11065:         selected.
11066: 
11067: =back
11068: 
11069: =cut
11070: 
11071: sub get_future_slots {
11072:     my ($cnum,$cdom,$now,$symb) = @_;
11073:     my $map;
11074:     if ($symb) {
11075:         ($map) = &Apache::lonnet::decode_symb($symb);
11076:     }
11077:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11078:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11079:     foreach my $slot (keys(%slots)) {
11080:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11081:         if ($symb) {
11082:             if ($slots{$slot}->{'symb'} ne '') {
11083:                 my $canuse;
11084:                 my %oksymbs;
11085:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11086:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11087:                 if ($oksymbs{$symb}) {
11088:                     $canuse = 1;
11089:                 } else {
11090:                     foreach my $item (@slotsymbs) {
11091:                         if ($item =~ /\.(page|sequence)$/) {
11092:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11093:                             if (($map ne '') && ($map eq $sloturl)) {
11094:                                 $canuse = 1;
11095:                                 last;
11096:                             }
11097:                         }
11098:                     }
11099:                 }
11100:                 next unless ($canuse);
11101:             }
11102:         }
11103:         if (($slots{$slot}->{'starttime'} > $now) &&
11104:             ($slots{$slot}->{'endtime'} > $now)) {
11105:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11106:                 my $userallowed = 0;
11107:                 if ($slots{$slot}->{'allowedsections'}) {
11108:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11109:                     if (!defined($env{'request.role.sec'})
11110:                         && grep(/^No section assigned$/,@allowed_sec)) {
11111:                         $userallowed=1;
11112:                     } else {
11113:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11114:                             $userallowed=1;
11115:                         }
11116:                     }
11117:                     unless ($userallowed) {
11118:                         if (defined($env{'request.course.groups'})) {
11119:                             my @groups = split(/:/,$env{'request.course.groups'});
11120:                             foreach my $group (@groups) {
11121:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11122:                                     $userallowed=1;
11123:                                     last;
11124:                                 }
11125:                             }
11126:                         }
11127:                     }
11128:                 }
11129:                 if ($slots{$slot}->{'allowedusers'}) {
11130:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11131:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11132:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11133:                         $userallowed = 1;
11134:                     }
11135:                 }
11136:                 next unless($userallowed);
11137:             }
11138:             my $startreserve = $slots{$slot}->{'startreserve'};
11139:             my $endreserve = $slots{$slot}->{'endreserve'};
11140:             my $symb = $slots{$slot}->{'symb'};
11141:             my $uniqueperiod;
11142:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11143:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11144:             }
11145:             if (($startreserve < $now) &&
11146:                 (!$endreserve || $endreserve > $now)) {
11147:                 my $lastres = $endreserve;
11148:                 if (!$lastres) {
11149:                     $lastres = $slots{$slot}->{'starttime'};
11150:                 }
11151:                 $reservable_now{$slot} = {
11152:                                            symb       => $symb,
11153:                                            endreserve => $lastres,
11154:                                            uniqueperiod => $uniqueperiod,
11155:                                          };
11156:             } elsif (($startreserve > $now) &&
11157:                      (!$endreserve || $endreserve > $startreserve)) {
11158:                 $future_reservable{$slot} = {
11159:                                               symb         => $symb,
11160:                                               startreserve => $startreserve,
11161:                                               uniqueperiod => $uniqueperiod,
11162:                                             };
11163:             }
11164:         }
11165:     }
11166:     my @unsorted_reservable = keys(%reservable_now);
11167:     if (@unsorted_reservable > 0) {
11168:         @sorted_reservable = 
11169:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11170:     }
11171:     my @unsorted_future = keys(%future_reservable);
11172:     if (@unsorted_future > 0) {
11173:         @sorted_future =
11174:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11175:     }
11176:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11177: }
11178: 
11179: =pod
11180: 
11181: =back
11182: 
11183: =head1 HTTP Helpers
11184: 
11185: =over 4
11186: 
11187: =item * &get_unprocessed_cgi($query,$possible_names)
11188: 
11189: Modify the %env hash to contain unprocessed CGI form parameters held in
11190: $query.  The parameters listed in $possible_names (an array reference),
11191: will be set in $env{'form.name'} if they do not already exist.
11192: 
11193: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11194: $possible_names is an ref to an array of form element names.  As an example:
11195: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11196: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11197: 
11198: =cut
11199: 
11200: sub get_unprocessed_cgi {
11201:   my ($query,$possible_names)= @_;
11202:   # $Apache::lonxml::debug=1;
11203:   foreach my $pair (split(/&/,$query)) {
11204:     my ($name, $value) = split(/=/,$pair);
11205:     $name = &unescape($name);
11206:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11207:       $value =~ tr/+/ /;
11208:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11209:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11210:     }
11211:   }
11212: }
11213: 
11214: =pod
11215: 
11216: =item * &cacheheader() 
11217: 
11218: returns cache-controlling header code
11219: 
11220: =cut
11221: 
11222: sub cacheheader {
11223:     unless ($env{'request.method'} eq 'GET') { return ''; }
11224:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11225:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11226:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11227:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11228:     return $output;
11229: }
11230: 
11231: =pod
11232: 
11233: =item * &no_cache($r) 
11234: 
11235: specifies header code to not have cache
11236: 
11237: =cut
11238: 
11239: sub no_cache {
11240:     my ($r) = @_;
11241:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11242: 	$env{'request.method'} ne 'GET') { return ''; }
11243:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11244:     $r->no_cache(1);
11245:     $r->header_out("Expires" => $date);
11246:     $r->header_out("Pragma" => "no-cache");
11247: }
11248: 
11249: sub content_type {
11250:     my ($r,$type,$charset) = @_;
11251:     if ($r) {
11252: 	#  Note that printout.pl calls this with undef for $r.
11253: 	&no_cache($r);
11254:     }
11255:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11256:     unless ($charset) {
11257: 	$charset=&Apache::lonlocal::current_encoding;
11258:     }
11259:     if ($charset) { $type.='; charset='.$charset; }
11260:     if ($r) {
11261: 	$r->content_type($type);
11262:     } else {
11263: 	print("Content-type: $type\n\n");
11264:     }
11265: }
11266: 
11267: =pod
11268: 
11269: =item * &add_to_env($name,$value) 
11270: 
11271: adds $name to the %env hash with value
11272: $value, if $name already exists, the entry is converted to an array
11273: reference and $value is added to the array.
11274: 
11275: =cut
11276: 
11277: sub add_to_env {
11278:   my ($name,$value)=@_;
11279:   if (defined($env{$name})) {
11280:     if (ref($env{$name})) {
11281:       #already have multiple values
11282:       push(@{ $env{$name} },$value);
11283:     } else {
11284:       #first time seeing multiple values, convert hash entry to an arrayref
11285:       my $first=$env{$name};
11286:       undef($env{$name});
11287:       push(@{ $env{$name} },$first,$value);
11288:     }
11289:   } else {
11290:     $env{$name}=$value;
11291:   }
11292: }
11293: 
11294: =pod
11295: 
11296: =item * &get_env_multiple($name) 
11297: 
11298: gets $name from the %env hash, it seemlessly handles the cases where multiple
11299: values may be defined and end up as an array ref.
11300: 
11301: returns an array of values
11302: 
11303: =cut
11304: 
11305: sub get_env_multiple {
11306:     my ($name) = @_;
11307:     my @values;
11308:     if (defined($env{$name})) {
11309:         # exists is it an array
11310:         if (ref($env{$name})) {
11311:             @values=@{ $env{$name} };
11312:         } else {
11313:             $values[0]=$env{$name};
11314:         }
11315:     }
11316:     return(@values);
11317: }
11318: 
11319: # Looks at given dependencies, and returns something depending on the context.
11320: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11321: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11322: # For all other contexts, returns ($output, $counter, $numpathchg).
11323: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11324: # $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.
11325: # $numpathchg: integer with the number of cleaned up dependency paths.
11326: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11327: # \%mapping: hash reference clean path -> original path for all dependencies.
11328: # @param {string} actionurl - The path to the handler, indicative of the context.
11329: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11330: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11331: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11332: # @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)
11333: # @return {Array} - array depending on the context (not a reference)
11334: sub ask_for_embedded_content {
11335:     # NOTE: documentation was added afterwards, it could be wrong
11336:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11337:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11338:         %currsubfile,%unused,$rem);
11339:     my $counter = 0;
11340:     my $numnew = 0;
11341:     my $numremref = 0;
11342:     my $numinvalid = 0;
11343:     my $numpathchg = 0;
11344:     my $numexisting = 0;
11345:     my $numunused = 0;
11346:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11347:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11348:     my $heading = &mt('Upload embedded files');
11349:     my $buttontext = &mt('Upload');
11350: 
11351:     # fills these variables based on the context:
11352:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11353:     # $path, $fileloc, $title, $rem, $filename
11354:     if ($env{'request.course.id'}) {
11355:         if ($actionurl eq '/adm/dependencies') {
11356:             $navmap = Apache::lonnavmaps::navmap->new();
11357:         }
11358:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11359:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11360:     }
11361:     if (($actionurl eq '/adm/portfolio') || 
11362:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11363:         my $current_path='/';
11364:         if ($env{'form.currentpath'}) {
11365:             $current_path = $env{'form.currentpath'};
11366:         }
11367:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11368:             $udom = $cdom;
11369:             $uname = $cnum;
11370:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11371:         } else {
11372:             $udom = $env{'user.domain'};
11373:             $uname = $env{'user.name'};
11374:             $url = '/userfiles/portfolio';
11375:         }
11376:         $toplevel = $url.'/';
11377:         $url .= $current_path;
11378:         $getpropath = 1;
11379:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11380:              ($actionurl eq '/adm/imsimport')) { 
11381:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11382:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11383:         $toplevel = $url;
11384:         if ($rest ne '') {
11385:             $url .= $rest;
11386:         }
11387:     } elsif ($actionurl eq '/adm/coursedocs') {
11388:         if (ref($args) eq 'HASH') {
11389:             $url = $args->{'docs_url'};
11390:             $toplevel = $url;
11391:             if ($args->{'context'} eq 'paste') {
11392:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11393:                 ($path) = 
11394:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11395:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11396:                 $fileloc =~ s{^/}{};
11397:             }
11398:         }
11399:     } elsif ($actionurl eq '/adm/dependencies')  {
11400:         if ($env{'request.course.id'} ne '') {
11401:             if (ref($args) eq 'HASH') {
11402:                 $url = $args->{'docs_url'};
11403:                 $title = $args->{'docs_title'};
11404:                 $toplevel = $url; 
11405:                 unless ($toplevel =~ m{^/}) {
11406:                     $toplevel = "/$url";
11407:                 }
11408:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11409:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11410:                     $path = $1;
11411:                 } else {
11412:                     ($path) =
11413:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11414:                 }
11415:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11416:                     $fileloc = $toplevel;
11417:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11418:                     my ($udom,$uname,$fname) =
11419:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11420:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11421:                 } else {
11422:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11423:                 }
11424:                 $fileloc =~ s{^/}{};
11425:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11426:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11427:             }
11428:         }
11429:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11430:         $udom = $cdom;
11431:         $uname = $cnum;
11432:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11433:         $toplevel = $url;
11434:         $path = $url;
11435:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11436:         $fileloc =~ s{^/}{};
11437:     }
11438:     
11439:     # parses the dependency paths to get some info
11440:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11441:     # $newfiles: hash URL -> 1 for new files or external URLs
11442:     # (will be completed later)
11443:     # $mapping:
11444:     #   for external URLs: external URL -> external URL
11445:     #   for relative paths: clean path -> original path
11446:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11447:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11448:     foreach my $file (keys(%{$allfiles})) {
11449:         my $embed_file;
11450:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11451:             $embed_file = $1;
11452:         } else {
11453:             $embed_file = $file;
11454:         }
11455:         my ($absolutepath,$cleaned_file);
11456:         if ($embed_file =~ m{^\w+://}) {
11457:             $cleaned_file = $embed_file;
11458:             $newfiles{$cleaned_file} = 1;
11459:             $mapping{$cleaned_file} = $embed_file;
11460:         } else {
11461:             $cleaned_file = &clean_path($embed_file);
11462:             if ($embed_file =~ m{^/}) {
11463:                 $absolutepath = $embed_file;
11464:             }
11465:             if ($cleaned_file =~ m{/}) {
11466:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11467:                 $path = &check_for_traversal($path,$url,$toplevel);
11468:                 my $item = $fname;
11469:                 if ($path ne '') {
11470:                     $item = $path.'/'.$fname;
11471:                     $subdependencies{$path}{$fname} = 1;
11472:                 } else {
11473:                     $dependencies{$item} = 1;
11474:                 }
11475:                 if ($absolutepath) {
11476:                     $mapping{$item} = $absolutepath;
11477:                 } else {
11478:                     $mapping{$item} = $embed_file;
11479:                 }
11480:             } else {
11481:                 $dependencies{$embed_file} = 1;
11482:                 if ($absolutepath) {
11483:                     $mapping{$cleaned_file} = $absolutepath;
11484:                 } else {
11485:                     $mapping{$cleaned_file} = $embed_file;
11486:                 }
11487:             }
11488:         }
11489:     }
11490:     
11491:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11492:     # and lists
11493:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11494:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11495:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11496:     #                                    the path had to be cleaned up
11497:     # $existing: hash clean path -> 1 if the file exists
11498:     # $numexisting: number of keys in $existing
11499:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11500:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11501:     #                                      dependency subdirectories that are
11502:     #                                      not listed as dependencies, with some exceptions using $rem
11503:     my $dirptr = 16384;
11504:     foreach my $path (keys(%subdependencies)) {
11505:         $currsubfile{$path} = {};
11506:         if (($actionurl eq '/adm/portfolio') || 
11507:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11508:             my ($sublistref,$listerror) =
11509:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11510:             if (ref($sublistref) eq 'ARRAY') {
11511:                 foreach my $line (@{$sublistref}) {
11512:                     my ($file_name,$rest) = split(/\&/,$line,2);
11513:                     $currsubfile{$path}{$file_name} = 1;
11514:                 }
11515:             }
11516:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11517:             if (opendir(my $dir,$url.'/'.$path)) {
11518:                 my @subdir_list = grep(!/^\./,readdir($dir));
11519:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11520:             }
11521:         } elsif (($actionurl eq '/adm/dependencies') ||
11522:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11523:                   ($args->{'context'} eq 'paste')) ||
11524:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11525:             if ($env{'request.course.id'} ne '') {
11526:                 my $dir;
11527:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11528:                     $dir = $fileloc;
11529:                 } else {
11530:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11531:                 }
11532:                 if ($dir ne '') {
11533:                     my ($sublistref,$listerror) =
11534:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11535:                     if (ref($sublistref) eq 'ARRAY') {
11536:                         foreach my $line (@{$sublistref}) {
11537:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11538:                                 undef,$mtime)=split(/\&/,$line,12);
11539:                             unless (($testdir&$dirptr) ||
11540:                                     ($file_name =~ /^\.\.?$/)) {
11541:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11542:                             }
11543:                         }
11544:                     }
11545:                 }
11546:             }
11547:         }
11548:         foreach my $file (keys(%{$subdependencies{$path}})) {
11549:             if (exists($currsubfile{$path}{$file})) {
11550:                 my $item = $path.'/'.$file;
11551:                 unless ($mapping{$item} eq $item) {
11552:                     $pathchanges{$item} = 1;
11553:                 }
11554:                 $existing{$item} = 1;
11555:                 $numexisting ++;
11556:             } else {
11557:                 $newfiles{$path.'/'.$file} = 1;
11558:             }
11559:         }
11560:         if ($actionurl eq '/adm/dependencies') {
11561:             foreach my $path (keys(%currsubfile)) {
11562:                 if (ref($currsubfile{$path}) eq 'HASH') {
11563:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11564:                          unless ($subdependencies{$path}{$file}) {
11565:                              next if (($rem ne '') &&
11566:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11567:                                        (ref($navmap) &&
11568:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11569:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11570:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11571:                              $unused{$path.'/'.$file} = 1; 
11572:                          }
11573:                     }
11574:                 }
11575:             }
11576:         }
11577:     }
11578:     
11579:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11580:     # for files in $url or $fileloc (target directory) in some contexts
11581:     my %currfile;
11582:     if (($actionurl eq '/adm/portfolio') ||
11583:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11584:         my ($dirlistref,$listerror) =
11585:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11586:         if (ref($dirlistref) eq 'ARRAY') {
11587:             foreach my $line (@{$dirlistref}) {
11588:                 my ($file_name,$rest) = split(/\&/,$line,2);
11589:                 $currfile{$file_name} = 1;
11590:             }
11591:         }
11592:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11593:         if (opendir(my $dir,$url)) {
11594:             my @dir_list = grep(!/^\./,readdir($dir));
11595:             map {$currfile{$_} = 1;} @dir_list;
11596:         }
11597:     } elsif (($actionurl eq '/adm/dependencies') ||
11598:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11599:               ($args->{'context'} eq 'paste')) ||
11600:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11601:         if ($env{'request.course.id'} ne '') {
11602:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11603:             if ($dir ne '') {
11604:                 my ($dirlistref,$listerror) =
11605:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11606:                 if (ref($dirlistref) eq 'ARRAY') {
11607:                     foreach my $line (@{$dirlistref}) {
11608:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11609:                             $size,undef,$mtime)=split(/\&/,$line,12);
11610:                         unless (($testdir&$dirptr) ||
11611:                                 ($file_name =~ /^\.\.?$/)) {
11612:                             $currfile{$file_name} = [$size,$mtime];
11613:                         }
11614:                     }
11615:                 }
11616:             }
11617:         }
11618:     }
11619:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11620:     # are not in subdirectories, using $currfile
11621:     foreach my $file (keys(%dependencies)) {
11622:         if (exists($currfile{$file})) {
11623:             unless ($mapping{$file} eq $file) {
11624:                 $pathchanges{$file} = 1;
11625:             }
11626:             $existing{$file} = 1;
11627:             $numexisting ++;
11628:         } else {
11629:             $newfiles{$file} = 1;
11630:         }
11631:     }
11632:     foreach my $file (keys(%currfile)) {
11633:         unless (($file eq $filename) ||
11634:                 ($file eq $filename.'.bak') ||
11635:                 ($dependencies{$file})) {
11636:             if ($actionurl eq '/adm/dependencies') {
11637:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11638:                     next if (($rem ne '') &&
11639:                              (($env{"httpref.$rem".$file} ne '') ||
11640:                               (ref($navmap) &&
11641:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11642:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11643:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11644:                 }
11645:             }
11646:             $unused{$file} = 1;
11647:         }
11648:     }
11649:     
11650:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11651:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11652:         ($args->{'context'} eq 'paste')) {
11653:         $counter = scalar(keys(%existing));
11654:         $numpathchg = scalar(keys(%pathchanges));
11655:         return ($output,$counter,$numpathchg,\%existing);
11656:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11657:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11658:         $counter = scalar(keys(%existing));
11659:         $numpathchg = scalar(keys(%pathchanges));
11660:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11661:     }
11662:     
11663:     # returns HTML otherwise, with dependency results and to ask for more uploads
11664:     
11665:     # $upload_output: missing dependencies (with upload form)
11666:     # $modify_output: uploaded dependencies (in use)
11667:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11668:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11669:         if ($actionurl eq '/adm/dependencies') {
11670:             next if ($embed_file =~ m{^\w+://});
11671:         }
11672:         $upload_output .= &start_data_table_row().
11673:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11674:                           '<span class="LC_filename">'.$embed_file.'</span>';
11675:         unless ($mapping{$embed_file} eq $embed_file) {
11676:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11677:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11678:         }
11679:         $upload_output .= '</td>';
11680:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11681:             $upload_output.='<td align="right">'.
11682:                             '<span class="LC_info LC_fontsize_medium">'.
11683:                             &mt("URL points to web address").'</span>';
11684:             $numremref++;
11685:         } elsif ($args->{'error_on_invalid_names'}
11686:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11687:             $upload_output.='<td align="right"><span class="LC_warning">'.
11688:                             &mt('Invalid characters').'</span>';
11689:             $numinvalid++;
11690:         } else {
11691:             $upload_output .= '<td>'.
11692:                               &embedded_file_element('upload_embedded',$counter,
11693:                                                      $embed_file,\%mapping,
11694:                                                      $allfiles,$codebase,'upload');
11695:             $counter ++;
11696:             $numnew ++;
11697:         }
11698:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11699:     }
11700:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11701:         if ($actionurl eq '/adm/dependencies') {
11702:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11703:             $modify_output .= &start_data_table_row().
11704:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11705:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11706:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11707:                               '<td>'.$size.'</td>'.
11708:                               '<td>'.$mtime.'</td>'.
11709:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11710:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11711:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11712:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11713:                               &embedded_file_element('upload_embedded',$counter,
11714:                                                      $embed_file,\%mapping,
11715:                                                      $allfiles,$codebase,'modify').
11716:                               '</div></td>'.
11717:                               &end_data_table_row()."\n";
11718:             $counter ++;
11719:         } else {
11720:             $upload_output .= &start_data_table_row().
11721:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11722:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11723:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11724:                               &Apache::loncommon::end_data_table_row()."\n";
11725:         }
11726:     }
11727:     my $delidx = $counter;
11728:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11729:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11730:         $delete_output .= &start_data_table_row().
11731:                           '<td><img src="'.&icon($oldfile).'" />'.
11732:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11733:                           '<td>'.$size.'</td>'.
11734:                           '<td>'.$mtime.'</td>'.
11735:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11736:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11737:                           &embedded_file_element('upload_embedded',$delidx,
11738:                                                  $oldfile,\%mapping,$allfiles,
11739:                                                  $codebase,'delete').'</td>'.
11740:                           &end_data_table_row()."\n"; 
11741:         $numunused ++;
11742:         $delidx ++;
11743:     }
11744:     if ($upload_output) {
11745:         $upload_output = &start_data_table().
11746:                          $upload_output.
11747:                          &end_data_table()."\n";
11748:     }
11749:     if ($modify_output) {
11750:         $modify_output = &start_data_table().
11751:                          &start_data_table_header_row().
11752:                          '<th>'.&mt('File').'</th>'.
11753:                          '<th>'.&mt('Size (KB)').'</th>'.
11754:                          '<th>'.&mt('Modified').'</th>'.
11755:                          '<th>'.&mt('Upload replacement?').'</th>'.
11756:                          &end_data_table_header_row().
11757:                          $modify_output.
11758:                          &end_data_table()."\n";
11759:     }
11760:     if ($delete_output) {
11761:         $delete_output = &start_data_table().
11762:                          &start_data_table_header_row().
11763:                          '<th>'.&mt('File').'</th>'.
11764:                          '<th>'.&mt('Size (KB)').'</th>'.
11765:                          '<th>'.&mt('Modified').'</th>'.
11766:                          '<th>'.&mt('Delete?').'</th>'.
11767:                          &end_data_table_header_row().
11768:                          $delete_output.
11769:                          &end_data_table()."\n";
11770:     }
11771:     my $applies = 0;
11772:     if ($numremref) {
11773:         $applies ++;
11774:     }
11775:     if ($numinvalid) {
11776:         $applies ++;
11777:     }
11778:     if ($numexisting) {
11779:         $applies ++;
11780:     }
11781:     if ($counter || $numunused) {
11782:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11783:                   ' method="post" enctype="multipart/form-data">'."\n".
11784:                   $state.'<h3>'.$heading.'</h3>'; 
11785:         if ($actionurl eq '/adm/dependencies') {
11786:             if ($numnew) {
11787:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11788:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11789:                            $upload_output.'<br />'."\n";
11790:             }
11791:             if ($numexisting) {
11792:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11793:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11794:                            $modify_output.'<br />'."\n";
11795:                            $buttontext = &mt('Save changes');
11796:             }
11797:             if ($numunused) {
11798:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11799:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11800:                            $delete_output.'<br />'."\n";
11801:                            $buttontext = &mt('Save changes');
11802:             }
11803:         } else {
11804:             $output .= $upload_output.'<br />'."\n";
11805:         }
11806:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11807:                    $counter.'" />'."\n";
11808:         if ($actionurl eq '/adm/dependencies') { 
11809:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11810:                        $numnew.'" />'."\n";
11811:         } elsif ($actionurl eq '') {
11812:             $output .=  '<input type="hidden" name="phase" value="three" />';
11813:         }
11814:     } elsif ($applies) {
11815:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11816:         if ($applies > 1) {
11817:             $output .=  
11818:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11819:             if ($numremref) {
11820:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11821:             }
11822:             if ($numinvalid) {
11823:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11824:             }
11825:             if ($numexisting) {
11826:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11827:             }
11828:             $output .= '</ul><br />';
11829:         } elsif ($numremref) {
11830:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11831:         } elsif ($numinvalid) {
11832:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11833:         } elsif ($numexisting) {
11834:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11835:         }
11836:         $output .= $upload_output.'<br />';
11837:     }
11838:     my ($pathchange_output,$chgcount);
11839:     $chgcount = $counter;
11840:     if (keys(%pathchanges) > 0) {
11841:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11842:             if ($counter) {
11843:                 $output .= &embedded_file_element('pathchange',$chgcount,
11844:                                                   $embed_file,\%mapping,
11845:                                                   $allfiles,$codebase,'change');
11846:             } else {
11847:                 $pathchange_output .= 
11848:                     &start_data_table_row().
11849:                     '<td><input type ="checkbox" name="namechange" value="'.
11850:                     $chgcount.'" checked="checked" /></td>'.
11851:                     '<td>'.$mapping{$embed_file}.'</td>'.
11852:                     '<td>'.$embed_file.
11853:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11854:                                            \%mapping,$allfiles,$codebase,'change').
11855:                     '</td>'.&end_data_table_row();
11856:             }
11857:             $numpathchg ++;
11858:             $chgcount ++;
11859:         }
11860:     }
11861:     if (($counter) || ($numunused)) {
11862:         if ($numpathchg) {
11863:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11864:                        $numpathchg.'" />'."\n";
11865:         }
11866:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11867:             ($actionurl eq '/adm/imsimport')) {
11868:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11869:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11870:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11871:         } elsif ($actionurl eq '/adm/dependencies') {
11872:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11873:         }
11874:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11875:     } elsif ($numpathchg) {
11876:         my %pathchange = ();
11877:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11878:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11879:             $output .= '<p>'.&mt('or').'</p>'; 
11880:         }
11881:     }
11882:     return ($output,$counter,$numpathchg);
11883: }
11884: 
11885: =pod
11886: 
11887: =item * clean_path($name)
11888: 
11889: Performs clean-up of directories, subdirectories and filename in an
11890: embedded object, referenced in an HTML file which is being uploaded
11891: to a course or portfolio, where 
11892: "Upload embedded images/multimedia files if HTML file" checkbox was
11893: checked.
11894: 
11895: Clean-up is similar to replacements in lonnet::clean_filename()
11896: except each / between sub-directory and next level is preserved.
11897: 
11898: =cut
11899: 
11900: sub clean_path {
11901:     my ($embed_file) = @_;
11902:     $embed_file =~s{^/+}{};
11903:     my @contents;
11904:     if ($embed_file =~ m{/}) {
11905:         @contents = split(/\//,$embed_file);
11906:     } else {
11907:         @contents = ($embed_file);
11908:     }
11909:     my $lastidx = scalar(@contents)-1;
11910:     for (my $i=0; $i<=$lastidx; $i++) { 
11911:         $contents[$i]=~s{\\}{/}g;
11912:         $contents[$i]=~s/\s+/\_/g;
11913:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11914:         if ($i == $lastidx) {
11915:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11916:         }
11917:     }
11918:     if ($lastidx > 0) {
11919:         return join('/',@contents);
11920:     } else {
11921:         return $contents[0];
11922:     }
11923: }
11924: 
11925: sub embedded_file_element {
11926:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11927:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11928:                    (ref($codebase) eq 'HASH'));
11929:     my $output;
11930:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11931:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11932:     }
11933:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11934:                &escape($embed_file).'" />';
11935:     unless (($context eq 'upload_embedded') && 
11936:             ($mapping->{$embed_file} eq $embed_file)) {
11937:         $output .='
11938:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11939:     }
11940:     my $attrib;
11941:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11942:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11943:     }
11944:     $output .=
11945:         "\n\t\t".
11946:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11947:         $attrib.'" />';
11948:     if (exists($codebase->{$mapping->{$embed_file}})) {
11949:         $output .=
11950:             "\n\t\t".
11951:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11952:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11953:     }
11954:     return $output;
11955: }
11956: 
11957: sub get_dependency_details {
11958:     my ($currfile,$currsubfile,$embed_file) = @_;
11959:     my ($size,$mtime,$showsize,$showmtime);
11960:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11961:         if ($embed_file =~ m{/}) {
11962:             my ($path,$fname) = split(/\//,$embed_file);
11963:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11964:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11965:             }
11966:         } else {
11967:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11968:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11969:             }
11970:         }
11971:         $showsize = $size/1024.0;
11972:         $showsize = sprintf("%.1f",$showsize);
11973:         if ($mtime > 0) {
11974:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11975:         }
11976:     }
11977:     return ($showsize,$showmtime);
11978: }
11979: 
11980: sub ask_embedded_js {
11981:     return <<"END";
11982: <script type="text/javascript"">
11983: // <![CDATA[
11984: function toggleBrowse(counter) {
11985:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11986:     var fileid = document.getElementById('embedded_item_'+counter);
11987:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11988:     if (chkboxid.checked == true) {
11989:         uploaddivid.style.display='block';
11990:     } else {
11991:         uploaddivid.style.display='none';
11992:         fileid.value = '';
11993:     }
11994: }
11995: // ]]>
11996: </script>
11997: 
11998: END
11999: }
12000: 
12001: sub upload_embedded {
12002:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12003:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12004:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12005:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12006:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12007:         my $orig_uploaded_filename =
12008:             $env{'form.embedded_item_'.$i.'.filename'};
12009:         foreach my $type ('orig','ref','attrib','codebase') {
12010:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12011:                 $env{'form.embedded_'.$type.'_'.$i} =
12012:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12013:             }
12014:         }
12015:         my ($path,$fname) =
12016:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12017:         # no path, whole string is fname
12018:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12019:         $fname = &Apache::lonnet::clean_filename($fname);
12020:         # See if there is anything left
12021:         next if ($fname eq '');
12022: 
12023:         # Check if file already exists as a file or directory.
12024:         my ($state,$msg);
12025:         if ($context eq 'portfolio') {
12026:             my $port_path = $dirpath;
12027:             if ($group ne '') {
12028:                 $port_path = "groups/$group/$port_path";
12029:             }
12030:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12031:                                               $fname,$group,'embedded_item_'.$i,
12032:                                               $dir_root,$port_path,$disk_quota,
12033:                                               $current_disk_usage,$uname,$udom);
12034:             if ($state eq 'will_exceed_quota'
12035:                 || $state eq 'file_locked') {
12036:                 $output .= $msg;
12037:                 next;
12038:             }
12039:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12040:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12041:             if ($state eq 'exists') {
12042:                 $output .= $msg;
12043:                 next;
12044:             }
12045:         }
12046:         # Check if extension is valid
12047:         if (($fname =~ /\.(\w+)$/) &&
12048:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12049:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12050:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12051:             next;
12052:         } elsif (($fname =~ /\.(\w+)$/) &&
12053:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12054:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12055:             next;
12056:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12057:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12058:             next;
12059:         }
12060:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12061:         my $subdir = $path;
12062:         $subdir =~ s{/+$}{};
12063:         if ($context eq 'portfolio') {
12064:             my $result;
12065:             if ($state eq 'existingfile') {
12066:                 $result=
12067:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12068:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12069:             } else {
12070:                 $result=
12071:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12072:                                                     $dirpath.
12073:                                                     $env{'form.currentpath'}.$subdir);
12074:                 if ($result !~ m|^/uploaded/|) {
12075:                     $output .= '<span class="LC_error">'
12076:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12077:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12078:                                .'</span><br />';
12079:                     next;
12080:                 } else {
12081:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12082:                                $path.$fname.'</span>').'<br />';     
12083:                 }
12084:             }
12085:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12086:             my $extendedsubdir = $dirpath.'/'.$subdir;
12087:             $extendedsubdir =~ s{/+$}{};
12088:             my $result =
12089:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12090:             if ($result !~ m|^/uploaded/|) {
12091:                 $output .= '<span class="LC_error">'
12092:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12093:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12094:                            .'</span><br />';
12095:                     next;
12096:             } else {
12097:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12098:                            $path.$fname.'</span>').'<br />';
12099:                 if ($context eq 'syllabus') {
12100:                     &Apache::lonnet::make_public_indefinitely($result);
12101:                 }
12102:             }
12103:         } else {
12104: # Save the file
12105:             my $target = $env{'form.embedded_item_'.$i};
12106:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12107:             my $dest = $fullpath.$fname;
12108:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12109:             my @parts=split(/\//,"$dirpath/$path");
12110:             my $count;
12111:             my $filepath = $dir_root;
12112:             foreach my $subdir (@parts) {
12113:                 $filepath .= "/$subdir";
12114:                 if (!-e $filepath) {
12115:                     mkdir($filepath,0770);
12116:                 }
12117:             }
12118:             my $fh;
12119:             if (!open($fh,'>'.$dest)) {
12120:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12121:                 $output .= '<span class="LC_error">'.
12122:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12123:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12124:                            '</span><br />';
12125:             } else {
12126:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12127:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12128:                     $output .= '<span class="LC_error">'.
12129:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12130:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12131:                               '</span><br />';
12132:                 } else {
12133:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12134:                                $url.'</span>').'<br />';
12135:                     unless ($context eq 'testbank') {
12136:                         $footer .= &mt('View embedded file: [_1]',
12137:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12138:                     }
12139:                 }
12140:                 close($fh);
12141:             }
12142:         }
12143:         if ($env{'form.embedded_ref_'.$i}) {
12144:             $pathchange{$i} = 1;
12145:         }
12146:     }
12147:     if ($output) {
12148:         $output = '<p>'.$output.'</p>';
12149:     }
12150:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12151:     $returnflag = 'ok';
12152:     my $numpathchgs = scalar(keys(%pathchange));
12153:     if ($numpathchgs > 0) {
12154:         if ($context eq 'portfolio') {
12155:             $output .= '<p>'.&mt('or').'</p>';
12156:         } elsif ($context eq 'testbank') {
12157:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12158:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12159:             $returnflag = 'modify_orightml';
12160:         }
12161:     }
12162:     return ($output.$footer,$returnflag,$numpathchgs);
12163: }
12164: 
12165: sub modify_html_form {
12166:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12167:     my $end = 0;
12168:     my $modifyform;
12169:     if ($context eq 'upload_embedded') {
12170:         return unless (ref($pathchange) eq 'HASH');
12171:         if ($env{'form.number_embedded_items'}) {
12172:             $end += $env{'form.number_embedded_items'};
12173:         }
12174:         if ($env{'form.number_pathchange_items'}) {
12175:             $end += $env{'form.number_pathchange_items'};
12176:         }
12177:         if ($end) {
12178:             for (my $i=0; $i<$end; $i++) {
12179:                 if ($i < $env{'form.number_embedded_items'}) {
12180:                     next unless($pathchange->{$i});
12181:                 }
12182:                 $modifyform .=
12183:                     &start_data_table_row().
12184:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12185:                     'checked="checked" /></td>'.
12186:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12187:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12188:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12189:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12190:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12191:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12192:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12193:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12194:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12195:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12196:                     &end_data_table_row();
12197:             }
12198:         }
12199:     } else {
12200:         $modifyform = $pathchgtable;
12201:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12202:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12203:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12204:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12205:         }
12206:     }
12207:     if ($modifyform) {
12208:         if ($actionurl eq '/adm/dependencies') {
12209:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12210:         }
12211:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12212:                '<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".
12213:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12214:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12215:                '</ol></p>'."\n".'<p>'.
12216:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12217:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12218:                &start_data_table()."\n".
12219:                &start_data_table_header_row().
12220:                '<th>'.&mt('Change?').'</th>'.
12221:                '<th>'.&mt('Current reference').'</th>'.
12222:                '<th>'.&mt('Required reference').'</th>'.
12223:                &end_data_table_header_row()."\n".
12224:                $modifyform.
12225:                &end_data_table().'<br />'."\n".$hiddenstate.
12226:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12227:                '</form>'."\n";
12228:     }
12229:     return;
12230: }
12231: 
12232: sub modify_html_refs {
12233:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12234:     my $container;
12235:     if ($context eq 'portfolio') {
12236:         $container = $env{'form.container'};
12237:     } elsif ($context eq 'coursedoc') {
12238:         $container = $env{'form.primaryurl'};
12239:     } elsif ($context eq 'manage_dependencies') {
12240:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12241:         $container = "/$container";
12242:     } elsif ($context eq 'syllabus') {
12243:         $container = $url;
12244:     } else {
12245:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12246:     }
12247:     my (%allfiles,%codebase,$output,$content);
12248:     my @changes = &get_env_multiple('form.namechange');
12249:     unless ((@changes > 0) || ($context eq 'syllabus')) {
12250:         if (wantarray) {
12251:             return ('',0,0); 
12252:         } else {
12253:             return;
12254:         }
12255:     }
12256:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12257:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12258:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12259:             if (wantarray) {
12260:                 return ('',0,0);
12261:             } else {
12262:                 return;
12263:             }
12264:         } 
12265:         $content = &Apache::lonnet::getfile($container);
12266:         if ($content eq '-1') {
12267:             if (wantarray) {
12268:                 return ('',0,0);
12269:             } else {
12270:                 return;
12271:             }
12272:         }
12273:     } else {
12274:         unless ($container =~ /^\Q$dir_root\E/) {
12275:             if (wantarray) {
12276:                 return ('',0,0);
12277:             } else {
12278:                 return;
12279:             }
12280:         } 
12281:         if (open(my $fh,'<',$container)) {
12282:             $content = join('', <$fh>);
12283:             close($fh);
12284:         } else {
12285:             if (wantarray) {
12286:                 return ('',0,0);
12287:             } else {
12288:                 return;
12289:             }
12290:         }
12291:     }
12292:     my ($count,$codebasecount) = (0,0);
12293:     my $mm = new File::MMagic;
12294:     my $mime_type = $mm->checktype_contents($content);
12295:     if ($mime_type eq 'text/html') {
12296:         my $parse_result = 
12297:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12298:                                                     \%codebase,\$content);
12299:         if ($parse_result eq 'ok') {
12300:             foreach my $i (@changes) {
12301:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12302:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12303:                 if ($allfiles{$ref}) {
12304:                     my $newname =  $orig;
12305:                     my ($attrib_regexp,$codebase);
12306:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12307:                     if ($attrib_regexp =~ /:/) {
12308:                         $attrib_regexp =~ s/\:/|/g;
12309:                     }
12310:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12311:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12312:                         $count += $numchg;
12313:                         $allfiles{$newname} = $allfiles{$ref};
12314:                         delete($allfiles{$ref});
12315:                     }
12316:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12317:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12318:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12319:                         $codebasecount ++;
12320:                     }
12321:                 }
12322:             }
12323:             my $skiprewrites;
12324:             if ($count || $codebasecount) {
12325:                 my $saveresult;
12326:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12327:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12328:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12329:                     if ($url eq $container) {
12330:                         my ($fname) = ($container =~ m{/([^/]+)$});
12331:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12332:                                             $count,'<span class="LC_filename">'.
12333:                                             $fname.'</span>').'</p>';
12334:                     } else {
12335:                          $output = '<p class="LC_error">'.
12336:                                    &mt('Error: update failed for: [_1].',
12337:                                    '<span class="LC_filename">'.
12338:                                    $container.'</span>').'</p>';
12339:                     }
12340:                     if ($context eq 'syllabus') {
12341:                         unless ($saveresult eq 'ok') {
12342:                             $skiprewrites = 1;
12343:                         }
12344:                     }
12345:                 } else {
12346:                     if (open(my $fh,'>',$container)) {
12347:                         print $fh $content;
12348:                         close($fh);
12349:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12350:                                   $count,'<span class="LC_filename">'.
12351:                                   $container.'</span>').'</p>';
12352:                     } else {
12353:                          $output = '<p class="LC_error">'.
12354:                                    &mt('Error: could not update [_1].',
12355:                                    '<span class="LC_filename">'.
12356:                                    $container.'</span>').'</p>';
12357:                     }
12358:                 }
12359:             }
12360:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12361:                 my ($actionurl,$state);
12362:                 $actionurl = "/public/$udom/$uname/syllabus";
12363:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12364:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12365:                                               \%codebase,
12366:                                               {'context' => 'rewrites',
12367:                                                'ignore_remote_references' => 1,});
12368:                 if (ref($mapping) eq 'HASH') {
12369:                     my $rewrites = 0;
12370:                     foreach my $key (keys(%{$mapping})) {
12371:                         next if ($key =~ m{^https?://});
12372:                         my $ref = $mapping->{$key};
12373:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12374:                         my $attrib;
12375:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12376:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12377:                         }
12378:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12379:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12380:                             $rewrites += $numchg;
12381:                         }
12382:                     }
12383:                     if ($rewrites) {
12384:                         my $saveresult; 
12385:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12386:                         if ($url eq $container) {
12387:                             my ($fname) = ($container =~ m{/([^/]+)$});
12388:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12389:                                             $count,'<span class="LC_filename">'.
12390:                                             $fname.'</span>').'</p>';
12391:                         } else {
12392:                             $output .= '<p class="LC_error">'.
12393:                                        &mt('Error: could not update links in [_1].',
12394:                                        '<span class="LC_filename">'.
12395:                                        $container.'</span>').'</p>';
12396: 
12397:                         }
12398:                     }
12399:                 }
12400:             }
12401:         } else {
12402:             &logthis('Failed to parse '.$container.
12403:                      ' to modify references: '.$parse_result);
12404:         }
12405:     }
12406:     if (wantarray) {
12407:         return ($output,$count,$codebasecount);
12408:     } else {
12409:         return $output;
12410:     }
12411: }
12412: 
12413: sub check_for_existing {
12414:     my ($path,$fname,$element) = @_;
12415:     my ($state,$msg);
12416:     if (-d $path.'/'.$fname) {
12417:         $state = 'exists';
12418:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12419:     } elsif (-e $path.'/'.$fname) {
12420:         $state = 'exists';
12421:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12422:     }
12423:     if ($state eq 'exists') {
12424:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12425:     }
12426:     return ($state,$msg);
12427: }
12428: 
12429: sub check_for_upload {
12430:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12431:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12432:     my $filesize = length($env{'form.'.$element});
12433:     if (!$filesize) {
12434:         my $msg = '<span class="LC_error">'.
12435:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12436:                       '<span class="LC_filename">'.$fname.'</span>',
12437:                       $filesize).'<br />'.
12438:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12439:                   '</span>';
12440:         return ('zero_bytes',$msg);
12441:     }
12442:     $filesize =  $filesize/1000; #express in k (1024?)
12443:     my $getpropath = 1;
12444:     my ($dirlistref,$listerror) =
12445:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12446:     my $found_file = 0;
12447:     my $locked_file = 0;
12448:     my @lockers;
12449:     my $navmap;
12450:     if ($env{'request.course.id'}) {
12451:         $navmap = Apache::lonnavmaps::navmap->new();
12452:     }
12453:     if (ref($dirlistref) eq 'ARRAY') {
12454:         foreach my $line (@{$dirlistref}) {
12455:             my ($file_name,$rest)=split(/\&/,$line,2);
12456:             if ($file_name eq $fname){
12457:                 $file_name = $path.$file_name;
12458:                 if ($group ne '') {
12459:                     $file_name = $group.$file_name;
12460:                 }
12461:                 $found_file = 1;
12462:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12463:                     foreach my $lock (@lockers) {
12464:                         if (ref($lock) eq 'ARRAY') {
12465:                             my ($symb,$crsid) = @{$lock};
12466:                             if ($crsid eq $env{'request.course.id'}) {
12467:                                 if (ref($navmap)) {
12468:                                     my $res = $navmap->getBySymb($symb);
12469:                                     foreach my $part (@{$res->parts()}) { 
12470:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12471:                                         unless (($slot_status == $res->RESERVED) ||
12472:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12473:                                             $locked_file = 1;
12474:                                         }
12475:                                     }
12476:                                 } else {
12477:                                     $locked_file = 1;
12478:                                 }
12479:                             } else {
12480:                                 $locked_file = 1;
12481:                             }
12482:                         }
12483:                    }
12484:                 } else {
12485:                     my @info = split(/\&/,$rest);
12486:                     my $currsize = $info[6]/1000;
12487:                     if ($currsize < $filesize) {
12488:                         my $extra = $filesize - $currsize;
12489:                         if (($current_disk_usage + $extra) > $disk_quota) {
12490:                             my $msg = '<p class="LC_warning">'.
12491:                                       &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.',
12492:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12493:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12494:                                                    $disk_quota,$current_disk_usage).'</p>';
12495:                             return ('will_exceed_quota',$msg);
12496:                         }
12497:                     }
12498:                 }
12499:             }
12500:         }
12501:     }
12502:     if (($current_disk_usage + $filesize) > $disk_quota){
12503:         my $msg = '<p class="LC_warning">'.
12504:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12505:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12506:         return ('will_exceed_quota',$msg);
12507:     } elsif ($found_file) {
12508:         if ($locked_file) {
12509:             my $msg = '<p class="LC_warning">';
12510:             $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>');
12511:             $msg .= '</p>';
12512:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12513:             return ('file_locked',$msg);
12514:         } else {
12515:             my $msg = '<p class="LC_error">';
12516:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12517:             $msg .= '</p>';
12518:             return ('existingfile',$msg);
12519:         }
12520:     }
12521: }
12522: 
12523: sub check_for_traversal {
12524:     my ($path,$url,$toplevel) = @_;
12525:     my @parts=split(/\//,$path);
12526:     my $cleanpath;
12527:     my $fullpath = $url;
12528:     for (my $i=0;$i<@parts;$i++) {
12529:         next if ($parts[$i] eq '.');
12530:         if ($parts[$i] eq '..') {
12531:             $fullpath =~ s{([^/]+/)$}{};
12532:         } else {
12533:             $fullpath .= $parts[$i].'/';
12534:         }
12535:     }
12536:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12537:         $cleanpath = $1;
12538:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12539:         my $curr_toprel = $1;
12540:         my @parts = split(/\//,$curr_toprel);
12541:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12542:         my @urlparts = split(/\//,$url_toprel);
12543:         my $doubledots;
12544:         my $startdiff = -1;
12545:         for (my $i=0; $i<@urlparts; $i++) {
12546:             if ($startdiff == -1) {
12547:                 unless ($urlparts[$i] eq $parts[$i]) {
12548:                     $startdiff = $i;
12549:                     $doubledots .= '../';
12550:                 }
12551:             } else {
12552:                 $doubledots .= '../';
12553:             }
12554:         }
12555:         if ($startdiff > -1) {
12556:             $cleanpath = $doubledots;
12557:             for (my $i=$startdiff; $i<@parts; $i++) {
12558:                 $cleanpath .= $parts[$i].'/';
12559:             }
12560:         }
12561:     }
12562:     $cleanpath =~ s{(/)$}{};
12563:     return $cleanpath;
12564: }
12565: 
12566: sub is_archive_file {
12567:     my ($mimetype) = @_;
12568:     if (($mimetype eq 'application/octet-stream') ||
12569:         ($mimetype eq 'application/x-stuffit') ||
12570:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12571:         return 1;
12572:     }
12573:     return;
12574: }
12575: 
12576: sub decompress_form {
12577:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12578:     my %lt = &Apache::lonlocal::texthash (
12579:         this => 'This file is an archive file.',
12580:         camt => 'This file is a Camtasia archive file.',
12581:         itsc => 'Its contents are as follows:',
12582:         youm => 'You may wish to extract its contents.',
12583:         extr => 'Extract contents',
12584:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12585:         proa => 'Process automatically?',
12586:         yes  => 'Yes',
12587:         no   => 'No',
12588:         fold => 'Title for folder containing movie',
12589:         movi => 'Title for page containing embedded movie', 
12590:     );
12591:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12592:     my ($is_camtasia,$topdir,%toplevel,@paths);
12593:     my $info = &list_archive_contents($fileloc,\@paths);
12594:     if (@paths) {
12595:         foreach my $path (@paths) {
12596:             $path =~ s{^/}{};
12597:             if ($path =~ m{^([^/]+)/$}) {
12598:                 $topdir = $1;
12599:             }
12600:             if ($path =~ m{^([^/]+)/}) {
12601:                 $toplevel{$1} = $path;
12602:             } else {
12603:                 $toplevel{$path} = $path;
12604:             }
12605:         }
12606:     }
12607:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12608:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12609:                         "$topdir/media/",
12610:                         "$topdir/media/$topdir.mp4",
12611:                         "$topdir/media/FirstFrame.png",
12612:                         "$topdir/media/player.swf",
12613:                         "$topdir/media/swfobject.js",
12614:                         "$topdir/media/expressInstall.swf");
12615:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12616:                          "$topdir/$topdir.mp4",
12617:                          "$topdir/$topdir\_config.xml",
12618:                          "$topdir/$topdir\_controller.swf",
12619:                          "$topdir/$topdir\_embed.css",
12620:                          "$topdir/$topdir\_First_Frame.png",
12621:                          "$topdir/$topdir\_player.html",
12622:                          "$topdir/$topdir\_Thumbnails.png",
12623:                          "$topdir/playerProductInstall.swf",
12624:                          "$topdir/scripts/",
12625:                          "$topdir/scripts/config_xml.js",
12626:                          "$topdir/scripts/handlebars.js",
12627:                          "$topdir/scripts/jquery-1.7.1.min.js",
12628:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12629:                          "$topdir/scripts/modernizr.js",
12630:                          "$topdir/scripts/player-min.js",
12631:                          "$topdir/scripts/swfobject.js",
12632:                          "$topdir/skins/",
12633:                          "$topdir/skins/configuration_express.xml",
12634:                          "$topdir/skins/express_show/",
12635:                          "$topdir/skins/express_show/player-min.css",
12636:                          "$topdir/skins/express_show/spritesheet.png");
12637:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12638:                          "$topdir/$topdir.mp4",
12639:                          "$topdir/$topdir\_config.xml",
12640:                          "$topdir/$topdir\_controller.swf",
12641:                          "$topdir/$topdir\_embed.css",
12642:                          "$topdir/$topdir\_First_Frame.png",
12643:                          "$topdir/$topdir\_player.html",
12644:                          "$topdir/$topdir\_Thumbnails.png",
12645:                          "$topdir/playerProductInstall.swf",
12646:                          "$topdir/scripts/",
12647:                          "$topdir/scripts/config_xml.js",
12648:                          "$topdir/scripts/techsmith-smart-player.min.js",
12649:                          "$topdir/skins/",
12650:                          "$topdir/skins/configuration_express.xml",
12651:                          "$topdir/skins/express_show/",
12652:                          "$topdir/skins/express_show/spritesheet.min.css",
12653:                          "$topdir/skins/express_show/spritesheet.png",
12654:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12655:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12656:         if (@diffs == 0) {
12657:             $is_camtasia = 6;
12658:         } else {
12659:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12660:             if (@diffs == 0) {
12661:                 $is_camtasia = 8;
12662:             } else {
12663:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12664:                 if (@diffs == 0) {
12665:                     $is_camtasia = 8;
12666:                 }
12667:             }
12668:         }
12669:     }
12670:     my $output;
12671:     if ($is_camtasia) {
12672:         $output = <<"ENDCAM";
12673: <script type="text/javascript" language="Javascript">
12674: // <![CDATA[
12675: 
12676: function camtasiaToggle() {
12677:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12678:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12679:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12680:                 document.getElementById('camtasia_titles').style.display='block';
12681:             } else {
12682:                 document.getElementById('camtasia_titles').style.display='none';
12683:             }
12684:         }
12685:     }
12686:     return;
12687: }
12688: 
12689: // ]]>
12690: </script>
12691: <p>$lt{'camt'}</p>
12692: ENDCAM
12693:     } else {
12694:         $output = '<p>'.$lt{'this'};
12695:         if ($info eq '') {
12696:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12697:         } else {
12698:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12699:                        '<div><pre>'.$info.'</pre></div>';
12700:         }
12701:     }
12702:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12703:     my $duplicates;
12704:     my $num = 0;
12705:     if (ref($dirlist) eq 'ARRAY') {
12706:         foreach my $item (@{$dirlist}) {
12707:             if (ref($item) eq 'ARRAY') {
12708:                 if (exists($toplevel{$item->[0]})) {
12709:                     $duplicates .= 
12710:                         &start_data_table_row().
12711:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12712:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12713:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12714:                         'value="1" />'.&mt('Yes').'</label>'.
12715:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12716:                         '<td>'.$item->[0].'</td>';
12717:                     if ($item->[2]) {
12718:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12719:                     } else {
12720:                         $duplicates .= '<td>'.&mt('File').'</td>';
12721:                     }
12722:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12723:                                    '<td>'.
12724:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12725:                                    '</td>'.
12726:                                    &end_data_table_row();
12727:                     $num ++;
12728:                 }
12729:             }
12730:         }
12731:     }
12732:     my $itemcount;
12733:     if (@paths > 0) {
12734:         $itemcount = scalar(@paths);
12735:     } else {
12736:         $itemcount = 1;
12737:     }
12738:     if ($is_camtasia) {
12739:         $output .= $lt{'auto'}.'<br />'.
12740:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12741:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12742:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12743:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12744:                    $lt{'no'}.'</label></span><br />'.
12745:                    '<div id="camtasia_titles" style="display:block">'.
12746:                    &Apache::lonhtmlcommon::start_pick_box().
12747:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12748:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12749:                    &Apache::lonhtmlcommon::row_closure().
12750:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12751:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12752:                    &Apache::lonhtmlcommon::row_closure(1).
12753:                    &Apache::lonhtmlcommon::end_pick_box().
12754:                    '</div>';
12755:     }
12756:     $output .= 
12757:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12758:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12759:         "\n";
12760:     if ($duplicates ne '') {
12761:         $output .= '<p><span class="LC_warning">'.
12762:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12763:                    &start_data_table().
12764:                    &start_data_table_header_row().
12765:                    '<th>'.&mt('Overwrite?').'</th>'.
12766:                    '<th>'.&mt('Name').'</th>'.
12767:                    '<th>'.&mt('Type').'</th>'.
12768:                    '<th>'.&mt('Size').'</th>'.
12769:                    '<th>'.&mt('Last modified').'</th>'.
12770:                    &end_data_table_header_row().
12771:                    $duplicates.
12772:                    &end_data_table().
12773:                    '</p>';
12774:     }
12775:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12776:     if (ref($hiddenelements) eq 'HASH') {
12777:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12778:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12779:         }
12780:     }
12781:     $output .= <<"END";
12782: <br />
12783: <input type="submit" name="decompress" value="$lt{'extr'}" />
12784: </form>
12785: $noextract
12786: END
12787:     return $output;
12788: }
12789: 
12790: sub decompression_utility {
12791:     my ($program) = @_;
12792:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12793:     my $location;
12794:     if (grep(/^\Q$program\E$/,@utilities)) { 
12795:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12796:                          '/usr/sbin/') {
12797:             if (-x $dir.$program) {
12798:                 $location = $dir.$program;
12799:                 last;
12800:             }
12801:         }
12802:     }
12803:     return $location;
12804: }
12805: 
12806: sub list_archive_contents {
12807:     my ($file,$pathsref) = @_;
12808:     my (@cmd,$output);
12809:     my $needsregexp;
12810:     if ($file =~ /\.zip$/) {
12811:         @cmd = (&decompression_utility('unzip'),"-l");
12812:         $needsregexp = 1;
12813:     } elsif (($file =~ m/\.tar\.gz$/) ||
12814:              ($file =~ /\.tgz$/)) {
12815:         @cmd = (&decompression_utility('tar'),"-ztf");
12816:     } elsif ($file =~ /\.tar\.bz2$/) {
12817:         @cmd = (&decompression_utility('tar'),"-jtf");
12818:     } elsif ($file =~ m|\.tar$|) {
12819:         @cmd = (&decompression_utility('tar'),"-tf");
12820:     }
12821:     if (@cmd) {
12822:         undef($!);
12823:         undef($@);
12824:         if (open(my $fh,"-|", @cmd, $file)) {
12825:             while (my $line = <$fh>) {
12826:                 $output .= $line;
12827:                 chomp($line);
12828:                 my $item;
12829:                 if ($needsregexp) {
12830:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12831:                 } else {
12832:                     $item = $line;
12833:                 }
12834:                 if ($item ne '') {
12835:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12836:                         push(@{$pathsref},$item);
12837:                     } 
12838:                 }
12839:             }
12840:             close($fh);
12841:         }
12842:     }
12843:     return $output;
12844: }
12845: 
12846: sub decompress_uploaded_file {
12847:     my ($file,$dir) = @_;
12848:     &Apache::lonnet::appenv({'cgi.file' => $file});
12849:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12850:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12851:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12852:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12853:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12854:     my $decompressed = $env{'cgi.decompressed'};
12855:     &Apache::lonnet::delenv('cgi.file');
12856:     &Apache::lonnet::delenv('cgi.dir');
12857:     &Apache::lonnet::delenv('cgi.decompressed');
12858:     return ($decompressed,$result);
12859: }
12860: 
12861: sub process_decompression {
12862:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12863:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12864:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12865:                &mt('Unexpected file path.').'</p>'."\n";
12866:     }
12867:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12868:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12869:                &mt('Unexpected course context.').'</p>'."\n";
12870:     }
12871:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12872:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12873:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12874:     }
12875:     my ($dir,$error,$warning,$output);
12876:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12877:         $error = &mt('Filename not a supported archive file type.').
12878:                  '<br />'.&mt('Filename should end with one of: [_1].',
12879:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12880:     } else {
12881:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12882:         if ($docuhome eq 'no_host') {
12883:             $error = &mt('Could not determine home server for course.');
12884:         } else {
12885:             my @ids=&Apache::lonnet::current_machine_ids();
12886:             my $currdir = "$dir_root/$destination";
12887:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12888:                 $dir = &LONCAPA::propath($docudom,$docuname).
12889:                        "$dir_root/$destination";
12890:             } else {
12891:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12892:                        "$dir_root/$docudom/$docuname/$destination";
12893:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12894:                     $error = &mt('Archive file not found.');
12895:                 }
12896:             }
12897:             my (@to_overwrite,@to_skip);
12898:             if ($env{'form.archive_overwrite_total'} > 0) {
12899:                 my $total = $env{'form.archive_overwrite_total'};
12900:                 for (my $i=0; $i<$total; $i++) {
12901:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12902:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12903:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12904:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12905:                     }
12906:                 }
12907:             }
12908:             my $numskip = scalar(@to_skip);
12909:             my $numoverwrite = scalar(@to_overwrite);
12910:             if (($numskip) && (!$numoverwrite)) { 
12911:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12912:             } elsif ($dir eq '') {
12913:                 $error = &mt('Directory containing archive file unavailable.');
12914:             } elsif (!$error) {
12915:                 my ($decompressed,$display);
12916:                 if (($numskip) || ($numoverwrite)) {
12917:                     my $tempdir = time.'_'.$$.int(rand(10000));
12918:                     mkdir("$dir/$tempdir",0755);
12919:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12920:                         ($decompressed,$display) = 
12921:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12922:                         foreach my $item (@to_skip) {
12923:                             if (($item ne '') && ($item !~ /\.\./)) {
12924:                                 if (-f "$dir/$tempdir/$item") { 
12925:                                     unlink("$dir/$tempdir/$item");
12926:                                 } elsif (-d "$dir/$tempdir/$item") {
12927:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12928:                                 }
12929:                             }
12930:                         }
12931:                         foreach my $item (@to_overwrite) {
12932:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12933:                                 if (($item ne '') && ($item !~ /\.\./)) {
12934:                                     if (-f "$dir/$item") {
12935:                                         unlink("$dir/$item");
12936:                                     } elsif (-d "$dir/$item") {
12937:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12938:                                     }
12939:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12940:                                 }
12941:                             }
12942:                         }
12943:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12944:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12945:                         }
12946:                     }
12947:                 } else {
12948:                     ($decompressed,$display) = 
12949:                         &decompress_uploaded_file($file,$dir);
12950:                 }
12951:                 if ($decompressed eq 'ok') {
12952:                     $output = '<p class="LC_info">'.
12953:                               &mt('Files extracted successfully from archive.').
12954:                               '</p>'."\n";
12955:                     my ($warning,$result,@contents);
12956:                     my ($newdirlistref,$newlisterror) =
12957:                         &Apache::lonnet::dirlist($currdir,$docudom,
12958:                                                  $docuname,1);
12959:                     my (%is_dir,%changes,@newitems);
12960:                     my $dirptr = 16384;
12961:                     if (ref($newdirlistref) eq 'ARRAY') {
12962:                         foreach my $dir_line (@{$newdirlistref}) {
12963:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12964:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
12965:                                 push(@newitems,$item);
12966:                                 if ($dirptr&$testdir) {
12967:                                     $is_dir{$item} = 1;
12968:                                 }
12969:                                 $changes{$item} = 1;
12970:                             }
12971:                         }
12972:                     }
12973:                     if (keys(%changes) > 0) {
12974:                         foreach my $item (sort(@newitems)) {
12975:                             if ($changes{$item}) {
12976:                                 push(@contents,$item);
12977:                             }
12978:                         }
12979:                     }
12980:                     if (@contents > 0) {
12981:                         my $wantform;
12982:                         unless ($env{'form.autoextract_camtasia'}) {
12983:                             $wantform = 1;
12984:                         }
12985:                         my (%children,%parent,%dirorder,%titles);
12986:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12987:                                                                 $currdir,\%is_dir,
12988:                                                                 \%children,\%parent,
12989:                                                                 \@contents,\%dirorder,
12990:                                                                 \%titles,$wantform);
12991:                         if ($datatable ne '') {
12992:                             $output .= &archive_options_form('decompressed',$datatable,
12993:                                                              $count,$hiddenelem);
12994:                             my $startcount = 6;
12995:                             $output .= &archive_javascript($startcount,$count,
12996:                                                            \%titles,\%children);
12997:                         }
12998:                         if ($env{'form.autoextract_camtasia'}) {
12999:                             my $version = $env{'form.autoextract_camtasia'};
13000:                             my %displayed;
13001:                             my $total = 1;
13002:                             $env{'form.archive_directory'} = [];
13003:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13004:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13005:                                 $path =~ s{/$}{};
13006:                                 my $item;
13007:                                 if ($path ne '') {
13008:                                     $item = "$path/$titles{$i}";
13009:                                 } else {
13010:                                     $item = $titles{$i};
13011:                                 }
13012:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13013:                                 if ($item eq $contents[0]) {
13014:                                     push(@{$env{'form.archive_directory'}},$i);
13015:                                     $env{'form.archive_'.$i} = 'display';
13016:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13017:                                     $displayed{'folder'} = $i;
13018:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13019:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13020:                                     $env{'form.archive_'.$i} = 'display';
13021:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13022:                                     $displayed{'web'} = $i;
13023:                                 } else {
13024:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13025:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13026:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13027:                                         push(@{$env{'form.archive_directory'}},$i);
13028:                                     }
13029:                                     $env{'form.archive_'.$i} = 'dependency';
13030:                                 }
13031:                                 $total ++;
13032:                             }
13033:                             for (my $i=1; $i<$total; $i++) {
13034:                                 next if ($i == $displayed{'web'});
13035:                                 next if ($i == $displayed{'folder'});
13036:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13037:                             }
13038:                             $env{'form.phase'} = 'decompress_cleanup';
13039:                             $env{'form.archivedelete'} = 1;
13040:                             $env{'form.archive_count'} = $total-1;
13041:                             $output .=
13042:                                 &process_extracted_files('coursedocs',$docudom,
13043:                                                          $docuname,$destination,
13044:                                                          $dir_root,$hiddenelem);
13045:                         }
13046:                     } else {
13047:                         $warning = &mt('No new items extracted from archive file.');
13048:                     }
13049:                 } else {
13050:                     $output = $display;
13051:                     $error = &mt('An error occurred during extraction from the archive file.');
13052:                 }
13053:             }
13054:         }
13055:     }
13056:     if ($error) {
13057:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13058:                    $error.'</p>'."\n";
13059:     }
13060:     if ($warning) {
13061:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13062:     }
13063:     return $output;
13064: }
13065: 
13066: sub get_extracted {
13067:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13068:         $titles,$wantform) = @_;
13069:     my $count = 0;
13070:     my $depth = 0;
13071:     my $datatable;
13072:     my @hierarchy;
13073:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13074:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13075:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13076:     foreach my $item (@{$contents}) {
13077:         $count ++;
13078:         @{$dirorder->{$count}} = @hierarchy;
13079:         $titles->{$count} = $item;
13080:         &archive_hierarchy($depth,$count,$parent,$children);
13081:         if ($wantform) {
13082:             $datatable .= &archive_row($is_dir->{$item},$item,
13083:                                        $currdir,$depth,$count);
13084:         }
13085:         if ($is_dir->{$item}) {
13086:             $depth ++;
13087:             push(@hierarchy,$count);
13088:             $parent->{$depth} = $count;
13089:             $datatable .=
13090:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13091:                                            \$depth,\$count,\@hierarchy,$dirorder,
13092:                                            $children,$parent,$titles,$wantform);
13093:             $depth --;
13094:             pop(@hierarchy);
13095:         }
13096:     }
13097:     return ($count,$datatable);
13098: }
13099: 
13100: sub recurse_extracted_archive {
13101:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13102:         $children,$parent,$titles,$wantform) = @_;
13103:     my $result='';
13104:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13105:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13106:             (ref($dirorder) eq 'HASH')) {
13107:         return $result;
13108:     }
13109:     my $dirptr = 16384;
13110:     my ($newdirlistref,$newlisterror) =
13111:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13112:     if (ref($newdirlistref) eq 'ARRAY') {
13113:         foreach my $dir_line (@{$newdirlistref}) {
13114:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13115:             unless ($item =~ /^\.+$/) {
13116:                 $$count ++;
13117:                 @{$dirorder->{$$count}} = @{$hierarchy};
13118:                 $titles->{$$count} = $item;
13119:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13120: 
13121:                 my $is_dir;
13122:                 if ($dirptr&$testdir) {
13123:                     $is_dir = 1;
13124:                 }
13125:                 if ($wantform) {
13126:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13127:                 }
13128:                 if ($is_dir) {
13129:                     $$depth ++;
13130:                     push(@{$hierarchy},$$count);
13131:                     $parent->{$$depth} = $$count;
13132:                     $result .=
13133:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13134:                                                    $docuname,$depth,$count,
13135:                                                    $hierarchy,$dirorder,$children,
13136:                                                    $parent,$titles,$wantform);
13137:                     $$depth --;
13138:                     pop(@{$hierarchy});
13139:                 }
13140:             }
13141:         }
13142:     }
13143:     return $result;
13144: }
13145: 
13146: sub archive_hierarchy {
13147:     my ($depth,$count,$parent,$children) =@_;
13148:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13149:         if (exists($parent->{$depth})) {
13150:              $children->{$parent->{$depth}} .= $count.':';
13151:         }
13152:     }
13153:     return;
13154: }
13155: 
13156: sub archive_row {
13157:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13158:     my ($name) = ($item =~ m{([^/]+)$});
13159:     my %choices = &Apache::lonlocal::texthash (
13160:                                        'display'    => 'Add as file',
13161:                                        'dependency' => 'Include as dependency',
13162:                                        'discard'    => 'Discard',
13163:                                       );
13164:     if ($is_dir) {
13165:         $choices{'display'} = &mt('Add as folder'); 
13166:     }
13167:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13168:     my $offset = 0;
13169:     foreach my $action ('display','dependency','discard') {
13170:         $offset ++;
13171:         if ($action ne 'display') {
13172:             $offset ++;
13173:         }  
13174:         $output .= '<td><span class="LC_nobreak">'.
13175:                    '<label><input type="radio" name="archive_'.$count.
13176:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13177:         my $text = $choices{$action};
13178:         if ($is_dir) {
13179:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13180:             if ($action eq 'display') {
13181:                 $text = &mt('Add as folder');
13182:             }
13183:         } else {
13184:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13185: 
13186:         }
13187:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13188:         if ($action eq 'dependency') {
13189:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13190:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13191:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13192:                        '<option value=""></option>'."\n".
13193:                        '</select>'."\n".
13194:                        '</div>';
13195:         } elsif ($action eq 'display') {
13196:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13197:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13198:                        '</div>';
13199:         }
13200:         $output .= '</td>';
13201:     }
13202:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13203:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13204:     for (my $i=0; $i<$depth; $i++) {
13205:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13206:     }
13207:     if ($is_dir) {
13208:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13209:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13210:     } else {
13211:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13212:     }
13213:     $output .= '&nbsp;'.$name.'</td>'."\n".
13214:                &end_data_table_row();
13215:     return $output;
13216: }
13217: 
13218: sub archive_options_form {
13219:     my ($form,$display,$count,$hiddenelem) = @_;
13220:     my %lt = &Apache::lonlocal::texthash(
13221:                perm => 'Permanently remove archive file?',
13222:                hows => 'How should each extracted item be incorporated in the course?',
13223:                cont => 'Content actions for all',
13224:                addf => 'Add as folder/file',
13225:                incd => 'Include as dependency for a displayed file',
13226:                disc => 'Discard',
13227:                no   => 'No',
13228:                yes  => 'Yes',
13229:                save => 'Save',
13230:     );
13231:     my $output = <<"END";
13232: <form name="$form" method="post" action="">
13233: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13234: <label>
13235:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13236: </label>
13237: &nbsp;
13238: <label>
13239:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13240: </span>
13241: </p>
13242: <input type="hidden" name="phase" value="decompress_cleanup" />
13243: <br />$lt{'hows'}
13244: <div class="LC_columnSection">
13245:   <fieldset>
13246:     <legend>$lt{'cont'}</legend>
13247:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13248:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13249:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13250:   </fieldset>
13251: </div>
13252: END
13253:     return $output.
13254:            &start_data_table()."\n".
13255:            $display."\n".
13256:            &end_data_table()."\n".
13257:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13258:            $hiddenelem.
13259:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13260:            '</form>';
13261: }
13262: 
13263: sub archive_javascript {
13264:     my ($startcount,$numitems,$titles,$children) = @_;
13265:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13266:     my $maintitle = $env{'form.comment'};
13267:     my $scripttag = <<START;
13268: <script type="text/javascript">
13269: // <![CDATA[
13270: 
13271: function checkAll(form,prefix) {
13272:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13273:     for (var i=0; i < form.elements.length; i++) {
13274:         var id = form.elements[i].id;
13275:         if ((id != '') && (id != undefined)) {
13276:             if (idstr.test(id)) {
13277:                 if (form.elements[i].type == 'radio') {
13278:                     form.elements[i].checked = true;
13279:                     var nostart = i-$startcount;
13280:                     var offset = nostart%7;
13281:                     var count = (nostart-offset)/7;    
13282:                     dependencyCheck(form,count,offset);
13283:                 }
13284:             }
13285:         }
13286:     }
13287: }
13288: 
13289: function propagateCheck(form,count) {
13290:     if (count > 0) {
13291:         var startelement = $startcount + ((count-1) * 7);
13292:         for (var j=1; j<6; j++) {
13293:             if ((j != 2) && (j != 4)) {
13294:                 var item = startelement + j; 
13295:                 if (form.elements[item].type == 'radio') {
13296:                     if (form.elements[item].checked) {
13297:                         containerCheck(form,count,j);
13298:                         break;
13299:                     }
13300:                 }
13301:             }
13302:         }
13303:     }
13304: }
13305: 
13306: numitems = $numitems
13307: var titles = new Array(numitems);
13308: var parents = new Array(numitems);
13309: for (var i=0; i<numitems; i++) {
13310:     parents[i] = new Array;
13311: }
13312: var maintitle = '$maintitle';
13313: 
13314: START
13315: 
13316:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13317:         my @contents = split(/:/,$children->{$container});
13318:         for (my $i=0; $i<@contents; $i ++) {
13319:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13320:         }
13321:     }
13322: 
13323:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13324:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13325:     }
13326: 
13327:     $scripttag .= <<END;
13328: 
13329: function containerCheck(form,count,offset) {
13330:     if (count > 0) {
13331:         dependencyCheck(form,count,offset);
13332:         var item = (offset+$startcount)+7*(count-1);
13333:         form.elements[item].checked = true;
13334:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13335:             if (parents[count].length > 0) {
13336:                 for (var j=0; j<parents[count].length; j++) {
13337:                     containerCheck(form,parents[count][j],offset);
13338:                 }
13339:             }
13340:         }
13341:     }
13342: }
13343: 
13344: function dependencyCheck(form,count,offset) {
13345:     if (count > 0) {
13346:         var chosen = (offset+$startcount)+7*(count-1);
13347:         var depitem = $startcount + ((count-1) * 7) + 4;
13348:         var currtype = form.elements[depitem].type;
13349:         if (form.elements[chosen].value == 'dependency') {
13350:             document.getElementById('arc_depon_'+count).style.display='block'; 
13351:             form.elements[depitem].options.length = 0;
13352:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13353:             for (var i=1; i<=numitems; i++) {
13354:                 if (i == count) {
13355:                     continue;
13356:                 }
13357:                 var startelement = $startcount + (i-1) * 7;
13358:                 for (var j=1; j<6; j++) {
13359:                     if ((j != 2) && (j!= 4)) {
13360:                         var item = startelement + j;
13361:                         if (form.elements[item].type == 'radio') {
13362:                             if (form.elements[item].checked) {
13363:                                 if (form.elements[item].value == 'display') {
13364:                                     var n = form.elements[depitem].options.length;
13365:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13366:                                 }
13367:                             }
13368:                         }
13369:                     }
13370:                 }
13371:             }
13372:         } else {
13373:             document.getElementById('arc_depon_'+count).style.display='none';
13374:             form.elements[depitem].options.length = 0;
13375:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13376:         }
13377:         titleCheck(form,count,offset);
13378:     }
13379: }
13380: 
13381: function propagateSelect(form,count,offset) {
13382:     if (count > 0) {
13383:         var item = (1+offset+$startcount)+7*(count-1);
13384:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13385:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13386:             if (parents[count].length > 0) {
13387:                 for (var j=0; j<parents[count].length; j++) {
13388:                     containerSelect(form,parents[count][j],offset,picked);
13389:                 }
13390:             }
13391:         }
13392:     }
13393: }
13394: 
13395: function containerSelect(form,count,offset,picked) {
13396:     if (count > 0) {
13397:         var item = (offset+$startcount)+7*(count-1);
13398:         if (form.elements[item].type == 'radio') {
13399:             if (form.elements[item].value == 'dependency') {
13400:                 if (form.elements[item+1].type == 'select-one') {
13401:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13402:                         if (form.elements[item+1].options[i].value == picked) {
13403:                             form.elements[item+1].selectedIndex = i;
13404:                             break;
13405:                         }
13406:                     }
13407:                 }
13408:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13409:                     if (parents[count].length > 0) {
13410:                         for (var j=0; j<parents[count].length; j++) {
13411:                             containerSelect(form,parents[count][j],offset,picked);
13412:                         }
13413:                     }
13414:                 }
13415:             }
13416:         }
13417:     }
13418: }
13419: 
13420: function titleCheck(form,count,offset) {
13421:     if (count > 0) {
13422:         var chosen = (offset+$startcount)+7*(count-1);
13423:         var depitem = $startcount + ((count-1) * 7) + 2;
13424:         var currtype = form.elements[depitem].type;
13425:         if (form.elements[chosen].value == 'display') {
13426:             document.getElementById('arc_title_'+count).style.display='block';
13427:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13428:                 document.getElementById('archive_title_'+count).value=maintitle;
13429:             }
13430:         } else {
13431:             document.getElementById('arc_title_'+count).style.display='none';
13432:             if (currtype == 'text') { 
13433:                 document.getElementById('archive_title_'+count).value='';
13434:             }
13435:         }
13436:     }
13437:     return;
13438: }
13439: 
13440: // ]]>
13441: </script>
13442: END
13443:     return $scripttag;
13444: }
13445: 
13446: sub process_extracted_files {
13447:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13448:     my $numitems = $env{'form.archive_count'};
13449:     return if ((!$numitems) || ($numitems =~ /\D/));
13450:     my @ids=&Apache::lonnet::current_machine_ids();
13451:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13452:         %folders,%containers,%mapinner,%prompttofetch);
13453:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13454:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13455:         $prefix = &LONCAPA::propath($docudom,$docuname);
13456:         $pathtocheck = "$dir_root/$destination";
13457:         $dir = $dir_root;
13458:         $ishome = 1;
13459:     } else {
13460:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13461:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13462:         $dir = "$dir_root/$docudom/$docuname";
13463:     }
13464:     my $currdir = "$dir_root/$destination";
13465:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13466:     if ($env{'form.folderpath'}) {
13467:         my @items = split('&',$env{'form.folderpath'});
13468:         $folders{'0'} = $items[-2];
13469:         if ($env{'form.folderpath'} =~ /\:1$/) {
13470:             $containers{'0'}='page';
13471:         } else {  
13472:             $containers{'0'}='sequence';
13473:         }
13474:     }
13475:     my @archdirs = &get_env_multiple('form.archive_directory');
13476:     if ($numitems) {
13477:         for (my $i=1; $i<=$numitems; $i++) {
13478:             my $path = $env{'form.archive_content_'.$i};
13479:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13480:                 my $item = $1;
13481:                 $toplevelitems{$item} = $i;
13482:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13483:                     $is_dir{$item} = 1;
13484:                 }
13485:             }
13486:         }
13487:     }
13488:     my ($output,%children,%parent,%titles,%dirorder,$result);
13489:     if (keys(%toplevelitems) > 0) {
13490:         my @contents = sort(keys(%toplevelitems));
13491:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13492:                                            \%parent,\@contents,\%dirorder,\%titles);
13493:     }
13494:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13495:     if ($numitems) {
13496:         for (my $i=1; $i<=$numitems; $i++) {
13497:             next if ($env{'form.archive_'.$i} eq 'dependency');
13498:             my $path = $env{'form.archive_content_'.$i};
13499:             if ($path =~ /^\Q$pathtocheck\E/) {
13500:                 if ($env{'form.archive_'.$i} eq 'discard') {
13501:                     if ($prefix ne '' && $path ne '') {
13502:                         if (-e $prefix.$path) {
13503:                             if ((@archdirs > 0) && 
13504:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13505:                                 $todeletedir{$prefix.$path} = 1;
13506:                             } else {
13507:                                 $todelete{$prefix.$path} = 1;
13508:                             }
13509:                         }
13510:                     }
13511:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13512:                     my ($docstitle,$title,$url,$outer);
13513:                     ($title) = ($path =~ m{/([^/]+)$});
13514:                     $docstitle = $env{'form.archive_title_'.$i};
13515:                     if ($docstitle eq '') {
13516:                         $docstitle = $title;
13517:                     }
13518:                     $outer = 0;
13519:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13520:                         if (@{$dirorder{$i}} > 0) {
13521:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13522:                                 if ($env{'form.archive_'.$item} eq 'display') {
13523:                                     $outer = $item;
13524:                                     last;
13525:                                 }
13526:                             }
13527:                         }
13528:                     }
13529:                     my ($errtext,$fatal) = 
13530:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13531:                                                '/'.$folders{$outer}.'.'.
13532:                                                $containers{$outer});
13533:                     next if ($fatal);
13534:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13535:                         if ($context eq 'coursedocs') {
13536:                             $mapinner{$i} = time;
13537:                             $folders{$i} = 'default_'.$mapinner{$i};
13538:                             $containers{$i} = 'sequence';
13539:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13540:                                       $folders{$i}.'.'.$containers{$i};
13541:                             my $newidx = &LONCAPA::map::getresidx();
13542:                             $LONCAPA::map::resources[$newidx]=
13543:                                 $docstitle.':'.$url.':false:normal:res';
13544:                             push(@LONCAPA::map::order,$newidx);
13545:                             my ($outtext,$errtext) =
13546:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13547:                                                         $docuname.'/'.$folders{$outer}.
13548:                                                         '.'.$containers{$outer},1,1);
13549:                             $newseqid{$i} = $newidx;
13550:                             unless ($errtext) {
13551:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13552:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
13553:                                             '</li>'."\n";
13554:                             }
13555:                         }
13556:                     } else {
13557:                         if ($context eq 'coursedocs') {
13558:                             my $newidx=&LONCAPA::map::getresidx();
13559:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13560:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13561:                                       $title;
13562:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13563:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13564:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13565:                                 }
13566:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13567:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13568:                                 }
13569:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13570:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13571:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13572:                                         unless ($ishome) {
13573:                                             my $fetch = "$newdest{$i}/$title";
13574:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13575:                                             $prompttofetch{$fetch} = 1;
13576:                                         }
13577:                                     }
13578:                                 }
13579:                                 $LONCAPA::map::resources[$newidx]=
13580:                                     $docstitle.':'.$url.':false:normal:res';
13581:                                 push(@LONCAPA::map::order, $newidx);
13582:                                 my ($outtext,$errtext)=
13583:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13584:                                                             $docuname.'/'.$folders{$outer}.
13585:                                                             '.'.$containers{$outer},1,1);
13586:                                 unless ($errtext) {
13587:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13588:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13589:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13590:                                                    '</li>'."\n";
13591:                                     }
13592:                                 }
13593:                             } else {
13594:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13595:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13596:                             }
13597:                         }
13598:                     }
13599:                 }
13600:             } else {
13601:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13602:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
13603:             }
13604:         }
13605:         for (my $i=1; $i<=$numitems; $i++) {
13606:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13607:             my $path = $env{'form.archive_content_'.$i};
13608:             if ($path =~ /^\Q$pathtocheck\E/) {
13609:                 my ($title) = ($path =~ m{/([^/]+)$});
13610:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13611:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13612:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13613:                         my ($itemidx,$fullpath,$relpath);
13614:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13615:                             my $container = $dirorder{$referrer{$i}}->[-1];
13616:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13617:                                 if ($dirorder{$i}->[$j] eq $container) {
13618:                                     $itemidx = $j;
13619:                                 }
13620:                             }
13621:                         }
13622:                         if ($itemidx eq '') {
13623:                             $itemidx =  0;
13624:                         } 
13625:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13626:                             if ($mapinner{$referrer{$i}}) {
13627:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13628:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13629:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13630:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13631:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13632:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13633:                                             if (!-e $fullpath) {
13634:                                                 mkdir($fullpath,0755);
13635:                                             }
13636:                                         }
13637:                                     } else {
13638:                                         last;
13639:                                     }
13640:                                 }
13641:                             }
13642:                         } elsif ($newdest{$referrer{$i}}) {
13643:                             $fullpath = $newdest{$referrer{$i}};
13644:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13645:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13646:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13647:                                     last;
13648:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13649:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13650:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13651:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13652:                                         if (!-e $fullpath) {
13653:                                             mkdir($fullpath,0755);
13654:                                         }
13655:                                     }
13656:                                 } else {
13657:                                     last;
13658:                                 }
13659:                             }
13660:                         }
13661:                         if ($fullpath ne '') {
13662:                             if (-e "$prefix$path") {
13663:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13664:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13665:                                 }
13666:                             }
13667:                             if (-e "$fullpath/$title") {
13668:                                 my $showpath;
13669:                                 if ($relpath ne '') {
13670:                                     $showpath = "$relpath/$title";
13671:                                 } else {
13672:                                     $showpath = "/$title";
13673:                                 } 
13674:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13675:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13676:                                            '</li>'."\n";
13677:                                 unless ($ishome) {
13678:                                     my $fetch = "$fullpath/$title";
13679:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
13680:                                     $prompttofetch{$fetch} = 1;
13681:                                 }
13682:                             }
13683:                         }
13684:                     }
13685:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13686:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13687:                                     &HTML::Entities::encode($path,'<>&"'),
13688:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13689:                                 '<br />';
13690:                 }
13691:             } else {
13692:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13693:                                 &HTML::Entities::encode($path)).'<br />';
13694:             }
13695:         }
13696:         if (keys(%todelete)) {
13697:             foreach my $key (keys(%todelete)) {
13698:                 unlink($key);
13699:             }
13700:         }
13701:         if (keys(%todeletedir)) {
13702:             foreach my $key (keys(%todeletedir)) {
13703:                 rmdir($key);
13704:             }
13705:         }
13706:         foreach my $dir (sort(keys(%is_dir))) {
13707:             if (($pathtocheck ne '') && ($dir ne ''))  {
13708:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13709:             }
13710:         }
13711:         if ($result ne '') {
13712:             $output .= '<ul>'."\n".
13713:                        $result."\n".
13714:                        '</ul>';
13715:         }
13716:         unless ($ishome) {
13717:             my $replicationfail;
13718:             foreach my $item (keys(%prompttofetch)) {
13719:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13720:                 unless ($fetchresult eq 'ok') {
13721:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13722:                 }
13723:             }
13724:             if ($replicationfail) {
13725:                 $output .= '<p class="LC_error">'.
13726:                            &mt('Course home server failed to retrieve:').'<ul>'.
13727:                            $replicationfail.
13728:                            '</ul></p>';
13729:             }
13730:         }
13731:     } else {
13732:         $warning = &mt('No items found in archive.');
13733:     }
13734:     if ($error) {
13735:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13736:                    $error.'</p>'."\n";
13737:     }
13738:     if ($warning) {
13739:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13740:     }
13741:     return $output;
13742: }
13743: 
13744: sub cleanup_empty_dirs {
13745:     my ($path) = @_;
13746:     if (($path ne '') && (-d $path)) {
13747:         if (opendir(my $dirh,$path)) {
13748:             my @dircontents = grep(!/^\./,readdir($dirh));
13749:             my $numitems = 0;
13750:             foreach my $item (@dircontents) {
13751:                 if (-d "$path/$item") {
13752:                     &cleanup_empty_dirs("$path/$item");
13753:                     if (-e "$path/$item") {
13754:                         $numitems ++;
13755:                     }
13756:                 } else {
13757:                     $numitems ++;
13758:                 }
13759:             }
13760:             if ($numitems == 0) {
13761:                 rmdir($path);
13762:             }
13763:             closedir($dirh);
13764:         }
13765:     }
13766:     return;
13767: }
13768: 
13769: =pod
13770: 
13771: =item * &get_folder_hierarchy()
13772: 
13773: Provides hierarchy of names of folders/sub-folders containing the current
13774: item,
13775: 
13776: Inputs: 3
13777:      - $navmap - navmaps object
13778: 
13779:      - $map - url for map (either the trigger itself, or map containing
13780:                            the resource, which is the trigger).
13781: 
13782:      - $showitem - 1 => show title for map itself; 0 => do not show.
13783: 
13784: Outputs: 1 @pathitems - array of folder/subfolder names.
13785: 
13786: =cut
13787: 
13788: sub get_folder_hierarchy {
13789:     my ($navmap,$map,$showitem) = @_;
13790:     my @pathitems;
13791:     if (ref($navmap)) {
13792:         my $mapres = $navmap->getResourceByUrl($map);
13793:         if (ref($mapres)) {
13794:             my $pcslist = $mapres->map_hierarchy();
13795:             if ($pcslist ne '') {
13796:                 my @pcs = split(/,/,$pcslist);
13797:                 foreach my $pc (@pcs) {
13798:                     if ($pc == 1) {
13799:                         push(@pathitems,&mt('Main Content'));
13800:                     } else {
13801:                         my $res = $navmap->getByMapPc($pc);
13802:                         if (ref($res)) {
13803:                             my $title = $res->compTitle();
13804:                             $title =~ s/\W+/_/g;
13805:                             if ($title ne '') {
13806:                                 push(@pathitems,$title);
13807:                             }
13808:                         }
13809:                     }
13810:                 }
13811:             }
13812:             if ($showitem) {
13813:                 if ($mapres->{ID} eq '0.0') {
13814:                     push(@pathitems,&mt('Main Content'));
13815:                 } else {
13816:                     my $maptitle = $mapres->compTitle();
13817:                     $maptitle =~ s/\W+/_/g;
13818:                     if ($maptitle ne '') {
13819:                         push(@pathitems,$maptitle);
13820:                     }
13821:                 }
13822:             }
13823:         }
13824:     }
13825:     return @pathitems;
13826: }
13827: 
13828: =pod
13829: 
13830: =item * &get_turnedin_filepath()
13831: 
13832: Determines path in a user's portfolio file for storage of files uploaded
13833: to a specific essayresponse or dropbox item.
13834: 
13835: Inputs: 3 required + 1 optional.
13836: $symb is symb for resource, $uname and $udom are for current user (required).
13837: $caller is optional (can be "submission", if routine is called when storing
13838: an upoaded file when "Submit Answer" button was pressed).
13839: 
13840: Returns array containing $path and $multiresp. 
13841: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13842: than one file upload item.  Callers of routine should append partid as a 
13843: subdirectory to $path in cases where $multiresp is 1.
13844: 
13845: Called by: homework/essayresponse.pm and homework/structuretags.pm
13846: 
13847: =cut
13848: 
13849: sub get_turnedin_filepath {
13850:     my ($symb,$uname,$udom,$caller) = @_;
13851:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13852:     my $turnindir;
13853:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13854:     $turnindir = $userhash{'turnindir'};
13855:     my ($path,$multiresp);
13856:     if ($turnindir eq '') {
13857:         if ($caller eq 'submission') {
13858:             $turnindir = &mt('turned in');
13859:             $turnindir =~ s/\W+/_/g;
13860:             my %newhash = (
13861:                             'turnindir' => $turnindir,
13862:                           );
13863:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13864:         }
13865:     }
13866:     if ($turnindir ne '') {
13867:         $path = '/'.$turnindir.'/';
13868:         my ($multipart,$turnin,@pathitems);
13869:         my $navmap = Apache::lonnavmaps::navmap->new();
13870:         if (defined($navmap)) {
13871:             my $mapres = $navmap->getResourceByUrl($map);
13872:             if (ref($mapres)) {
13873:                 my $pcslist = $mapres->map_hierarchy();
13874:                 if ($pcslist ne '') {
13875:                     foreach my $pc (split(/,/,$pcslist)) {
13876:                         my $res = $navmap->getByMapPc($pc);
13877:                         if (ref($res)) {
13878:                             my $title = $res->compTitle();
13879:                             $title =~ s/\W+/_/g;
13880:                             if ($title ne '') {
13881:                                 if (($pc > 1) && (length($title) > 12)) {
13882:                                     $title = substr($title,0,12);
13883:                                 }
13884:                                 push(@pathitems,$title);
13885:                             }
13886:                         }
13887:                     }
13888:                 }
13889:                 my $maptitle = $mapres->compTitle();
13890:                 $maptitle =~ s/\W+/_/g;
13891:                 if ($maptitle ne '') {
13892:                     if (length($maptitle) > 12) {
13893:                         $maptitle = substr($maptitle,0,12);
13894:                     }
13895:                     push(@pathitems,$maptitle);
13896:                 }
13897:                 unless ($env{'request.state'} eq 'construct') {
13898:                     my $res = $navmap->getBySymb($symb);
13899:                     if (ref($res)) {
13900:                         my $partlist = $res->parts();
13901:                         my $totaluploads = 0;
13902:                         if (ref($partlist) eq 'ARRAY') {
13903:                             foreach my $part (@{$partlist}) {
13904:                                 my @types = $res->responseType($part);
13905:                                 my @ids = $res->responseIds($part);
13906:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13907:                                     if ($types[$i] eq 'essay') {
13908:                                         my $partid = $part.'_'.$ids[$i];
13909:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13910:                                             $totaluploads ++;
13911:                                         }
13912:                                     }
13913:                                 }
13914:                             }
13915:                             if ($totaluploads > 1) {
13916:                                 $multiresp = 1;
13917:                             }
13918:                         }
13919:                     }
13920:                 }
13921:             } else {
13922:                 return;
13923:             }
13924:         } else {
13925:             return;
13926:         }
13927:         my $restitle=&Apache::lonnet::gettitle($symb);
13928:         $restitle =~ s/\W+/_/g;
13929:         if ($restitle eq '') {
13930:             $restitle = ($resurl =~ m{/[^/]+$});
13931:             if ($restitle eq '') {
13932:                 $restitle = time;
13933:             }
13934:         }
13935:         if (length($restitle) > 12) {
13936:             $restitle = substr($restitle,0,12);
13937:         }
13938:         push(@pathitems,$restitle);
13939:         $path .= join('/',@pathitems);
13940:     }
13941:     return ($path,$multiresp);
13942: }
13943: 
13944: =pod
13945: 
13946: =back
13947: 
13948: =head1 CSV Upload/Handling functions
13949: 
13950: =over 4
13951: 
13952: =item * &upfile_store($r)
13953: 
13954: Store uploaded file, $r should be the HTTP Request object,
13955: needs $env{'form.upfile'}
13956: returns $datatoken to be put into hidden field
13957: 
13958: =cut
13959: 
13960: sub upfile_store {
13961:     my $r=shift;
13962:     $env{'form.upfile'}=~s/\r/\n/gs;
13963:     $env{'form.upfile'}=~s/\f/\n/gs;
13964:     $env{'form.upfile'}=~s/\n+/\n/gs;
13965:     $env{'form.upfile'}=~s/\n+$//gs;
13966: 
13967:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13968:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13969:                                      time.'_'.$$);
13970:     return if ($datatoken eq '');
13971: 
13972:     {
13973:         my $datafile = $r->dir_config('lonDaemons').
13974:                            '/tmp/'.$datatoken.'.tmp';
13975:         if ( open(my $fh,'>',$datafile) ) {
13976:             print $fh $env{'form.upfile'};
13977:             close($fh);
13978:         }
13979:     }
13980:     return $datatoken;
13981: }
13982: 
13983: =pod
13984: 
13985: =item * &load_tmp_file($r,$datatoken)
13986: 
13987: Load uploaded file from tmp, $r should be the HTTP Request object,
13988: $datatoken is the name to assign to the temporary file.
13989: sets $env{'form.upfile'} to the contents of the file
13990: 
13991: =cut
13992: 
13993: sub load_tmp_file {
13994:     my ($r,$datatoken) = @_;
13995:     return if ($datatoken eq '');
13996:     my @studentdata=();
13997:     {
13998:         my $studentfile = $r->dir_config('lonDaemons').
13999:                               '/tmp/'.$datatoken.'.tmp';
14000:         if ( open(my $fh,'<',$studentfile) ) {
14001:             @studentdata=<$fh>;
14002:             close($fh);
14003:         }
14004:     }
14005:     $env{'form.upfile'}=join('',@studentdata);
14006: }
14007: 
14008: sub valid_datatoken {
14009:     my ($datatoken) = @_;
14010:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14011:         return $datatoken;
14012:     }
14013:     return;
14014: }
14015: 
14016: =pod
14017: 
14018: =item * &upfile_record_sep()
14019: 
14020: Separate uploaded file into records
14021: returns array of records,
14022: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14023: 
14024: =cut
14025: 
14026: sub upfile_record_sep {
14027:     if ($env{'form.upfiletype'} eq 'xml') {
14028:     } else {
14029: 	my @records;
14030: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14031: 	    if ($line=~/^\s*$/) { next; }
14032: 	    push(@records,$line);
14033: 	}
14034: 	return @records;
14035:     }
14036: }
14037: 
14038: =pod
14039: 
14040: =item * &record_sep($record)
14041: 
14042: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14043: 
14044: =cut
14045: 
14046: sub takeleft {
14047:     my $index=shift;
14048:     return substr('0000'.$index,-4,4);
14049: }
14050: 
14051: sub record_sep {
14052:     my $record=shift;
14053:     my %components=();
14054:     if ($env{'form.upfiletype'} eq 'xml') {
14055:     } elsif ($env{'form.upfiletype'} eq 'space') {
14056:         my $i=0;
14057:         foreach my $field (split(/\s+/,$record)) {
14058:             $field=~s/^(\"|\')//;
14059:             $field=~s/(\"|\')$//;
14060:             $components{&takeleft($i)}=$field;
14061:             $i++;
14062:         }
14063:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14064:         my $i=0;
14065:         foreach my $field (split(/\t/,$record)) {
14066:             $field=~s/^(\"|\')//;
14067:             $field=~s/(\"|\')$//;
14068:             $components{&takeleft($i)}=$field;
14069:             $i++;
14070:         }
14071:     } else {
14072:         my $separator=',';
14073:         if ($env{'form.upfiletype'} eq 'semisv') {
14074:             $separator=';';
14075:         }
14076:         my $i=0;
14077: # the character we are looking for to indicate the end of a quote or a record 
14078:         my $looking_for=$separator;
14079: # do not add the characters to the fields
14080:         my $ignore=0;
14081: # we just encountered a separator (or the beginning of the record)
14082:         my $just_found_separator=1;
14083: # store the field we are working on here
14084:         my $field='';
14085: # work our way through all characters in record
14086:         foreach my $character ($record=~/(.)/g) {
14087:             if ($character eq $looking_for) {
14088:                if ($character ne $separator) {
14089: # Found the end of a quote, again looking for separator
14090:                   $looking_for=$separator;
14091:                   $ignore=1;
14092:                } else {
14093: # Found a separator, store away what we got
14094:                   $components{&takeleft($i)}=$field;
14095: 	          $i++;
14096:                   $just_found_separator=1;
14097:                   $ignore=0;
14098:                   $field='';
14099:                }
14100:                next;
14101:             }
14102: # single or double quotation marks after a separator indicate beginning of a quote
14103: # we are now looking for the end of the quote and need to ignore separators
14104:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14105:                $looking_for=$character;
14106:                next;
14107:             }
14108: # ignore would be true after we reached the end of a quote
14109:             if ($ignore) { next; }
14110:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14111:             $field.=$character;
14112:             $just_found_separator=0; 
14113:         }
14114: # catch the very last entry, since we never encountered the separator
14115:         $components{&takeleft($i)}=$field;
14116:     }
14117:     return %components;
14118: }
14119: 
14120: ######################################################
14121: ######################################################
14122: 
14123: =pod
14124: 
14125: =item * &upfile_select_html()
14126: 
14127: Return HTML code to select a file from the users machine and specify 
14128: the file type.
14129: 
14130: =cut
14131: 
14132: ######################################################
14133: ######################################################
14134: sub upfile_select_html {
14135:     my %Types = (
14136:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14137:                  semisv => &mt('Semicolon separated values'),
14138:                  space => &mt('Space separated'),
14139:                  tab   => &mt('Tabulator separated'),
14140: #                 xml   => &mt('HTML/XML'),
14141:                  );
14142:     my $Str = '<input type="file" name="upfile" size="50" />'.
14143:         '<br />'.&mt('Type').': <select name="upfiletype">';
14144:     foreach my $type (sort(keys(%Types))) {
14145:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14146:     }
14147:     $Str .= "</select>\n";
14148:     return $Str;
14149: }
14150: 
14151: sub get_samples {
14152:     my ($records,$toget) = @_;
14153:     my @samples=({});
14154:     my $got=0;
14155:     foreach my $rec (@$records) {
14156: 	my %temp = &record_sep($rec);
14157: 	if (! grep(/\S/, values(%temp))) { next; }
14158: 	if (%temp) {
14159: 	    $samples[$got]=\%temp;
14160: 	    $got++;
14161: 	    if ($got == $toget) { last; }
14162: 	}
14163:     }
14164:     return \@samples;
14165: }
14166: 
14167: ######################################################
14168: ######################################################
14169: 
14170: =pod
14171: 
14172: =item * &csv_print_samples($r,$records)
14173: 
14174: Prints a table of sample values from each column uploaded $r is an
14175: Apache Request ref, $records is an arrayref from
14176: &Apache::loncommon::upfile_record_sep
14177: 
14178: =cut
14179: 
14180: ######################################################
14181: ######################################################
14182: sub csv_print_samples {
14183:     my ($r,$records) = @_;
14184:     my $samples = &get_samples($records,5);
14185: 
14186:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14187:               &start_data_table_header_row());
14188:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14189:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14190:     $r->print(&end_data_table_header_row());
14191:     foreach my $hash (@$samples) {
14192: 	$r->print(&start_data_table_row());
14193: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14194: 	    $r->print('<td>');
14195: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14196: 	    $r->print('</td>');
14197: 	}
14198: 	$r->print(&end_data_table_row());
14199:     }
14200:     $r->print(&end_data_table().'<br />'."\n");
14201: }
14202: 
14203: ######################################################
14204: ######################################################
14205: 
14206: =pod
14207: 
14208: =item * &csv_print_select_table($r,$records,$d)
14209: 
14210: Prints a table to create associations between values and table columns.
14211: 
14212: $r is an Apache Request ref,
14213: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14214: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14215: 
14216: =cut
14217: 
14218: ######################################################
14219: ######################################################
14220: sub csv_print_select_table {
14221:     my ($r,$records,$d) = @_;
14222:     my $i=0;
14223:     my $samples = &get_samples($records,1);
14224:     $r->print(&mt('Associate columns with student attributes.')."\n".
14225: 	      &start_data_table().&start_data_table_header_row().
14226:               '<th>'.&mt('Attribute').'</th>'.
14227:               '<th>'.&mt('Column').'</th>'.
14228:               &end_data_table_header_row()."\n");
14229:     foreach my $array_ref (@$d) {
14230: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14231: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14232: 
14233: 	$r->print('<td><select name="f'.$i.'"'.
14234: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14235: 	$r->print('<option value="none"></option>');
14236: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14237: 	    $r->print('<option value="'.$sample.'"'.
14238:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14239:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14240: 	}
14241: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14242: 	$i++;
14243:     }
14244:     $r->print(&end_data_table());
14245:     $i--;
14246:     return $i;
14247: }
14248: 
14249: ######################################################
14250: ######################################################
14251: 
14252: =pod
14253: 
14254: =item * &csv_samples_select_table($r,$records,$d)
14255: 
14256: Prints a table of sample values from the upload and can make associate samples to internal names.
14257: 
14258: $r is an Apache Request ref,
14259: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14260: $d is an array of 2 element arrays (internal name, displayed name)
14261: 
14262: =cut
14263: 
14264: ######################################################
14265: ######################################################
14266: sub csv_samples_select_table {
14267:     my ($r,$records,$d) = @_;
14268:     my $i=0;
14269:     #
14270:     my $max_samples = 5;
14271:     my $samples = &get_samples($records,$max_samples);
14272:     $r->print(&start_data_table().
14273:               &start_data_table_header_row().'<th>'.
14274:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14275:               &end_data_table_header_row());
14276: 
14277:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14278: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14279: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14280: 	foreach my $option (@$d) {
14281: 	    my ($value,$display,$defaultcol)=@{ $option };
14282: 	    $r->print('<option value="'.$value.'"'.
14283:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14284:                       $display.'</option>');
14285: 	}
14286: 	$r->print('</select></td><td>');
14287: 	foreach my $line (0..($max_samples-1)) {
14288: 	    if (defined($samples->[$line]{$key})) { 
14289: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14290: 	    }
14291: 	}
14292: 	$r->print('</td>'.&end_data_table_row());
14293: 	$i++;
14294:     }
14295:     $r->print(&end_data_table());
14296:     $i--;
14297:     return($i);
14298: }
14299: 
14300: ######################################################
14301: ######################################################
14302: 
14303: =pod
14304: 
14305: =item * &clean_excel_name($name)
14306: 
14307: Returns a replacement for $name which does not contain any illegal characters.
14308: 
14309: =cut
14310: 
14311: ######################################################
14312: ######################################################
14313: sub clean_excel_name {
14314:     my ($name) = @_;
14315:     $name =~ s/[:\*\?\/\\]//g;
14316:     if (length($name) > 31) {
14317:         $name = substr($name,0,31);
14318:     }
14319:     return $name;
14320: }
14321: 
14322: =pod
14323: 
14324: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14325: 
14326: Returns either 1 or undef
14327: 
14328: 1 if the part is to be hidden, undef if it is to be shown
14329: 
14330: Arguments are:
14331: 
14332: $id the id of the part to be checked
14333: $symb, optional the symb of the resource to check
14334: $udom, optional the domain of the user to check for
14335: $uname, optional the username of the user to check for
14336: 
14337: =cut
14338: 
14339: sub check_if_partid_hidden {
14340:     my ($id,$symb,$udom,$uname) = @_;
14341:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14342: 					 $symb,$udom,$uname);
14343:     my $truth=1;
14344:     #if the string starts with !, then the list is the list to show not hide
14345:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14346:     my @hiddenlist=split(/,/,$hiddenparts);
14347:     foreach my $checkid (@hiddenlist) {
14348: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14349:     }
14350:     return !$truth;
14351: }
14352: 
14353: 
14354: ############################################################
14355: ############################################################
14356: 
14357: =pod
14358: 
14359: =back 
14360: 
14361: =head1 cgi-bin script and graphing routines
14362: 
14363: =over 4
14364: 
14365: =item * &get_cgi_id()
14366: 
14367: Inputs: none
14368: 
14369: Returns an id which can be used to pass environment variables
14370: to various cgi-bin scripts.  These environment variables will
14371: be removed from the users environment after a given time by
14372: the routine &Apache::lonnet::transfer_profile_to_env.
14373: 
14374: =cut
14375: 
14376: ############################################################
14377: ############################################################
14378: my $uniq=0;
14379: sub get_cgi_id {
14380:     $uniq=($uniq+1)%100000;
14381:     return (time.'_'.$$.'_'.$uniq);
14382: }
14383: 
14384: ############################################################
14385: ############################################################
14386: 
14387: =pod
14388: 
14389: =item * &DrawBarGraph()
14390: 
14391: Facilitates the plotting of data in a (stacked) bar graph.
14392: Puts plot definition data into the users environment in order for 
14393: graph.png to plot it.  Returns an <img> tag for the plot.
14394: The bars on the plot are labeled '1','2',...,'n'.
14395: 
14396: Inputs:
14397: 
14398: =over 4
14399: 
14400: =item $Title: string, the title of the plot
14401: 
14402: =item $xlabel: string, text describing the X-axis of the plot
14403: 
14404: =item $ylabel: string, text describing the Y-axis of the plot
14405: 
14406: =item $Max: scalar, the maximum Y value to use in the plot
14407: If $Max is < any data point, the graph will not be rendered.
14408: 
14409: =item $colors: array ref holding the colors to be used for the data sets when
14410: they are plotted.  If undefined, default values will be used.
14411: 
14412: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14413: 
14414: =item @Values: An array of array references.  Each array reference holds data
14415: to be plotted in a stacked bar chart.
14416: 
14417: =item If the final element of @Values is a hash reference the key/value
14418: pairs will be added to the graph definition.
14419: 
14420: =back
14421: 
14422: Returns:
14423: 
14424: An <img> tag which references graph.png and the appropriate identifying
14425: information for the plot.
14426: 
14427: =cut
14428: 
14429: ############################################################
14430: ############################################################
14431: sub DrawBarGraph {
14432:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14433:     #
14434:     if (! defined($colors)) {
14435:         $colors = ['#33ff00', 
14436:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14437:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14438:                   ]; 
14439:     }
14440:     my $extra_settings = {};
14441:     if (ref($Values[-1]) eq 'HASH') {
14442:         $extra_settings = pop(@Values);
14443:     }
14444:     #
14445:     my $identifier = &get_cgi_id();
14446:     my $id = 'cgi.'.$identifier;        
14447:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14448:         return '';
14449:     }
14450:     #
14451:     my @Labels;
14452:     if (defined($labels)) {
14453:         @Labels = @$labels;
14454:     } else {
14455:         for (my $i=0;$i<@{$Values[0]};$i++) {
14456:             push(@Labels,$i+1);
14457:         }
14458:     }
14459:     #
14460:     my $NumBars = scalar(@{$Values[0]});
14461:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14462:     my %ValuesHash;
14463:     my $NumSets=1;
14464:     foreach my $array (@Values) {
14465:         next if (! ref($array));
14466:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14467:             join(',',@$array);
14468:     }
14469:     #
14470:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14471:     if ($NumBars < 3) {
14472:         $width = 120+$NumBars*32;
14473:         $xskip = 1;
14474:         $bar_width = 30;
14475:     } elsif ($NumBars < 5) {
14476:         $width = 120+$NumBars*20;
14477:         $xskip = 1;
14478:         $bar_width = 20;
14479:     } elsif ($NumBars < 10) {
14480:         $width = 120+$NumBars*15;
14481:         $xskip = 1;
14482:         $bar_width = 15;
14483:     } elsif ($NumBars <= 25) {
14484:         $width = 120+$NumBars*11;
14485:         $xskip = 5;
14486:         $bar_width = 8;
14487:     } elsif ($NumBars <= 50) {
14488:         $width = 120+$NumBars*8;
14489:         $xskip = 5;
14490:         $bar_width = 4;
14491:     } else {
14492:         $width = 120+$NumBars*8;
14493:         $xskip = 5;
14494:         $bar_width = 4;
14495:     }
14496:     #
14497:     $Max = 1 if ($Max < 1);
14498:     if ( int($Max) < $Max ) {
14499:         $Max++;
14500:         $Max = int($Max);
14501:     }
14502:     $Title  = '' if (! defined($Title));
14503:     $xlabel = '' if (! defined($xlabel));
14504:     $ylabel = '' if (! defined($ylabel));
14505:     $ValuesHash{$id.'.title'}    = &escape($Title);
14506:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14507:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14508:     $ValuesHash{$id.'.y_max_value'} = $Max;
14509:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14510:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14511:     $ValuesHash{$id.'.PlotType'} = 'bar';
14512:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14513:     $ValuesHash{$id.'.height'}   = $height;
14514:     $ValuesHash{$id.'.width'}    = $width;
14515:     $ValuesHash{$id.'.xskip'}    = $xskip;
14516:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14517:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14518:     #
14519:     # Deal with other parameters
14520:     while (my ($key,$value) = each(%$extra_settings)) {
14521:         $ValuesHash{$id.'.'.$key} = $value;
14522:     }
14523:     #
14524:     &Apache::lonnet::appenv(\%ValuesHash);
14525:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14526: }
14527: 
14528: ############################################################
14529: ############################################################
14530: 
14531: =pod
14532: 
14533: =item * &DrawXYGraph()
14534: 
14535: Facilitates the plotting of data in an XY graph.
14536: Puts plot definition data into the users environment in order for 
14537: graph.png to plot it.  Returns an <img> tag for the plot.
14538: 
14539: Inputs:
14540: 
14541: =over 4
14542: 
14543: =item $Title: string, the title of the plot
14544: 
14545: =item $xlabel: string, text describing the X-axis of the plot
14546: 
14547: =item $ylabel: string, text describing the Y-axis of the plot
14548: 
14549: =item $Max: scalar, the maximum Y value to use in the plot
14550: If $Max is < any data point, the graph will not be rendered.
14551: 
14552: =item $colors: Array ref containing the hex color codes for the data to be 
14553: plotted in.  If undefined, default values will be used.
14554: 
14555: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14556: 
14557: =item $Ydata: Array ref containing Array refs.  
14558: Each of the contained arrays will be plotted as a separate curve.
14559: 
14560: =item %Values: hash indicating or overriding any default values which are 
14561: passed to graph.png.  
14562: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14563: 
14564: =back
14565: 
14566: Returns:
14567: 
14568: An <img> tag which references graph.png and the appropriate identifying
14569: information for the plot.
14570: 
14571: =cut
14572: 
14573: ############################################################
14574: ############################################################
14575: sub DrawXYGraph {
14576:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14577:     #
14578:     # Create the identifier for the graph
14579:     my $identifier = &get_cgi_id();
14580:     my $id = 'cgi.'.$identifier;
14581:     #
14582:     $Title  = '' if (! defined($Title));
14583:     $xlabel = '' if (! defined($xlabel));
14584:     $ylabel = '' if (! defined($ylabel));
14585:     my %ValuesHash = 
14586:         (
14587:          $id.'.title'  => &escape($Title),
14588:          $id.'.xlabel' => &escape($xlabel),
14589:          $id.'.ylabel' => &escape($ylabel),
14590:          $id.'.y_max_value'=> $Max,
14591:          $id.'.labels'     => join(',',@$Xlabels),
14592:          $id.'.PlotType'   => 'XY',
14593:          );
14594:     #
14595:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14596:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14597:     }
14598:     #
14599:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14600:         return '';
14601:     }
14602:     my $NumSets=1;
14603:     foreach my $array (@{$Ydata}){
14604:         next if (! ref($array));
14605:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14606:     }
14607:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14608:     #
14609:     # Deal with other parameters
14610:     while (my ($key,$value) = each(%Values)) {
14611:         $ValuesHash{$id.'.'.$key} = $value;
14612:     }
14613:     #
14614:     &Apache::lonnet::appenv(\%ValuesHash);
14615:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14616: }
14617: 
14618: ############################################################
14619: ############################################################
14620: 
14621: =pod
14622: 
14623: =item * &DrawXYYGraph()
14624: 
14625: Facilitates the plotting of data in an XY graph with two Y axes.
14626: Puts plot definition data into the users environment in order for 
14627: graph.png to plot it.  Returns an <img> tag for the plot.
14628: 
14629: Inputs:
14630: 
14631: =over 4
14632: 
14633: =item $Title: string, the title of the plot
14634: 
14635: =item $xlabel: string, text describing the X-axis of the plot
14636: 
14637: =item $ylabel: string, text describing the Y-axis of the plot
14638: 
14639: =item $colors: Array ref containing the hex color codes for the data to be 
14640: plotted in.  If undefined, default values will be used.
14641: 
14642: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14643: 
14644: =item $Ydata1: The first data set
14645: 
14646: =item $Min1: The minimum value of the left Y-axis
14647: 
14648: =item $Max1: The maximum value of the left Y-axis
14649: 
14650: =item $Ydata2: The second data set
14651: 
14652: =item $Min2: The minimum value of the right Y-axis
14653: 
14654: =item $Max2: The maximum value of the left Y-axis
14655: 
14656: =item %Values: hash indicating or overriding any default values which are 
14657: passed to graph.png.  
14658: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14659: 
14660: =back
14661: 
14662: Returns:
14663: 
14664: An <img> tag which references graph.png and the appropriate identifying
14665: information for the plot.
14666: 
14667: =cut
14668: 
14669: ############################################################
14670: ############################################################
14671: sub DrawXYYGraph {
14672:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14673:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14674:     #
14675:     # Create the identifier for the graph
14676:     my $identifier = &get_cgi_id();
14677:     my $id = 'cgi.'.$identifier;
14678:     #
14679:     $Title  = '' if (! defined($Title));
14680:     $xlabel = '' if (! defined($xlabel));
14681:     $ylabel = '' if (! defined($ylabel));
14682:     my %ValuesHash = 
14683:         (
14684:          $id.'.title'  => &escape($Title),
14685:          $id.'.xlabel' => &escape($xlabel),
14686:          $id.'.ylabel' => &escape($ylabel),
14687:          $id.'.labels' => join(',',@$Xlabels),
14688:          $id.'.PlotType' => 'XY',
14689:          $id.'.NumSets' => 2,
14690:          $id.'.two_axes' => 1,
14691:          $id.'.y1_max_value' => $Max1,
14692:          $id.'.y1_min_value' => $Min1,
14693:          $id.'.y2_max_value' => $Max2,
14694:          $id.'.y2_min_value' => $Min2,
14695:          );
14696:     #
14697:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14698:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14699:     }
14700:     #
14701:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14702:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14703:         return '';
14704:     }
14705:     my $NumSets=1;
14706:     foreach my $array ($Ydata1,$Ydata2){
14707:         next if (! ref($array));
14708:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14709:     }
14710:     #
14711:     # Deal with other parameters
14712:     while (my ($key,$value) = each(%Values)) {
14713:         $ValuesHash{$id.'.'.$key} = $value;
14714:     }
14715:     #
14716:     &Apache::lonnet::appenv(\%ValuesHash);
14717:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14718: }
14719: 
14720: ############################################################
14721: ############################################################
14722: 
14723: =pod
14724: 
14725: =back 
14726: 
14727: =head1 Statistics helper routines?  
14728: 
14729: Bad place for them but what the hell.
14730: 
14731: =over 4
14732: 
14733: =item * &chartlink()
14734: 
14735: Returns a link to the chart for a specific student.  
14736: 
14737: Inputs:
14738: 
14739: =over 4
14740: 
14741: =item $linktext: The text of the link
14742: 
14743: =item $sname: The students username
14744: 
14745: =item $sdomain: The students domain
14746: 
14747: =back
14748: 
14749: =back
14750: 
14751: =cut
14752: 
14753: ############################################################
14754: ############################################################
14755: sub chartlink {
14756:     my ($linktext, $sname, $sdomain) = @_;
14757:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14758:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14759:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14760:        '">'.$linktext.'</a>';
14761: }
14762: 
14763: #######################################################
14764: #######################################################
14765: 
14766: =pod
14767: 
14768: =head1 Course Environment Routines
14769: 
14770: =over 4
14771: 
14772: =item * &restore_course_settings()
14773: 
14774: =item * &store_course_settings()
14775: 
14776: Restores/Store indicated form parameters from the course environment.
14777: Will not overwrite existing values of the form parameters.
14778: 
14779: Inputs: 
14780: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14781: 
14782: a hash ref describing the data to be stored.  For example:
14783:    
14784: %Save_Parameters = ('Status' => 'scalar',
14785:     'chartoutputmode' => 'scalar',
14786:     'chartoutputdata' => 'scalar',
14787:     'Section' => 'array',
14788:     'Group' => 'array',
14789:     'StudentData' => 'array',
14790:     'Maps' => 'array');
14791: 
14792: Returns: both routines return nothing
14793: 
14794: =back
14795: 
14796: =cut
14797: 
14798: #######################################################
14799: #######################################################
14800: sub store_course_settings {
14801:     return &store_settings($env{'request.course.id'},@_);
14802: }
14803: 
14804: sub store_settings {
14805:     # save to the environment
14806:     # appenv the same items, just to be safe
14807:     my $udom  = $env{'user.domain'};
14808:     my $uname = $env{'user.name'};
14809:     my ($context,$prefix,$Settings) = @_;
14810:     my %SaveHash;
14811:     my %AppHash;
14812:     while (my ($setting,$type) = each(%$Settings)) {
14813:         my $basename = join('.','internal',$context,$prefix,$setting);
14814:         my $envname = 'environment.'.$basename;
14815:         if (exists($env{'form.'.$setting})) {
14816:             # Save this value away
14817:             if ($type eq 'scalar' &&
14818:                 (! exists($env{$envname}) || 
14819:                  $env{$envname} ne $env{'form.'.$setting})) {
14820:                 $SaveHash{$basename} = $env{'form.'.$setting};
14821:                 $AppHash{$envname}   = $env{'form.'.$setting};
14822:             } elsif ($type eq 'array') {
14823:                 my $stored_form;
14824:                 if (ref($env{'form.'.$setting})) {
14825:                     $stored_form = join(',',
14826:                                         map {
14827:                                             &escape($_);
14828:                                         } sort(@{$env{'form.'.$setting}}));
14829:                 } else {
14830:                     $stored_form = 
14831:                         &escape($env{'form.'.$setting});
14832:                 }
14833:                 # Determine if the array contents are the same.
14834:                 if ($stored_form ne $env{$envname}) {
14835:                     $SaveHash{$basename} = $stored_form;
14836:                     $AppHash{$envname}   = $stored_form;
14837:                 }
14838:             }
14839:         }
14840:     }
14841:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14842:                                           $udom,$uname);
14843:     if ($put_result !~ /^(ok|delayed)/) {
14844:         &Apache::lonnet::logthis('unable to save form parameters, '.
14845:                                  'got error:'.$put_result);
14846:     }
14847:     # Make sure these settings stick around in this session, too
14848:     &Apache::lonnet::appenv(\%AppHash);
14849:     return;
14850: }
14851: 
14852: sub restore_course_settings {
14853:     return &restore_settings($env{'request.course.id'},@_);
14854: }
14855: 
14856: sub restore_settings {
14857:     my ($context,$prefix,$Settings) = @_;
14858:     while (my ($setting,$type) = each(%$Settings)) {
14859:         next if (exists($env{'form.'.$setting}));
14860:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14861:             '.'.$setting;
14862:         if (exists($env{$envname})) {
14863:             if ($type eq 'scalar') {
14864:                 $env{'form.'.$setting} = $env{$envname};
14865:             } elsif ($type eq 'array') {
14866:                 $env{'form.'.$setting} = [ 
14867:                                            map { 
14868:                                                &unescape($_); 
14869:                                            } split(',',$env{$envname})
14870:                                            ];
14871:             }
14872:         }
14873:     }
14874: }
14875: 
14876: #######################################################
14877: #######################################################
14878: 
14879: =pod
14880: 
14881: =head1 Domain E-mail Routines  
14882: 
14883: =over 4
14884: 
14885: =item * &build_recipient_list()
14886: 
14887: Build recipient lists for following types of e-mail:
14888: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14889: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14890: module change checking, student/employee ID conflict checks, as
14891: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14892: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14893: 
14894: Inputs:
14895: defmail (scalar - email address of default recipient), 
14896: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14897: requestsmail, updatesmail, or idconflictsmail).
14898: 
14899: defdom (domain for which to retrieve configuration settings),
14900: 
14901: origmail (scalar - email address of recipient from loncapa.conf, 
14902: i.e., predates configuration by DC via domainprefs.pm
14903: 
14904: $requname username of requester (if mailing type is helpdeskmail)
14905: 
14906: $requdom domain of requester (if mailing type is helpdeskmail)
14907: 
14908: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14909: 
14910: 
14911: Returns: comma separated list of addresses to which to send e-mail.
14912: 
14913: =back
14914: 
14915: =cut
14916: 
14917: ############################################################
14918: ############################################################
14919: sub build_recipient_list {
14920:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14921:     my @recipients;
14922:     my ($otheremails,$lastresort,$allbcc,$addtext);
14923:     my %domconfig =
14924:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14925:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14926:         if (exists($domconfig{'contacts'}{$mailing})) {
14927:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14928:                 my @contacts = ('adminemail','supportemail');
14929:                 foreach my $item (@contacts) {
14930:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14931:                         my $addr = $domconfig{'contacts'}{$item}; 
14932:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14933:                             push(@recipients,$addr);
14934:                         }
14935:                     }
14936:                 }
14937:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14938:                 if ($mailing eq 'helpdeskmail') {
14939:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14940:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14941:                         my @ok_bccs;
14942:                         foreach my $bcc (@bccs) {
14943:                             $bcc =~ s/^\s+//g;
14944:                             $bcc =~ s/\s+$//g;
14945:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14946:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14947:                                     push(@ok_bccs,$bcc);
14948:                                 }
14949:                             }
14950:                         }
14951:                         if (@ok_bccs > 0) {
14952:                             $allbcc = join(', ',@ok_bccs);
14953:                         }
14954:                     }
14955:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14956:                 }
14957:             }
14958:         } elsif ($origmail ne '') {
14959:             $lastresort = $origmail;
14960:         }
14961:         if ($mailing eq 'helpdeskmail') {
14962:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14963:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14964:                 my ($inststatus,$inststatus_checked);
14965:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14966:                     ($env{'user.domain'} ne 'public')) {
14967:                     $inststatus_checked = 1;
14968:                     $inststatus = $env{'environment.inststatus'};
14969:                 }
14970:                 unless ($inststatus_checked) {
14971:                     if (($requname ne '') && ($requdom ne '')) {
14972:                         if (($requname =~ /^$match_username$/) &&
14973:                             ($requdom =~ /^$match_domain$/) &&
14974:                             (&Apache::lonnet::domain($requdom))) {
14975:                             my $requhome = &Apache::lonnet::homeserver($requname,
14976:                                                                       $requdom);
14977:                             unless ($requhome eq 'no_host') {
14978:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14979:                                 $inststatus = $userenv{'inststatus'};
14980:                                 $inststatus_checked = 1;
14981:                             }
14982:                         }
14983:                     }
14984:                 }
14985:                 unless ($inststatus_checked) {
14986:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14987:                         my %srch = (srchby     => 'email',
14988:                                     srchdomain => $defdom,
14989:                                     srchterm   => $reqemail,
14990:                                     srchtype   => 'exact');
14991:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14992:                         foreach my $uname (keys(%srch_results)) {
14993:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14994:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14995:                                 $inststatus_checked = 1;
14996:                                 last;
14997:                             }
14998:                         }
14999:                         unless ($inststatus_checked) {
15000:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15001:                             if ($dirsrchres eq 'ok') {
15002:                                 foreach my $uname (keys(%srch_results)) {
15003:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15004:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15005:                                         $inststatus_checked = 1;
15006:                                         last;
15007:                                     }
15008:                                 }
15009:                             }
15010:                         }
15011:                     }
15012:                 }
15013:                 if ($inststatus ne '') {
15014:                     foreach my $status (split(/\:/,$inststatus)) {
15015:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15016:                             my @contacts = ('adminemail','supportemail');
15017:                             foreach my $item (@contacts) {
15018:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15019:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15020:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15021:                                         push(@recipients,$addr);
15022:                                     }
15023:                                 }
15024:                             }
15025:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15026:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15027:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15028:                                 my @ok_bccs;
15029:                                 foreach my $bcc (@bccs) {
15030:                                     $bcc =~ s/^\s+//g;
15031:                                     $bcc =~ s/\s+$//g;
15032:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15033:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15034:                                             push(@ok_bccs,$bcc);
15035:                                         }
15036:                                     }
15037:                                 }
15038:                                 if (@ok_bccs > 0) {
15039:                                     $allbcc = join(', ',@ok_bccs);
15040:                                 }
15041:                             }
15042:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15043:                             last;
15044:                         }
15045:                     }
15046:                 }
15047:             }
15048:         }
15049:     } elsif ($origmail ne '') {
15050:         $lastresort = $origmail;
15051:     }
15052:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15053:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15054:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15055:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15056:             my %what = (
15057:                           perlvar => 1,
15058:                        );
15059:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15060:             if ($primary) {
15061:                 my $gotaddr;
15062:                 my ($result,$returnhash) =
15063:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15064:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15065:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15066:                         $lastresort = $returnhash->{'lonSupportEMail'};
15067:                         $gotaddr = 1;
15068:                     }
15069:                 }
15070:                 unless ($gotaddr) {
15071:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15072:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15073:                     unless ($uintdom eq $intdom) {
15074:                         my %domconfig =
15075:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15076:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15077:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15078:                                 my @contacts = ('adminemail','supportemail');
15079:                                 foreach my $item (@contacts) {
15080:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15081:                                         my $addr = $domconfig{'contacts'}{$item};
15082:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15083:                                             push(@recipients,$addr);
15084:                                         }
15085:                                     }
15086:                                 }
15087:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15088:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15089:                                 }
15090:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15091:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15092:                                     my @ok_bccs;
15093:                                     foreach my $bcc (@bccs) {
15094:                                         $bcc =~ s/^\s+//g;
15095:                                         $bcc =~ s/\s+$//g;
15096:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15097:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15098:                                                 push(@ok_bccs,$bcc);
15099:                                             }
15100:                                         }
15101:                                     }
15102:                                     if (@ok_bccs > 0) {
15103:                                         $allbcc = join(', ',@ok_bccs);
15104:                                     }
15105:                                 }
15106:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15107:                             }
15108:                         }
15109:                     }
15110:                 }
15111:             }
15112:         }
15113:     }
15114:     if (defined($defmail)) {
15115:         if ($defmail ne '') {
15116:             push(@recipients,$defmail);
15117:         }
15118:     }
15119:     if ($otheremails) {
15120:         my @others;
15121:         if ($otheremails =~ /,/) {
15122:             @others = split(/,/,$otheremails);
15123:         } else {
15124:             push(@others,$otheremails);
15125:         }
15126:         foreach my $addr (@others) {
15127:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15128:                 push(@recipients,$addr);
15129:             }
15130:         }
15131:     }
15132:     if ($mailing eq 'helpdeskmail') {
15133:         if ((!@recipients) && ($lastresort ne '')) {
15134:             push(@recipients,$lastresort);
15135:         }
15136:     } elsif ($lastresort ne '') {
15137:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15138:             push(@recipients,$lastresort);
15139:         }
15140:     }
15141:     my $recipientlist = join(',',@recipients);
15142:     if (wantarray) {
15143:         return ($recipientlist,$allbcc,$addtext);
15144:     } else {
15145:         return $recipientlist;
15146:     }
15147: }
15148: 
15149: ############################################################
15150: ############################################################
15151: 
15152: =pod
15153: 
15154: =over 4
15155: 
15156: =item * &mime_email()
15157: 
15158: Sends an email with a possible attachment
15159: 
15160: Inputs:
15161: 
15162: =over 4
15163: 
15164: from -              Sender's email address
15165: 
15166: to -                Email address of recipient
15167: 
15168: subject -           Subject of email
15169: 
15170: body -              Body of email
15171: 
15172: cc_string -         Carbon copy email address
15173: 
15174: bcc -               Blind carbon copy email address
15175: 
15176: type -              File type of attachment
15177: 
15178: attachment_path -   Path of file to be attached
15179: 
15180: file_name -         Name of file to be attached
15181: 
15182: attachment_text -   The body of an attachment of type "TEXT"
15183: 
15184: =back
15185: 
15186: =back
15187: 
15188: =cut
15189: 
15190: ############################################################
15191: ############################################################
15192: 
15193: sub mime_email {
15194:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
15195:         $file_name, $attachment_text) = @_;
15196:     my $msg = MIME::Lite->new(
15197:              From    => $from,
15198:              To      => $to,
15199:              Subject => $subject,
15200:              Type    =>'TEXT',
15201:              Data    => $body,
15202:              );
15203:     if ($cc_string ne '') {
15204:         $msg->add("Cc" => $cc_string);
15205:     }
15206:     if ($bcc ne '') {
15207:         $msg->add("Bcc" => $bcc);
15208:     }
15209:     $msg->attr("content-type"         => "text/plain");
15210:     $msg->attr("content-type.charset" => "UTF-8");
15211:     # Attach file if given
15212:     if ($attachment_path) {
15213:         unless ($file_name) {
15214:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15215:         }
15216:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15217:         $msg->attach(Type     => $type,
15218:                      Path     => $attachment_path,
15219:                      Filename => $file_name
15220:                      );
15221:     # Otherwise attach text if given
15222:     } elsif ($attachment_text) {
15223:         $msg->attach(Type => 'TEXT',
15224:                      Data => $attachment_text);
15225:     }
15226:     # Send it
15227:     $msg->send('sendmail');
15228: }
15229: 
15230: ############################################################
15231: ############################################################
15232: 
15233: =pod
15234: 
15235: =head1 Course Catalog Routines
15236: 
15237: =over 4
15238: 
15239: =item * &gather_categories()
15240: 
15241: Converts category definitions - keys of categories hash stored in  
15242: coursecategories in configuration.db on the primary library server in a 
15243: domain - to an array.  Also generates javascript and idx hash used to 
15244: generate Domain Coordinator interface for editing Course Categories.
15245: 
15246: Inputs:
15247: 
15248: categories (reference to hash of category definitions).
15249: 
15250: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15251:       categories and subcategories).
15252: 
15253: idx (reference to hash of counters used in Domain Coordinator interface for 
15254:       editing Course Categories).
15255: 
15256: jsarray (reference to array of categories used to create Javascript arrays for
15257:          Domain Coordinator interface for editing Course Categories).
15258: 
15259: Returns: nothing
15260: 
15261: Side effects: populates cats, idx and jsarray. 
15262: 
15263: =cut
15264: 
15265: sub gather_categories {
15266:     my ($categories,$cats,$idx,$jsarray) = @_;
15267:     my %counters;
15268:     my $num = 0;
15269:     foreach my $item (keys(%{$categories})) {
15270:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15271:         if ($container eq '' && $depth == 0) {
15272:             $cats->[$depth][$categories->{$item}] = $cat;
15273:         } else {
15274:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15275:         }
15276:         my ($escitem,$tail) = split(/:/,$item,2);
15277:         if ($counters{$tail} eq '') {
15278:             $counters{$tail} = $num;
15279:             $num ++;
15280:         }
15281:         if (ref($idx) eq 'HASH') {
15282:             $idx->{$item} = $counters{$tail};
15283:         }
15284:         if (ref($jsarray) eq 'ARRAY') {
15285:             push(@{$jsarray->[$counters{$tail}]},$item);
15286:         }
15287:     }
15288:     return;
15289: }
15290: 
15291: =pod
15292: 
15293: =item * &extract_categories()
15294: 
15295: Used to generate breadcrumb trails for course categories.
15296: 
15297: Inputs:
15298: 
15299: categories (reference to hash of category definitions).
15300: 
15301: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15302:       categories and subcategories).
15303: 
15304: trails (reference to array of breacrumb trails for each category).
15305: 
15306: allitems (reference to hash - key is category key 
15307:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15308: 
15309: idx (reference to hash of counters used in Domain Coordinator interface for
15310:       editing Course Categories).
15311: 
15312: jsarray (reference to array of categories used to create Javascript arrays for
15313:          Domain Coordinator interface for editing Course Categories).
15314: 
15315: subcats (reference to hash of arrays containing all subcategories within each 
15316:          category, -recursive)
15317: 
15318: maxd (reference to hash used to hold max depth for all top-level categories).
15319: 
15320: Returns: nothing
15321: 
15322: Side effects: populates trails and allitems hash references.
15323: 
15324: =cut
15325: 
15326: sub extract_categories {
15327:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15328:     if (ref($categories) eq 'HASH') {
15329:         &gather_categories($categories,$cats,$idx,$jsarray);
15330:         if (ref($cats->[0]) eq 'ARRAY') {
15331:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15332:                 my $name = $cats->[0][$i];
15333:                 my $item = &escape($name).'::0';
15334:                 my $trailstr;
15335:                 if ($name eq 'instcode') {
15336:                     $trailstr = &mt('Official courses (with institutional codes)');
15337:                 } elsif ($name eq 'communities') {
15338:                     $trailstr = &mt('Communities');
15339:                 } elsif ($name eq 'placement') {
15340:                     $trailstr = &mt('Placement Tests');
15341:                 } else {
15342:                     $trailstr = $name;
15343:                 }
15344:                 if ($allitems->{$item} eq '') {
15345:                     push(@{$trails},$trailstr);
15346:                     $allitems->{$item} = scalar(@{$trails})-1;
15347:                 }
15348:                 my @parents = ($name);
15349:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15350:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15351:                         my $category = $cats->[1]{$name}[$j];
15352:                         if (ref($subcats) eq 'HASH') {
15353:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15354:                         }
15355:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15356:                     }
15357:                 } else {
15358:                     if (ref($subcats) eq 'HASH') {
15359:                         $subcats->{$item} = [];
15360:                     }
15361:                     if (ref($maxd) eq 'HASH') {
15362:                         $maxd->{$name} = 1;
15363:                     }
15364:                 }
15365:             }
15366:         }
15367:     }
15368:     return;
15369: }
15370: 
15371: =pod
15372: 
15373: =item * &recurse_categories()
15374: 
15375: Recursively used to generate breadcrumb trails for course categories.
15376: 
15377: Inputs:
15378: 
15379: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15380:       categories and subcategories).
15381: 
15382: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15383: 
15384: category (current course category, for which breadcrumb trail is being generated).
15385: 
15386: trails (reference to array of breadcrumb trails for each category).
15387: 
15388: allitems (reference to hash - key is category key
15389:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15390: 
15391: parents (array containing containers directories for current category, 
15392:          back to top level). 
15393: 
15394: Returns: nothing
15395: 
15396: Side effects: populates trails and allitems hash references
15397: 
15398: =cut
15399: 
15400: sub recurse_categories {
15401:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15402:     my $shallower = $depth - 1;
15403:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15404:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15405:             my $name = $cats->[$depth]{$category}[$k];
15406:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15407:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15408:             if ($allitems->{$item} eq '') {
15409:                 push(@{$trails},$trailstr);
15410:                 $allitems->{$item} = scalar(@{$trails})-1;
15411:             }
15412:             my $deeper = $depth+1;
15413:             push(@{$parents},$category);
15414:             if (ref($subcats) eq 'HASH') {
15415:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15416:                 for (my $j=@{$parents}; $j>=0; $j--) {
15417:                     my $higher;
15418:                     if ($j > 0) {
15419:                         $higher = &escape($parents->[$j]).':'.
15420:                                   &escape($parents->[$j-1]).':'.$j;
15421:                     } else {
15422:                         $higher = &escape($parents->[$j]).'::'.$j;
15423:                     }
15424:                     push(@{$subcats->{$higher}},$subcat);
15425:                 }
15426:             }
15427:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15428:                                 $subcats,$maxd);
15429:             pop(@{$parents});
15430:         }
15431:     } else {
15432:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15433:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15434:         if ($allitems->{$item} eq '') {
15435:             push(@{$trails},$trailstr);
15436:             $allitems->{$item} = scalar(@{$trails})-1;
15437:         }
15438:         if (ref($maxd) eq 'HASH') {
15439:             if ($depth > $maxd->{$parents->[0]}) {
15440:                 $maxd->{$parents->[0]} = $depth;
15441:             }
15442:         }
15443:     }
15444:     return;
15445: }
15446: 
15447: =pod
15448: 
15449: =item * &assign_categories_table()
15450: 
15451: Create a datatable for display of hierarchical categories in a domain,
15452: with checkboxes to allow a course to be categorized. 
15453: 
15454: Inputs:
15455: 
15456: cathash - reference to hash of categories defined for the domain (from
15457:           configuration.db)
15458: 
15459: currcat - scalar with an & separated list of categories assigned to a course. 
15460: 
15461: type    - scalar contains course type (Course or Community).
15462: 
15463: disabled - scalar (optional) contains disabled="disabled" if input elements are
15464:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15465: 
15466: Returns: $output (markup to be displayed) 
15467: 
15468: =cut
15469: 
15470: sub assign_categories_table {
15471:     my ($cathash,$currcat,$type,$disabled) = @_;
15472:     my $output;
15473:     if (ref($cathash) eq 'HASH') {
15474:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15475:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15476:         $maxdepth = scalar(@cats);
15477:         if (@cats > 0) {
15478:             my $itemcount = 0;
15479:             if (ref($cats[0]) eq 'ARRAY') {
15480:                 my @currcategories;
15481:                 if ($currcat ne '') {
15482:                     @currcategories = split('&',$currcat);
15483:                 }
15484:                 my $table;
15485:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15486:                     my $parent = $cats[0][$i];
15487:                     next if ($parent eq 'instcode');
15488:                     if ($type eq 'Community') {
15489:                         next unless ($parent eq 'communities');
15490:                     } elsif ($type eq 'Placement') {
15491:                         next unless ($parent eq 'placement');
15492:                     } else {
15493:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15494:                     }
15495:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15496:                     my $item = &escape($parent).'::0';
15497:                     my $checked = '';
15498:                     if (@currcategories > 0) {
15499:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15500:                             $checked = ' checked="checked"';
15501:                         }
15502:                     }
15503:                     my $parent_title = $parent;
15504:                     if ($parent eq 'communities') {
15505:                         $parent_title = &mt('Communities');
15506:                     } elsif ($parent eq 'placement') {
15507:                         $parent_title = &mt('Placement Tests');
15508:                     }
15509:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15510:                               '<input type="checkbox" name="usecategory" value="'.
15511:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15512:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15513:                     my $depth = 1;
15514:                     push(@path,$parent);
15515:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15516:                     pop(@path);
15517:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15518:                     $itemcount ++;
15519:                 }
15520:                 if ($itemcount) {
15521:                     $output = &Apache::loncommon::start_data_table().
15522:                               $table.
15523:                               &Apache::loncommon::end_data_table();
15524:                 }
15525:             }
15526:         }
15527:     }
15528:     return $output;
15529: }
15530: 
15531: =pod
15532: 
15533: =item * &assign_category_rows()
15534: 
15535: Create a datatable row for display of nested categories in a domain,
15536: with checkboxes to allow a course to be categorized,called recursively.
15537: 
15538: Inputs:
15539: 
15540: itemcount - track row number for alternating colors
15541: 
15542: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15543:       categories and subcategories.
15544: 
15545: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15546: 
15547: parent - parent of current category item
15548: 
15549: path - Array containing all categories back up through the hierarchy from the
15550:        current category to the top level.
15551: 
15552: currcategories - reference to array of current categories assigned to the course
15553: 
15554: disabled - scalar (optional) contains disabled="disabled" if input elements are
15555:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15556: 
15557: Returns: $output (markup to be displayed).
15558: 
15559: =cut
15560: 
15561: sub assign_category_rows {
15562:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15563:     my ($text,$name,$item,$chgstr);
15564:     if (ref($cats) eq 'ARRAY') {
15565:         my $maxdepth = scalar(@{$cats});
15566:         if (ref($cats->[$depth]) eq 'HASH') {
15567:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15568:                 my $numchildren = @{$cats->[$depth]{$parent}};
15569:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15570:                 $text .= '<td><table class="LC_data_table">';
15571:                 for (my $j=0; $j<$numchildren; $j++) {
15572:                     $name = $cats->[$depth]{$parent}[$j];
15573:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15574:                     my $deeper = $depth+1;
15575:                     my $checked = '';
15576:                     if (ref($currcategories) eq 'ARRAY') {
15577:                         if (@{$currcategories} > 0) {
15578:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15579:                                 $checked = ' checked="checked"';
15580:                             }
15581:                         }
15582:                     }
15583:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15584:                              '<input type="checkbox" name="usecategory" value="'.
15585:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15586:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15587:                              '</td><td>';
15588:                     if (ref($path) eq 'ARRAY') {
15589:                         push(@{$path},$name);
15590:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15591:                         pop(@{$path});
15592:                     }
15593:                     $text .= '</td></tr>';
15594:                 }
15595:                 $text .= '</table></td>';
15596:             }
15597:         }
15598:     }
15599:     return $text;
15600: }
15601: 
15602: =pod
15603: 
15604: =back
15605: 
15606: =cut
15607: 
15608: ############################################################
15609: ############################################################
15610: 
15611: 
15612: sub commit_customrole {
15613:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15614:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15615:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15616:                          ($end?', ending '.localtime($end):'').': <b>'.
15617:               &Apache::lonnet::assigncustomrole(
15618:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15619:                  '</b><br />';
15620:     return $output;
15621: }
15622: 
15623: sub commit_standardrole {
15624:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15625:     my ($output,$logmsg,$linefeed);
15626:     if ($context eq 'auto') {
15627:         $linefeed = "\n";
15628:     } else {
15629:         $linefeed = "<br />\n";
15630:     }  
15631:     if ($three eq 'st') {
15632:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15633:                                          $one,$two,$sec,$context,$credits);
15634:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15635:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15636:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15637:         } else {
15638:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15639:                ($start?', '.&mt('starting').' '.localtime($start):'').
15640:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15641:             if ($context eq 'auto') {
15642:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15643:             } else {
15644:                $output .= '<b>'.$result.'</b>'.$linefeed.
15645:                &mt('Add to classlist').': <b>ok</b>';
15646:             }
15647:             $output .= $linefeed;
15648:         }
15649:     } else {
15650:         $output = &mt('Assigning').' '.$three.' in '.$url.
15651:                ($start?', '.&mt('starting').' '.localtime($start):'').
15652:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15653:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15654:         if ($context eq 'auto') {
15655:             $output .= $result.$linefeed;
15656:         } else {
15657:             $output .= '<b>'.$result.'</b>'.$linefeed;
15658:         }
15659:     }
15660:     return $output;
15661: }
15662: 
15663: sub commit_studentrole {
15664:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15665:         $credits) = @_;
15666:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15667:     if ($context eq 'auto') {
15668:         $linefeed = "\n";
15669:     } else {
15670:         $linefeed = '<br />'."\n";
15671:     }
15672:     if (defined($one) && defined($two)) {
15673:         my $cid=$one.'_'.$two;
15674:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15675:         my $secchange = 0;
15676:         my $expire_role_result;
15677:         my $modify_section_result;
15678:         if ($oldsec ne '-1') { 
15679:             if ($oldsec ne $sec) {
15680:                 $secchange = 1;
15681:                 my $now = time;
15682:                 my $uurl='/'.$cid;
15683:                 $uurl=~s/\_/\//g;
15684:                 if ($oldsec) {
15685:                     $uurl.='/'.$oldsec;
15686:                 }
15687:                 $oldsecurl = $uurl;
15688:                 $expire_role_result = 
15689:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15690:                 if ($env{'request.course.sec'} ne '') { 
15691:                     if ($expire_role_result eq 'refused') {
15692:                         my @roles = ('st');
15693:                         my @statuses = ('previous');
15694:                         my @roledoms = ($one);
15695:                         my $withsec = 1;
15696:                         my %roleshash = 
15697:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15698:                                               \@statuses,\@roles,\@roledoms,$withsec);
15699:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15700:                             my ($oldstart,$oldend) = 
15701:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15702:                             if ($oldend > 0 && $oldend <= $now) {
15703:                                 $expire_role_result = 'ok';
15704:                             }
15705:                         }
15706:                     }
15707:                 }
15708:                 $result = $expire_role_result;
15709:             }
15710:         }
15711:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15712:             $modify_section_result = 
15713:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15714:                                                            undef,undef,undef,$sec,
15715:                                                            $end,$start,'','',$cid,
15716:                                                            '',$context,$credits);
15717:             if ($modify_section_result =~ /^ok/) {
15718:                 if ($secchange == 1) {
15719:                     if ($sec eq '') {
15720:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15721:                     } else {
15722:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15723:                     }
15724:                 } elsif ($oldsec eq '-1') {
15725:                     if ($sec eq '') {
15726:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15727:                     } else {
15728:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15729:                     }
15730:                 } else {
15731:                     if ($sec eq '') {
15732:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15733:                     } else {
15734:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15735:                     }
15736:                 }
15737:             } else {
15738:                 if ($secchange) { 
15739:                     $$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;
15740:                 } else {
15741:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15742:                 }
15743:             }
15744:             $result = $modify_section_result;
15745:         } elsif ($secchange == 1) {
15746:             if ($oldsec eq '') {
15747:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15748:             } else {
15749:                 $$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;
15750:             }
15751:             if ($expire_role_result eq 'refused') {
15752:                 my $newsecurl = '/'.$cid;
15753:                 $newsecurl =~ s/\_/\//g;
15754:                 if ($sec ne '') {
15755:                     $newsecurl.='/'.$sec;
15756:                 }
15757:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15758:                     if ($sec eq '') {
15759:                         $$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;
15760:                     } else {
15761:                         $$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;
15762:                     }
15763:                 }
15764:             }
15765:         }
15766:     } else {
15767:         $$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;
15768:         $result = "error: incomplete course id\n";
15769:     }
15770:     return $result;
15771: }
15772: 
15773: sub show_role_extent {
15774:     my ($scope,$context,$role) = @_;
15775:     $scope =~ s{^/}{};
15776:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15777:     push(@courseroles,'co');
15778:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15779:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15780:         $scope =~ s{/}{_};
15781:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15782:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15783:         my ($audom,$auname) = split(/\//,$scope);
15784:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15785:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15786:     } else {
15787:         $scope =~ s{/$}{};
15788:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15789:                    &Apache::lonnet::domain($scope,'description').'</span>');
15790:     }
15791: }
15792: 
15793: ############################################################
15794: ############################################################
15795: 
15796: sub check_clone {
15797:     my ($args,$linefeed) = @_;
15798:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15799:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15800:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15801:     my $clonemsg;
15802:     my $can_clone = 0;
15803:     my $lctype = lc($args->{'crstype'});
15804:     if ($lctype ne 'community') {
15805:         $lctype = 'course';
15806:     }
15807:     if ($clonehome eq 'no_host') {
15808:         if ($args->{'crstype'} eq 'Community') {
15809:             $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'});
15810:         } else {
15811:             $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'});
15812:         }     
15813:     } else {
15814: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15815:         if ($args->{'crstype'} eq 'Community') {
15816:             if ($clonedesc{'type'} ne 'Community') {
15817:                 $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'});
15818:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15819:             }
15820:         }
15821: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15822:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15823: 	    $can_clone = 1;
15824: 	} else {
15825: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15826: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15827:             if ($clonehash{'cloners'} eq '') {
15828:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15829:                 if ($domdefs{'canclone'}) {
15830:                     unless ($domdefs{'canclone'} eq 'none') {
15831:                         if ($domdefs{'canclone'} eq 'domain') {
15832:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15833:                                 $can_clone = 1;
15834:                             }
15835:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15836:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15837:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15838:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15839:                                 $can_clone = 1;
15840:                             }
15841:                         }
15842:                     }
15843:                 }
15844:             } else {
15845: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15846:                 if (grep(/^\*$/,@cloners)) {
15847:                     $can_clone = 1;
15848:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15849:                     $can_clone = 1;
15850:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15851:                     $can_clone = 1;
15852:                 }
15853:                 unless ($can_clone) {
15854:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15855:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15856:                         my (%gotdomdefaults,%gotcodedefaults);
15857:                         foreach my $cloner (@cloners) {
15858:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15859:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15860:                                 my (%codedefaults,@code_order);
15861:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15862:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15863:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15864:                                     }
15865:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15866:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15867:                                     }
15868:                                 } else {
15869:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15870:                                                                             \%codedefaults,
15871:                                                                             \@code_order);
15872:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15873:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15874:                                 }
15875:                                 if (@code_order > 0) {
15876:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15877:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15878:                                                                                 $args->{'crscode'})) {
15879:                                         $can_clone = 1;
15880:                                         last;
15881:                                     }
15882:                                 }
15883:                             }
15884:                         }
15885:                     }
15886:                 }
15887:             }
15888:             unless ($can_clone) {
15889:                 my $ccrole = 'cc';
15890:                 if ($args->{'crstype'} eq 'Community') {
15891:                     $ccrole = 'co';
15892:                 }
15893: 	        my %roleshash =
15894: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15895: 					          $args->{'ccdomain'},
15896:                                                   'userroles',['active'],[$ccrole],
15897: 					          [$args->{'clonedomain'}]);
15898: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15899:                     $can_clone = 1;
15900:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15901:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15902:                     $can_clone = 1;
15903:                 }
15904:             }
15905:             unless ($can_clone) {
15906:                 if ($args->{'crstype'} eq 'Community') {
15907:                     $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'});
15908:                 } else {
15909:                     $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'});
15910:                 }
15911: 	    }
15912:         }
15913:     }
15914:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15915: }
15916: 
15917: sub construct_course {
15918:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15919:         $cnum,$category,$coderef) = @_;
15920:     my $outcome;
15921:     my $linefeed =  '<br />'."\n";
15922:     if ($context eq 'auto') {
15923:         $linefeed = "\n";
15924:     }
15925: 
15926: #
15927: # Are we cloning?
15928: #
15929:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15930:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15931: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15932: 	if ($context ne 'auto') {
15933:             if ($clonemsg ne '') {
15934: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15935:             }
15936: 	}
15937: 	$outcome .= $clonemsg.$linefeed;
15938: 
15939:         if (!$can_clone) {
15940: 	    return (0,$outcome);
15941: 	}
15942:     }
15943: 
15944: #
15945: # Open course
15946: #
15947:     my $showncrstype;
15948:     if ($args->{'crstype'} eq 'Placement') {
15949:         $showncrstype = 'placement test'; 
15950:     } else {  
15951:         $showncrstype = lc($args->{'crstype'});
15952:     }
15953:     my %cenv=();
15954:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15955:                                              $args->{'cdescr'},
15956:                                              $args->{'curl'},
15957:                                              $args->{'course_home'},
15958:                                              $args->{'nonstandard'},
15959:                                              $args->{'crscode'},
15960:                                              $args->{'ccuname'}.':'.
15961:                                              $args->{'ccdomain'},
15962:                                              $args->{'crstype'},
15963:                                              $cnum,$context,$category);
15964: 
15965:     # Note: The testing routines depend on this being output; see 
15966:     # Utils::Course. This needs to at least be output as a comment
15967:     # if anyone ever decides to not show this, and Utils::Course::new
15968:     # will need to be suitably modified.
15969:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15970:     if ($$courseid =~ /^error:/) {
15971:         return (0,$outcome);
15972:     }
15973: 
15974: #
15975: # Check if created correctly
15976: #
15977:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15978:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15979:     if ($crsuhome eq 'no_host') {
15980:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15981:         return (0,$outcome);
15982:     }
15983:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15984: 
15985: #
15986: # Do the cloning
15987: #   
15988:     if ($can_clone && $cloneid) {
15989: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15990: 	if ($context ne 'auto') {
15991: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15992: 	}
15993: 	$outcome .= $clonemsg.$linefeed;
15994: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15995: # Copy all files
15996: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15997: # Restore URL
15998: 	$cenv{'url'}=$oldcenv{'url'};
15999: # Restore title
16000: 	$cenv{'description'}=$oldcenv{'description'};
16001: # Restore creation date, creator and creation context.
16002:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16003:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16004:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16005: # Mark as cloned
16006: 	$cenv{'clonedfrom'}=$cloneid;
16007: # Need to clone grading mode
16008:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16009:         $cenv{'grading'}=$newenv{'grading'};
16010: # Do not clone these environment entries
16011:         &Apache::lonnet::del('environment',
16012:                   ['default_enrollment_start_date',
16013:                    'default_enrollment_end_date',
16014:                    'question.email',
16015:                    'policy.email',
16016:                    'comment.email',
16017:                    'pch.users.denied',
16018:                    'plc.users.denied',
16019:                    'hidefromcat',
16020:                    'checkforpriv',
16021:                    'categories',
16022:                    'internal.uniquecode'],
16023:                    $$crsudom,$$crsunum);
16024:         if ($args->{'textbook'}) {
16025:             $cenv{'internal.textbook'} = $args->{'textbook'};
16026:         }
16027:     }
16028: 
16029: #
16030: # Set environment (will override cloned, if existing)
16031: #
16032:     my @sections = ();
16033:     my @xlists = ();
16034:     if ($args->{'crstype'}) {
16035:         $cenv{'type'}=$args->{'crstype'};
16036:     }
16037:     if ($args->{'crsid'}) {
16038:         $cenv{'courseid'}=$args->{'crsid'};
16039:     }
16040:     if ($args->{'crscode'}) {
16041:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16042:     }
16043:     if ($args->{'crsquota'} ne '') {
16044:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16045:     } else {
16046:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16047:     }
16048:     if ($args->{'ccuname'}) {
16049:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16050:                                         ':'.$args->{'ccdomain'};
16051:     } else {
16052:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16053:     }
16054:     if ($args->{'defaultcredits'}) {
16055:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16056:     }
16057:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16058:     if ($args->{'crssections'}) {
16059:         $cenv{'internal.sectionnums'} = '';
16060:         if ($args->{'crssections'} =~ m/,/) {
16061:             @sections = split/,/,$args->{'crssections'};
16062:         } else {
16063:             $sections[0] = $args->{'crssections'};
16064:         }
16065:         if (@sections > 0) {
16066:             foreach my $item (@sections) {
16067:                 my ($sec,$gp) = split/:/,$item;
16068:                 my $class = $args->{'crscode'}.$sec;
16069:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16070:                 $cenv{'internal.sectionnums'} .= $item.',';
16071:                 unless ($addcheck eq 'ok') {
16072:                     push(@badclasses,$class);
16073:                 }
16074:             }
16075:             $cenv{'internal.sectionnums'} =~ s/,$//;
16076:         }
16077:     }
16078: # do not hide course coordinator from staff listing, 
16079: # even if privileged
16080:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16081: # add course coordinator's domain to domains to check for privileged users
16082: # if different to course domain
16083:     if ($$crsudom ne $args->{'ccdomain'}) {
16084:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16085:     }
16086: # add crosslistings
16087:     if ($args->{'crsxlist'}) {
16088:         $cenv{'internal.crosslistings'}='';
16089:         if ($args->{'crsxlist'} =~ m/,/) {
16090:             @xlists = split/,/,$args->{'crsxlist'};
16091:         } else {
16092:             $xlists[0] = $args->{'crsxlist'};
16093:         }
16094:         if (@xlists > 0) {
16095:             foreach my $item (@xlists) {
16096:                 my ($xl,$gp) = split/:/,$item;
16097:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16098:                 $cenv{'internal.crosslistings'} .= $item.',';
16099:                 unless ($addcheck eq 'ok') {
16100:                     push(@badclasses,$xl);
16101:                 }
16102:             }
16103:             $cenv{'internal.crosslistings'} =~ s/,$//;
16104:         }
16105:     }
16106:     if ($args->{'autoadds'}) {
16107:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16108:     }
16109:     if ($args->{'autodrops'}) {
16110:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16111:     }
16112: # check for notification of enrollment changes
16113:     my @notified = ();
16114:     if ($args->{'notify_owner'}) {
16115:         if ($args->{'ccuname'} ne '') {
16116:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16117:         }
16118:     }
16119:     if ($args->{'notify_dc'}) {
16120:         if ($uname ne '') { 
16121:             push(@notified,$uname.':'.$udom);
16122:         }
16123:     }
16124:     if (@notified > 0) {
16125:         my $notifylist;
16126:         if (@notified > 1) {
16127:             $notifylist = join(',',@notified);
16128:         } else {
16129:             $notifylist = $notified[0];
16130:         }
16131:         $cenv{'internal.notifylist'} = $notifylist;
16132:     }
16133:     if (@badclasses > 0) {
16134:         my %lt=&Apache::lonlocal::texthash(
16135:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16136:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16137:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16138:         );
16139:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16140:                            &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'};
16141:         if ($context eq 'auto') {
16142:             $outcome .= $badclass_msg.$linefeed;
16143:         } else {
16144:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16145:         }
16146:         foreach my $item (@badclasses) {
16147:             if ($context eq 'auto') {
16148:                 $outcome .= " - $item\n";
16149:             } else {
16150:                 $outcome .= "<li>$item</li>\n";
16151:             }
16152:         }
16153:         if ($context eq 'auto') {
16154:             $outcome .= $linefeed;
16155:         } else {
16156:             $outcome .= "</ul><br /><br /></div>\n";
16157:         } 
16158:     }
16159:     if ($args->{'no_end_date'}) {
16160:         $args->{'endaccess'} = 0;
16161:     }
16162:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16163:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16164:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16165:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16166:     if ($args->{'showphotos'}) {
16167:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16168:     }
16169:     $cenv{'internal.authtype'} = $args->{'authtype'};
16170:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16171:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16172:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16173:             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'); 
16174:             if ($context eq 'auto') {
16175:                 $outcome .= $krb_msg;
16176:             } else {
16177:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16178:             }
16179:             $outcome .= $linefeed;
16180:         }
16181:     }
16182:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16183:        if ($args->{'setpolicy'}) {
16184:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16185:        }
16186:        if ($args->{'setcontent'}) {
16187:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16188:        }
16189:        if ($args->{'setcomment'}) {
16190:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16191:        }
16192:     }
16193:     if ($args->{'reshome'}) {
16194: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16195: 	$cenv{'reshome'}=~s/\/+$/\//;
16196:     }
16197: #
16198: # course has keyed access
16199: #
16200:     if ($args->{'setkeys'}) {
16201:        $cenv{'keyaccess'}='yes';
16202:     }
16203: # if specified, key authority is not course, but user
16204: # only active if keyaccess is yes
16205:     if ($args->{'keyauth'}) {
16206: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16207: 	$user = &LONCAPA::clean_username($user);
16208: 	$domain = &LONCAPA::clean_username($domain);
16209: 	if ($user ne '' && $domain ne '') {
16210: 	    $cenv{'keyauth'}=$user.':'.$domain;
16211: 	}
16212:     }
16213: 
16214: #
16215: #  generate and store uniquecode (available to course requester), if course should have one.
16216: #
16217:     if ($args->{'uniquecode'}) {
16218:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16219:         if ($code) {
16220:             $cenv{'internal.uniquecode'} = $code;
16221:             my %crsinfo =
16222:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16223:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16224:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16225:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16226:             } 
16227:             if (ref($coderef)) {
16228:                 $$coderef = $code;
16229:             }
16230:         }
16231:     }
16232: 
16233:     if ($args->{'disresdis'}) {
16234:         $cenv{'pch.roles.denied'}='st';
16235:     }
16236:     if ($args->{'disablechat'}) {
16237:         $cenv{'plc.roles.denied'}='st';
16238:     }
16239: 
16240:     # Record we've not yet viewed the Course Initialization Helper for this 
16241:     # course
16242:     $cenv{'course.helper.not.run'} = 1;
16243:     #
16244:     # Use new Randomseed
16245:     #
16246:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16247:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16248:     #
16249:     # The encryption code and receipt prefix for this course
16250:     #
16251:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16252:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16253:     #
16254:     # By default, use standard grading
16255:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16256: 
16257:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16258:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16259: #
16260: # Open all assignments
16261: #
16262:     if ($args->{'openall'}) {
16263:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16264:        my %storecontent = ($storeunder         => time,
16265:                            $storeunder.'.type' => 'date_start');
16266:        
16267:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
16268:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16269:    }
16270: #
16271: # Set first page
16272: #
16273:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16274: 	    || ($cloneid)) {
16275: 	use LONCAPA::map;
16276: 	$outcome .= &mt('Setting first resource').': ';
16277: 
16278: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16279:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16280: 
16281:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16282:         my $title; my $url;
16283:         if ($args->{'firstres'} eq 'syl') {
16284: 	    $title=&mt('Syllabus');
16285:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16286:         } else {
16287:             $title=&mt('Table of Contents');
16288:             $url='/adm/navmaps';
16289:         }
16290: 
16291:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16292: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16293: 
16294: 	if ($errtext) { $fatal=2; }
16295:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16296:     }
16297: 
16298: # 
16299: # Set params for Placement Tests
16300: #
16301:     if ($args->{'crstype'} eq 'Placement') {
16302:        my %storecontent; 
16303:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16304:        my %defaults = (
16305:                         buttonshide   => { value => 'yes',
16306:                                            type => 'string_yesno',},
16307:                         type          => { value => 'randomizetry',
16308:                                            type  => 'string_questiontype',},
16309:                         maxtries      => { value => 1,
16310:                                            type => 'int_pos',},
16311:                         problemstatus => { value => 'no',
16312:                                            type  => 'string_problemstatus',},
16313:                       );
16314:        foreach my $key (keys(%defaults)) {
16315:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16316:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16317:        }
16318:        &Apache::lonnet::cput
16319:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
16320:     }
16321: 
16322:     return (1,$outcome);
16323: }
16324: 
16325: sub make_unique_code {
16326:     my ($cdom,$cnum) = @_;
16327:     # get lock on uniquecodes db
16328:     my $lockhash = {
16329:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16330:                                                   ':'.$env{'user.domain'},
16331:                    };
16332:     my $tries = 0;
16333:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16334:     my ($code,$error);
16335:   
16336:     while (($gotlock ne 'ok') && ($tries<3)) {
16337:         $tries ++;
16338:         sleep 1;
16339:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16340:     }
16341:     if ($gotlock eq 'ok') {
16342:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16343:         my $gotcode;
16344:         my $attempts = 0;
16345:         while ((!$gotcode) && ($attempts < 100)) {
16346:             $code = &generate_code();
16347:             if (!exists($currcodes{$code})) {
16348:                 $gotcode = 1;
16349:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16350:                     $error = 'nostore';
16351:                 }
16352:             }
16353:             $attempts ++;
16354:         }
16355:         my @del_lock = ($cnum."\0".'uniquecodes');
16356:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16357:     } else {
16358:         $error = 'nolock';
16359:     }
16360:     return ($code,$error);
16361: }
16362: 
16363: sub generate_code {
16364:     my $code;
16365:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16366:     for (my $i=0; $i<6; $i++) {
16367:         my $lettnum = int (rand 2);
16368:         my $item = '';
16369:         if ($lettnum) {
16370:             $item = $letts[int( rand(18) )];
16371:         } else {
16372:             $item = 1+int( rand(8) );
16373:         }
16374:         $code .= $item;
16375:     }
16376:     return $code;
16377: }
16378: 
16379: ############################################################
16380: ############################################################
16381: 
16382: # Community, Course and Placement Test
16383: sub course_type {
16384:     my ($cid) = @_;
16385:     if (!defined($cid)) {
16386:         $cid = $env{'request.course.id'};
16387:     }
16388:     if (defined($env{'course.'.$cid.'.type'})) {
16389:         return $env{'course.'.$cid.'.type'};
16390:     } else {
16391:         return 'Course';
16392:     }
16393: }
16394: 
16395: sub group_term {
16396:     my $crstype = &course_type();
16397:     my %names = (
16398:                   'Course' => 'group',
16399:                   'Community' => 'group',
16400:                   'Placement' => 'group',
16401:                 );
16402:     return $names{$crstype};
16403: }
16404: 
16405: sub course_types {
16406:     my @types = ('official','unofficial','community','textbook','placement','lti');
16407:     my %typename = (
16408:                          official   => 'Official course',
16409:                          unofficial => 'Unofficial course',
16410:                          community  => 'Community',
16411:                          textbook   => 'Textbook course',
16412:                          placement  => 'Placement test',
16413:                          lti        => 'LTI provider',
16414:                    );
16415:     return (\@types,\%typename);
16416: }
16417: 
16418: sub icon {
16419:     my ($file)=@_;
16420:     my $curfext = lc((split(/\./,$file))[-1]);
16421:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16422:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16423:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16424: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16425: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16426: 	            $curfext.".gif") {
16427: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16428: 		$curfext.".gif";
16429: 	}
16430:     }
16431:     return &lonhttpdurl($iconname);
16432: } 
16433: 
16434: sub lonhttpdurl {
16435: #
16436: # Had been used for "small fry" static images on separate port 8080.
16437: # Modify here if lightweight http functionality desired again.
16438: # Currently eliminated due to increasing firewall issues.
16439: #
16440:     my ($url)=@_;
16441:     return $url;
16442: }
16443: 
16444: sub connection_aborted {
16445:     my ($r)=@_;
16446:     $r->print(" ");$r->rflush();
16447:     my $c = $r->connection;
16448:     return $c->aborted();
16449: }
16450: 
16451: #    Escapes strings that may have embedded 's that will be put into
16452: #    strings as 'strings'.
16453: sub escape_single {
16454:     my ($input) = @_;
16455:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16456:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16457:     return $input;
16458: }
16459: 
16460: #  Same as escape_single, but escape's "'s  This 
16461: #  can be used for  "strings"
16462: sub escape_double {
16463:     my ($input) = @_;
16464:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16465:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16466:     return $input;
16467: }
16468:  
16469: #   Escapes the last element of a full URL.
16470: sub escape_url {
16471:     my ($url)   = @_;
16472:     my @urlslices = split(/\//, $url,-1);
16473:     my $lastitem = &escape(pop(@urlslices));
16474:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16475: }
16476: 
16477: sub compare_arrays {
16478:     my ($arrayref1,$arrayref2) = @_;
16479:     my (@difference,%count);
16480:     @difference = ();
16481:     %count = ();
16482:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16483:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16484:         foreach my $element (keys(%count)) {
16485:             if ($count{$element} == 1) {
16486:                 push(@difference,$element);
16487:             }
16488:         }
16489:     }
16490:     return @difference;
16491: }
16492: 
16493: sub lon_status_items {
16494:     my %defaults = (
16495:                      E         => 100,
16496:                      W         => 4,
16497:                      N         => 1,
16498:                      U         => 5,
16499:                      threshold => 200,
16500:                      sysmail   => 2500,
16501:                    );
16502:     my %names = (
16503:                    E => 'Errors',
16504:                    W => 'Warnings',
16505:                    N => 'Notices',
16506:                    U => 'Unsent',
16507:                 );
16508:     return (\%defaults,\%names);
16509: }
16510: 
16511: # -------------------------------------------------------- Initialize user login
16512: sub init_user_environment {
16513:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16514:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16515: 
16516:     my $public=($username eq 'public' && $domain eq 'public');
16517: 
16518:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16519:     my $now=time;
16520: 
16521:     if ($public) {
16522: 	my $max_public=100;
16523: 	my $oldest;
16524: 	my $oldest_time=0;
16525: 	for(my $next=1;$next<=$max_public;$next++) {
16526: 	    if (-e $lonids."/publicuser_$next.id") {
16527: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16528: 		if ($mtime<$oldest_time || !$oldest_time) {
16529: 		    $oldest_time=$mtime;
16530: 		    $oldest=$next;
16531: 		}
16532: 	    } else {
16533: 		$cookie="publicuser_$next";
16534: 		last;
16535: 	    }
16536: 	}
16537: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16538:     } else {
16539: 	# See if old ID present, if so, remove if this isn't a robot,
16540: 	# killing any existing non-robot sessions
16541: 	if (!$args->{'robot'}) {
16542: 	    opendir(DIR,$lonids);
16543: 	    while ($filename=readdir(DIR)) {
16544: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16545:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16546:                             &GDBM_READER(),0640)) {
16547:                         my $linkedfile;
16548:                         if (exists($oldenv{'user.linkedenv'})) {
16549:                             $linkedfile = $oldenv{'user.linkedenv'};
16550:                         }
16551:                         untie(%oldenv);
16552:                         if (unlink("$lonids/$filename")) {
16553:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16554:                                 if (-l "$lonids/$linkedfile.id") {
16555:                                     unlink("$lonids/$linkedfile.id");
16556:                                 }
16557:                             }
16558:                         }
16559:                     } else {
16560:                         unlink($lonids.'/'.$filename);
16561:                     }
16562: 		}
16563: 	    }
16564: 	    closedir(DIR);
16565: # If there is a undeleted lockfile for the user's paste buffer remove it.
16566:             my $namespace = 'nohist_courseeditor';
16567:             my $lockingkey = 'paste'."\0".'locked_num';
16568:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16569:                                                 $domain,$username);
16570:             if (exists($lockhash{$lockingkey})) {
16571:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16572:                 unless ($delresult eq 'ok') {
16573:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16574:                 }
16575:             }
16576: 	}
16577: # Give them a new cookie
16578: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16579: 		                   : $now.$$.int(rand(10000)));
16580: 	$cookie="$username\_$id\_$domain\_$authhost";
16581:     
16582: # Initialize roles
16583: 
16584: 	($userroles,$firstaccenv,$timerintenv) = 
16585:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16586:     }
16587: # ------------------------------------ Check browser type and MathML capability
16588: 
16589:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16590:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16591: 
16592: # ------------------------------------------------------------- Get environment
16593: 
16594:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16595:     my ($tmp) = keys(%userenv);
16596:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16597: 	undef(%userenv);
16598:     }
16599:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16600: 	$form->{'interface'}=$userenv{'interface'};
16601:     }
16602:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16603: 
16604: # --------------- Do not trust query string to be put directly into environment
16605:     foreach my $option ('interface','localpath','localres') {
16606:         $form->{$option}=~s/[\n\r\=]//gs;
16607:     }
16608: # --------------------------------------------------------- Write first profile
16609: 
16610:     {
16611: 	my %initial_env = 
16612: 	    ("user.name"          => $username,
16613: 	     "user.domain"        => $domain,
16614: 	     "user.home"          => $authhost,
16615: 	     "browser.type"       => $clientbrowser,
16616: 	     "browser.version"    => $clientversion,
16617: 	     "browser.mathml"     => $clientmathml,
16618: 	     "browser.unicode"    => $clientunicode,
16619: 	     "browser.os"         => $clientos,
16620:              "browser.mobile"     => $clientmobile,
16621:              "browser.info"       => $clientinfo,
16622:              "browser.osversion"  => $clientosversion,
16623: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16624: 	     "request.course.fn"  => '',
16625: 	     "request.course.uri" => '',
16626: 	     "request.course.sec" => '',
16627: 	     "request.role"       => 'cm',
16628: 	     "request.role.adv"   => $env{'user.adv'},
16629: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16630: 
16631:         if ($form->{'localpath'}) {
16632: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16633: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16634:         }
16635: 	
16636: 	if ($form->{'interface'}) {
16637: 	    $form->{'interface'}=~s/\W//gs;
16638: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16639: 	    $env{'browser.interface'}=$form->{'interface'};
16640: 	}
16641: 
16642:         if ($form->{'iptoken'}) {
16643:             my $lonhost = $r->dir_config('lonHostID');
16644:             $initial_env{"user.noloadbalance"} = $lonhost;
16645:             $env{'user.noloadbalance'} = $lonhost;
16646:         }
16647: 
16648:         if ($form->{'noloadbalance'}) {
16649:             my @hosts = &Apache::lonnet::current_machine_ids();
16650:             my $hosthere = $form->{'noloadbalance'};
16651:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16652:                 $initial_env{"user.noloadbalance"} = $hosthere;
16653:                 $env{'user.noloadbalance'} = $hosthere;
16654:             }
16655:         }
16656: 
16657:         unless ($domain eq 'public') {
16658:             my %is_adv = ( is_adv => $env{'user.adv'} );
16659:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16660: 
16661:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16662:                 $userenv{'availabletools.'.$tool} = 
16663:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16664:                                                       undef,\%userenv,\%domdef,\%is_adv);
16665:             }
16666: 
16667:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
16668:                 $userenv{'canrequest.'.$crstype} =
16669:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16670:                                                       'reload','requestcourses',
16671:                                                       \%userenv,\%domdef,\%is_adv);
16672:             }
16673: 
16674:             $userenv{'canrequest.author'} =
16675:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16676:                                                   'reload','requestauthor',
16677:                                                   \%userenv,\%domdef,\%is_adv);
16678:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16679:                                                  $domain,$username);
16680:             my $reqstatus = $reqauthor{'author_status'};
16681:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16682:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16683:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16684:                                                       $reqauthor{'author'}{'timestamp'};
16685:                 }
16686:             }
16687:             my ($types,$typename) = &course_types();
16688:             if (ref($types) eq 'ARRAY') {
16689:                 my @options = ('approval','validate','autolimit');
16690:                 my $optregex = join('|',@options);
16691:                 my (%willtrust,%trustchecked);
16692:                 foreach my $type (@{$types}) {
16693:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
16694:                     if ($dom_str ne '') {
16695:                         my $updatedstr = '';
16696:                         my @possdomains = split(',',$dom_str);
16697:                         foreach my $entry (@possdomains) {
16698:                             my ($extdom,$extopt) = split(':',$entry);
16699:                             unless ($trustchecked{$extdom}) {
16700:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
16701:                                 $trustchecked{$extdom} = 1;
16702:                             }
16703:                             if ($willtrust{$extdom}) {
16704:                                 $updatedstr .= $entry.',';
16705:                             }
16706:                         }
16707:                         $updatedstr =~ s/,$//;
16708:                         if ($updatedstr) {
16709:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
16710:                         } else {
16711:                             delete($userenv{'reqcrsotherdom.'.$type});
16712:                         }
16713:                     }
16714:                 }
16715:             }
16716:         }
16717: 	$env{'user.environment'} = "$lonids/$cookie.id";
16718: 
16719: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16720: 		 &GDBM_WRCREAT(),0640)) {
16721: 	    &_add_to_env(\%disk_env,\%initial_env);
16722: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16723: 	    &_add_to_env(\%disk_env,$userroles);
16724:             if (ref($firstaccenv) eq 'HASH') {
16725:                 &_add_to_env(\%disk_env,$firstaccenv);
16726:             }
16727:             if (ref($timerintenv) eq 'HASH') {
16728:                 &_add_to_env(\%disk_env,$timerintenv);
16729:             }
16730: 	    if (ref($args->{'extra_env'})) {
16731: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16732: 	    }
16733: 	    untie(%disk_env);
16734: 	} else {
16735: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16736: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16737: 	    return 'error: '.$!;
16738: 	}
16739:     }
16740:     $env{'request.role'}='cm';
16741:     $env{'request.role.adv'}=$env{'user.adv'};
16742:     $env{'browser.type'}=$clientbrowser;
16743: 
16744:     return $cookie;
16745: 
16746: }
16747: 
16748: sub _add_to_env {
16749:     my ($idf,$env_data,$prefix) = @_;
16750:     if (ref($env_data) eq 'HASH') {
16751:         while (my ($key,$value) = each(%$env_data)) {
16752: 	    $idf->{$prefix.$key} = $value;
16753: 	    $env{$prefix.$key}   = $value;
16754:         }
16755:     }
16756: }
16757: 
16758: # --- Get the symbolic name of a problem and the url
16759: sub get_symb {
16760:     my ($request,$silent) = @_;
16761:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16762:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16763:     if ($symb eq '') {
16764:         if (!$silent) {
16765:             if (ref($request)) { 
16766:                 $request->print("Unable to handle ambiguous references:$url:.");
16767:             }
16768:             return ();
16769:         }
16770:     }
16771:     &Apache::lonenc::check_decrypt(\$symb);
16772:     return ($symb);
16773: }
16774: 
16775: # --------------------------------------------------------------Get annotation
16776: 
16777: sub get_annotation {
16778:     my ($symb,$enc) = @_;
16779: 
16780:     my $key = $symb;
16781:     if (!$enc) {
16782:         $key =
16783:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16784:     }
16785:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16786:     return $annotation{$key};
16787: }
16788: 
16789: sub clean_symb {
16790:     my ($symb,$delete_enc) = @_;
16791: 
16792:     &Apache::lonenc::check_decrypt(\$symb);
16793:     my $enc = $env{'request.enc'};
16794:     if ($delete_enc) {
16795:         delete($env{'request.enc'});
16796:     }
16797: 
16798:     return ($symb,$enc);
16799: }
16800: 
16801: ############################################################
16802: ############################################################
16803: 
16804: =pod
16805: 
16806: =head1 Routines for building display used to search for courses
16807: 
16808: 
16809: =over 4
16810: 
16811: =item * &build_filters()
16812: 
16813: Create markup for a table used to set filters to use when selecting
16814: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16815: and quotacheck.pl
16816: 
16817: 
16818: Inputs:
16819: 
16820: filterlist - anonymous array of fields to include as potential filters 
16821: 
16822: crstype - course type
16823: 
16824: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16825:               to pop-open a course selector (will contain "extra element"). 
16826: 
16827: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16828: 
16829: filter - anonymous hash of criteria and their values
16830: 
16831: action - form action
16832: 
16833: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16834: 
16835: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16836: 
16837: cloneruname - username of owner of new course who wants to clone
16838: 
16839: clonerudom - domain of owner of new course who wants to clone
16840: 
16841: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16842: 
16843: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16844: 
16845: codedom - domain
16846: 
16847: formname - value of form element named "form". 
16848: 
16849: fixeddom - domain, if fixed.
16850: 
16851: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16852: 
16853: cnameelement - name of form element in form on opener page which will receive title of selected course 
16854: 
16855: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16856: 
16857: cdomelement - name of form element in form on opener page which will receive domain of selected course
16858: 
16859: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16860: 
16861: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16862: 
16863: clonewarning - warning message about missing information for intended course owner when DC creates a course
16864: 
16865: 
16866: Returns: $output - HTML for display of search criteria, and hidden form elements.
16867: 
16868: 
16869: Side Effects: None
16870: 
16871: =cut
16872: 
16873: # ---------------------------------------------- search for courses based on last activity etc.
16874: 
16875: sub build_filters {
16876:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16877:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16878:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16879:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16880:         $clonetext,$clonewarning) = @_;
16881:     my ($list,$jscript);
16882:     my $onchange = 'javascript:updateFilters(this)';
16883:     my ($domainselectform,$sincefilterform,$createdfilterform,
16884:         $ownerdomselectform,$persondomselectform,$instcodeform,
16885:         $typeselectform,$instcodetitle);
16886:     if ($formname eq '') {
16887:         $formname = $caller;
16888:     }
16889:     foreach my $item (@{$filterlist}) {
16890:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16891:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16892:             if ($item eq 'domainfilter') {
16893:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16894:             } elsif ($item eq 'coursefilter') {
16895:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16896:             } elsif ($item eq 'ownerfilter') {
16897:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16898:             } elsif ($item eq 'ownerdomfilter') {
16899:                 $filter->{'ownerdomfilter'} =
16900:                     &LONCAPA::clean_domain($filter->{$item});
16901:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16902:                                                        'ownerdomfilter',1);
16903:             } elsif ($item eq 'personfilter') {
16904:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16905:             } elsif ($item eq 'persondomfilter') {
16906:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16907:                                                         'persondomfilter',1);
16908:             } else {
16909:                 $filter->{$item} =~ s/\W//g;
16910:             }
16911:             if (!$filter->{$item}) {
16912:                 $filter->{$item} = '';
16913:             }
16914:         }
16915:         if ($item eq 'domainfilter') {
16916:             my $allow_blank = 1;
16917:             if ($formname eq 'portform') {
16918:                 $allow_blank=0;
16919:             } elsif ($formname eq 'studentform') {
16920:                 $allow_blank=0;
16921:             }
16922:             if ($fixeddom) {
16923:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16924:                                     ' value="'.$codedom.'" />'.
16925:                                     &Apache::lonnet::domain($codedom,'description');
16926:             } else {
16927:                 $domainselectform = &select_dom_form($filter->{$item},
16928:                                                      'domainfilter',
16929:                                                       $allow_blank,'',$onchange);
16930:             }
16931:         } else {
16932:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16933:         }
16934:     }
16935: 
16936:     # last course activity filter and selection
16937:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16938: 
16939:     # course created filter and selection
16940:     if (exists($filter->{'createdfilter'})) {
16941:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16942:     }
16943: 
16944:     my $prefix = $crstype;
16945:     if ($crstype eq 'Placement') {
16946:         $prefix = 'Placement Test'
16947:     }
16948:     my %lt = &Apache::lonlocal::texthash(
16949:                 'cac' => "$prefix Activity",
16950:                 'ccr' => "$prefix Created",
16951:                 'cde' => "$prefix Title",
16952:                 'cdo' => "$prefix Domain",
16953:                 'ins' => 'Institutional Code',
16954:                 'inc' => 'Institutional Categorization',
16955:                 'cow' => "$prefix Owner/Co-owner",
16956:                 'cop' => "$prefix Personnel Includes",
16957:                 'cog' => 'Type',
16958:              );
16959: 
16960:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16961:         my $typeval = 'Course';
16962:         if ($crstype eq 'Community') {
16963:             $typeval = 'Community';
16964:         } elsif ($crstype eq 'Placement') {
16965:             $typeval = 'Placement';
16966:         }
16967:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16968:     } else {
16969:         $typeselectform =  '<select name="type" size="1"';
16970:         if ($onchange) {
16971:             $typeselectform .= ' onchange="'.$onchange.'"';
16972:         }
16973:         $typeselectform .= '>'."\n";
16974:         foreach my $posstype ('Course','Community','Placement') {
16975:             my $shown;
16976:             if ($posstype eq 'Placement') {
16977:                 $shown = &mt('Placement Test');
16978:             } else {
16979:                 $shown = &mt($posstype);
16980:             }
16981:             $typeselectform.='<option value="'.$posstype.'"'.
16982:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16983:         }
16984:         $typeselectform.="</select>";
16985:     }
16986: 
16987:     my ($cloneableonlyform,$cloneabletitle);
16988:     if (exists($filter->{'cloneableonly'})) {
16989:         my $cloneableon = '';
16990:         my $cloneableoff = ' checked="checked"';
16991:         if ($filter->{'cloneableonly'}) {
16992:             $cloneableon = $cloneableoff;
16993:             $cloneableoff = '';
16994:         }
16995:         $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>';
16996:         if ($formname eq 'ccrs') {
16997:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16998:         } else {
16999:             $cloneabletitle = &mt('Cloneable by you');
17000:         }
17001:     }
17002:     my $officialjs;
17003:     if ($crstype eq 'Course') {
17004:         if (exists($filter->{'instcodefilter'})) {
17005: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17006: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17007:             if ($codedom) { 
17008:                 $officialjs = 1;
17009:                 ($instcodeform,$jscript,$$numtitlesref) =
17010:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17011:                                                                   $officialjs,$codetitlesref);
17012:                 if ($jscript) {
17013:                     $jscript = '<script type="text/javascript">'."\n".
17014:                                '// <![CDATA['."\n".
17015:                                $jscript."\n".
17016:                                '// ]]>'."\n".
17017:                                '</script>'."\n";
17018:                 }
17019:             }
17020:             if ($instcodeform eq '') {
17021:                 $instcodeform =
17022:                     '<input type="text" name="instcodefilter" size="10" value="'.
17023:                     $list->{'instcodefilter'}.'" />';
17024:                 $instcodetitle = $lt{'ins'};
17025:             } else {
17026:                 $instcodetitle = $lt{'inc'};
17027:             }
17028:             if ($fixeddom) {
17029:                 $instcodetitle .= '<br />('.$codedom.')';
17030:             }
17031:         }
17032:     }
17033:     my $output = qq|
17034: <form method="post" name="filterpicker" action="$action">
17035: <input type="hidden" name="form" value="$formname" />
17036: |;
17037:     if ($formname eq 'modifycourse') {
17038:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17039:                    '<input type="hidden" name="prevphase" value="'.
17040:                    $prevphase.'" />'."\n";
17041:     } elsif ($formname eq 'quotacheck') {
17042:         $output .= qq|
17043: <input type="hidden" name="sortby" value="" />
17044: <input type="hidden" name="sortorder" value="" />
17045: |;
17046:     } else {
17047:         my $name_input;
17048:         if ($cnameelement ne '') {
17049:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17050:                           $cnameelement.'" />';
17051:         }
17052:         $output .= qq|
17053: <input type="hidden" name="cnumelement" value="$cnumelement" />
17054: <input type="hidden" name="cdomelement" value="$cdomelement" />
17055: $name_input
17056: $roleelement
17057: $multelement
17058: $typeelement
17059: |;
17060:         if ($formname eq 'portform') {
17061:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17062:         }
17063:     }
17064:     if ($fixeddom) {
17065:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17066:     }
17067:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17068:     if ($sincefilterform) {
17069:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17070:                   .$sincefilterform
17071:                   .&Apache::lonhtmlcommon::row_closure();
17072:     }
17073:     if ($createdfilterform) {
17074:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17075:                   .$createdfilterform
17076:                   .&Apache::lonhtmlcommon::row_closure();
17077:     }
17078:     if ($domainselectform) {
17079:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17080:                   .$domainselectform
17081:                   .&Apache::lonhtmlcommon::row_closure();
17082:     }
17083:     if ($typeselectform) {
17084:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17085:             $output .= $typeselectform;
17086:         } else {
17087:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17088:                       .$typeselectform
17089:                       .&Apache::lonhtmlcommon::row_closure();
17090:         }
17091:     }
17092:     if ($instcodeform) {
17093:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17094:                   .$instcodeform
17095:                   .&Apache::lonhtmlcommon::row_closure();
17096:     }
17097:     if (exists($filter->{'ownerfilter'})) {
17098:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17099:                    '<table><tr><td>'.&mt('Username').'<br />'.
17100:                    '<input type="text" name="ownerfilter" size="20" value="'.
17101:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17102:                    $ownerdomselectform.'</td></tr></table>'.
17103:                    &Apache::lonhtmlcommon::row_closure();
17104:     }
17105:     if (exists($filter->{'personfilter'})) {
17106:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17107:                    '<table><tr><td>'.&mt('Username').'<br />'.
17108:                    '<input type="text" name="personfilter" size="20" value="'.
17109:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17110:                    $persondomselectform.'</td></tr></table>'.
17111:                    &Apache::lonhtmlcommon::row_closure();
17112:     }
17113:     if (exists($filter->{'coursefilter'})) {
17114:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17115:                   .'<input type="text" name="coursefilter" size="25" value="'
17116:                   .$list->{'coursefilter'}.'" />'
17117:                   .&Apache::lonhtmlcommon::row_closure();
17118:     }
17119:     if ($cloneableonlyform) {
17120:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17121:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17122:     }
17123:     if (exists($filter->{'descriptfilter'})) {
17124:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17125:                   .'<input type="text" name="descriptfilter" size="40" value="'
17126:                   .$list->{'descriptfilter'}.'" />'
17127:                   .&Apache::lonhtmlcommon::row_closure(1);
17128:     }
17129:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17130:                '<input type="hidden" name="updater" value="" />'."\n".
17131:                '<input type="submit" name="gosearch" value="'.
17132:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17133:     return $jscript.$clonewarning.$output;
17134: }
17135: 
17136: =pod 
17137: 
17138: =item * &timebased_select_form()
17139: 
17140: Create markup for a dropdown list used to select a time-based
17141: filter e.g., Course Activity, Course Created, when searching for courses
17142: or communities
17143: 
17144: Inputs:
17145: 
17146: item - name of form element (sincefilter or createdfilter)
17147: 
17148: filter - anonymous hash of criteria and their values
17149: 
17150: Returns: HTML for a select box contained a blank, then six time selections,
17151:          with value set in incoming form variables currently selected. 
17152: 
17153: Side Effects: None
17154: 
17155: =cut
17156: 
17157: sub timebased_select_form {
17158:     my ($item,$filter) = @_;
17159:     if (ref($filter) eq 'HASH') {
17160:         $filter->{$item} =~ s/[^\d-]//g;
17161:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17162:         return &select_form(
17163:                             $filter->{$item},
17164:                             $item,
17165:                             {      '-1' => '',
17166:                                 '86400' => &mt('today'),
17167:                                '604800' => &mt('last week'),
17168:                               '2592000' => &mt('last month'),
17169:                               '7776000' => &mt('last three months'),
17170:                              '15552000' => &mt('last six months'),
17171:                              '31104000' => &mt('last year'),
17172:                     'select_form_order' =>
17173:                            ['-1','86400','604800','2592000','7776000',
17174:                             '15552000','31104000']});
17175:     }
17176: }
17177: 
17178: =pod
17179: 
17180: =item * &js_changer()
17181: 
17182: Create script tag containing Javascript used to submit course search form
17183: when course type or domain is changed, and also to hide 'Searching ...' on
17184: page load completion for page showing search result.
17185: 
17186: Inputs: None
17187: 
17188: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
17189: 
17190: Side Effects: None
17191: 
17192: =cut
17193: 
17194: sub js_changer {
17195:     return <<ENDJS;
17196: <script type="text/javascript">
17197: // <![CDATA[
17198: function updateFilters(caller) {
17199:     if (typeof(caller) != "undefined") {
17200:         document.filterpicker.updater.value = caller.name;
17201:     }
17202:     document.filterpicker.submit();
17203: }
17204: 
17205: function hideSearching() {
17206:     if (document.getElementById('searching')) {
17207:         document.getElementById('searching').style.display = 'none';
17208:     }
17209:     return;
17210: }
17211: 
17212: // ]]>
17213: </script>
17214: 
17215: ENDJS
17216: }
17217: 
17218: =pod
17219: 
17220: =item * &search_courses()
17221: 
17222: Process selected filters form course search form and pass to lonnet::courseiddump
17223: to retrieve a hash for which keys are courseIDs which match the selected filters.
17224: 
17225: Inputs:
17226: 
17227: dom - domain being searched 
17228: 
17229: type - course type ('Course' or 'Community' or '.' if any).
17230: 
17231: filter - anonymous hash of criteria and their values
17232: 
17233: numtitles - for institutional codes - number of categories
17234: 
17235: cloneruname - optional username of new course owner
17236: 
17237: clonerudom - optional domain of new course owner
17238: 
17239: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
17240:             (used when DC is using course creation form)
17241: 
17242: codetitles - reference to array of titles of components in institutional codes (official courses).
17243: 
17244: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17245:            (and so can clone automatically)
17246: 
17247: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17248: 
17249: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
17250:               courses to clone 
17251: 
17252: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17253: 
17254: 
17255: Side Effects: None
17256: 
17257: =cut
17258: 
17259: 
17260: sub search_courses {
17261:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17262:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17263:     my (%courses,%showcourses,$cloner);
17264:     if (($filter->{'ownerfilter'} ne '') ||
17265:         ($filter->{'ownerdomfilter'} ne '')) {
17266:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17267:                                        $filter->{'ownerdomfilter'};
17268:     }
17269:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17270:         if (!$filter->{$item}) {
17271:             $filter->{$item}='.';
17272:         }
17273:     }
17274:     my $now = time;
17275:     my $timefilter =
17276:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17277:     my ($createdbefore,$createdafter);
17278:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17279:         $createdbefore = $now;
17280:         $createdafter = $now-$filter->{'createdfilter'};
17281:     }
17282:     my ($instcodefilter,$regexpok);
17283:     if ($numtitles) {
17284:         if ($env{'form.official'} eq 'on') {
17285:             $instcodefilter =
17286:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17287:             $regexpok = 1;
17288:         } elsif ($env{'form.official'} eq 'off') {
17289:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17290:             unless ($instcodefilter eq '') {
17291:                 $regexpok = -1;
17292:             }
17293:         }
17294:     } else {
17295:         $instcodefilter = $filter->{'instcodefilter'};
17296:     }
17297:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17298:     if ($type eq '') { $type = '.'; }
17299: 
17300:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17301:         $cloner = $cloneruname.':'.$clonerudom;
17302:     }
17303:     %courses = &Apache::lonnet::courseiddump($dom,
17304:                                              $filter->{'descriptfilter'},
17305:                                              $timefilter,
17306:                                              $instcodefilter,
17307:                                              $filter->{'combownerfilter'},
17308:                                              $filter->{'coursefilter'},
17309:                                              undef,undef,$type,$regexpok,undef,undef,
17310:                                              undef,undef,$cloner,$cc_clone,
17311:                                              $filter->{'cloneableonly'},
17312:                                              $createdbefore,$createdafter,undef,
17313:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17314:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17315:         my $ccrole;
17316:         if ($type eq 'Community') {
17317:             $ccrole = 'co';
17318:         } else {
17319:             $ccrole = 'cc';
17320:         }
17321:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17322:                                                      $filter->{'persondomfilter'},
17323:                                                      'userroles',undef,
17324:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17325:                                                      $dom);
17326:         foreach my $role (keys(%rolehash)) {
17327:             my ($cnum,$cdom,$courserole) = split(':',$role);
17328:             my $cid = $cdom.'_'.$cnum;
17329:             if (exists($courses{$cid})) {
17330:                 if (ref($courses{$cid}) eq 'HASH') {
17331:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17332:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17333:                             push(@{$courses{$cid}{roles}},$courserole);
17334:                         }
17335:                     } else {
17336:                         $courses{$cid}{roles} = [$courserole];
17337:                     }
17338:                     $showcourses{$cid} = $courses{$cid};
17339:                 }
17340:             }
17341:         }
17342:         %courses = %showcourses;
17343:     }
17344:     return %courses;
17345: }
17346: 
17347: =pod
17348: 
17349: =back
17350: 
17351: =head1 Routines for version requirements for current course.
17352: 
17353: =over 4
17354: 
17355: =item * &check_release_required()
17356: 
17357: Compares required LON-CAPA version with version on server, and
17358: if required version is newer looks for a server with the required version.
17359: 
17360: Looks first at servers in user's owen domain; if none suitable, looks at
17361: servers in course's domain are permitted to host sessions for user's domain.
17362: 
17363: Inputs:
17364: 
17365: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17366: 
17367: $courseid - Course ID of current course
17368: 
17369: $rolecode - User's current role in course (for switchserver query string).
17370: 
17371: $required - LON-CAPA version needed by course (format: Major.Minor).
17372: 
17373: 
17374: Returns:
17375: 
17376: $switchserver - query string tp append to /adm/switchserver call (if 
17377:                 current server's LON-CAPA version is too old. 
17378: 
17379: $warning - Message is displayed if no suitable server could be found.
17380: 
17381: =cut
17382: 
17383: sub check_release_required {
17384:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17385:     my ($switchserver,$warning);
17386:     if ($required ne '') {
17387:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17388:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17389:         if ($reqdmajor ne '' && $reqdminor ne '') {
17390:             my $otherserver;
17391:             if (($major eq '' && $minor eq '') ||
17392:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17393:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17394:                 my $switchlcrev =
17395:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17396:                                                            $userdomserver);
17397:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17398:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17399:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17400:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17401:                     if ($cdom ne $env{'user.domain'}) {
17402:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17403:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17404:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17405:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17406:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17407:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17408:                         my $canhost =
17409:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17410:                                                               $coursedomserver,
17411:                                                               $remoterev,
17412:                                                               $udomdefaults{'remotesessions'},
17413:                                                               $defdomdefaults{'hostedsessions'});
17414: 
17415:                         if ($canhost) {
17416:                             $otherserver = $coursedomserver;
17417:                         } else {
17418:                             $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.");
17419:                         }
17420:                     } else {
17421:                         $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).");
17422:                     }
17423:                 } else {
17424:                     $otherserver = $userdomserver;
17425:                 }
17426:             }
17427:             if ($otherserver ne '') {
17428:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17429:             }
17430:         }
17431:     }
17432:     return ($switchserver,$warning);
17433: }
17434: 
17435: =pod
17436: 
17437: =item * &check_release_result()
17438: 
17439: Inputs:
17440: 
17441: $switchwarning - Warning message if no suitable server found to host session.
17442: 
17443: $switchserver - query string to append to /adm/switchserver containing lonHostID
17444:                 and current role.
17445: 
17446: Returns: HTML to display with information about requirement to switch server.
17447:          Either displaying warning with link to Roles/Courses screen or
17448:          display link to switchserver.
17449: 
17450: =cut
17451: 
17452: sub check_release_result {
17453:     my ($switchwarning,$switchserver) = @_;
17454:     my $output = &start_page('Selected course unavailable on this server').
17455:                  '<p class="LC_warning">';
17456:     if ($switchwarning) {
17457:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17458:         if (&show_course()) {
17459:             $output .= &mt('Display courses');
17460:         } else {
17461:             $output .= &mt('Display roles');
17462:         }
17463:         $output .= '</a>';
17464:     } elsif ($switchserver) {
17465:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17466:                    '<br />'.
17467:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17468:                    &mt('Switch Server').
17469:                    '</a>';
17470:     }
17471:     $output .= '</p>'.&end_page();
17472:     return $output;
17473: }
17474: 
17475: =pod
17476: 
17477: =item * &needs_coursereinit()
17478: 
17479: Determine if course contents stored for user's session needs to be
17480: refreshed, because content has changed since "Big Hash" last tied.
17481: 
17482: Check for change is made if time last checked is more than 10 minutes ago
17483: (by default).
17484: 
17485: Inputs:
17486: 
17487: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17488: 
17489: $interval (optional) - Time which may elapse (in s) between last check for content
17490:                        change in current course. (default: 600 s).  
17491: 
17492: Returns: an array; first element is:
17493: 
17494: =over 4
17495: 
17496: 'switch' - if content updates mean user's session
17497:            needs to be switched to a server running a newer LON-CAPA version
17498:  
17499: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17500:            on current server hosting user's session                
17501: 
17502: ''       - if no action required.
17503: 
17504: =back
17505: 
17506: If first item element is 'switch':
17507: 
17508: second item is $switchwarning - Warning message if no suitable server found to host session. 
17509: 
17510: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17511:                               and current role. 
17512: 
17513: otherwise: no other elements returned.
17514: 
17515: =back
17516: 
17517: =cut
17518: 
17519: sub needs_coursereinit {
17520:     my ($loncaparev,$interval) = @_;
17521:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17522:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17523:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17524:     my $now = time;
17525:     if ($interval eq '') {
17526:         $interval = 600;
17527:     }
17528:     if (($now-$env{'request.course.timechecked'})>$interval) {
17529:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17530:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17531:         if ($blocked) {
17532:             return ();
17533:         }
17534:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17535:         if ($lastchange > $env{'request.course.tied'}) {
17536:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17537:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17538:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17539:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17540:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17541:                                              $curr_reqd_hash{'internal.releaserequired'}});
17542:                     my ($switchserver,$switchwarning) =
17543:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17544:                                                 $curr_reqd_hash{'internal.releaserequired'});
17545:                     if ($switchwarning ne '' || $switchserver ne '') {
17546:                         return ('switch',$switchwarning,$switchserver);
17547:                     }
17548:                 }
17549:             }
17550:             return ('update');
17551:         }
17552:     }
17553:     return ();
17554: }
17555: 
17556: sub update_content_constraints {
17557:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
17558:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17559:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17560:     my (%checkresponsetypes,%checkcrsrestypes);
17561:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17562:         my ($item,$name,$value) = split(/:/,$key);
17563:         if ($item eq 'resourcetag') {
17564:             if ($name eq 'responsetype') {
17565:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17566:             }
17567:         } elsif ($item eq 'course') {
17568:             if ($name eq 'courserestype') {
17569:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
17570:             }
17571:         }
17572:     }
17573:     my $navmap = Apache::lonnavmaps::navmap->new();
17574:     if (defined($navmap)) {
17575:         my (%allresponses,%allcrsrestypes);
17576:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
17577:             if ($res->is_tool()) {
17578:                 if ($allcrsrestypes{'exttool'}) {
17579:                     $allcrsrestypes{'exttool'} ++;
17580:                 } else {
17581:                     $allcrsrestypes{'exttool'} = 1;
17582:                 }
17583:                 next;
17584:             }
17585:             my %responses = $res->responseTypes();
17586:             foreach my $key (keys(%responses)) {
17587:                 next unless(exists($checkresponsetypes{$key}));
17588:                 $allresponses{$key} += $responses{$key};
17589:             }
17590:         }
17591:         foreach my $key (keys(%allresponses)) {
17592:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17593:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17594:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17595:             }
17596:         }
17597:         foreach my $key (keys(%allcrsrestypes)) {
17598:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
17599:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17600:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17601:             }
17602:         }
17603:         undef($navmap);
17604:     }
17605:     my (@resources,@order,@resparms,@zombies);
17606:     if ($keeporder) {
17607:         use LONCAPA::map;
17608:         @resources = @LONCAPA::map::resources;
17609:         @order = @LONCAPA::map::order;
17610:         @resparms = @LONCAPA::map::resparms;
17611:         @zombies = @LONCAPA::map::zombies;
17612:     }
17613:     my $suppmap = 'supplemental.sequence';
17614:     my ($suppcount,$supptools,$errors) = (0,0,0);
17615:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
17616:                                                             $suppcount,$supptools,$errors);
17617:     if ($keeporder) {
17618:         @LONCAPA::map::resources = @resources;
17619:         @LONCAPA::map::order = @order;
17620:         @LONCAPA::map::resparms = @resparms;
17621:         @LONCAPA::map::zombies = @zombies;
17622:     }
17623:     if ($supptools) {
17624:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
17625:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17626:             ($reqdmajor,$reqdminor) = ($major,$minor);
17627:         }
17628:     }
17629:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17630:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17631:     }
17632:     return;
17633: }
17634: 
17635: sub allmaps_incourse {
17636:     my ($cdom,$cnum,$chome,$cid) = @_;
17637:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17638:         $cid = $env{'request.course.id'};
17639:         $cdom = $env{'course.'.$cid.'.domain'};
17640:         $cnum = $env{'course.'.$cid.'.num'};
17641:         $chome = $env{'course.'.$cid.'.home'};
17642:     }
17643:     my %allmaps = ();
17644:     my $lastchange =
17645:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17646:     if ($lastchange > $env{'request.course.tied'}) {
17647:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17648:         unless ($ferr) {
17649:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
17650:         }
17651:     }
17652:     my $navmap = Apache::lonnavmaps::navmap->new();
17653:     if (defined($navmap)) {
17654:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17655:             $allmaps{$res->src()} = 1;
17656:         }
17657:     }
17658:     return \%allmaps;
17659: }
17660: 
17661: sub parse_supplemental_title {
17662:     my ($title) = @_;
17663: 
17664:     my ($foldertitle,$renametitle);
17665:     if ($title =~ /&amp;&amp;&amp;/) {
17666:         $title = &HTML::Entites::decode($title);
17667:     }
17668:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17669:         $renametitle=$4;
17670:         my ($time,$uname,$udom) = ($1,$2,$3);
17671:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17672:         my $name =  &plainname($uname,$udom);
17673:         $name = &HTML::Entities::encode($name,'"<>&\'');
17674:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17675:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17676:             $name.': <br />'.$foldertitle;
17677:     }
17678:     if (wantarray) {
17679:         return ($title,$foldertitle,$renametitle);
17680:     }
17681:     return $title;
17682: }
17683: 
17684: sub recurse_supplemental {
17685:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
17686:     if ($suppmap) {
17687:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17688:         if ($fatal) {
17689:             $errors ++;
17690:         } else {
17691:             if ($#LONCAPA::map::resources > 0) {
17692:                 foreach my $res (@LONCAPA::map::resources) {
17693:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17694:                     if (($src ne '') && ($status eq 'res')) {
17695:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17696:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
17697:                                                                    $numfiles,$numexttools,$errors);
17698:                         } else {
17699:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
17700:                                 $numexttools ++;
17701:                             }
17702:                             $numfiles ++;
17703:                         }
17704:                     }
17705:                 }
17706:             }
17707:         }
17708:     }
17709:     return ($numfiles,$numexttools,$errors);
17710: }
17711: 
17712: sub symb_to_docspath {
17713:     my ($symb,$navmapref) = @_;
17714:     return unless ($symb && ref($navmapref));
17715:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17716:     if ($resurl=~/\.(sequence|page)$/) {
17717:         $mapurl=$resurl;
17718:     } elsif ($resurl eq 'adm/navmaps') {
17719:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17720:     }
17721:     my $mapresobj;
17722:     unless (ref($$navmapref)) {
17723:         $$navmapref = Apache::lonnavmaps::navmap->new();
17724:     }
17725:     if (ref($$navmapref)) {
17726:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17727:     }
17728:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17729:     my $type=$2;
17730:     my $path;
17731:     if (ref($mapresobj)) {
17732:         my $pcslist = $mapresobj->map_hierarchy();
17733:         if ($pcslist ne '') {
17734:             foreach my $pc (split(/,/,$pcslist)) {
17735:                 next if ($pc <= 1);
17736:                 my $res = $$navmapref->getByMapPc($pc);
17737:                 if (ref($res)) {
17738:                     my $thisurl = $res->src();
17739:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17740:                     my $thistitle = $res->title();
17741:                     $path .= '&'.
17742:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17743:                              &escape($thistitle).
17744:                              ':'.$res->randompick().
17745:                              ':'.$res->randomout().
17746:                              ':'.$res->encrypted().
17747:                              ':'.$res->randomorder().
17748:                              ':'.$res->is_page();
17749:                 }
17750:             }
17751:         }
17752:         $path =~ s/^\&//;
17753:         my $maptitle = $mapresobj->title();
17754:         if ($mapurl eq 'default') {
17755:             $maptitle = 'Main Content';
17756:         }
17757:         $path .= (($path ne '')? '&' : '').
17758:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17759:                  &escape($maptitle).
17760:                  ':'.$mapresobj->randompick().
17761:                  ':'.$mapresobj->randomout().
17762:                  ':'.$mapresobj->encrypted().
17763:                  ':'.$mapresobj->randomorder().
17764:                  ':'.$mapresobj->is_page();
17765:     } else {
17766:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17767:         my $ispage = (($type eq 'page')? 1 : '');
17768:         if ($mapurl eq 'default') {
17769:             $maptitle = 'Main Content';
17770:         }
17771:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17772:                 &escape($maptitle).':::::'.$ispage;
17773:     }
17774:     unless ($mapurl eq 'default') {
17775:         $path = 'default&'.
17776:                 &escape('Main Content').
17777:                 ':::::&'.$path;
17778:     }
17779:     return $path;
17780: }
17781: 
17782: sub captcha_display {
17783:     my ($context,$lonhost,$defdom) = @_;
17784:     my ($output,$error);
17785:     my ($captcha,$pubkey,$privkey,$version) = 
17786:         &get_captcha_config($context,$lonhost,$defdom);
17787:     if ($captcha eq 'original') {
17788:         $output = &create_captcha();
17789:         unless ($output) {
17790:             $error = 'captcha';
17791:         }
17792:     } elsif ($captcha eq 'recaptcha') {
17793:         $output = &create_recaptcha($pubkey,$version);
17794:         unless ($output) {
17795:             $error = 'recaptcha';
17796:         }
17797:     }
17798:     return ($output,$error,$captcha,$version);
17799: }
17800: 
17801: sub captcha_response {
17802:     my ($context,$lonhost,$defdom) = @_;
17803:     my ($captcha_chk,$captcha_error);
17804:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17805:     if ($captcha eq 'original') {
17806:         ($captcha_chk,$captcha_error) = &check_captcha();
17807:     } elsif ($captcha eq 'recaptcha') {
17808:         $captcha_chk = &check_recaptcha($privkey,$version);
17809:     } else {
17810:         $captcha_chk = 1;
17811:     }
17812:     return ($captcha_chk,$captcha_error);
17813: }
17814: 
17815: sub get_captcha_config {
17816:     my ($context,$lonhost,$dom_in_effect) = @_;
17817:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17818:     my $hostname = &Apache::lonnet::hostname($lonhost);
17819:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17820:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17821:     if ($context eq 'usercreation') {
17822:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17823:         if (ref($domconfig{$context}) eq 'HASH') {
17824:             $hashtocheck = $domconfig{$context}{'cancreate'};
17825:             if (ref($hashtocheck) eq 'HASH') {
17826:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17827:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17828:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17829:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17830:                     }
17831:                     if ($privkey && $pubkey) {
17832:                         $captcha = 'recaptcha';
17833:                         $version = $hashtocheck->{'recaptchaversion'};
17834:                         if ($version ne '2') {
17835:                             $version = 1;
17836:                         }
17837:                     } else {
17838:                         $captcha = 'original';
17839:                     }
17840:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17841:                     $captcha = 'original';
17842:                 }
17843:             }
17844:         } else {
17845:             $captcha = 'captcha';
17846:         }
17847:     } elsif ($context eq 'login') {
17848:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17849:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17850:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17851:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17852:             if ($privkey && $pubkey) {
17853:                 $captcha = 'recaptcha';
17854:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17855:                 if ($version ne '2') {
17856:                     $version = 1; 
17857:                 }
17858:             } else {
17859:                 $captcha = 'original';
17860:             }
17861:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17862:             $captcha = 'original';
17863:         }
17864:     } elsif ($context eq 'passwords') {
17865:         if ($dom_in_effect) {
17866:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17867:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17868:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17869:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17870:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17871:                 }
17872:                 if ($privkey && $pubkey) {
17873:                     $captcha = 'recaptcha';
17874:                     $version = $passwdconf{'recaptchaversion'};
17875:                     if ($version ne '2') {
17876:                         $version = 1;
17877:                     }
17878:                 } else {
17879:                     $captcha = 'original';
17880:                 }
17881:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17882:                 $captcha = 'original';
17883:             }
17884:         }
17885:     } 
17886:     return ($captcha,$pubkey,$privkey,$version);
17887: }
17888: 
17889: sub create_captcha {
17890:     my %captcha_params = &captcha_settings();
17891:     my ($output,$maxtries,$tries) = ('',10,0);
17892:     while ($tries < $maxtries) {
17893:         $tries ++;
17894:         my $captcha = Authen::Captcha->new (
17895:                                            output_folder => $captcha_params{'output_dir'},
17896:                                            data_folder   => $captcha_params{'db_dir'},
17897:                                           );
17898:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17899: 
17900:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17901:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17902:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17903:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17904:                       '<br />'.
17905:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17906:             last;
17907:         }
17908:     }
17909:     if ($output eq '') {
17910:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17911:     }
17912:     return $output;
17913: }
17914: 
17915: sub captcha_settings {
17916:     my %captcha_params = (
17917:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17918:                            www_output_dir => "/captchaspool",
17919:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17920:                            numchars       => '5',
17921:                          );
17922:     return %captcha_params;
17923: }
17924: 
17925: sub check_captcha {
17926:     my ($captcha_chk,$captcha_error);
17927:     my $code = $env{'form.code'};
17928:     my $md5sum = $env{'form.crypt'};
17929:     my %captcha_params = &captcha_settings();
17930:     my $captcha = Authen::Captcha->new(
17931:                       output_folder => $captcha_params{'output_dir'},
17932:                       data_folder   => $captcha_params{'db_dir'},
17933:                   );
17934:     $captcha_chk = $captcha->check_code($code,$md5sum);
17935:     my %captcha_hash = (
17936:                         0       => 'Code not checked (file error)',
17937:                        -1      => 'Failed: code expired',
17938:                        -2      => 'Failed: invalid code (not in database)',
17939:                        -3      => 'Failed: invalid code (code does not match crypt)',
17940:     );
17941:     if ($captcha_chk != 1) {
17942:         $captcha_error = $captcha_hash{$captcha_chk}
17943:     }
17944:     return ($captcha_chk,$captcha_error);
17945: }
17946: 
17947: sub create_recaptcha {
17948:     my ($pubkey,$version) = @_;
17949:     if ($version >= 2) {
17950:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17951:     } else {
17952:         my $use_ssl;
17953:         if ($ENV{'SERVER_PORT'} == 443) {
17954:             $use_ssl = 1;
17955:         }
17956:         my $captcha = Captcha::reCAPTCHA->new;
17957:         return $captcha->get_options_setter({theme => 'white'})."\n".
17958:                $captcha->get_html($pubkey,undef,$use_ssl).
17959:                &mt('If the text is hard to read, [_1] will replace them.',
17960:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17961:                '<br /><br />';
17962:     }
17963: }
17964: 
17965: sub check_recaptcha {
17966:     my ($privkey,$version) = @_;
17967:     my $captcha_chk;
17968:     if ($version >= 2) {
17969:         my %info = (
17970:                      secret   => $privkey, 
17971:                      response => $env{'form.g-recaptcha-response'},
17972:                      remoteip => $ENV{'REMOTE_ADDR'},
17973:                    );
17974:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
17975:         $request->content(join('&',map {
17976:                          my $name = escape($_);
17977:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
17978:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
17979:                          : &escape($info{$_}) );
17980:         } keys(%info)));
17981:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
17982:         if ($response->is_success)  {
17983:             my $data = JSON::DWIW->from_json($response->decoded_content);
17984:             if (ref($data) eq 'HASH') {
17985:                 if ($data->{'success'}) {
17986:                     $captcha_chk = 1;
17987:                 }
17988:             }
17989:         }
17990:     } else {
17991:         my $captcha = Captcha::reCAPTCHA->new;
17992:         my $captcha_result =
17993:             $captcha->check_answer(
17994:                                     $privkey,
17995:                                     $ENV{'REMOTE_ADDR'},
17996:                                     $env{'form.recaptcha_challenge_field'},
17997:                                     $env{'form.recaptcha_response_field'},
17998:                                   );
17999:         if ($captcha_result->{is_valid}) {
18000:             $captcha_chk = 1;
18001:         }
18002:     }
18003:     return $captcha_chk;
18004: }
18005: 
18006: sub emailusername_info {
18007:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18008:     my %titles = &Apache::lonlocal::texthash (
18009:                      lastname      => 'Last Name',
18010:                      firstname     => 'First Name',
18011:                      institution   => 'School/college/university',
18012:                      location      => "School's city, state/province, country",
18013:                      web           => "School's web address",
18014:                      officialemail => 'E-mail address at institution (if different)',
18015:                      id            => 'Student/Employee ID',
18016:                  );
18017:     return (\@fields,\%titles);
18018: }
18019: 
18020: sub cleanup_html {
18021:     my ($incoming) = @_;
18022:     my $outgoing;
18023:     if ($incoming ne '') {
18024:         $outgoing = $incoming;
18025:         $outgoing =~ s/;/&#059;/g;
18026:         $outgoing =~ s/\#/&#035;/g;
18027:         $outgoing =~ s/\&/&#038;/g;
18028:         $outgoing =~ s/</&#060;/g;
18029:         $outgoing =~ s/>/&#062;/g;
18030:         $outgoing =~ s/\(/&#040/g;
18031:         $outgoing =~ s/\)/&#041;/g;
18032:         $outgoing =~ s/"/&#034;/g;
18033:         $outgoing =~ s/'/&#039;/g;
18034:         $outgoing =~ s/\$/&#036;/g;
18035:         $outgoing =~ s{/}{&#047;}g;
18036:         $outgoing =~ s/=/&#061;/g;
18037:         $outgoing =~ s/\\/&#092;/g
18038:     }
18039:     return $outgoing;
18040: }
18041: 
18042: # Checks for critical messages and returns a redirect url if one exists.
18043: # $interval indicates how often to check for messages.
18044: # $context is the calling context -- roles, grades, contents, menu or flip. 
18045: sub critical_redirect {
18046:     my ($interval,$context) = @_;
18047:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18048:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18049:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18050:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18051:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
18052:             if ($blocked) {
18053:                 my $checkrole = "cm./$cdom/$cnum";
18054:                 if ($env{'request.course.sec'} ne '') {
18055:                     $checkrole .= "/$env{'request.course.sec'}";
18056:                 }
18057:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18058:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18059:                     return;
18060:                 }
18061:             }
18062:         }
18063:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
18064:                                         $env{'user.name'});
18065:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18066:         my $redirecturl;
18067:         if ($what[0]) {
18068: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
18069: 	        $redirecturl='/adm/email?critical=display';
18070: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
18071:                 return (1, $url);
18072:             }
18073:         }
18074:     } 
18075:     return ();
18076: }
18077: 
18078: # Use:
18079: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18080: #
18081: ##################################################
18082: #          password associated functions         #
18083: ##################################################
18084: sub des_keys {
18085:     # Make a new key for DES encryption.
18086:     # Each key has two parts which are returned separately.
18087:     # Please note:  Each key must be passed through the &hex function
18088:     # before it is output to the web browser.  The hex versions cannot
18089:     # be used to decrypt.
18090:     my @hexstr=('0','1','2','3','4','5','6','7',
18091:                 '8','9','a','b','c','d','e','f');
18092:     my $lkey='';
18093:     for (0..7) {
18094:         $lkey.=$hexstr[rand(15)];
18095:     }
18096:     my $ukey='';
18097:     for (0..7) {
18098:         $ukey.=$hexstr[rand(15)];
18099:     }
18100:     return ($lkey,$ukey);
18101: }
18102: 
18103: sub des_decrypt {
18104:     my ($key,$cyphertext) = @_;
18105:     my $keybin=pack("H16",$key);
18106:     my $cypher;
18107:     if ($Crypt::DES::VERSION>=2.03) {
18108:         $cypher=new Crypt::DES $keybin;
18109:     } else {
18110:         $cypher=new DES $keybin;
18111:     }
18112:     my $plaintext='';
18113:     my $cypherlength = length($cyphertext);
18114:     my $numchunks = int($cypherlength/32);
18115:     for (my $j=0; $j<$numchunks; $j++) {
18116:         my $start = $j*32;
18117:         my $cypherblock = substr($cyphertext,$start,32);
18118:         my $chunk =
18119:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18120:         $chunk .=
18121:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18122:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18123:         $plaintext .= $chunk;
18124:     }
18125:     return $plaintext;
18126: }
18127: 
18128: sub make_short_symbs {
18129:     my ($cdom,$cnum,$navmap) = @_;
18130:     return unless (ref($navmap));
18131:     my ($numnew,@errors);
18132:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18133:     if (@toshorten) {
18134:         my (%maps,%resources,%titles);
18135:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18136:                                                                'shorturls',$cdom,$cnum);
18137:         my %tocreate;
18138:         if (keys(%resources)) {
18139:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18140:                 my $symb = $resources{$item};
18141:                 if ($symb) {
18142:                     $tocreate{$cnum.'&'.$symb} = 1;
18143:                 }
18144:             }
18145:         }
18146:         if (keys(%tocreate)) {
18147:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18148:             my $su = Short::URL->new(no_vowels => 1);
18149:             my $init = '';
18150:             my (%newunique,%addcourse,%courseonly,%failed);
18151:             # get lock on tiny db
18152:             my $now = time;
18153:             my $lockhash = {
18154:                                 "lock\0$now" => $env{'user.name'}.
18155:                                                 ':'.$env{'user.domain'},
18156:                             };
18157:             my $tries = 0;
18158:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18159:             my ($code,$error);
18160:             while (($gotlock ne 'ok') && ($tries<3)) {
18161:                 $tries ++;
18162:                 sleep 1;
18163:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18164:             }
18165:             if ($gotlock eq 'ok') {
18166:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18167:                                        \%addcourse,\%courseonly,\%failed);
18168:                 if (keys(%failed)) {
18169:                     my $numfailed = scalar(keys(%failed));
18170:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18171:                 }
18172:                 if (keys(%newunique)) {
18173:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18174:                     if ($putres eq 'ok') {
18175:                         $numnew = scalar(keys(%newunique));
18176:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18177:                         unless ($newputres eq 'ok') {
18178:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18179:                         }
18180:                     } else {
18181:                         push(@errors,&mt('error: could not store unique six character URLs'));
18182:                     }
18183:                 }
18184:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18185:                 unless ($dellockres eq 'ok') {
18186:                     push(@errors,&mt('error: could not release lockfile'));
18187:                 }
18188:             } else {
18189:                 push(@errors,&mt('error: could not obtain lockfile'));
18190:             }
18191:             if (keys(%courseonly)) {
18192:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18193:                 if ($result ne 'ok') {
18194:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18195:                 }
18196:             }
18197:         }
18198:     }
18199:     return ($numnew,\@errors);
18200: }
18201: 
18202: sub shorten_symbs {
18203:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18204:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18205:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18206:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18207:     my (%possibles,%collisions);
18208:     foreach my $key (keys(%{$tocreate})) {
18209:         my $num = String::CRC32::crc32($key);
18210:         my $tiny = $su->encode($num,$init);
18211:         if ($tiny) {
18212:             $possibles{$tiny} = $key;
18213:         }
18214:     }
18215:     if (!$init) {
18216:         $init = 1;
18217:     } else {
18218:         $init ++;
18219:     }
18220:     if (keys(%possibles)) {
18221:         my @posstiny = keys(%possibles);
18222:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18223:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18224:         if (keys(%currtiny)) {
18225:             foreach my $key (keys(%currtiny)) {
18226:                 next if ($currtiny{$key} eq '');
18227:                 if ($currtiny{$key} eq $possibles{$key}) {
18228:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18229:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18230:                         $courseonly->{$tsymb} = $key;
18231:                     }
18232:                 } else {
18233:                     $collisions{$possibles{$key}} = 1;
18234:                 }
18235:                 delete($possibles{$key});
18236:             }
18237:         }
18238:         foreach my $key (keys(%possibles)) {
18239:             $newunique->{$key} = $possibles{$key};
18240:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18241:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18242:                 $addcourse->{$tsymb} = $key;
18243:             }
18244:         }
18245:     }
18246:     if (keys(%collisions)) {
18247:         if ($init <5) {
18248:             if (!$init) {
18249:                 $init = 1;
18250:             } else {
18251:                 $init ++;
18252:             }
18253:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18254:                                    $newunique,$addcourse,$courseonly,$failed);
18255:         } else {
18256:             foreach my $key (keys(%collisions)) {
18257:                 $failed->{$key} = 1;
18258:             }
18259:         }
18260:     }
18261:     return $init;
18262: }
18263: 
18264: sub is_nonframeable {
18265:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18266:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18267:     return if (($remprotocol eq '') || ($remhost eq ''));
18268: 
18269:     $remprotocol = lc($remprotocol);
18270:     $remhost = lc($remhost);
18271:     my $remport = 80;
18272:     if ($remprotocol eq 'https') {
18273:         $remport = 443;
18274:     }
18275:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18276:     if ($cached) {
18277:         unless ($nocache) {
18278:             if ($result) {
18279:                 return 1;
18280:             } else {
18281:                 return 0;
18282:             }
18283:         }
18284:     }
18285:     my $uselink;
18286:     my $request = new HTTP::Request('HEAD',$url);
18287:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
18288:     if ($response->is_success()) {
18289:         my $secpolicy = lc($response->header('content-security-policy'));
18290:         my $xframeop = lc($response->header('x-frame-options'));
18291:         $secpolicy =~ s/^\s+|\s+$//g;
18292:         $xframeop =~ s/^\s+|\s+$//g;
18293:         if (($secpolicy ne '') || ($xframeop ne '')) {
18294:             my $remotehost = $remprotocol.'://'.$remhost;
18295:             my ($origin,$protocol,$port);
18296:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18297:                 $port = $ENV{'SERVER_PORT'};
18298:             } else {
18299:                 $port = 80;
18300:             }
18301:             if ($absolute eq '') {
18302:                 $protocol = 'http:';
18303:                 if ($port == 443) {
18304:                     $protocol = 'https:';
18305:                 }
18306:                 $origin = $protocol.'//'.lc($hostname);
18307:             } else {
18308:                 $origin = lc($absolute);
18309:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18310:             }
18311:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18312:                 my $framepolicy = $1;
18313:                 $framepolicy =~ s/^\s+|\s+$//g;
18314:                 my @policies = split(/\s+/,$framepolicy);
18315:                 if (@policies) {
18316:                     if (grep(/^\Q'none'\E$/,@policies)) {
18317:                         $uselink = 1;
18318:                     } else {
18319:                         $uselink = 1;
18320:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18321:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18322:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18323:                             undef($uselink);
18324:                         }
18325:                         if ($uselink) {
18326:                             if (grep(/^\Q'self'\E$/,@policies)) {
18327:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18328:                                     undef($uselink);
18329:                                 }
18330:                             }
18331:                         }
18332:                         if ($uselink) {
18333:                             my @possok;
18334:                             if ($ip ne '') {
18335:                                 push(@possok,$ip);
18336:                             }
18337:                             my $hoststr = '';
18338:                             foreach my $part (reverse(split(/\./,$hostname))) {
18339:                                 if ($hoststr eq '') {
18340:                                     $hoststr = $part;
18341:                                 } else {
18342:                                     $hoststr = "$part.$hoststr";
18343:                                 }
18344:                                 if ($hoststr eq $hostname) {
18345:                                     push(@possok,$hostname);
18346:                                 } else {
18347:                                     push(@possok,"*.$hoststr");
18348:                                 }
18349:                             }
18350:                             if (@possok) {
18351:                                 foreach my $poss (@possok) {
18352:                                     last if (!$uselink);
18353:                                     foreach my $policy (@policies) {
18354:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18355:                                             undef($uselink);
18356:                                             last;
18357:                                         }
18358:                                     }
18359:                                 }
18360:                             }
18361:                         }
18362:                     }
18363:                 }
18364:             } elsif ($xframeop ne '') {
18365:                 $uselink = 1;
18366:                 my @policies = split(/\s*,\s*/,$xframeop);
18367:                 if (@policies) {
18368:                     unless (grep(/^deny$/,@policies)) {
18369:                         if ($origin ne '') {
18370:                             if (grep(/^sameorigin$/,@policies)) {
18371:                                 if ($remotehost eq $origin) {
18372:                                     undef($uselink);
18373:                                 }
18374:                             }
18375:                             if ($uselink) {
18376:                                 foreach my $policy (@policies) {
18377:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18378:                                         my $allowfrom = $1;
18379:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18380:                                             undef($uselink);
18381:                                             last;
18382:                                         }
18383:                                     }
18384:                                 }
18385:                             }
18386:                         }
18387:                     }
18388:                 }
18389:             }
18390:         }
18391:     }
18392:     if ($nocache) {
18393:         if ($cached) {
18394:             my $devalidate;
18395:             if ($uselink && !$result) {
18396:                 $devalidate = 1;
18397:             } elsif (!$uselink && $result) {
18398:                 $devalidate = 1;
18399:             }
18400:             if ($devalidate) {
18401:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18402:             }
18403:         }
18404:     } else {
18405:         if ($uselink) {
18406:             $result = 1;
18407:         } else {
18408:             $result = 0;
18409:         }
18410:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18411:     }
18412:     return $uselink;
18413: }
18414: 
18415: 1;
18416: __END__;
18417: 

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