File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1349: download - view: text, annotated - select for diffs
Tue Nov 10 17:19:17 2020 UTC (3 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Move &css_links() from grades.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.1349 2020/11/10 17:19:17 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 Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use MIME::Lite;
   86: use MIME::Types;
   87: use File::Copy();
   88: use File::Path();
   89: use String::CRC32();
   90: use Short::URL();
   91: 
   92: # ---------------------------------------------- Designs
   93: use vars qw(%defaultdesign);
   94: 
   95: my $readit;
   96: 
   97: 
   98: ##
   99: ## Global Variables
  100: ##
  101: 
  102: 
  103: # ----------------------------------------------- SSI with retries:
  104: #
  105: 
  106: =pod
  107: 
  108: =head1 Server Side include with retries:
  109: 
  110: =over 4
  111: 
  112: =item * &ssi_with_retries(resource,retries form)
  113: 
  114: Performs an ssi with some number of retries.  Retries continue either
  115: until the result is ok or until the retry count supplied by the
  116: caller is exhausted.  
  117: 
  118: Inputs:
  119: 
  120: =over 4
  121: 
  122: resource   - Identifies the resource to insert.
  123: 
  124: retries    - Count of the number of retries allowed.
  125: 
  126: form       - Hash that identifies the rendering options.
  127: 
  128: =back
  129: 
  130: Returns:
  131: 
  132: =over 4
  133: 
  134: content    - The content of the response.  If retries were exhausted this is empty.
  135: 
  136: response   - The response from the last attempt (which may or may not have been successful.
  137: 
  138: =back
  139: 
  140: =back
  141: 
  142: =cut
  143: 
  144: sub ssi_with_retries {
  145:     my ($resource, $retries, %form) = @_;
  146: 
  147: 
  148:     my $ok = 0;			# True if we got a good response.
  149:     my $content;
  150:     my $response;
  151: 
  152:     # Try to get the ssi done. within the retries count:
  153: 
  154:     do {
  155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  156: 	$ok      = $response->is_success;
  157:         if (!$ok) {
  158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  159:         }
  160: 	$retries--;
  161:     } while (!$ok && ($retries > 0));
  162: 
  163:     if (!$ok) {
  164: 	$content = '';		# On error return an empty content.
  165:     }
  166:     return ($content, $response);
  167: 
  168: }
  169: 
  170: 
  171: 
  172: # ----------------------------------------------- Filetypes/Languages/Copyright
  173: my %language;
  174: my %supported_language;
  175: my %supported_codes;
  176: my %latex_language;		# For choosing hyphenation in <transl..>
  177: my %latex_language_bykey;	# for choosing hyphenation from metadata
  178: my %cprtag;
  179: my %scprtag;
  180: my %fe; my %fd; my %fm;
  181: my %category_extensions;
  182: 
  183: # ---------------------------------------------- Thesaurus variables
  184: #
  185: # %Keywords:
  186: #      A hash used by &keyword to determine if a word is considered a keyword.
  187: # $thesaurus_db_file 
  188: #      Scalar containing the full path to the thesaurus database.
  189: 
  190: my %Keywords;
  191: my $thesaurus_db_file;
  192: 
  193: #
  194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  195: # thesaurus.tab, and filecategories.tab.
  196: #
  197: BEGIN {
  198:     # Variable initialization
  199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  200:     #
  201:     unless ($readit) {
  202: # ------------------------------------------------------------------- languages
  203:     {
  204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  205:                                    '/language.tab';
  206:         if ( open(my $fh,'<',$langtabfile) ) {
  207:             while (my $line = <$fh>) {
  208:                 next if ($line=~/^\#/);
  209:                 chomp($line);
  210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  211:                 $language{$key}=$val.' - '.$enc;
  212:                 if ($sup) {
  213:                     $supported_language{$key}=$sup;
  214: 		    $supported_codes{$key}   = $code;
  215:                 }
  216: 		if ($latex) {
  217: 		    $latex_language_bykey{$key} = $latex;
  218: 		    $latex_language{$code} = $latex;
  219: 		}
  220:             }
  221:             close($fh);
  222:         }
  223:     }
  224: # ------------------------------------------------------------------ copyrights
  225:     {
  226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  227:                                   '/copyright.tab';
  228:         if ( open (my $fh,'<',$copyrightfile) ) {
  229:             while (my $line = <$fh>) {
  230:                 next if ($line=~/^\#/);
  231:                 chomp($line);
  232:                 my ($key,$val)=(split(/\s+/,$line,2));
  233:                 $cprtag{$key}=$val;
  234:             }
  235:             close($fh);
  236:         }
  237:     }
  238: # ----------------------------------------------------------- source copyrights
  239:     {
  240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  241:                                   '/source_copyright.tab';
  242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  243:             while (my $line = <$fh>) {
  244:                 next if ($line =~ /^\#/);
  245:                 chomp($line);
  246:                 my ($key,$val)=(split(/\s+/,$line,2));
  247:                 $scprtag{$key}=$val;
  248:             }
  249:             close($fh);
  250:         }
  251:     }
  252: 
  253: # -------------------------------------------------------------- default domain designs
  254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  255:     my $designfile = $designdir.'/default.tab';
  256:     if ( open (my $fh,'<',$designfile) ) {
  257:         while (my $line = <$fh>) {
  258:             next if ($line =~ /^\#/);
  259:             chomp($line);
  260:             my ($key,$val)=(split(/\=/,$line));
  261:             if ($val) { $defaultdesign{$key}=$val; }
  262:         }
  263:         close($fh);
  264:     }
  265: 
  266: # ------------------------------------------------------------- file categories
  267:     {
  268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  269:                                   '/filecategories.tab';
  270:         if ( open (my $fh,'<',$categoryfile) ) {
  271: 	    while (my $line = <$fh>) {
  272: 		next if ($line =~ /^\#/);
  273: 		chomp($line);
  274:                 my ($extension,$category)=(split(/\s+/,$line,2));
  275:                 push(@{$category_extensions{lc($category)}},$extension);
  276:             }
  277:             close($fh);
  278:         }
  279: 
  280:     }
  281: # ------------------------------------------------------------------ file types
  282:     {
  283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  284:                '/filetypes.tab';
  285:         if ( open (my $fh,'<',$typesfile) ) {
  286:             while (my $line = <$fh>) {
  287: 		next if ($line =~ /^\#/);
  288: 		chomp($line);
  289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  290:                 if ($descr ne '') {
  291:                     $fe{$ending}=lc($emb);
  292:                     $fd{$ending}=$descr;
  293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  294:                 }
  295:             }
  296:             close($fh);
  297:         }
  298:     }
  299:     &Apache::lonnet::logthis(
  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
  301:     $readit=1;
  302:     }  # end of unless($readit) 
  303:     
  304: }
  305: 
  306: ###############################################################
  307: ##           HTML and Javascript Helper Functions            ##
  308: ###############################################################
  309: 
  310: =pod 
  311: 
  312: =head1 HTML and Javascript Functions
  313: 
  314: =over 4
  315: 
  316: =item * &browser_and_searcher_javascript()
  317: 
  318: X<browsing, javascript>X<searching, javascript>Returns a string
  319: containing javascript with two functions, C<openbrowser> and
  320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  321: tags.
  322: 
  323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  324: 
  325: inputs: formname, elementname, only, omit
  326: 
  327: formname and elementname indicate the name of the html form and name of
  328: the element that the results of the browsing selection are to be placed in. 
  329: 
  330: Specifying 'only' will restrict the browser to displaying only files
  331: with the given extension.  Can be a comma separated list.
  332: 
  333: Specifying 'omit' will restrict the browser to NOT displaying files
  334: with the given extension.  Can be a comma separated list.
  335: 
  336: =item * &opensearcher(formname,elementname) [javascript]
  337: 
  338: Inputs: formname, elementname
  339: 
  340: formname and elementname specify the name of the html form and the name
  341: of the element the selection from the search results will be placed in.
  342: 
  343: =cut
  344: 
  345: sub browser_and_searcher_javascript {
  346:     my ($mode)=@_;
  347:     if (!defined($mode)) { $mode='edit'; }
  348:     my $resurl=&escape_single(&lastresurl());
  349:     return <<END;
  350: // <!-- BEGIN LON-CAPA Internal
  351:     var editbrowser = null;
  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
  353:         var url = '$resurl/?';
  354:         if (editbrowser == null) {
  355:             url += 'launch=1&';
  356:         }
  357:         url += 'catalogmode=interactive&';
  358:         url += 'mode=$mode&';
  359:         url += 'inhibitmenu=yes&';
  360:         url += 'form=' + formname + '&';
  361:         if (only != null) {
  362:             url += 'only=' + only + '&';
  363:         } else {
  364:             url += 'only=&';
  365: 	}
  366:         if (omit != null) {
  367:             url += 'omit=' + omit + '&';
  368:         } else {
  369:             url += 'omit=&';
  370: 	}
  371:         if (titleelement != null) {
  372:             url += 'titleelement=' + titleelement + '&';
  373:         } else {
  374: 	    url += 'titleelement=&';
  375: 	}
  376:         url += 'element=' + elementname + '';
  377:         var title = 'Browser';
  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  379:         options += ',width=700,height=600';
  380:         editbrowser = open(url,title,options,'1');
  381:         editbrowser.focus();
  382:     }
  383:     var editsearcher;
  384:     function opensearcher(formname,elementname,titleelement) {
  385:         var url = '/adm/searchcat?';
  386:         if (editsearcher == null) {
  387:             url += 'launch=1&';
  388:         }
  389:         url += 'catalogmode=interactive&';
  390:         url += 'mode=$mode&';
  391:         url += 'form=' + formname + '&';
  392:         if (titleelement != null) {
  393:             url += 'titleelement=' + titleelement + '&';
  394:         } else {
  395: 	    url += 'titleelement=&';
  396: 	}
  397:         url += 'element=' + elementname + '';
  398:         var title = 'Search';
  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  400:         options += ',width=700,height=600';
  401:         editsearcher = open(url,title,options,'1');
  402:         editsearcher.focus();
  403:     }
  404: // END LON-CAPA Internal -->
  405: END
  406: }
  407: 
  408: sub lastresurl {
  409:     if ($env{'environment.lastresurl'}) {
  410: 	return $env{'environment.lastresurl'}
  411:     } else {
  412: 	return '/res';
  413:     }
  414: }
  415: 
  416: sub storeresurl {
  417:     my $resurl=&Apache::lonnet::clutter(shift);
  418:     unless ($resurl=~/^\/res/) { return 0; }
  419:     $resurl=~s/\/$//;
  420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  422:     return 1;
  423: }
  424: 
  425: sub studentbrowser_javascript {
  426:    unless (
  427:             (($env{'request.course.id'}) && 
  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  430: 					  '/'.$env{'request.course.sec'})
  431: 	      ))
  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
  433:           ) { return ''; }  
  434:    return (<<'ENDSTDBRW');
  435: <script type="text/javascript" language="Javascript">
  436: // <![CDATA[
  437:     var stdeditbrowser;
  438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  439:         var url = '/adm/pickstudent?';
  440:         var filter;
  441: 	if (!ignorefilter) {
  442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  443: 	}
  444:         if (filter != null) {
  445:            if (filter != '') {
  446:                url += 'filter='+filter+'&';
  447: 	   }
  448:         }
  449:         url += 'form=' + formname + '&unameelement='+uname+
  450:                                     '&udomelement='+udom+
  451:                                     '&clicker='+clicker;
  452: 	if (roleflag) { url+="&roles=1"; }
  453:         if (courseadv == 'condition') {
  454:             if (document.getElementById('courseadv')) {
  455:                 courseadv = document.getElementById('courseadv').value;
  456:             }
  457:         }
  458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  459:         var title = 'Student_Browser';
  460:         var options = 'scrollbars=1,resizable=1,menubar=0';
  461:         options += ',width=700,height=600';
  462:         stdeditbrowser = open(url,title,options,'1');
  463:         stdeditbrowser.focus();
  464:     }
  465: // ]]>
  466: </script>
  467: ENDSTDBRW
  468: }
  469: 
  470: sub resourcebrowser_javascript {
  471:    unless ($env{'request.course.id'}) { return ''; }
  472:    return (<<'ENDRESBRW');
  473: <script type="text/javascript" language="Javascript">
  474: // <![CDATA[
  475:     var reseditbrowser;
  476:     function openresbrowser(formname,reslink) {
  477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  478:         var title = 'Resource_Browser';
  479:         var options = 'scrollbars=1,resizable=1,menubar=0';
  480:         options += ',width=700,height=500';
  481:         reseditbrowser = open(url,title,options,'1');
  482:         reseditbrowser.focus();
  483:     }
  484: // ]]>
  485: </script>
  486: ENDRESBRW
  487: }
  488: 
  489: sub selectstudent_link {
  490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  494:    if ($env{'request.course.id'}) {  
  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  497: 					'/'.$env{'request.course.sec'})) {
  498: 	   return '';
  499:        }
  500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  501:        if ($courseadv eq 'only') {
  502:            $callargs .= ",'',1,'$courseadv'";
  503:        } elsif ($courseadv eq 'none') {
  504:            $callargs .= ",'','','$courseadv'";
  505:        } elsif ($courseadv eq 'condition') {
  506:            $callargs .= ",'','','$courseadv'";
  507:        }
  508:        return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  510:               &mt('Select User').'</a></span>';
  511:    }
  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  513:        $callargs .= ",'',1"; 
  514:        return '<span class="LC_nobreak">'.
  515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  516:               &mt('Select User').'</a></span>';
  517:    }
  518:    return '';
  519: }
  520: 
  521: sub selectresource_link {
  522:    my ($form,$reslink,$arg)=@_;
  523:    
  524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  526:    unless ($env{'request.course.id'}) { return $arg; }
  527:    return '<span class="LC_nobreak">'.
  528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  529:               $arg.'</a></span>';
  530: }
  531: 
  532: 
  533: 
  534: sub authorbrowser_javascript {
  535:     return <<"ENDAUTHORBRW";
  536: <script type="text/javascript" language="JavaScript">
  537: // <![CDATA[
  538: var stdeditbrowser;
  539: 
  540: function openauthorbrowser(formname,udom) {
  541:     var url = '/adm/pickauthor?';
  542:     url += 'form='+formname+'&roledom='+udom;
  543:     var title = 'Author_Browser';
  544:     var options = 'scrollbars=1,resizable=1,menubar=0';
  545:     options += ',width=700,height=600';
  546:     stdeditbrowser = open(url,title,options,'1');
  547:     stdeditbrowser.focus();
  548: }
  549: 
  550: // ]]>
  551: </script>
  552: ENDAUTHORBRW
  553: }
  554: 
  555: sub coursebrowser_javascript {
  556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  557:         $credits_element,$instcode) = @_;
  558:     my $wintitle = 'Course_Browser';
  559:     if ($crstype eq 'Community') {
  560:         $wintitle = 'Community_Browser';
  561:     }
  562:     my $id_functions = &javascript_index_functions();
  563:     my $output = '
  564: <script type="text/javascript" language="JavaScript">
  565: // <![CDATA[
  566:     var stdeditbrowser;'."\n";
  567: 
  568:     $output .= <<"ENDSTDBRW";
  569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  570:         var url = '/adm/pickcourse?';
  571:         var formid = getFormIdByName(formname);
  572:         var domainfilter = getDomainFromSelectbox(formname,udom);
  573:         if (domainfilter != null) {
  574:            if (domainfilter != '') {
  575:                url += 'domainfilter='+domainfilter+'&';
  576: 	   }
  577:         }
  578:         url += 'form=' + formname + '&cnumelement='+uname+
  579: 	                            '&cdomelement='+udom+
  580:                                     '&cnameelement='+desc;
  581:         if (extra_element !=null && extra_element != '') {
  582:             if (formname == 'rolechoice' || formname == 'studentform') {
  583:                 url += '&roleelement='+extra_element;
  584:                 if (domainfilter == null || domainfilter == '') {
  585:                     url += '&domainfilter='+extra_element;
  586:                 }
  587:             }
  588:             else {
  589:                 if (formname == 'portform') {
  590:                     url += '&setroles='+extra_element;
  591:                 } else {
  592:                     if (formname == 'rules') {
  593:                         url += '&fixeddom='+extra_element; 
  594:                     }
  595:                 }
  596:             }     
  597:         }
  598:         if (type != null && type != '') {
  599:             url += '&type='+type;
  600:         }
  601:         if (type_elem != null && type_elem != '') {
  602:             url += '&typeelement='+type_elem;
  603:         }
  604:         if (formname == 'ccrs') {
  605:             var ownername = document.forms[formid].ccuname.value;
  606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  607:             url += '&cloner='+ownername+':'+ownerdom;
  608:             if (type == 'Course') {
  609:                 url += '&crscode='+document.forms[formid].crscode.value;
  610:             }
  611:         }
  612:         if (formname == 'requestcrs') {
  613:             url += '&crsdom=$domainfilter&crscode=$instcode';
  614:         }
  615:         if (multflag !=null && multflag != '') {
  616:             url += '&multiple='+multflag;
  617:         }
  618:         var title = '$wintitle';
  619:         var options = 'scrollbars=1,resizable=1,menubar=0';
  620:         options += ',width=700,height=600';
  621:         stdeditbrowser = open(url,title,options,'1');
  622:         stdeditbrowser.focus();
  623:     }
  624: $id_functions
  625: ENDSTDBRW
  626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  628:                                       $credits_element);
  629:     }
  630:     $output .= '
  631: // ]]>
  632: </script>';
  633:     return $output;
  634: }
  635: 
  636: sub javascript_index_functions {
  637:     return <<"ENDJS";
  638: 
  639: function getFormIdByName(formname) {
  640:     for (var i=0;i<document.forms.length;i++) {
  641:         if (document.forms[i].name == formname) {
  642:             return i;
  643:         }
  644:     }
  645:     return -1;
  646: }
  647: 
  648: function getIndexByName(formid,item) {
  649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  650:         if (document.forms[formid].elements[i].name == item) {
  651:             return i;
  652:         }
  653:     }
  654:     return -1;
  655: }
  656: 
  657: function getDomainFromSelectbox(formname,udom) {
  658:     var userdom;
  659:     var formid = getFormIdByName(formname);
  660:     if (formid > -1) {
  661:         var domid = getIndexByName(formid,udom);
  662:         if (domid > -1) {
  663:             if (document.forms[formid].elements[domid].type == 'select-one') {
  664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  665:             }
  666:             if (document.forms[formid].elements[domid].type == 'hidden') {
  667:                 userdom=document.forms[formid].elements[domid].value;
  668:             }
  669:         }
  670:     }
  671:     return userdom;
  672: }
  673: 
  674: ENDJS
  675: 
  676: }
  677: 
  678: sub javascript_array_indexof {
  679:     return <<ENDJS;
  680: <script type="text/javascript" language="JavaScript">
  681: // <![CDATA[
  682: 
  683: if (!Array.prototype.indexOf) {
  684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  685:         "use strict";
  686:         if (this === void 0 || this === null) {
  687:             throw new TypeError();
  688:         }
  689:         var t = Object(this);
  690:         var len = t.length >>> 0;
  691:         if (len === 0) {
  692:             return -1;
  693:         }
  694:         var n = 0;
  695:         if (arguments.length > 0) {
  696:             n = Number(arguments[1]);
  697:             if (n !== n) { // shortcut for verifying if it is NaN
  698:                 n = 0;
  699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  701:             }
  702:         }
  703:         if (n >= len) {
  704:             return -1;
  705:         }
  706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  707:         for (; k < len; k++) {
  708:             if (k in t && t[k] === searchElement) {
  709:                 return k;
  710:             }
  711:         }
  712:         return -1;
  713:     }
  714: }
  715: 
  716: // ]]>
  717: </script>
  718: 
  719: ENDJS
  720: 
  721: }
  722: 
  723: sub userbrowser_javascript {
  724:     my $id_functions = &javascript_index_functions();
  725:     return <<"ENDUSERBRW";
  726: 
  727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  728:     var url = '/adm/pickuser?';
  729:     var userdom = getDomainFromSelectbox(formname,udom);
  730:     if (userdom != null) {
  731:        if (userdom != '') {
  732:            url += 'srchdom='+userdom+'&';
  733:        }
  734:     }
  735:     url += 'form=' + formname + '&unameelement='+uname+
  736:                                 '&udomelement='+udom+
  737:                                 '&ulastelement='+ulast+
  738:                                 '&ufirstelement='+ufirst+
  739:                                 '&uemailelement='+uemail+
  740:                                 '&hideudomelement='+hideudom+
  741:                                 '&coursedom='+crsdom;
  742:     if ((caller != null) && (caller != undefined)) {
  743:         url += '&caller='+caller;
  744:     }
  745:     var title = 'User_Browser';
  746:     var options = 'scrollbars=1,resizable=1,menubar=0';
  747:     options += ',width=700,height=600';
  748:     var stdeditbrowser = open(url,title,options,'1');
  749:     stdeditbrowser.focus();
  750: }
  751: 
  752: function fix_domain (formname,udom,origdom,uname) {
  753:     var formid = getFormIdByName(formname);
  754:     if (formid > -1) {
  755:         var unameid = getIndexByName(formid,uname);
  756:         var domid = getIndexByName(formid,udom);
  757:         var hidedomid = getIndexByName(formid,origdom);
  758:         if (hidedomid > -1) {
  759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  760:             var unameval = document.forms[formid].elements[unameid].value;
  761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  762:                 if (domid > -1) {
  763:                     var slct = document.forms[formid].elements[domid];
  764:                     if (slct.type == 'select-one') {
  765:                         var i;
  766:                         for (i=0;i<slct.length;i++) {
  767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  768:                         }
  769:                     }
  770:                     if (slct.type == 'hidden') {
  771:                         slct.value = fixeddom;
  772:                     }
  773:                 }
  774:             }
  775:         }
  776:     }
  777:     return;
  778: }
  779: 
  780: $id_functions
  781: ENDUSERBRW
  782: }
  783: 
  784: sub setsec_javascript {
  785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  787:         $communityrolestr);
  788:     if ($role_element ne '') {
  789:         my @allroles = ('st','ta','ep','in','ad');
  790:         foreach my $crstype ('Course','Community') {
  791:             if ($crstype eq 'Community') {
  792:                 foreach my $role (@allroles) {
  793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  794:                 }
  795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  796:             } else {
  797:                 foreach my $role (@allroles) {
  798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  799:                 }
  800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  801:             }
  802:         }
  803:         $rolestr = '"'.join('","',@allroles).'"';
  804:         $courserolestr = '"'.join('","',@courserolenames).'"';
  805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  806:     }
  807:     my $setsections = qq|
  808: function setSect(sectionlist) {
  809:     var sectionsArray = new Array();
  810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  811:         sectionsArray = sectionlist.split(",");
  812:     }
  813:     var numSections = sectionsArray.length;
  814:     document.$formname.$sec_element.length = 0;
  815:     if (numSections == 0) {
  816:         document.$formname.$sec_element.multiple=false;
  817:         document.$formname.$sec_element.size=1;
  818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  819:     } else {
  820:         if (numSections == 1) {
  821:             document.$formname.$sec_element.multiple=false;
  822:             document.$formname.$sec_element.size=1;
  823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  826:         } else {
  827:             for (var i=0; i<numSections; i++) {
  828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  829:             }
  830:             document.$formname.$sec_element.multiple=true
  831:             if (numSections < 3) {
  832:                 document.$formname.$sec_element.size=numSections;
  833:             } else {
  834:                 document.$formname.$sec_element.size=3;
  835:             }
  836:             document.$formname.$sec_element.options[0].selected = false
  837:         }
  838:     }
  839: }
  840: 
  841: function setRole(crstype) {
  842: |;
  843:     if ($role_element eq '') {
  844:         $setsections .= '    return;
  845: }
  846: ';
  847:     } else {
  848:         $setsections .= qq|
  849:     var elementLength = document.$formname.$role_element.length;
  850:     var allroles = Array($rolestr);
  851:     var courserolenames = Array($courserolestr);
  852:     var communityrolenames = Array($communityrolestr);
  853:     if (elementLength != undefined) {
  854:         if (document.$formname.$role_element.options[5].value == 'cc') {
  855:             if (crstype == 'Course') {
  856:                 return;
  857:             } else {
  858:                 allroles[5] = 'co';
  859:                 for (var i=0; i<6; i++) {
  860:                     document.$formname.$role_element.options[i].value = allroles[i];
  861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  862:                 }
  863:             }
  864:         } else {
  865:             if (crstype == 'Community') {
  866:                 return;
  867:             } else {
  868:                 allroles[5] = 'cc';
  869:                 for (var i=0; i<6; i++) {
  870:                     document.$formname.$role_element.options[i].value = allroles[i];
  871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  872:                 }
  873:             }
  874:         }
  875:     }
  876:     return;
  877: }
  878: |;
  879:     }
  880:     if ($credits_element) {
  881:         $setsections .= qq|
  882: function setCredits(defaultcredits) {
  883:     document.$formname.$credits_element.value = defaultcredits;
  884:     return;
  885: }
  886: |;
  887:     }
  888:     return $setsections;
  889: }
  890: 
  891: sub selectcourse_link {
  892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  893:        $typeelement) = @_;
  894:    my $type = $selecttype;
  895:    my $linktext = &mt('Select Course');
  896:    if ($selecttype eq 'Community') {
  897:        $linktext = &mt('Select Community');
  898:    } elsif ($selecttype eq 'Placement') {
  899:        $linktext = &mt('Select Placement Test'); 
  900:    } elsif ($selecttype eq 'Course/Community') {
  901:        $linktext = &mt('Select Course/Community');
  902:        $type = '';
  903:    } elsif ($selecttype eq 'Select') {
  904:        $linktext = &mt('Select');
  905:        $type = '';
  906:    }
  907:    return '<span class="LC_nobreak">'
  908:          ."<a href='"
  909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  912:          ."'>".$linktext.'</a>'
  913:          .'</span>';
  914: }
  915: 
  916: sub selectauthor_link {
  917:    my ($form,$udom)=@_;
  918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  919:           &mt('Select Author').'</a>';
  920: }
  921: 
  922: sub selectuser_link {
  923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  924:         $coursedom,$linktext,$caller) = @_;
  925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  927:            ');">'.$linktext.'</a>';
  928: }
  929: 
  930: sub check_uncheck_jscript {
  931:     my $jscript = <<"ENDSCRT";
  932: function checkAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             if (!field[i].disabled) { 
  936:                 field[i].checked = true;
  937:             }
  938:         }
  939:     } else {
  940:         if (!field.disabled) { 
  941:             field.checked = true;
  942:         }
  943:     }
  944: }
  945:  
  946: function uncheckAll(field) {
  947:     if (field.length > 0) {
  948:         for (i = 0; i < field.length; i++) {
  949:             field[i].checked = false ;
  950:         }
  951:     } else {
  952:         field.checked = false ;
  953:     }
  954: }
  955: ENDSCRT
  956:     return $jscript;
  957: }
  958: 
  959: sub select_timezone {
  960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  962:    if ($includeempty) {
  963:        $output .= '<option value=""';
  964:        if (($selected eq '') || ($selected eq 'local')) {
  965:            $output .= ' selected="selected" ';
  966:        }
  967:        $output .= '> </option>';
  968:    }
  969:    my @timezones = DateTime::TimeZone->all_names;
  970:    foreach my $tzone (@timezones) {
  971:        $output.= '<option value="'.$tzone.'"';
  972:        if ($tzone eq $selected) {
  973:            $output.=' selected="selected"';
  974:        }
  975:        $output.=">$tzone</option>\n";
  976:    }
  977:    $output.="</select>";
  978:    return $output;
  979: }
  980: 
  981: sub select_datelocale {
  982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  984:     if ($includeempty) {
  985:         $output .= '<option value=""';
  986:         if ($selected eq '') {
  987:             $output .= ' selected="selected" ';
  988:         }
  989:         $output .= '> </option>';
  990:     }
  991:     my @languages = &Apache::lonlocal::preferred_languages();
  992:     my (@possibles,%locale_names);
  993:     my @locales = DateTime::Locale->ids();
  994:     foreach my $id (@locales) {
  995:         if ($id ne '') {
  996:             my ($en_terr,$native_terr);
  997:             my $loc = DateTime::Locale->load($id);
  998:             if (ref($loc)) {
  999:                 $en_terr = $loc->name();
 1000:                 $native_terr = $loc->native_name();
 1001:                 if (grep(/^en$/,@languages) || !@languages) {
 1002:                     if ($en_terr ne '') {
 1003:                         $locale_names{$id} = '('.$en_terr.')';
 1004:                     } elsif ($native_terr ne '') {
 1005:                         $locale_names{$id} = $native_terr;
 1006:                     }
 1007:                 } else {
 1008:                     if ($native_terr ne '') {
 1009:                         $locale_names{$id} = $native_terr.' ';
 1010:                     } elsif ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     }
 1013:                 }
 1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1015:                 push(@possibles,$id);
 1016:             } 
 1017:         }
 1018:     }
 1019:     foreach my $item (sort(@possibles)) {
 1020:         $output.= '<option value="'.$item.'"';
 1021:         if ($item eq $selected) {
 1022:             $output.=' selected="selected"';
 1023:         }
 1024:         $output.=">$item";
 1025:         if ($locale_names{$item} ne '') {
 1026:             $output.='  '.$locale_names{$item};
 1027:         }
 1028:         $output.="</option>\n";
 1029:     }
 1030:     $output.="</select>";
 1031:     return $output;
 1032: }
 1033: 
 1034: sub select_language {
 1035:     my ($name,$selected,$includeempty,$noedit) = @_;
 1036:     my %langchoices;
 1037:     if ($includeempty) {
 1038:         %langchoices = ('' => 'No language preference');
 1039:     }
 1040:     foreach my $id (&languageids()) {
 1041:         my $code = &supportedlanguagecode($id);
 1042:         if ($code) {
 1043:             $langchoices{$code} = &plainlanguagedescription($id);
 1044:         }
 1045:     }
 1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1048: }
 1049: 
 1050: =pod
 1051: 
 1052: 
 1053: =item * &list_languages()
 1054: 
 1055: Returns an array reference that is suitable for use in language prompters.
 1056: Each array element is itself a two element array.  The first element
 1057: is the language code.  The second element a descsriptiuon of the 
 1058: language itself.  This is suitable for use in e.g.
 1059: &Apache::edit::select_arg (once dereferenced that is).
 1060: 
 1061: =cut 
 1062: 
 1063: sub list_languages {
 1064:     my @lang_choices;
 1065: 
 1066:     foreach my $id (&languageids()) {
 1067: 	my $code = &supportedlanguagecode($id);
 1068: 	if ($code) {
 1069: 	    my $selector    = $supported_codes{$id};
 1070: 	    my $description = &plainlanguagedescription($id);
 1071: 	    push(@lang_choices, [$selector, $description]);
 1072: 	}
 1073:     }
 1074:     return \@lang_choices;
 1075: }
 1076: 
 1077: =pod
 1078: 
 1079: =item * &linked_select_forms(...)
 1080: 
 1081: linked_select_forms returns a string containing a <script></script> block
 1082: and html for two <select> menus.  The select menus will be linked in that
 1083: changing the value of the first menu will result in new values being placed
 1084: in the second menu.  The values in the select menu will appear in alphabetical
 1085: order unless a defined order is provided.
 1086: 
 1087: linked_select_forms takes the following ordered inputs:
 1088: 
 1089: =over 4
 1090: 
 1091: =item * $formname, the name of the <form> tag
 1092: 
 1093: =item * $middletext, the text which appears between the <select> tags
 1094: 
 1095: =item * $firstdefault, the default value for the first menu
 1096: 
 1097: =item * $firstselectname, the name of the first <select> tag
 1098: 
 1099: =item * $secondselectname, the name of the second <select> tag
 1100: 
 1101: =item * $hashref, a reference to a hash containing the data for the menus.
 1102: 
 1103: =item * $menuorder, the order of values in the first menu
 1104: 
 1105: =item * $onchangefirst, additional javascript call to execute for an onchange
 1106:         event for the first <select> tag
 1107: 
 1108: =item * $onchangesecond, additional javascript call to execute for an onchange
 1109:         event for the second <select> tag
 1110: 
 1111: =item * $suffix, to differentiate separate uses of select2data javascript
 1112:         objects in a page.
 1113: 
 1114: =back 
 1115: 
 1116: Below is an example of such a hash.  Only the 'text', 'default', and 
 1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1118: values for the first select menu.  The text that coincides with the 
 1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1120: and text for the second menu are given in the hash pointed to by 
 1121: $menu{$choice1}->{'select2'}.  
 1122: 
 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
 1124:                        default => "B3",
 1125:                        select2 => { 
 1126:                            B1 => "Choice B1",
 1127:                            B2 => "Choice B2",
 1128:                            B3 => "Choice B3",
 1129:                            B4 => "Choice B4"
 1130:                            },
 1131:                        order => ['B4','B3','B1','B2'],
 1132:                    },
 1133:                A2 => { text =>"Choice A2" ,
 1134:                        default => "C2",
 1135:                        select2 => { 
 1136:                            C1 => "Choice C1",
 1137:                            C2 => "Choice C2",
 1138:                            C3 => "Choice C3"
 1139:                            },
 1140:                        order => ['C2','C1','C3'],
 1141:                    },
 1142:                A3 => { text =>"Choice A3" ,
 1143:                        default => "D6",
 1144:                        select2 => { 
 1145:                            D1 => "Choice D1",
 1146:                            D2 => "Choice D2",
 1147:                            D3 => "Choice D3",
 1148:                            D4 => "Choice D4",
 1149:                            D5 => "Choice D5",
 1150:                            D6 => "Choice D6",
 1151:                            D7 => "Choice D7"
 1152:                            },
 1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1154:                    }
 1155:                );
 1156: 
 1157: =cut
 1158: 
 1159: sub linked_select_forms {
 1160:     my ($formname,
 1161:         $middletext,
 1162:         $firstdefault,
 1163:         $firstselectname,
 1164:         $secondselectname, 
 1165:         $hashref,
 1166:         $menuorder,
 1167:         $onchangefirst,
 1168:         $onchangesecond,
 1169:         $suffix
 1170:         ) = @_;
 1171:     my $second = "document.$formname.$secondselectname";
 1172:     my $first = "document.$formname.$firstselectname";
 1173:     # output the javascript to do the changing
 1174:     my $result = '';
 1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1176:     $result.="// <![CDATA[\n";
 1177:     $result.="var select2data${suffix} = new Object();\n";
 1178:     $" = '","';
 1179:     my $debug = '';
 1180:     foreach my $s1 (sort(keys(%$hashref))) {
 1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1183:             $hashref->{$s1}->{'default'}."');\n";
 1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1187:             @s2values = @{$hashref->{$s1}->{'order'}};
 1188:         }
 1189:         $result.="\"@s2values\");\n";
 1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1191:         my @s2texts;
 1192:         foreach my $value (@s2values) {
 1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1194:         }
 1195:         $result.="\"@s2texts\");\n";
 1196:     }
 1197:     $"=' ';
 1198:     $result.= <<"END";
 1199: 
 1200: function select1${suffix}_changed() {
 1201:     // Determine new choice
 1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1203:     // update select2
 1204:     var values     = select2data${suffix}[newvalue].values;
 1205:     var texts      = select2data${suffix}[newvalue].texts;
 1206:     var select2def = select2data${suffix}[newvalue].def;
 1207:     var i;
 1208:     // out with the old
 1209:     $second.options.length = 0;
 1210:     // in with the new
 1211:     for (i=0;i<values.length; i++) {
 1212:         $second.options[i] = new Option(values[i]);
 1213:         $second.options[i].value = values[i];
 1214:         $second.options[i].text = texts[i];
 1215:         if (values[i] == select2def) {
 1216:             $second.options[i].selected = true;
 1217:         }
 1218:     }
 1219: }
 1220: // ]]>
 1221: </script>
 1222: END
 1223:     # output the initial values for the selection lists
 1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1225:     my @order = sort(keys(%{$hashref}));
 1226:     if (ref($menuorder) eq 'ARRAY') {
 1227:         @order = @{$menuorder};
 1228:     }
 1229:     foreach my $value (@order) {
 1230:         $result.="    <option value=\"$value\" ";
 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1233:     }
 1234:     $result .= "</select>\n";
 1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1236:     $result .= $middletext;
 1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1238:     if ($onchangesecond) {
 1239:         $result .= ' onchange="'.$onchangesecond.'"';
 1240:     }
 1241:     $result .= ">\n";
 1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1243:     
 1244:     my @secondorder = sort(keys(%select2));
 1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1247:     }
 1248:     foreach my $value (@secondorder) {
 1249:         $result.="    <option value=\"$value\" ";        
 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1251:         $result.=">".&mt($select2{$value})."</option>\n";
 1252:     }
 1253:     $result .= "</select>\n";
 1254:     #    return $debug;
 1255:     return $result;
 1256: }   #  end of sub linked_select_forms {
 1257: 
 1258: =pod
 1259: 
 1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1261: 
 1262: Returns a string corresponding to an HTML link to the given help
 1263: $topic, where $topic corresponds to the name of a .tex file in
 1264: /home/httpd/html/adm/help/tex, with underscores replaced by
 1265: spaces. 
 1266: 
 1267: $text will optionally be linked to the same topic, allowing you to
 1268: link text in addition to the graphic. If you do not want to link
 1269: text, but wish to specify one of the later parameters, pass an
 1270: empty string. 
 1271: 
 1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1273: the link will not open a new window. If false, the link will open
 1274: a new window using Javascript. (Default is false.) 
 1275: 
 1276: $width and $height are optional numerical parameters that will
 1277: override the width and height of the popped up window, which may
 1278: be useful for certain help topics with big pictures included.
 1279: 
 1280: $imgid is the id of the img tag used for the help icon. This may be
 1281: used in a javascript call to switch the image src.  See 
 1282: lonhtmlcommon::htmlareaselectactive() for an example.
 1283: 
 1284: =cut
 1285: 
 1286: sub help_open_topic {
 1287:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1288:     $text = "" if (not defined $text);
 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
 1290:     $width = 500 if (not defined $width);
 1291:     $height = 400 if (not defined $height);
 1292:     my $filename = $topic;
 1293:     $filename =~ s/ /_/g;
 1294: 
 1295:     my $template = "";
 1296:     my $link;
 1297:     
 1298:     $topic=~s/\W/\_/g;
 1299: 
 1300:     if (!$stayOnPage) {
 1301: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1302:     } elsif ($stayOnPage eq 'popup') {
 1303:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1304:     } else {
 1305: 	$link = "/adm/help/${filename}.hlp";
 1306:     }
 1307: 
 1308:     # Add the text
 1309:     my $target = ' target="_top"';
 1310:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1311:         $target = '';
 1312:     }
 1313:     if ($text ne "") {	
 1314: 	$template.='<span class="LC_help_open_topic">'
 1315:                   .'<a'.$target.' href="'.$link.'">'
 1316:                   .$text.'</a>';
 1317:     }
 1318: 
 1319:     # (Always) Add the graphic
 1320:     my $title = &mt('Online Help');
 1321:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1322:     if ($imgid ne '') {
 1323:         $imgid = ' id="'.$imgid.'"';
 1324:     }
 1325:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1326:               .'<img src="'.$helpicon.'" border="0"'
 1327:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1328:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1329:               .' /></a>';
 1330:     if ($text ne "") {	
 1331:         $template.='</span>';
 1332:     }
 1333:     return $template;
 1334: 
 1335: }
 1336: 
 1337: # This is a quicky function for Latex cheatsheet editing, since it 
 1338: # appears in at least four places
 1339: sub helpLatexCheatsheet {
 1340:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1341:     my $out;
 1342:     my $addOther = '';
 1343:     if ($topic) {
 1344: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1345:     }
 1346:     $out = '<span>' # Start cheatsheet
 1347: 	  .$addOther
 1348:           .'<span>'
 1349: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1350: 	  .'</span> <span>'
 1351: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1352: 	  .'</span>';
 1353:     unless ($not_author) {
 1354:         $out .= '<span>'
 1355:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1356:                .'</span> <span>'
 1357:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1358: 	       .'</span>';
 1359:     }
 1360:     $out .= '</span>'; # End cheatsheet
 1361:     return $out;
 1362: }
 1363: 
 1364: sub general_help {
 1365:     my $helptopic='Student_Intro';
 1366:     if ($env{'request.role'}=~/^(ca|au)/) {
 1367: 	$helptopic='Authoring_Intro';
 1368:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1369: 	$helptopic='Course_Coordination_Intro';
 1370:     } elsif ($env{'request.role'}=~/^dc/) {
 1371:         $helptopic='Domain_Coordination_Intro';
 1372:     }
 1373:     return $helptopic;
 1374: }
 1375: 
 1376: sub update_help_link {
 1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1378:     my $origurl = $ENV{'REQUEST_URI'};
 1379:     $origurl=~s|^/~|/priv/|;
 1380:     my $timestamp = time;
 1381:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1382:         $$datum = &escape($$datum);
 1383:     }
 1384: 
 1385:     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";
 1386:     my $output .= <<"ENDOUTPUT";
 1387: <script type="text/javascript">
 1388: // <![CDATA[
 1389: banner_link = '$banner_link';
 1390: // ]]>
 1391: </script>
 1392: ENDOUTPUT
 1393:     return $output;
 1394: }
 1395: 
 1396: # now just updates the help link and generates a blue icon
 1397: sub help_open_menu {
 1398:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1399: 	= @_;    
 1400:     $stayOnPage = 1;
 1401:     my $output;
 1402:     if ($component_help) {
 1403: 	if (!$text) {
 1404: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1405: 				       $width,$height);
 1406: 	} else {
 1407: 	    my $help_text;
 1408: 	    $help_text=&unescape($topic);
 1409: 	    $output='<table><tr><td>'.
 1410: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1411: 				 $width,$height).'</td></tr></table>';
 1412: 	}
 1413:     }
 1414:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1415:     return $output.$banner_link;
 1416: }
 1417: 
 1418: sub top_nav_help {
 1419:     my ($text) = @_;
 1420:     $text = &mt($text);
 1421:     my $stay_on_page = 1;
 1422: 
 1423:     my ($link,$banner_link);
 1424:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1425:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1426: 	                         : "javascript:helpMenu('open')";
 1427:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1428:     }
 1429:     my $title = &mt('Get help');
 1430:     if ($link) {
 1431:         return <<"END";
 1432: $banner_link
 1433: <a href="$link" title="$title">$text</a>
 1434: END
 1435:     } else {
 1436:         return '&nbsp;'.$text.'&nbsp;';
 1437:     }
 1438: }
 1439: 
 1440: sub help_menu_js {
 1441:     my ($httphost) = @_;
 1442:     my $stayOnPage = 1;
 1443:     my $width = 620;
 1444:     my $height = 600;
 1445:     my $helptopic=&general_help();
 1446:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1447:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1448:     my $start_page =
 1449:         &Apache::loncommon::start_page('Help Menu', undef,
 1450: 				       {'frameset'    => 1,
 1451: 					'js_ready'    => 1,
 1452:                                         'use_absolute' => $httphost,
 1453: 					'add_entries' => {
 1454: 					    'border' => '0', 
 1455: 					    'rows'   => "110,*",},});
 1456:     my $end_page =
 1457:         &Apache::loncommon::end_page({'frameset' => 1,
 1458: 				      'js_ready' => 1,});
 1459: 
 1460:     my $template .= <<"ENDTEMPLATE";
 1461: <script type="text/javascript">
 1462: // <![CDATA[
 1463: // <!-- BEGIN LON-CAPA Internal
 1464: var banner_link = '';
 1465: function helpMenu(target) {
 1466:     var caller = this;
 1467:     if (target == 'open') {
 1468:         var newWindow = null;
 1469:         try {
 1470:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1471:         }
 1472:         catch(error) {
 1473:             writeHelp(caller);
 1474:             return;
 1475:         }
 1476:         if (newWindow) {
 1477:             caller = newWindow;
 1478:         }
 1479:     }
 1480:     writeHelp(caller);
 1481:     return;
 1482: }
 1483: function writeHelp(caller) {
 1484:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1485:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1486:     caller.document.close();
 1487:     caller.focus();
 1488: }
 1489: // END LON-CAPA Internal -->
 1490: // ]]>
 1491: </script>
 1492: ENDTEMPLATE
 1493:     return $template;
 1494: }
 1495: 
 1496: sub help_open_bug {
 1497:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1498:     unless ($env{'user.adv'}) { return ''; }
 1499:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1500:     $text = "" if (not defined $text);
 1501: 	$stayOnPage=1;
 1502:     $width = 600 if (not defined $width);
 1503:     $height = 600 if (not defined $height);
 1504: 
 1505:     $topic=~s/\W+/\+/g;
 1506:     my $link='';
 1507:     my $template='';
 1508:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1509: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1510:     if (!$stayOnPage)
 1511:     {
 1512: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1513:     }
 1514:     else
 1515:     {
 1516: 	$link = $url;
 1517:     }
 1518: 
 1519:     my $target = ' target="_top"';
 1520:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 1521:         $target = '';
 1522:     }
 1523:     # Add the text
 1524:     if ($text ne "")
 1525:     {
 1526: 	$template .= 
 1527:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1528:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1529:     }
 1530: 
 1531:     # Add the graphic
 1532:     my $title = &mt('Report a Bug');
 1533:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1534:     $template .= <<"ENDTEMPLATE";
 1535:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1536: ENDTEMPLATE
 1537:     if ($text ne '') { $template.='</td></tr></table>' };
 1538:     return $template;
 1539: 
 1540: }
 1541: 
 1542: sub help_open_faq {
 1543:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1544:     unless ($env{'user.adv'}) { return ''; }
 1545:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1546:     $text = "" if (not defined $text);
 1547: 	$stayOnPage=1;
 1548:     $width = 350 if (not defined $width);
 1549:     $height = 400 if (not defined $height);
 1550: 
 1551:     $topic=~s/\W+/\+/g;
 1552:     my $link='';
 1553:     my $template='';
 1554:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1555:     if (!$stayOnPage)
 1556:     {
 1557: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1558:     }
 1559:     else
 1560:     {
 1561: 	$link = $url;
 1562:     }
 1563: 
 1564:     # Add the text
 1565:     if ($text ne "")
 1566:     {
 1567: 	$template .= 
 1568:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1569:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1570:     }
 1571: 
 1572:     # Add the graphic
 1573:     my $title = &mt('View the FAQ');
 1574:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1575:     $template .= <<"ENDTEMPLATE";
 1576:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1577: ENDTEMPLATE
 1578:     if ($text ne '') { $template.='</td></tr></table>' };
 1579:     return $template;
 1580: 
 1581: }
 1582: 
 1583: ###############################################################
 1584: ###############################################################
 1585: 
 1586: =pod
 1587: 
 1588: =item * &change_content_javascript():
 1589: 
 1590: This and the next function allow you to create small sections of an
 1591: otherwise static HTML page that you can update on the fly with
 1592: Javascript, even in Netscape 4.
 1593: 
 1594: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1595: must be written to the HTML page once. It will prove the Javascript
 1596: function "change(name, content)". Calling the change function with the
 1597: name of the section 
 1598: you want to update, matching the name passed to C<changable_area>, and
 1599: the new content you want to put in there, will put the content into
 1600: that area.
 1601: 
 1602: B<Note>: Netscape 4 only reserves enough space for the changable area
 1603: to contain room for the original contents. You need to "make space"
 1604: for whatever changes you wish to make, and be B<sure> to check your
 1605: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1606: it's adequate for updating a one-line status display, but little more.
 1607: This script will set the space to 100% width, so you only need to
 1608: worry about height in Netscape 4.
 1609: 
 1610: Modern browsers are much less limiting, and if you can commit to the
 1611: user not using Netscape 4, this feature may be used freely with
 1612: pretty much any HTML.
 1613: 
 1614: =cut
 1615: 
 1616: sub change_content_javascript {
 1617:     # If we're on Netscape 4, we need to use Layer-based code
 1618:     if ($env{'browser.type'} eq 'netscape' &&
 1619: 	$env{'browser.version'} =~ /^4\./) {
 1620: 	return (<<NETSCAPE4);
 1621: 	function change(name, content) {
 1622: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1623: 	    doc.open();
 1624: 	    doc.write(content);
 1625: 	    doc.close();
 1626: 	}
 1627: NETSCAPE4
 1628:     } else {
 1629: 	# Otherwise, we need to use semi-standards-compliant code
 1630: 	# (technically, "innerHTML" isn't standard but the equivalent
 1631: 	# is really scary, and every useful browser supports it
 1632: 	return (<<DOMBASED);
 1633: 	function change(name, content) {
 1634: 	    element = document.getElementById(name);
 1635: 	    element.innerHTML = content;
 1636: 	}
 1637: DOMBASED
 1638:     }
 1639: }
 1640: 
 1641: =pod
 1642: 
 1643: =item * &changable_area($name,$origContent):
 1644: 
 1645: This provides a "changable area" that can be modified on the fly via
 1646: the Javascript code provided in C<change_content_javascript>. $name is
 1647: the name you will use to reference the area later; do not repeat the
 1648: same name on a given HTML page more then once. $origContent is what
 1649: the area will originally contain, which can be left blank.
 1650: 
 1651: =cut
 1652: 
 1653: sub changable_area {
 1654:     my ($name, $origContent) = @_;
 1655: 
 1656:     if ($env{'browser.type'} eq 'netscape' &&
 1657: 	$env{'browser.version'} =~ /^4\./) {
 1658: 	# If this is netscape 4, we need to use the Layer tag
 1659: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1660:     } else {
 1661: 	return "<span id='$name'>$origContent</span>";
 1662:     }
 1663: }
 1664: 
 1665: =pod
 1666: 
 1667: =item * &viewport_geometry_js 
 1668: 
 1669: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1670: 
 1671: =cut
 1672: 
 1673: 
 1674: sub viewport_geometry_js { 
 1675:     return <<"GEOMETRY";
 1676: var Geometry = {};
 1677: function init_geometry() {
 1678:     if (Geometry.init) { return };
 1679:     Geometry.init=1;
 1680:     if (window.innerHeight) {
 1681:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1682:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1683:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1684:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1685:     }
 1686:     else if (document.documentElement && document.documentElement.clientHeight) {
 1687:         Geometry.getViewportHeight =
 1688:             function() { return document.documentElement.clientHeight; };
 1689:         Geometry.getViewportWidth =
 1690:             function() { return document.documentElement.clientWidth; };
 1691: 
 1692:         Geometry.getHorizontalScroll =
 1693:             function() { return document.documentElement.scrollLeft; };
 1694:         Geometry.getVerticalScroll =
 1695:             function() { return document.documentElement.scrollTop; };
 1696:     }
 1697:     else if (document.body.clientHeight) {
 1698:         Geometry.getViewportHeight =
 1699:             function() { return document.body.clientHeight; };
 1700:         Geometry.getViewportWidth =
 1701:             function() { return document.body.clientWidth; };
 1702:         Geometry.getHorizontalScroll =
 1703:             function() { return document.body.scrollLeft; };
 1704:         Geometry.getVerticalScroll =
 1705:             function() { return document.body.scrollTop; };
 1706:     }
 1707: }
 1708: 
 1709: GEOMETRY
 1710: }
 1711: 
 1712: =pod
 1713: 
 1714: =item * &viewport_size_js()
 1715: 
 1716: 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. 
 1717: 
 1718: =cut
 1719: 
 1720: sub viewport_size_js {
 1721:     my $geometry = &viewport_geometry_js();
 1722:     return <<"DIMS";
 1723: 
 1724: $geometry
 1725: 
 1726: function getViewportDims(width,height) {
 1727:     init_geometry();
 1728:     width.value = Geometry.getViewportWidth();
 1729:     height.value = Geometry.getViewportHeight();
 1730:     return;
 1731: }
 1732: 
 1733: DIMS
 1734: }
 1735: 
 1736: =pod
 1737: 
 1738: =item * &resize_textarea_js()
 1739: 
 1740: emits the needed javascript to resize a textarea to be as big as possible
 1741: 
 1742: creates a function resize_textrea that takes two IDs first should be
 1743: the id of the element to resize, second should be the id of a div that
 1744: surrounds everything that comes after the textarea, this routine needs
 1745: to be attached to the <body> for the onload and onresize events.
 1746: 
 1747: =back
 1748: 
 1749: =cut
 1750: 
 1751: sub resize_textarea_js {
 1752:     my $geometry = &viewport_geometry_js();
 1753:     return <<"RESIZE";
 1754:     <script type="text/javascript">
 1755: // <![CDATA[
 1756: $geometry
 1757: 
 1758: function getX(element) {
 1759:     var x = 0;
 1760:     while (element) {
 1761: 	x += element.offsetLeft;
 1762: 	element = element.offsetParent;
 1763:     }
 1764:     return x;
 1765: }
 1766: function getY(element) {
 1767:     var y = 0;
 1768:     while (element) {
 1769: 	y += element.offsetTop;
 1770: 	element = element.offsetParent;
 1771:     }
 1772:     return y;
 1773: }
 1774: 
 1775: 
 1776: function resize_textarea(textarea_id,bottom_id) {
 1777:     init_geometry();
 1778:     var textarea        = document.getElementById(textarea_id);
 1779:     //alert(textarea);
 1780: 
 1781:     var textarea_top    = getY(textarea);
 1782:     var textarea_height = textarea.offsetHeight;
 1783:     var bottom          = document.getElementById(bottom_id);
 1784:     var bottom_top      = getY(bottom);
 1785:     var bottom_height   = bottom.offsetHeight;
 1786:     var window_height   = Geometry.getViewportHeight();
 1787:     var fudge           = 23;
 1788:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1789:     if (new_height < 300) {
 1790: 	new_height = 300;
 1791:     }
 1792:     textarea.style.height=new_height+'px';
 1793: }
 1794: // ]]>
 1795: </script>
 1796: RESIZE
 1797: 
 1798: }
 1799: 
 1800: sub colorfuleditor_js {
 1801:     my $browse_or_search;
 1802:     my $respath;
 1803:     my ($cnum,$cdom) = &crsauthor_url();
 1804:     if ($cnum) {
 1805:         $respath = "/res/$cdom/$cnum/";
 1806:         my %js_lt = &Apache::lonlocal::texthash(
 1807:             sunm => 'Sub-directory name',
 1808:             save => 'Save page to make this permanent',
 1809:         );
 1810:         &js_escape(\%js_lt);
 1811:         $browse_or_search = <<"END";
 1812: 
 1813:     function toggleChooser(form,element,titleid,only,search) {
 1814:         var disp = 'none';
 1815:         if (document.getElementById('chooser_'+element)) {
 1816:             var curr = document.getElementById('chooser_'+element).style.display;
 1817:             if (curr == 'none') {
 1818:                 disp='inline';
 1819:                 if (form.elements['chooser_'+element].length) {
 1820:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1821:                         form.elements['chooser_'+element][i].checked = false;
 1822:                     }
 1823:                 }
 1824:                 toggleResImport(form,element);
 1825:             }
 1826:             document.getElementById('chooser_'+element).style.display = disp;
 1827:         }
 1828:     }
 1829: 
 1830:     function toggleCrsFile(form,element,numdirs) {
 1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1832:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1833:             if (curr == 'none') {
 1834:                 if (numdirs) {
 1835:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1836:                     if (numdirs > 1) {
 1837:                         window['select1'+element+'_changed']();
 1838:                     }
 1839:                 }
 1840:             } 
 1841:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1842:             
 1843:         }
 1844:         if (document.getElementById('chooser_'+element+'_upload')) {
 1845:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1846:             if (document.getElementById('uploadcrsres_'+element)) {
 1847:                 document.getElementById('uploadcrsres_'+element).value = '';
 1848:             }
 1849:         }
 1850:         return;
 1851:     }
 1852: 
 1853:     function toggleCrsUpload(form,element,numcrsdirs) {
 1854:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1855:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1856:         }
 1857:         if (document.getElementById('chooser_'+element+'_upload')) {
 1858:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1859:             if (curr == 'none') {
 1860:                 if (numcrsdirs) {
 1861:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1862:                    form.elements['newsubdir_'+element][0].checked = true;
 1863:                    toggleNewsubdir(form,element);
 1864:                 }
 1865:             }
 1866:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1867:         }
 1868:         return;
 1869:     }
 1870: 
 1871:     function toggleResImport(form,element) {
 1872:         var choices = new Array('crsres','upload');
 1873:         for (var i=0; i<choices.length; i++) {
 1874:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1875:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1876:             }
 1877:         }
 1878:     }
 1879: 
 1880:     function toggleNewsubdir(form,element) {
 1881:         var newsub = form.elements['newsubdir_'+element];
 1882:         if (newsub) {
 1883:             if (newsub.length) {
 1884:                 for (var j=0; j<newsub.length; j++) {
 1885:                     if (newsub[j].checked) {
 1886:                         if (document.getElementById('newsubdirname_'+element)) {
 1887:                             if (newsub[j].value == '1') {
 1888:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1889:                                 if (document.getElementById('newsubdir_'+element)) {
 1890:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1891:                                 }
 1892:                             } else {
 1893:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1894:                                 document.getElementById('newsubdirname_'+element).value = "";
 1895:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1896:                             }
 1897:                         }
 1898:                         break; 
 1899:                     }
 1900:                 }
 1901:             }
 1902:         }
 1903:     }
 1904: 
 1905:     function updateCrsFile(form,element) {
 1906:         var directory = form.elements['coursepath_'+element];
 1907:         var filename = form.elements['coursefile_'+element];
 1908:         var path = directory.options[directory.selectedIndex].value;
 1909:         var file = filename.options[filename.selectedIndex].value;
 1910:         form.elements[element].value = '$respath';
 1911:         if (path == '/') {
 1912:             form.elements[element].value += file;
 1913:         } else {
 1914:             form.elements[element].value += path+'/'+file;
 1915:         }
 1916:         unClean();
 1917:         if (document.getElementById('previewimg_'+element)) {
 1918:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1919:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1920:         }
 1921:         if (document.getElementById('showimg_'+element)) {
 1922:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1923:         }
 1924:         toggleChooser(form,element);
 1925:         return;
 1926:     }
 1927: 
 1928:     function uploadDone(suffix,name) {
 1929:         if (name) {
 1930: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1931:             unClean();
 1932:             toggleChooser(document.forms["lonhomework"],suffix);
 1933:         }
 1934:     }
 1935: 
 1936: \$(document).ready(function(){
 1937: 
 1938:     \$(document).delegate('form :submit', 'click', function( event ) {
 1939:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1940:             var buttonId = this.id;
 1941:             var suffix = buttonId.toString();
 1942:             suffix = suffix.replace(/^crsupload_/,'');
 1943:             event.preventDefault();
 1944:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1945:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1946:             \$(this.form).submit();
 1947:             document.lonhomework.target = '';
 1948:             if (document.getElementById('crsuploadto_'+suffix)) {
 1949:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1950:             }
 1951:             return false;
 1952:         }
 1953:     });
 1954: });
 1955: END
 1956:     }
 1957:     return <<"COLORFULEDIT"
 1958: <script type="text/javascript">
 1959: // <![CDATA[>
 1960:     function fold_box(curDepth, lastresource){
 1961: 
 1962:     // we need a list because there can be several blocks you need to fold in one tag
 1963:         var block = document.getElementsByName('foldblock_'+curDepth);
 1964:     // but there is only one folding button per tag
 1965:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1966: 
 1967:         if(block.item(0).style.display == 'none'){
 1968: 
 1969:             foldbutton.value = '@{[&mt("Hide")]}';
 1970:             for (i = 0; i < block.length; i++){
 1971:                 block.item(i).style.display = '';
 1972:             }
 1973:         }else{
 1974: 
 1975:             foldbutton.value = '@{[&mt("Show")]}';
 1976:             for (i = 0; i < block.length; i++){
 1977:                 // block.item(i).style.visibility = 'collapse';
 1978:                 block.item(i).style.display = 'none';
 1979:             }
 1980:         };
 1981:         saveState(lastresource);
 1982:     }
 1983: 
 1984:     function saveState (lastresource) {
 1985: 
 1986:         var tag_list = getTagList();
 1987:         if(tag_list != null){
 1988:             var timestamp = new Date().getTime();
 1989:             var key = lastresource;
 1990: 
 1991:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1992:             // starting with timestamp
 1993:             var value = timestamp+';';
 1994: 
 1995:             // building the list of key-value pairs
 1996:             for(var i = 0; i < tag_list.length; i++){
 1997:                 value += tag_list[i]+',';
 1998:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1999:             }
 2000: 
 2001:             // only iterate whole storage if nothing to override
 2002:             if(localStorage.getItem(key) == null){        
 2003: 
 2004:                 // prevent storage from growing large
 2005:                 if(localStorage.length > 50){
 2006:                     var regex_getTimestamp = /^(?:\d)+;/;
 2007:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2008:                     var oldest_key;
 2009:                     
 2010:                     for(var i = 1; i < localStorage.length; i++){
 2011:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2012:                             oldest_key = localStorage.key(i);
 2013:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2014:                         }
 2015:                     }
 2016:                     localStorage.removeItem(oldest_key);
 2017:                 }
 2018:             }
 2019:             localStorage.setItem(key,value);
 2020:         }
 2021:     }
 2022: 
 2023:     // restore folding status of blocks (on page load)
 2024:     function restoreState (lastresource) {
 2025:         if(localStorage.getItem(lastresource) != null){
 2026:             var key = lastresource;
 2027:             var value = localStorage.getItem(key);
 2028:             var regex_delTimestamp = /^\d+;/;
 2029: 
 2030:             value.replace(regex_delTimestamp, '');
 2031: 
 2032:             var valueArr = value.split(';');
 2033:             var pairs;
 2034:             var elements;
 2035:             for (var i = 0; i < valueArr.length; i++){
 2036:                 pairs = valueArr[i].split(',');
 2037:                 elements = document.getElementsByName(pairs[0]);
 2038: 
 2039:                 for (var j = 0; j < elements.length; j++){  
 2040:                     elements[j].style.display = pairs[1];
 2041:                     if (pairs[1] == "none"){
 2042:                         var regex_id = /([_\\d]+)\$/;
 2043:                         regex_id.exec(pairs[0]);
 2044:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2045:                     }
 2046:                 }
 2047:             }
 2048:         }
 2049:     }
 2050: 
 2051:     function getTagList () {
 2052:         
 2053:         var stringToSearch = document.lonhomework.innerHTML;
 2054: 
 2055:         var ret = new Array();
 2056:         var regex_findBlock = /(foldblock_.*?)"/g;
 2057:         var tag_list = stringToSearch.match(regex_findBlock);
 2058: 
 2059:         if(tag_list != null){
 2060:             for(var i = 0; i < tag_list.length; i++){            
 2061:                 ret.push(tag_list[i].replace(/"/, ''));
 2062:             }
 2063:         }
 2064:         return ret;
 2065:     }
 2066: 
 2067:     function saveScrollPosition (resource) {
 2068:         var tag_list = getTagList();
 2069: 
 2070:         // we dont always want to jump to the first block
 2071:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2072:         if(\$(window).scrollTop() > 170){
 2073:             if(tag_list != null){
 2074:                 var result;
 2075:                 for(var i = 0; i < tag_list.length; i++){
 2076:                     if(isElementInViewport(tag_list[i])){
 2077:                         result += tag_list[i]+';';
 2078:                     }
 2079:                 }
 2080:                 sessionStorage.setItem('anchor_'+resource, result);
 2081:             }
 2082:         } else {
 2083:             // we dont need to save zero, just delete the item to leave everything tidy
 2084:             sessionStorage.removeItem('anchor_'+resource);
 2085:         }
 2086:     }
 2087: 
 2088:     function restoreScrollPosition(resource){
 2089: 
 2090:         var elem = sessionStorage.getItem('anchor_'+resource);
 2091:         if(elem != null){
 2092:             var tag_list = elem.split(';');
 2093:             var elem_list;
 2094: 
 2095:             for(var i = 0; i < tag_list.length; i++){
 2096:                 elem_list = document.getElementsByName(tag_list[i]);
 2097:                 
 2098:                 if(elem_list.length > 0){
 2099:                     elem = elem_list[0];
 2100:                     break;
 2101:                 }
 2102:             }
 2103:             elem.scrollIntoView();
 2104:         }
 2105:     }
 2106: 
 2107:     function isElementInViewport(el) {
 2108: 
 2109:         // change to last element instead of first
 2110:         var elem = document.getElementsByName(el);
 2111:         var rect = elem[0].getBoundingClientRect();
 2112: 
 2113:         return (
 2114:             rect.top >= 0 &&
 2115:             rect.left >= 0 &&
 2116:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2117:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2118:         );
 2119:     }
 2120:     
 2121:     function autosize(depth){
 2122:         var cmInst = window['cm'+depth];
 2123:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2124: 
 2125:         // is fixed size, switching to dynamic
 2126:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2127:             cmInst.setSize("","auto");
 2128:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2129:             sessionStorage.setItem("autosized_"+depth, "yes");
 2130: 
 2131:         // is dynamic size, switching to fixed
 2132:         } else {
 2133:             cmInst.setSize("","300px");
 2134:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2135:             sessionStorage.removeItem("autosized_"+depth);
 2136:         }
 2137:     }
 2138: 
 2139: $browse_or_search
 2140: 
 2141: // ]]>
 2142: </script>
 2143: COLORFULEDIT
 2144: }
 2145: 
 2146: sub xmleditor_js {
 2147:     return <<XMLEDIT
 2148: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2149: <script type="text/javascript">
 2150: // <![CDATA[>
 2151: 
 2152:     function saveScrollPosition (resource) {
 2153: 
 2154:         var scrollPos = \$(window).scrollTop();
 2155:         sessionStorage.setItem(resource,scrollPos);
 2156:     }
 2157: 
 2158:     function restoreScrollPosition(resource){
 2159: 
 2160:         var scrollPos = sessionStorage.getItem(resource);
 2161:         \$(window).scrollTop(scrollPos);
 2162:     }
 2163: 
 2164:     // unless internet explorer
 2165:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2166: 
 2167:         \$(document).ready(function() {
 2168:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2169:         });
 2170:     }
 2171: 
 2172:     // inserts text at cursor position into codemirror (xml editor only)
 2173:     function insertText(text){
 2174:         cm.focus();
 2175:         var curPos = cm.getCursor();
 2176:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2177:     }
 2178: // ]]>
 2179: </script>
 2180: XMLEDIT
 2181: }
 2182: 
 2183: sub insert_folding_button {
 2184:     my $curDepth = $Apache::lonxml::curdepth;
 2185:     my $lastresource = $env{'request.ambiguous'};
 2186: 
 2187:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2188:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2189: }
 2190: 
 2191: sub crsauthor_url {
 2192:     my ($url) = @_;
 2193:     if ($url eq '') {
 2194:         $url = $ENV{'REQUEST_URI'};
 2195:     }
 2196:     my ($cnum,$cdom);
 2197:     if ($env{'request.course.id'}) {
 2198:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2199:         if ($audom ne '' && $auname ne '') {
 2200:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2201:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2202:                 $cnum = $auname;
 2203:                 $cdom = $audom;
 2204:             }
 2205:         }
 2206:     }
 2207:     return ($cnum,$cdom);
 2208: }
 2209: 
 2210: sub import_crsauthor_form {
 2211:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2212:     return (0) unless ($env{'request.course.id'});
 2213:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2215:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2216:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2217:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2218:     my @ids=&Apache::lonnet::current_machine_ids();
 2219:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2220:     
 2221:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2222:         $is_home = 1;
 2223:     }
 2224:     $relpath = "/priv/$cdom/$cnum";
 2225:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2226:     my %lt = &Apache::lonlocal::texthash (
 2227:         fnam => 'Filename',
 2228:         dire => 'Directory',
 2229:     );
 2230:     my $numdirs = scalar(keys(%files));
 2231:     my (%possexts,$singledir,@singledirfiles);
 2232:     if ($only) {
 2233:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2234:     }
 2235:     my (%nonemptydirs,$possdirs);
 2236:     if ($numdirs > 1) {
 2237:         my @order;
 2238:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2239:             if (ref($files{$key}) eq 'HASH') {
 2240:                 my $shown = $key;
 2241:                 if ($key eq '') {
 2242:                     $shown = '/';
 2243:                 }
 2244:                 my @ordered = ();
 2245:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2246:                     next if ($file =~ /\.rights$/);
 2247:                     if ($only) {
 2248:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2249:                         unless ($possexts{lc($ext)}) {
 2250:                             next;
 2251:                         }
 2252:                     }
 2253:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2254:                     push(@ordered,$file);
 2255:                 }
 2256:                 if (@ordered) {
 2257:                     push(@order,$key);
 2258:                     $nonemptydirs{$key} = 1;
 2259:                     $selimport_menus{$key}->{'text'} = $shown;
 2260:                     $selimport_menus{$key}->{'default'} = '';
 2261:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2262:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2263:                 }
 2264:             }
 2265:         }
 2266:         $possdirs = scalar(keys(%nonemptydirs));
 2267:         if ($possdirs > 1) {
 2268:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2269:             $output = $lt{'dire'}.
 2270:                       &linked_select_forms($form,'<br />'.
 2271:                                            $lt{'fnam'},'',
 2272:                                            $firstselectname,$secondselectname,
 2273:                                            \%selimport_menus,\@order,
 2274:                                            $onchangefirst,'',$suffix).'<br />';
 2275:         } elsif ($possdirs == 1) {
 2276:             $singledir = (keys(%nonemptydirs))[0];
 2277:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2278:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2279:             }
 2280:             delete($selimport_menus{$singledir});
 2281:         }
 2282:     } elsif ($numdirs == 1) {
 2283:         $singledir = (keys(%files))[0];
 2284:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2285:             if ($only) {
 2286:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2287:                 unless ($possexts{lc($ext)}) {
 2288:                     next;
 2289:                 }
 2290:             } else {
 2291:                 next if ($file =~ /\.rights$/);
 2292:             }
 2293:             push(@singledirfiles,$file);
 2294:         }
 2295:         if (@singledirfiles) {
 2296:             $possdirs = 1;
 2297:         }
 2298:     }
 2299:     if (($possdirs == 1) && (@singledirfiles)) {
 2300:         my $showdir = $singledir;
 2301:         if ($singledir eq '') {
 2302:             $showdir = '/';
 2303:         }
 2304:         $output = $lt{'dire'}.
 2305:                   '<select name="'.$firstselectname.'">'.
 2306:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2307:                   '</select><br />'.
 2308:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2309:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2310:         foreach my $file (@singledirfiles) {
 2311:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2312:         }
 2313:         $output .= '</select><br />'."\n";
 2314:     }
 2315:     return ($possdirs,$output);
 2316: }
 2317: 
 2318: =pod
 2319: 
 2320: =head1 Excel and CSV file utility routines
 2321: 
 2322: =cut
 2323: 
 2324: ###############################################################
 2325: ###############################################################
 2326: 
 2327: =pod
 2328: 
 2329: =over 4
 2330: 
 2331: =item * &csv_translate($text) 
 2332: 
 2333: Translate $text to allow it to be output as a 'comma separated values' 
 2334: format.
 2335: 
 2336: =cut
 2337: 
 2338: ###############################################################
 2339: ###############################################################
 2340: sub csv_translate {
 2341:     my $text = shift;
 2342:     $text =~ s/\"/\"\"/g;
 2343:     $text =~ s/\n/ /g;
 2344:     return $text;
 2345: }
 2346: 
 2347: ###############################################################
 2348: ###############################################################
 2349: 
 2350: =pod
 2351: 
 2352: =item * &define_excel_formats()
 2353: 
 2354: Define some commonly used Excel cell formats.
 2355: 
 2356: Currently supported formats:
 2357: 
 2358: =over 4
 2359: 
 2360: =item header
 2361: 
 2362: =item bold
 2363: 
 2364: =item h1
 2365: 
 2366: =item h2
 2367: 
 2368: =item h3
 2369: 
 2370: =item h4
 2371: 
 2372: =item i
 2373: 
 2374: =item date
 2375: 
 2376: =back
 2377: 
 2378: Inputs: $workbook
 2379: 
 2380: Returns: $format, a hash reference.
 2381: 
 2382: 
 2383: =cut
 2384: 
 2385: ###############################################################
 2386: ###############################################################
 2387: sub define_excel_formats {
 2388:     my ($workbook) = @_;
 2389:     my $format;
 2390:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2391:                                                 bottom    => 1,
 2392:                                                 align     => 'center');
 2393:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2394:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2395:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2396:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2397:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2398:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2399:     $format->{'date'} = $workbook->add_format(num_format=>
 2400:                                             'mm/dd/yyyy hh:mm:ss');
 2401:     return $format;
 2402: }
 2403: 
 2404: ###############################################################
 2405: ###############################################################
 2406: 
 2407: =pod
 2408: 
 2409: =item * &create_workbook()
 2410: 
 2411: Create an Excel worksheet.  If it fails, output message on the
 2412: request object and return undefs.
 2413: 
 2414: Inputs: Apache request object
 2415: 
 2416: Returns (undef) on failure, 
 2417:     Excel worksheet object, scalar with filename, and formats 
 2418:     from &Apache::loncommon::define_excel_formats on success
 2419: 
 2420: =cut
 2421: 
 2422: ###############################################################
 2423: ###############################################################
 2424: sub create_workbook {
 2425:     my ($r) = @_;
 2426:         #
 2427:     # Create the excel spreadsheet
 2428:     my $filename = '/prtspool/'.
 2429:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2430:         time.'_'.rand(1000000000).'.xls';
 2431:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2432:     if (! defined($workbook)) {
 2433:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2434:         $r->print(
 2435:             '<p class="LC_error">'
 2436:            .&mt('Problems occurred in creating the new Excel file.')
 2437:            .' '.&mt('This error has been logged.')
 2438:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2439:            .'</p>'
 2440:         );
 2441:         return (undef);
 2442:     }
 2443:     #
 2444:     $workbook->set_tempdir(LONCAPA::tempdir());
 2445:     #
 2446:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2447:     return ($workbook,$filename,$format);
 2448: }
 2449: 
 2450: ###############################################################
 2451: ###############################################################
 2452: 
 2453: =pod
 2454: 
 2455: =item * &create_text_file()
 2456: 
 2457: Create a file to write to and eventually make available to the user.
 2458: If file creation fails, outputs an error message on the request object and 
 2459: return undefs.
 2460: 
 2461: Inputs: Apache request object, and file suffix
 2462: 
 2463: Returns (undef) on failure, 
 2464:     Filehandle and filename on success.
 2465: 
 2466: =cut
 2467: 
 2468: ###############################################################
 2469: ###############################################################
 2470: sub create_text_file {
 2471:     my ($r,$suffix) = @_;
 2472:     if (! defined($suffix)) { $suffix = 'txt'; };
 2473:     my $fh;
 2474:     my $filename = '/prtspool/'.
 2475:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2476:         time.'_'.rand(1000000000).'.'.$suffix;
 2477:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2478:     if (! defined($fh)) {
 2479:         $r->log_error("Couldn't open $filename for output $!");
 2480:         $r->print(
 2481:             '<p class="LC_error">'
 2482:            .&mt('Problems occurred in creating the output file.')
 2483:            .' '.&mt('This error has been logged.')
 2484:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2485:            .'</p>'
 2486:         );
 2487:     }
 2488:     return ($fh,$filename)
 2489: }
 2490: 
 2491: 
 2492: =pod 
 2493: 
 2494: =back
 2495: 
 2496: =cut
 2497: 
 2498: ###############################################################
 2499: ##        Home server <option> list generating code          ##
 2500: ###############################################################
 2501: 
 2502: # ------------------------------------------
 2503: 
 2504: sub domain_select {
 2505:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2506:     my @possdoms;
 2507:     if (ref($incdoms) eq 'ARRAY') {
 2508:         @possdoms = @{$incdoms};
 2509:     } else {
 2510:         @possdoms = &Apache::lonnet::all_domains();
 2511:     }
 2512: 
 2513:     my %domains=map { 
 2514: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2515:     } @possdoms;
 2516: 
 2517:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2518:         foreach my $dom (@{$excdoms}) {
 2519:             delete($domains{$dom});
 2520:         }
 2521:     }
 2522: 
 2523:     if ($multiple) {
 2524: 	$domains{''}=&mt('Any domain');
 2525: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2526: 	return &multiple_select_form($name,$value,4,\%domains);
 2527:     } else {
 2528: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2529: 	return &select_form($name,$value,\%domains);
 2530:     }
 2531: }
 2532: 
 2533: #-------------------------------------------
 2534: 
 2535: =pod
 2536: 
 2537: =head1 Routines for form select boxes
 2538: 
 2539: =over 4
 2540: 
 2541: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2542: 
 2543: Returns a string containing a <select> element int multiple mode
 2544: 
 2545: 
 2546: Args:
 2547:   $name - name of the <select> element
 2548:   $value - scalar or array ref of values that should already be selected
 2549:   $size - number of rows long the select element is
 2550:   $hash - the elements should be 'option' => 'shown text'
 2551:           (shown text should already have been &mt())
 2552:   $order - (optional) array ref of the order to show the elements in
 2553: 
 2554: =cut
 2555: 
 2556: #-------------------------------------------
 2557: sub multiple_select_form {
 2558:     my ($name,$value,$size,$hash,$order)=@_;
 2559:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2560:     my $output='';
 2561:     if (! defined($size)) {
 2562:         $size = 4;
 2563:         if (scalar(keys(%$hash))<4) {
 2564:             $size = scalar(keys(%$hash));
 2565:         }
 2566:     }
 2567:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2568:     my @order;
 2569:     if (ref($order) eq 'ARRAY')  {
 2570:         @order = @{$order};
 2571:     } else {
 2572:         @order = sort(keys(%$hash));
 2573:     }
 2574:     if (exists($$hash{'select_form_order'})) {
 2575:         @order = @{$$hash{'select_form_order'}};
 2576:     }
 2577:         
 2578:     foreach my $key (@order) {
 2579:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2580:         $output.='selected="selected" ' if ($selected{$key});
 2581:         $output.='>'.$hash->{$key}."</option>\n";
 2582:     }
 2583:     $output.="</select>\n";
 2584:     return $output;
 2585: }
 2586: 
 2587: #-------------------------------------------
 2588: 
 2589: =pod
 2590: 
 2591: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2592: 
 2593: Returns a string containing a <select name='$name' size='1'> form to 
 2594: allow a user to select options from a ref to a hash containing:
 2595: option_name => displayed text. An optional $onchange can include
 2596: a javascript onchange item, e.g., onchange="this.form.submit();".
 2597: An optional arg -- $readonly -- if true will cause the select form
 2598: to be disabled, e.g., for the case where an instructor has a section-
 2599: specific role, and is viewing/modifying parameters. 
 2600: 
 2601: See lonrights.pm for an example invocation and use.
 2602: 
 2603: =cut
 2604: 
 2605: #-------------------------------------------
 2606: sub select_form {
 2607:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2608:     return unless (ref($hashref) eq 'HASH');
 2609:     if ($onchange) {
 2610:         $onchange = ' onchange="'.$onchange.'"';
 2611:     }
 2612:     my $disabled;
 2613:     if ($readonly) {
 2614:         $disabled = ' disabled="disabled"';
 2615:     }
 2616:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2617:     my @keys;
 2618:     if (exists($hashref->{'select_form_order'})) {
 2619: 	@keys=@{$hashref->{'select_form_order'}};
 2620:     } else {
 2621: 	@keys=sort(keys(%{$hashref}));
 2622:     }
 2623:     foreach my $key (@keys) {
 2624:         $selectform.=
 2625: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2626:             ($key eq $def ? 'selected="selected" ' : '').
 2627:                 ">".$hashref->{$key}."</option>\n";
 2628:     }
 2629:     $selectform.="</select>";
 2630:     return $selectform;
 2631: }
 2632: 
 2633: # For display filters
 2634: 
 2635: sub display_filter {
 2636:     my ($context) = @_;
 2637:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2638:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2639:     my $phraseinput = 'hidden';
 2640:     my $includeinput = 'hidden';
 2641:     my ($checked,$includetypestext);
 2642:     if ($env{'form.displayfilter'} eq 'containing') {
 2643:         $phraseinput = 'text'; 
 2644:         if ($context eq 'parmslog') {
 2645:             $includeinput = 'checkbox';
 2646:             if ($env{'form.includetypes'}) {
 2647:                 $checked = ' checked="checked"';
 2648:             }
 2649:             $includetypestext = &mt('Include parameter types');
 2650:         }
 2651:     } else {
 2652:         $includetypestext = '&nbsp;';
 2653:     }
 2654:     my ($additional,$secondid,$thirdid);
 2655:     if ($context eq 'parmslog') {
 2656:         $additional = 
 2657:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2658:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2659:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2660:             '</label>';
 2661:         $secondid = 'includetypes';
 2662:         $thirdid = 'includetypestext';
 2663:     }
 2664:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2665:                                                     '$secondid','$thirdid')";
 2666:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2667: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2668: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2669: 	   '</label></span> <span class="LC_nobreak">'.
 2670:            &mt('Filter: [_1]',
 2671: 	   &select_form($env{'form.displayfilter'},
 2672: 			'displayfilter',
 2673: 			{'currentfolder' => 'Current folder/page',
 2674: 			 'containing' => 'Containing phrase',
 2675: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2676: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2677:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2678:                          '" />'.$additional;
 2679: }
 2680: 
 2681: sub display_filter_js {
 2682:     my $includetext = &mt('Include parameter types');
 2683:     return <<"ENDJS";
 2684:   
 2685: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2686:     var firstType = 'hidden';
 2687:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2688:         firstType = 'text';
 2689:     }
 2690:     firstObject = document.getElementById(firstid);
 2691:     if (typeof(firstObject) == 'object') {
 2692:         if (firstObject.type != firstType) {
 2693:             changeInputType(firstObject,firstType);
 2694:         }
 2695:     }
 2696:     if (context == 'parmslog') {
 2697:         var secondType = 'hidden';
 2698:         if (firstType == 'text') {
 2699:             secondType = 'checkbox';
 2700:         }
 2701:         secondObject = document.getElementById(secondid);  
 2702:         if (typeof(secondObject) == 'object') {
 2703:             if (secondObject.type != secondType) {
 2704:                 changeInputType(secondObject,secondType);
 2705:             }
 2706:         }
 2707:         var textItem = document.getElementById(thirdid);
 2708:         var currtext = textItem.innerHTML;
 2709:         var newtext;
 2710:         if (firstType == 'text') {
 2711:             newtext = '$includetext';
 2712:         } else {
 2713:             newtext = '&nbsp;';
 2714:         }
 2715:         if (currtext != newtext) {
 2716:             textItem.innerHTML = newtext;
 2717:         }
 2718:     }
 2719:     return;
 2720: }
 2721: 
 2722: function changeInputType(oldObject,newType) {
 2723:     var newObject = document.createElement('input');
 2724:     newObject.type = newType;
 2725:     if (oldObject.size) {
 2726:         newObject.size = oldObject.size;
 2727:     }
 2728:     if (oldObject.value) {
 2729:         newObject.value = oldObject.value;
 2730:     }
 2731:     if (oldObject.name) {
 2732:         newObject.name = oldObject.name;
 2733:     }
 2734:     if (oldObject.id) {
 2735:         newObject.id = oldObject.id;
 2736:     }
 2737:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2738:     return;
 2739: }
 2740: 
 2741: ENDJS
 2742: }
 2743: 
 2744: sub gradeleveldescription {
 2745:     my $gradelevel=shift;
 2746:     my %gradelevels=(0 => 'Not specified',
 2747: 		     1 => 'Grade 1',
 2748: 		     2 => 'Grade 2',
 2749: 		     3 => 'Grade 3',
 2750: 		     4 => 'Grade 4',
 2751: 		     5 => 'Grade 5',
 2752: 		     6 => 'Grade 6',
 2753: 		     7 => 'Grade 7',
 2754: 		     8 => 'Grade 8',
 2755: 		     9 => 'Grade 9',
 2756: 		     10 => 'Grade 10',
 2757: 		     11 => 'Grade 11',
 2758: 		     12 => 'Grade 12',
 2759: 		     13 => 'Grade 13',
 2760: 		     14 => '100 Level',
 2761: 		     15 => '200 Level',
 2762: 		     16 => '300 Level',
 2763: 		     17 => '400 Level',
 2764: 		     18 => 'Graduate Level');
 2765:     return &mt($gradelevels{$gradelevel});
 2766: }
 2767: 
 2768: sub select_level_form {
 2769:     my ($deflevel,$name)=@_;
 2770:     unless ($deflevel) { $deflevel=0; }
 2771:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2772:     for (my $i=0; $i<=18; $i++) {
 2773:         $selectform.="<option value=\"$i\" ".
 2774:             ($i==$deflevel ? 'selected="selected" ' : '').
 2775:                 ">".&gradeleveldescription($i)."</option>\n";
 2776:     }
 2777:     $selectform.="</select>";
 2778:     return $selectform;
 2779: }
 2780: 
 2781: #-------------------------------------------
 2782: 
 2783: =pod
 2784: 
 2785: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2786: 
 2787: Returns a string containing a <select name='$name' size='1'> form to 
 2788: allow a user to select the domain to preform an operation in.  
 2789: See loncreateuser.pm for an example invocation and use.
 2790: 
 2791: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2792: selected");
 2793: 
 2794: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2795: 
 2796: 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.
 2797: 
 2798: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2799: 
 2800: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2801: 
 2802: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2803: 
 2804: =cut
 2805: 
 2806: #-------------------------------------------
 2807: sub select_dom_form {
 2808:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2809:     if ($onchange) {
 2810:         $onchange = ' onchange="'.$onchange.'"';
 2811:     }
 2812:     if ($disabled) {
 2813:         $disabled = ' disabled="disabled"';
 2814:     }
 2815:     my (@domains,%exclude);
 2816:     if (ref($incdoms) eq 'ARRAY') {
 2817:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2818:     } else {
 2819:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2820:     }
 2821:     if ($includeempty) { @domains=('',@domains); }
 2822:     if (ref($excdoms) eq 'ARRAY') {
 2823:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2824:     }
 2825:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2826:     foreach my $dom (@domains) {
 2827:         next if ($exclude{$dom});
 2828:         $selectdomain.="<option value=\"$dom\" ".
 2829:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2830:         if ($showdomdesc) {
 2831:             if ($dom ne '') {
 2832:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2833:                 if ($domdesc ne '') {
 2834:                     $selectdomain .= ' ('.$domdesc.')';
 2835:                 }
 2836:             } 
 2837:         }
 2838:         $selectdomain .= "</option>\n";
 2839:     }
 2840:     $selectdomain.="</select>";
 2841:     return $selectdomain;
 2842: }
 2843: 
 2844: #-------------------------------------------
 2845: 
 2846: =pod
 2847: 
 2848: =item * &home_server_form_item($domain,$name,$defaultflag)
 2849: 
 2850: input: 4 arguments (two required, two optional) - 
 2851:     $domain - domain of new user
 2852:     $name - name of form element
 2853:     $default - Value of 'default' causes a default item to be first 
 2854:                             option, and selected by default. 
 2855:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2856:                             if 1 server found, or default, if 0 found.
 2857: output: returns 2 items: 
 2858: (a) form element which contains either:
 2859:    (i) <select name="$name">
 2860:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2861:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2862:        </select>
 2863:        form item if there are multiple library servers in $domain, or
 2864:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2865:        if there is only one library server in $domain.
 2866: 
 2867: (b) number of library servers found.
 2868: 
 2869: See loncreateuser.pm for example of use.
 2870: 
 2871: =cut
 2872: 
 2873: #-------------------------------------------
 2874: sub home_server_form_item {
 2875:     my ($domain,$name,$default,$hide) = @_;
 2876:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2877:     my $result;
 2878:     my $numlib = keys(%servers);
 2879:     if ($numlib > 1) {
 2880:         $result .= '<select name="'.$name.'" />'."\n";
 2881:         if ($default) {
 2882:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2883:                        '</option>'."\n";
 2884:         }
 2885:         foreach my $hostid (sort(keys(%servers))) {
 2886:             $result.= '<option value="'.$hostid.'">'.
 2887: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2888:         }
 2889:         $result .= '</select>'."\n";
 2890:     } elsif ($numlib == 1) {
 2891:         my $hostid;
 2892:         foreach my $item (keys(%servers)) {
 2893:             $hostid = $item;
 2894:         }
 2895:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2896:                    $hostid.'" />';
 2897:                    if (!$hide) {
 2898:                        $result .= $hostid.' '.$servers{$hostid};
 2899:                    }
 2900:                    $result .= "\n";
 2901:     } elsif ($default) {
 2902:         $result .= '<input type="hidden" name="'.$name.
 2903:                    '" value="default" />';
 2904:                    if (!$hide) {
 2905:                        $result .= &mt('default');
 2906:                    }
 2907:                    $result .= "\n";
 2908:     }
 2909:     return ($result,$numlib);
 2910: }
 2911: 
 2912: =pod
 2913: 
 2914: =back 
 2915: 
 2916: =cut
 2917: 
 2918: ###############################################################
 2919: ##                  Decoding User Agent                      ##
 2920: ###############################################################
 2921: 
 2922: =pod
 2923: 
 2924: =head1 Decoding the User Agent
 2925: 
 2926: =over 4
 2927: 
 2928: =item * &decode_user_agent()
 2929: 
 2930: Inputs: $r
 2931: 
 2932: Outputs:
 2933: 
 2934: =over 4
 2935: 
 2936: =item * $httpbrowser
 2937: 
 2938: =item * $clientbrowser
 2939: 
 2940: =item * $clientversion
 2941: 
 2942: =item * $clientmathml
 2943: 
 2944: =item * $clientunicode
 2945: 
 2946: =item * $clientos
 2947: 
 2948: =item * $clientmobile
 2949: 
 2950: =item * $clientinfo
 2951: 
 2952: =item * $clientosversion
 2953: 
 2954: =back
 2955: 
 2956: =back 
 2957: 
 2958: =cut
 2959: 
 2960: ###############################################################
 2961: ###############################################################
 2962: sub decode_user_agent {
 2963:     my ($r)=@_;
 2964:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2965:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2966:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2967:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2968:     my $clientbrowser='unknown';
 2969:     my $clientversion='0';
 2970:     my $clientmathml='';
 2971:     my $clientunicode='0';
 2972:     my $clientmobile=0;
 2973:     my $clientosversion='';
 2974:     for (my $i=0;$i<=$#browsertype;$i++) {
 2975:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2976: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2977: 	    $clientbrowser=$bname;
 2978:             $httpbrowser=~/$vreg/i;
 2979: 	    $clientversion=$1;
 2980:             $clientmathml=($clientversion>=$minv);
 2981:             $clientunicode=($clientversion>=$univ);
 2982: 	}
 2983:     }
 2984:     my $clientos='unknown';
 2985:     my $clientinfo;
 2986:     if (($httpbrowser=~/linux/i) ||
 2987:         ($httpbrowser=~/unix/i) ||
 2988:         ($httpbrowser=~/ux/i) ||
 2989:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2990:     if (($httpbrowser=~/vax/i) ||
 2991:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2992:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2993:     if (($httpbrowser=~/mac/i) ||
 2994:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2995:     if ($httpbrowser=~/win/i) {
 2996:         $clientos='win';
 2997:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2998:             $clientosversion = $1;
 2999:         }
 3000:     }
 3001:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3002:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3003:         $clientmobile=lc($1);
 3004:     }
 3005:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3006:         $clientinfo = 'firefox-'.$1;
 3007:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3008:         $clientinfo = 'chromeframe-'.$1;
 3009:     }
 3010:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3011:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3012:             $clientosversion);
 3013: }
 3014: 
 3015: ###############################################################
 3016: ##    Authentication changing form generation subroutines    ##
 3017: ###############################################################
 3018: ##
 3019: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3020: ## hash, and have reasonable default values.
 3021: ##
 3022: ##    formname = the name given in the <form> tag.
 3023: #-------------------------------------------
 3024: 
 3025: =pod
 3026: 
 3027: =head1 Authentication Routines
 3028: 
 3029: =over 4
 3030: 
 3031: =item * &authform_xxxxxx()
 3032: 
 3033: The authform_xxxxxx subroutines provide javascript and html forms which 
 3034: handle some of the conveniences required for authentication forms.  
 3035: This is not an optimal method, but it works.  
 3036: 
 3037: =over 4
 3038: 
 3039: =item * authform_header
 3040: 
 3041: =item * authform_authorwarning
 3042: 
 3043: =item * authform_nochange
 3044: 
 3045: =item * authform_kerberos
 3046: 
 3047: =item * authform_internal
 3048: 
 3049: =item * authform_filesystem
 3050: 
 3051: =item * authform_lti
 3052: 
 3053: =back
 3054: 
 3055: See loncreateuser.pm for invocation and use examples.
 3056: 
 3057: =cut
 3058: 
 3059: #-------------------------------------------
 3060: sub authform_header{  
 3061:     my %in = (
 3062:         formname => 'cu',
 3063:         kerb_def_dom => '',
 3064:         @_,
 3065:     );
 3066:     $in{'formname'} = 'document.' . $in{'formname'};
 3067:     my $result='';
 3068: 
 3069: #---------------------------------------------- Code for upper case translation
 3070:     my $Javascript_toUpperCase;
 3071:     unless ($in{kerb_def_dom}) {
 3072:         $Javascript_toUpperCase =<<"END";
 3073:         switch (choice) {
 3074:            case 'krb': currentform.elements[choicearg].value =
 3075:                currentform.elements[choicearg].value.toUpperCase();
 3076:                break;
 3077:            default:
 3078:         }
 3079: END
 3080:     } else {
 3081:         $Javascript_toUpperCase = "";
 3082:     }
 3083: 
 3084:     my $radioval = "'nochange'";
 3085:     if (defined($in{'curr_authtype'})) {
 3086:         if ($in{'curr_authtype'} ne '') {
 3087:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3088:         }
 3089:     }
 3090:     my $argfield = 'null';
 3091:     if (defined($in{'mode'})) {
 3092:         if ($in{'mode'} eq 'modifycourse')  {
 3093:             if (defined($in{'curr_autharg'})) {
 3094:                 if ($in{'curr_autharg'} ne '') {
 3095:                     $argfield = "'$in{'curr_autharg'}'";
 3096:                 }
 3097:             }
 3098:         }
 3099:     }
 3100: 
 3101:     $result.=<<"END";
 3102: var current = new Object();
 3103: current.radiovalue = $radioval;
 3104: current.argfield = $argfield;
 3105: 
 3106: function changed_radio(choice,currentform) {
 3107:     var choicearg = choice + 'arg';
 3108:     // If a radio button in changed, we need to change the argfield
 3109:     if (current.radiovalue != choice) {
 3110:         current.radiovalue = choice;
 3111:         if (current.argfield != null) {
 3112:             currentform.elements[current.argfield].value = '';
 3113:         }
 3114:         if (choice == 'nochange') {
 3115:             current.argfield = null;
 3116:         } else {
 3117:             current.argfield = choicearg;
 3118:             switch(choice) {
 3119:                 case 'krb': 
 3120:                     currentform.elements[current.argfield].value = 
 3121:                         "$in{'kerb_def_dom'}";
 3122:                 break;
 3123:               default:
 3124:                 break;
 3125:             }
 3126:         }
 3127:     }
 3128:     return;
 3129: }
 3130: 
 3131: function changed_text(choice,currentform) {
 3132:     var choicearg = choice + 'arg';
 3133:     if (currentform.elements[choicearg].value !='') {
 3134:         $Javascript_toUpperCase
 3135:         // clear old field
 3136:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3137:             currentform.elements[current.argfield].value = '';
 3138:         }
 3139:         current.argfield = choicearg;
 3140:     }
 3141:     set_auth_radio_buttons(choice,currentform);
 3142:     return;
 3143: }
 3144: 
 3145: function set_auth_radio_buttons(newvalue,currentform) {
 3146:     var numauthchoices = currentform.login.length;
 3147:     if (typeof numauthchoices  == "undefined") {
 3148:         return;
 3149:     } 
 3150:     var i=0;
 3151:     while (i < numauthchoices) {
 3152:         if (currentform.login[i].value == newvalue) { break; }
 3153:         i++;
 3154:     }
 3155:     if (i == numauthchoices) {
 3156:         return;
 3157:     }
 3158:     current.radiovalue = newvalue;
 3159:     currentform.login[i].checked = true;
 3160:     return;
 3161: }
 3162: END
 3163:     return $result;
 3164: }
 3165: 
 3166: sub authform_authorwarning {
 3167:     my $result='';
 3168:     $result='<i>'.
 3169:         &mt('As a general rule, only authors or co-authors should be '.
 3170:             'filesystem authenticated '.
 3171:             '(which allows access to the server filesystem).')."</i>\n";
 3172:     return $result;
 3173: }
 3174: 
 3175: sub authform_nochange {
 3176:     my %in = (
 3177:               formname => 'document.cu',
 3178:               kerb_def_dom => 'MSU.EDU',
 3179:               @_,
 3180:           );
 3181:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3182:     my $result;
 3183:     if (!$authnum) {
 3184:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3185:     } else {
 3186:         $result = '<label>'.&mt('[_1] Do not change login data',
 3187:                   '<input type="radio" name="login" value="nochange" '.
 3188:                   'checked="checked" onclick="'.
 3189:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3190: 	    '</label>';
 3191:     }
 3192:     return $result;
 3193: }
 3194: 
 3195: sub authform_kerberos {
 3196:     my %in = (
 3197:               formname => 'document.cu',
 3198:               kerb_def_dom => 'MSU.EDU',
 3199:               kerb_def_auth => 'krb4',
 3200:               @_,
 3201:               );
 3202:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3203:         $autharg,$jscall,$disabled);
 3204:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3205:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3206:        $check5 = ' checked="checked"';
 3207:     } else {
 3208:        $check4 = ' checked="checked"';
 3209:     }
 3210:     if ($in{'readonly'}) {
 3211:         $disabled = ' disabled="disabled"';
 3212:     }
 3213:     $krbarg = $in{'kerb_def_dom'};
 3214:     if (defined($in{'curr_authtype'})) {
 3215:         if ($in{'curr_authtype'} eq 'krb') {
 3216:             $krbcheck = ' checked="checked"';
 3217:             if (defined($in{'mode'})) {
 3218:                 if ($in{'mode'} eq 'modifyuser') {
 3219:                     $krbcheck = '';
 3220:                 }
 3221:             }
 3222:             if (defined($in{'curr_kerb_ver'})) {
 3223:                 if ($in{'curr_krb_ver'} eq '5') {
 3224:                     $check5 = ' checked="checked"';
 3225:                     $check4 = '';
 3226:                 } else {
 3227:                     $check4 = ' checked="checked"';
 3228:                     $check5 = '';
 3229:                 }
 3230:             }
 3231:             if (defined($in{'curr_autharg'})) {
 3232:                 $krbarg = $in{'curr_autharg'};
 3233:             }
 3234:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3235:                 if (defined($in{'curr_autharg'})) {
 3236:                     $result = 
 3237:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3238:         $in{'curr_autharg'},$krbver);
 3239:                 } else {
 3240:                     $result =
 3241:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3242:                 }
 3243:                 return $result; 
 3244:             }
 3245:         }
 3246:     } else {
 3247:         if ($authnum == 1) {
 3248:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3249:         }
 3250:     }
 3251:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3252:         return;
 3253:     } elsif ($authtype eq '') {
 3254:         if (defined($in{'mode'})) {
 3255:             if ($in{'mode'} eq 'modifycourse') {
 3256:                 if ($authnum == 1) {
 3257:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3258:                 }
 3259:             }
 3260:         }
 3261:     }
 3262:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3263:     if ($authtype eq '') {
 3264:         $authtype = '<input type="radio" name="login" value="krb" '.
 3265:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3266:                     $krbcheck.$disabled.' />';
 3267:     }
 3268:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3269:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3270:          $in{'curr_authtype'} eq 'krb5') ||
 3271:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3272:          $in{'curr_authtype'} eq 'krb4')) {
 3273:         $result .= &mt
 3274:         ('[_1] Kerberos authenticated with domain [_2] '.
 3275:          '[_3] Version 4 [_4] Version 5 [_5]',
 3276:          '<label>'.$authtype,
 3277:          '</label><input type="text" size="10" name="krbarg" '.
 3278:              'value="'.$krbarg.'" '.
 3279:              'onchange="'.$jscall.'"'.$disabled.' />',
 3280:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3281:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3282: 	 '</label>');
 3283:     } elsif ($can_assign{'krb4'}) {
 3284:         $result .= &mt
 3285:         ('[_1] Kerberos authenticated with domain [_2] '.
 3286:          '[_3] Version 4 [_4]',
 3287:          '<label>'.$authtype,
 3288:          '</label><input type="text" size="10" name="krbarg" '.
 3289:              'value="'.$krbarg.'" '.
 3290:              'onchange="'.$jscall.'"'.$disabled.' />',
 3291:          '<label><input type="hidden" name="krbver" value="4" />',
 3292:          '</label>');
 3293:     } elsif ($can_assign{'krb5'}) {
 3294:         $result .= &mt
 3295:         ('[_1] Kerberos authenticated with domain [_2] '.
 3296:          '[_3] Version 5 [_4]',
 3297:          '<label>'.$authtype,
 3298:          '</label><input type="text" size="10" name="krbarg" '.
 3299:              'value="'.$krbarg.'" '.
 3300:              'onchange="'.$jscall.'"'.$disabled.' />',
 3301:          '<label><input type="hidden" name="krbver" value="5" />',
 3302:          '</label>');
 3303:     }
 3304:     return $result;
 3305: }
 3306: 
 3307: sub authform_internal {
 3308:     my %in = (
 3309:                 formname => 'document.cu',
 3310:                 kerb_def_dom => 'MSU.EDU',
 3311:                 @_,
 3312:                 );
 3313:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3314:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3315:     if ($in{'readonly'}) {
 3316:         $disabled = ' disabled="disabled"';
 3317:     }
 3318:     if (defined($in{'curr_authtype'})) {
 3319:         if ($in{'curr_authtype'} eq 'int') {
 3320:             if ($can_assign{'int'}) {
 3321:                 $intcheck = 'checked="checked" ';
 3322:                 if (defined($in{'mode'})) {
 3323:                     if ($in{'mode'} eq 'modifyuser') {
 3324:                         $intcheck = '';
 3325:                     }
 3326:                 }
 3327:                 if (defined($in{'curr_autharg'})) {
 3328:                     $intarg = $in{'curr_autharg'};
 3329:                 }
 3330:             } else {
 3331:                 $result = &mt('Currently internally authenticated.');
 3332:                 return $result;
 3333:             }
 3334:         }
 3335:     } else {
 3336:         if ($authnum == 1) {
 3337:             $authtype = '<input type="hidden" name="login" value="int" />';
 3338:         }
 3339:     }
 3340:     if (!$can_assign{'int'}) {
 3341:         return;
 3342:     } elsif ($authtype eq '') {
 3343:         if (defined($in{'mode'})) {
 3344:             if ($in{'mode'} eq 'modifycourse') {
 3345:                 if ($authnum == 1) {
 3346:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3347:                 }
 3348:             }
 3349:         }
 3350:     }
 3351:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3352:     if ($authtype eq '') {
 3353:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3354:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3355:     }
 3356:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3357:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3358:     $result = &mt
 3359:         ('[_1] Internally authenticated (with initial password [_2])',
 3360:          '<label>'.$authtype,'</label>'.$autharg);
 3361:     $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>';
 3362:     return $result;
 3363: }
 3364: 
 3365: sub authform_local {
 3366:     my %in = (
 3367:               formname => 'document.cu',
 3368:               kerb_def_dom => 'MSU.EDU',
 3369:               @_,
 3370:               );
 3371:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3372:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3373:     if ($in{'readonly'}) {
 3374:         $disabled = ' disabled="disabled"';
 3375:     } 
 3376:     if (defined($in{'curr_authtype'})) {
 3377:         if ($in{'curr_authtype'} eq 'loc') {
 3378:             if ($can_assign{'loc'}) {
 3379:                 $loccheck = 'checked="checked" ';
 3380:                 if (defined($in{'mode'})) {
 3381:                     if ($in{'mode'} eq 'modifyuser') {
 3382:                         $loccheck = '';
 3383:                     }
 3384:                 }
 3385:                 if (defined($in{'curr_autharg'})) {
 3386:                     $locarg = $in{'curr_autharg'};
 3387:                 }
 3388:             } else {
 3389:                 $result = &mt('Currently using local (institutional) authentication.');
 3390:                 return $result;
 3391:             }
 3392:         }
 3393:     } else {
 3394:         if ($authnum == 1) {
 3395:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3396:         }
 3397:     }
 3398:     if (!$can_assign{'loc'}) {
 3399:         return;
 3400:     } elsif ($authtype eq '') {
 3401:         if (defined($in{'mode'})) {
 3402:             if ($in{'mode'} eq 'modifycourse') {
 3403:                 if ($authnum == 1) {
 3404:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3405:                 }
 3406:             }
 3407:         }
 3408:     }
 3409:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3410:     if ($authtype eq '') {
 3411:         $authtype = '<input type="radio" name="login" value="loc" '.
 3412:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3413:                     $jscall.'"'.$disabled.' />';
 3414:     }
 3415:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3416:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3417:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3418:                   '<label>'.$authtype,'</label>'.$autharg);
 3419:     return $result;
 3420: }
 3421: 
 3422: sub authform_filesystem {
 3423:     my %in = (
 3424:               formname => 'document.cu',
 3425:               kerb_def_dom => 'MSU.EDU',
 3426:               @_,
 3427:               );
 3428:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3429:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3430:     if ($in{'readonly'}) {
 3431:         $disabled = ' disabled="disabled"';
 3432:     }
 3433:     if (defined($in{'curr_authtype'})) {
 3434:         if ($in{'curr_authtype'} eq 'fsys') {
 3435:             if ($can_assign{'fsys'}) {
 3436:                 $fsyscheck = 'checked="checked" ';
 3437:                 if (defined($in{'mode'})) {
 3438:                     if ($in{'mode'} eq 'modifyuser') {
 3439:                         $fsyscheck = '';
 3440:                     }
 3441:                 }
 3442:             } else {
 3443:                 $result = &mt('Currently Filesystem Authenticated.');
 3444:                 return $result;
 3445:             }
 3446:         }
 3447:     } else {
 3448:         if ($authnum == 1) {
 3449:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3450:         }
 3451:     }
 3452:     if (!$can_assign{'fsys'}) {
 3453:         return;
 3454:     } elsif ($authtype eq '') {
 3455:         if (defined($in{'mode'})) {
 3456:             if ($in{'mode'} eq 'modifycourse') {
 3457:                 if ($authnum == 1) {
 3458:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3459:                 }
 3460:             }
 3461:         }
 3462:     }
 3463:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3464:     if ($authtype eq '') {
 3465:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3466:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3467:                     $jscall.'"'.$disabled.' />';
 3468:     }
 3469:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3470:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3471:     $result = &mt
 3472:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3473:          '<label>'.$authtype,'</label>'.$autharg);
 3474:     return $result;
 3475: }
 3476: 
 3477: sub authform_lti {
 3478:     my %in = (
 3479:               formname => 'document.cu',
 3480:               kerb_def_dom => 'MSU.EDU',
 3481:               @_,
 3482:               );
 3483:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3484:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3485:     if ($in{'readonly'}) {
 3486:         $disabled = ' disabled="disabled"';
 3487:     }
 3488:     if (defined($in{'curr_authtype'})) {
 3489:         if ($in{'curr_authtype'} eq 'lti') {
 3490:             if ($can_assign{'lti'}) {
 3491:                 $lticheck = 'checked="checked" ';
 3492:                 if (defined($in{'mode'})) {
 3493:                     if ($in{'mode'} eq 'modifyuser') {
 3494:                         $lticheck = '';
 3495:                     }
 3496:                 }
 3497:             } else {
 3498:                 $result = &mt('Currently LTI Authenticated.');
 3499:                 return $result;
 3500:             }
 3501:         }
 3502:     } else {
 3503:         if ($authnum == 1) {
 3504:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3505:         }
 3506:     }
 3507:     if (!$can_assign{'lti'}) {
 3508:         return;
 3509:     } elsif ($authtype eq '') {
 3510:         if (defined($in{'mode'})) {
 3511:             if ($in{'mode'} eq 'modifycourse') {
 3512:                 if ($authnum == 1) {
 3513:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3514:                 }
 3515:             }
 3516:         }
 3517:     }
 3518:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3519:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3520:         $authtype = '<input type="radio" name="login" value="lti" '.
 3521:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3522:                     $jscall.'"'.$disabled.' />';
 3523:     }
 3524:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3525:     if ($authtype) {
 3526:         $result = &mt('[_1] LTI Authenticated',
 3527:                       '<label>'.$authtype.'</label>'.$autharg);
 3528:     } else {
 3529:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3530:                   $autharg;
 3531:     }
 3532:     return $result;
 3533: }
 3534: 
 3535: sub get_assignable_auth {
 3536:     my ($dom) = @_;
 3537:     if ($dom eq '') {
 3538:         $dom = $env{'request.role.domain'};
 3539:     }
 3540:     my %can_assign = (
 3541:                           krb4 => 1,
 3542:                           krb5 => 1,
 3543:                           int  => 1,
 3544:                           loc  => 1,
 3545:                           lti  => 1,
 3546:                      );
 3547:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3548:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3549:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3550:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3551:             my $context;
 3552:             if ($env{'request.role'} =~ /^au/) {
 3553:                 $context = 'author';
 3554:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3555:                 $context = 'domain';
 3556:             } elsif ($env{'request.course.id'}) {
 3557:                 $context = 'course';
 3558:             }
 3559:             if ($context) {
 3560:                 if (ref($authhash->{$context}) eq 'HASH') {
 3561:                    %can_assign = %{$authhash->{$context}}; 
 3562:                 }
 3563:             }
 3564:         }
 3565:     }
 3566:     my $authnum = 0;
 3567:     foreach my $key (keys(%can_assign)) {
 3568:         if ($can_assign{$key}) {
 3569:             $authnum ++;
 3570:         }
 3571:     }
 3572:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3573:         $authnum --;
 3574:     }
 3575:     return ($authnum,%can_assign);
 3576: }
 3577: 
 3578: sub check_passwd_rules {
 3579:     my ($domain,$plainpass) = @_;
 3580:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3581:     my ($min,$max,@chars,@brokerule,$warning);
 3582:     $min = $Apache::lonnet::passwdmin;
 3583:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3584:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3585:             if ($passwdconf{'min'} > $min) {
 3586:                 $min = $passwdconf{'min'};
 3587:             }
 3588:         }
 3589:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3590:             $max = $passwdconf{'max'};
 3591:         }
 3592:         @chars = @{$passwdconf{'chars'}};
 3593:     }
 3594:     if (($min) && (length($plainpass) < $min)) {
 3595:         push(@brokerule,'min');
 3596:     }
 3597:     if (($max) && (length($plainpass) > $max)) {
 3598:         push(@brokerule,'max');
 3599:     }
 3600:     if (@chars) {
 3601:         my %rules;
 3602:         map { $rules{$_} = 1; } @chars;
 3603:         if ($rules{'uc'}) {
 3604:             unless ($plainpass =~ /[A-Z]/) {
 3605:                 push(@brokerule,'uc');
 3606:             }
 3607:         }
 3608:         if ($rules{'lc'}) {
 3609:             unless ($plainpass =~ /[a-z]/) {
 3610:                 push(@brokerule,'lc');
 3611:             }
 3612:         }
 3613:         if ($rules{'num'}) {
 3614:             unless ($plainpass =~ /\d/) {
 3615:                 push(@brokerule,'num');
 3616:             }
 3617:         }
 3618:         if ($rules{'spec'}) {
 3619:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3620:                 push(@brokerule,'spec');
 3621:             }
 3622:         }
 3623:     }
 3624:     if (@brokerule) {
 3625:         my %rulenames = &Apache::lonlocal::texthash(
 3626:             uc   => 'At least one upper case letter',
 3627:             lc   => 'At least one lower case letter',
 3628:             num  => 'At least one number',
 3629:             spec => 'At least one non-alphanumeric',
 3630:         );
 3631:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3632:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3633:         $rulenames{'num'} .= ': 0123456789';
 3634:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3635:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3636:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3637:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3638:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3639:             if (grep(/^$rule$/,@brokerule)) {
 3640:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3641:             }
 3642:         }
 3643:         $warning .= '</ul>';
 3644:     }
 3645:     if (wantarray) {
 3646:         return @brokerule;
 3647:     }
 3648:     return $warning;
 3649: }
 3650: 
 3651: ###############################################################
 3652: ##    Get Kerberos Defaults for Domain                 ##
 3653: ###############################################################
 3654: ##
 3655: ## Returns default kerberos version and an associated argument
 3656: ## as listed in file domain.tab. If not listed, provides
 3657: ## appropriate default domain and kerberos version.
 3658: ##
 3659: #-------------------------------------------
 3660: 
 3661: =pod
 3662: 
 3663: =item * &get_kerberos_defaults()
 3664: 
 3665: get_kerberos_defaults($target_domain) returns the default kerberos
 3666: version and domain. If not found, it defaults to version 4 and the 
 3667: domain of the server.
 3668: 
 3669: =over 4
 3670: 
 3671: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3672: 
 3673: =back
 3674: 
 3675: =back
 3676: 
 3677: =cut
 3678: 
 3679: #-------------------------------------------
 3680: sub get_kerberos_defaults {
 3681:     my $domain=shift;
 3682:     my ($krbdef,$krbdefdom);
 3683:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3684:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3685:         $krbdef = $domdefaults{'auth_def'};
 3686:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3687:     } else {
 3688:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3689:         my $krbdefdom=$1;
 3690:         $krbdefdom=~tr/a-z/A-Z/;
 3691:         $krbdef = "krb4";
 3692:     }
 3693:     return ($krbdef,$krbdefdom);
 3694: }
 3695: 
 3696: 
 3697: ###############################################################
 3698: ##                Thesaurus Functions                        ##
 3699: ###############################################################
 3700: 
 3701: =pod
 3702: 
 3703: =head1 Thesaurus Functions
 3704: 
 3705: =over 4
 3706: 
 3707: =item * &initialize_keywords()
 3708: 
 3709: Initializes the package variable %Keywords if it is empty.  Uses the
 3710: package variable $thesaurus_db_file.
 3711: 
 3712: =cut
 3713: 
 3714: ###################################################
 3715: 
 3716: sub initialize_keywords {
 3717:     return 1 if (scalar keys(%Keywords));
 3718:     # If we are here, %Keywords is empty, so fill it up
 3719:     #   Make sure the file we need exists...
 3720:     if (! -e $thesaurus_db_file) {
 3721:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3722:                                  " failed because it does not exist");
 3723:         return 0;
 3724:     }
 3725:     #   Set up the hash as a database
 3726:     my %thesaurus_db;
 3727:     if (! tie(%thesaurus_db,'GDBM_File',
 3728:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3729:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3730:                                  $thesaurus_db_file);
 3731:         return 0;
 3732:     } 
 3733:     #  Get the average number of appearances of a word.
 3734:     my $avecount = $thesaurus_db{'average.count'};
 3735:     #  Put keywords (those that appear > average) into %Keywords
 3736:     while (my ($word,$data)=each (%thesaurus_db)) {
 3737:         my ($count,undef) = split /:/,$data;
 3738:         $Keywords{$word}++ if ($count > $avecount);
 3739:     }
 3740:     untie %thesaurus_db;
 3741:     # Remove special values from %Keywords.
 3742:     foreach my $value ('total.count','average.count') {
 3743:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3744:   }
 3745:     return 1;
 3746: }
 3747: 
 3748: ###################################################
 3749: 
 3750: =pod
 3751: 
 3752: =item * &keyword($word)
 3753: 
 3754: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3755: than the average number of times in the thesaurus database.  Calls 
 3756: &initialize_keywords
 3757: 
 3758: =cut
 3759: 
 3760: ###################################################
 3761: 
 3762: sub keyword {
 3763:     return if (!&initialize_keywords());
 3764:     my $word=lc(shift());
 3765:     $word=~s/\W//g;
 3766:     return exists($Keywords{$word});
 3767: }
 3768: 
 3769: ###############################################################
 3770: 
 3771: =pod 
 3772: 
 3773: =item * &get_related_words()
 3774: 
 3775: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3776: an array of words.  If the keyword is not in the thesaurus, an empty array
 3777: will be returned.  The order of the words returned is determined by the
 3778: database which holds them.
 3779: 
 3780: Uses global $thesaurus_db_file.
 3781: 
 3782: 
 3783: =cut
 3784: 
 3785: ###############################################################
 3786: sub get_related_words {
 3787:     my $keyword = shift;
 3788:     my %thesaurus_db;
 3789:     if (! -e $thesaurus_db_file) {
 3790:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3791:                                  "failed because the file does not exist");
 3792:         return ();
 3793:     }
 3794:     if (! tie(%thesaurus_db,'GDBM_File',
 3795:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3796:         return ();
 3797:     } 
 3798:     my @Words=();
 3799:     my $count=0;
 3800:     if (exists($thesaurus_db{$keyword})) {
 3801: 	# The first element is the number of times
 3802: 	# the word appears.  We do not need it now.
 3803: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3804: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3805: 	my $threshold=$mostfrequentcount/10;
 3806:         foreach my $possibleword (@RelatedWords) {
 3807:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3808:             if ($wordcount>$threshold) {
 3809: 		push(@Words,$word);
 3810:                 $count++;
 3811:                 if ($count>10) { last; }
 3812: 	    }
 3813:         }
 3814:     }
 3815:     untie %thesaurus_db;
 3816:     return @Words;
 3817: }
 3818: ###############################################################
 3819: #
 3820: #  Spell checking
 3821: #
 3822: 
 3823: =pod
 3824: 
 3825: =back
 3826: 
 3827: =head1 Spell checking
 3828: 
 3829: =over 4
 3830: 
 3831: =item * &check_spelling($wordlist $language)
 3832: 
 3833: Takes a string containing words and feeds it to an external
 3834: spellcheck program via a pipeline. Returns a string containing
 3835: them mis-spelled words.
 3836: 
 3837: Parameters:
 3838: 
 3839: =over 4
 3840: 
 3841: =item - $wordlist
 3842: 
 3843: String that will be fed into the spellcheck program.
 3844: 
 3845: =item - $language
 3846: 
 3847: Language string that specifies the language for which the spell
 3848: check will be performed.
 3849: 
 3850: =back
 3851: 
 3852: =back
 3853: 
 3854: Note: This sub assumes that aspell is installed.
 3855: 
 3856: 
 3857: =cut
 3858: 
 3859: 
 3860: sub check_spelling {
 3861:     my ($wordlist, $language) = @_;
 3862:     my @misspellings;
 3863:     
 3864:     # Generate the speller and set the langauge.
 3865:     # if explicitly selected:
 3866: 
 3867:     my $speller = Text::Aspell->new;
 3868:     if ($language) {
 3869: 	$speller->set_option('lang', $language);
 3870:     }
 3871: 
 3872:     # Turn the word list into an array of words by splittingon whitespace
 3873: 
 3874:     my @words = split(/\s+/, $wordlist);
 3875: 
 3876:     foreach my $word (@words) {
 3877: 	if(! $speller->check($word)) {
 3878: 	    push(@misspellings, $word);
 3879: 	}
 3880:     }
 3881:     return join(' ', @misspellings);
 3882:     
 3883: }
 3884: 
 3885: # -------------------------------------------------------------- Plaintext name
 3886: =pod
 3887: 
 3888: =head1 User Name Functions
 3889: 
 3890: =over 4
 3891: 
 3892: =item * &plainname($uname,$udom,$first)
 3893: 
 3894: Takes a users logon name and returns it as a string in
 3895: "first middle last generation" form 
 3896: if $first is set to 'lastname' then it returns it as
 3897: 'lastname generation, firstname middlename' if their is a lastname
 3898: 
 3899: =cut
 3900: 
 3901: 
 3902: ###############################################################
 3903: sub plainname {
 3904:     my ($uname,$udom,$first)=@_;
 3905:     return if (!defined($uname) || !defined($udom));
 3906:     my %names=&getnames($uname,$udom);
 3907:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3908: 					  $names{'middlename'},
 3909: 					  $names{'lastname'},
 3910: 					  $names{'generation'},$first);
 3911:     $name=~s/^\s+//;
 3912:     $name=~s/\s+$//;
 3913:     $name=~s/\s+/ /g;
 3914:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3915:     return $name;
 3916: }
 3917: 
 3918: # -------------------------------------------------------------------- Nickname
 3919: =pod
 3920: 
 3921: =item * &nickname($uname,$udom)
 3922: 
 3923: Gets a users name and returns it as a string as
 3924: 
 3925: "&quot;nickname&quot;"
 3926: 
 3927: if the user has a nickname or
 3928: 
 3929: "first middle last generation"
 3930: 
 3931: if the user does not
 3932: 
 3933: =cut
 3934: 
 3935: sub nickname {
 3936:     my ($uname,$udom)=@_;
 3937:     return if (!defined($uname) || !defined($udom));
 3938:     my %names=&getnames($uname,$udom);
 3939:     my $name=$names{'nickname'};
 3940:     if ($name) {
 3941:        $name='&quot;'.$name.'&quot;'; 
 3942:     } else {
 3943:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3944: 	     $names{'lastname'}.' '.$names{'generation'};
 3945:        $name=~s/\s+$//;
 3946:        $name=~s/\s+/ /g;
 3947:     }
 3948:     return $name;
 3949: }
 3950: 
 3951: sub getnames {
 3952:     my ($uname,$udom)=@_;
 3953:     return if (!defined($uname) || !defined($udom));
 3954:     if ($udom eq 'public' && $uname eq 'public') {
 3955: 	return ('lastname' => &mt('Public'));
 3956:     }
 3957:     my $id=$uname.':'.$udom;
 3958:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3959:     if ($cached) {
 3960: 	return %{$names};
 3961:     } else {
 3962: 	my %loadnames=&Apache::lonnet::get('environment',
 3963:                     ['firstname','middlename','lastname','generation','nickname'],
 3964: 					 $udom,$uname);
 3965: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3966: 	return %loadnames;
 3967:     }
 3968: }
 3969: 
 3970: # -------------------------------------------------------------------- getemails
 3971: 
 3972: =pod
 3973: 
 3974: =item * &getemails($uname,$udom)
 3975: 
 3976: Gets a user's email information and returns it as a hash with keys:
 3977: notification, critnotification, permanentemail
 3978: 
 3979: For notification and critnotification, values are comma-separated lists 
 3980: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3981:  
 3982: 
 3983: =cut
 3984: 
 3985: 
 3986: sub getemails {
 3987:     my ($uname,$udom)=@_;
 3988:     if ($udom eq 'public' && $uname eq 'public') {
 3989: 	return;
 3990:     }
 3991:     if (!$udom) { $udom=$env{'user.domain'}; }
 3992:     if (!$uname) { $uname=$env{'user.name'}; }
 3993:     my $id=$uname.':'.$udom;
 3994:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3995:     if ($cached) {
 3996: 	return %{$names};
 3997:     } else {
 3998: 	my %loadnames=&Apache::lonnet::get('environment',
 3999:                     			   ['notification','critnotification',
 4000: 					    'permanentemail'],
 4001: 					   $udom,$uname);
 4002: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4003: 	return %loadnames;
 4004:     }
 4005: }
 4006: 
 4007: sub flush_email_cache {
 4008:     my ($uname,$udom)=@_;
 4009:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4010:     if (!$uname) { $uname=$env{'user.name'};   }
 4011:     return if ($udom eq 'public' && $uname eq 'public');
 4012:     my $id=$uname.':'.$udom;
 4013:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4014: }
 4015: 
 4016: # -------------------------------------------------------------------- getlangs
 4017: 
 4018: =pod
 4019: 
 4020: =item * &getlangs($uname,$udom)
 4021: 
 4022: Gets a user's language preference and returns it as a hash with key:
 4023: language.
 4024: 
 4025: =cut
 4026: 
 4027: 
 4028: sub getlangs {
 4029:     my ($uname,$udom) = @_;
 4030:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4031:     if (!$uname) { $uname=$env{'user.name'};   }
 4032:     my $id=$uname.':'.$udom;
 4033:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4034:     if ($cached) {
 4035:         return %{$langs};
 4036:     } else {
 4037:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4038:                                            $udom,$uname);
 4039:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4040:         return %loadlangs;
 4041:     }
 4042: }
 4043: 
 4044: sub flush_langs_cache {
 4045:     my ($uname,$udom)=@_;
 4046:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4047:     if (!$uname) { $uname=$env{'user.name'};   }
 4048:     return if ($udom eq 'public' && $uname eq 'public');
 4049:     my $id=$uname.':'.$udom;
 4050:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4051: }
 4052: 
 4053: # ------------------------------------------------------------------ Screenname
 4054: 
 4055: =pod
 4056: 
 4057: =item * &screenname($uname,$udom)
 4058: 
 4059: Gets a users screenname and returns it as a string
 4060: 
 4061: =cut
 4062: 
 4063: sub screenname {
 4064:     my ($uname,$udom)=@_;
 4065:     if ($uname eq $env{'user.name'} &&
 4066: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4067:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4068:     return $names{'screenname'};
 4069: }
 4070: 
 4071: 
 4072: # ------------------------------------------------------------- Confirm Wrapper
 4073: =pod
 4074: 
 4075: =item * &confirmwrapper($message)
 4076: 
 4077: Wrap messages about completion of operation in box
 4078: 
 4079: =cut
 4080: 
 4081: sub confirmwrapper {
 4082:     my ($message)=@_;
 4083:     if ($message) {
 4084:         return "\n".'<div class="LC_confirm_box">'."\n"
 4085:                .$message."\n"
 4086:                .'</div>'."\n";
 4087:     } else {
 4088:         return $message;
 4089:     }
 4090: }
 4091: 
 4092: # ------------------------------------------------------------- Message Wrapper
 4093: 
 4094: sub messagewrapper {
 4095:     my ($link,$username,$domain,$subject,$text)=@_;
 4096:     return 
 4097:         '<a href="/adm/email?compose=individual&amp;'.
 4098:         'recname='.$username.'&amp;recdom='.$domain.
 4099: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4100:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4101: }
 4102: 
 4103: # --------------------------------------------------------------- Notes Wrapper
 4104: 
 4105: sub noteswrapper {
 4106:     my ($link,$un,$do)=@_;
 4107:     return 
 4108: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4109: }
 4110: 
 4111: # ------------------------------------------------------------- Aboutme Wrapper
 4112: 
 4113: sub aboutmewrapper {
 4114:     my ($link,$username,$domain,$target,$class)=@_;
 4115:     if (!defined($username)  && !defined($domain)) {
 4116:         return;
 4117:     }
 4118:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4119: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4120: }
 4121: 
 4122: # ------------------------------------------------------------ Syllabus Wrapper
 4123: 
 4124: sub syllabuswrapper {
 4125:     my ($linktext,$coursedir,$domain)=@_;
 4126:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4127: }
 4128: 
 4129: # -----------------------------------------------------------------------------
 4130: 
 4131: sub track_student_link {
 4132:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4133:     my $link ="/adm/trackstudent?";
 4134:     my $title = 'View recent activity';
 4135:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4136:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4137:         $link .= "selected_student=$sname:$sdom";
 4138:         $title .= ' of this student';
 4139:     } 
 4140:     if (defined($target) && $target !~ /^\s*$/) {
 4141:         $target = qq{target="$target"};
 4142:     } else {
 4143:         $target = '';
 4144:     }
 4145:     if ($start) { $link.='&amp;start='.$start; }
 4146:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4147:     $title = &mt($title);
 4148:     $linktext = &mt($linktext);
 4149:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4150: 	&help_open_topic('View_recent_activity');
 4151: }
 4152: 
 4153: sub slot_reservations_link {
 4154:     my ($linktext,$sname,$sdom,$target) = @_;
 4155:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4156:     my $title = 'View slot reservation history';
 4157:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4158:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4159:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4160:         $title .= ' of this student';
 4161:     }
 4162:     if (defined($target) && $target !~ /^\s*$/) {
 4163:         $target = qq{target="$target"};
 4164:     } else {
 4165:         $target = '';
 4166:     }
 4167:     $title = &mt($title);
 4168:     $linktext = &mt($linktext);
 4169:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4170: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4171: 
 4172: }
 4173: 
 4174: # ===================================================== Display a student photo
 4175: 
 4176: 
 4177: sub student_image_tag {
 4178:     my ($domain,$user)=@_;
 4179:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4180:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4181: 	return '<img src="'.$imgsrc.'" align="right" />';
 4182:     } else {
 4183: 	return '';
 4184:     }
 4185: }
 4186: 
 4187: =pod
 4188: 
 4189: =back
 4190: 
 4191: =head1 Access .tab File Data
 4192: 
 4193: =over 4
 4194: 
 4195: =item * &languageids() 
 4196: 
 4197: returns list of all language ids
 4198: 
 4199: =cut
 4200: 
 4201: sub languageids {
 4202:     return sort(keys(%language));
 4203: }
 4204: 
 4205: =pod
 4206: 
 4207: =item * &languagedescription() 
 4208: 
 4209: returns description of a specified language id
 4210: 
 4211: =cut
 4212: 
 4213: sub languagedescription {
 4214:     my $code=shift;
 4215:     return  ($supported_language{$code}?'* ':'').
 4216:             $language{$code}.
 4217: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4218: }
 4219: 
 4220: =pod
 4221: 
 4222: =item * &plainlanguagedescription
 4223: 
 4224: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4225: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4226: 
 4227: =cut
 4228: 
 4229: sub plainlanguagedescription {
 4230:     my $code=shift;
 4231:     return $language{$code};
 4232: }
 4233: 
 4234: =pod
 4235: 
 4236: =item * &supportedlanguagecode
 4237: 
 4238: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4239: code.
 4240: 
 4241: =cut
 4242: 
 4243: sub supportedlanguagecode {
 4244:     my $code=shift;
 4245:     return $supported_language{$code};
 4246: }
 4247: 
 4248: =pod
 4249: 
 4250: =item * &latexlanguage()
 4251: 
 4252: Given a language key code returns the correspondnig language to use
 4253: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4254: is no supported hyphenation for the language code.
 4255: 
 4256: =cut
 4257: 
 4258: sub latexlanguage {
 4259:     my $code = shift;
 4260:     return $latex_language{$code};
 4261: }
 4262: 
 4263: =pod
 4264: 
 4265: =item * &latexhyphenation()
 4266: 
 4267: Same as above but what's supplied is the language as it might be stored
 4268: in the metadata.
 4269: 
 4270: =cut
 4271: 
 4272: sub latexhyphenation {
 4273:     my $key = shift;
 4274:     return $latex_language_bykey{$key};
 4275: }
 4276: 
 4277: =pod
 4278: 
 4279: =item * &copyrightids() 
 4280: 
 4281: returns list of all copyrights
 4282: 
 4283: =cut
 4284: 
 4285: sub copyrightids {
 4286:     return sort(keys(%cprtag));
 4287: }
 4288: 
 4289: =pod
 4290: 
 4291: =item * &copyrightdescription() 
 4292: 
 4293: returns description of a specified copyright id
 4294: 
 4295: =cut
 4296: 
 4297: sub copyrightdescription {
 4298:     return &mt($cprtag{shift(@_)});
 4299: }
 4300: 
 4301: =pod
 4302: 
 4303: =item * &source_copyrightids() 
 4304: 
 4305: returns list of all source copyrights
 4306: 
 4307: =cut
 4308: 
 4309: sub source_copyrightids {
 4310:     return sort(keys(%scprtag));
 4311: }
 4312: 
 4313: =pod
 4314: 
 4315: =item * &source_copyrightdescription() 
 4316: 
 4317: returns description of a specified source copyright id
 4318: 
 4319: =cut
 4320: 
 4321: sub source_copyrightdescription {
 4322:     return &mt($scprtag{shift(@_)});
 4323: }
 4324: 
 4325: =pod
 4326: 
 4327: =item * &filecategories() 
 4328: 
 4329: returns list of all file categories
 4330: 
 4331: =cut
 4332: 
 4333: sub filecategories {
 4334:     return sort(keys(%category_extensions));
 4335: }
 4336: 
 4337: =pod
 4338: 
 4339: =item * &filecategorytypes() 
 4340: 
 4341: returns list of file types belonging to a given file
 4342: category
 4343: 
 4344: =cut
 4345: 
 4346: sub filecategorytypes {
 4347:     my ($cat) = @_;
 4348:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4349:         return @{$category_extensions{lc($cat)}};
 4350:     } else {
 4351:         return ();
 4352:     }
 4353: }
 4354: 
 4355: =pod
 4356: 
 4357: =item * &fileembstyle() 
 4358: 
 4359: returns embedding style for a specified file type
 4360: 
 4361: =cut
 4362: 
 4363: sub fileembstyle {
 4364:     return $fe{lc(shift(@_))};
 4365: }
 4366: 
 4367: sub filemimetype {
 4368:     return $fm{lc(shift(@_))};
 4369: }
 4370: 
 4371: 
 4372: sub filecategoryselect {
 4373:     my ($name,$value)=@_;
 4374:     return &select_form($value,$name,
 4375:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4376: }
 4377: 
 4378: =pod
 4379: 
 4380: =item * &filedescription() 
 4381: 
 4382: returns description for a specified file type
 4383: 
 4384: =cut
 4385: 
 4386: sub filedescription {
 4387:     my $file_description = $fd{lc(shift())};
 4388:     $file_description =~ s:([\[\]]):~$1:g;
 4389:     return &mt($file_description);
 4390: }
 4391: 
 4392: =pod
 4393: 
 4394: =item * &filedescriptionex() 
 4395: 
 4396: returns description for a specified file type with
 4397: extra formatting
 4398: 
 4399: =cut
 4400: 
 4401: sub filedescriptionex {
 4402:     my $ex=shift;
 4403:     my $file_description = $fd{lc($ex)};
 4404:     $file_description =~ s:([\[\]]):~$1:g;
 4405:     return '.'.$ex.' '.&mt($file_description);
 4406: }
 4407: 
 4408: # End of .tab access
 4409: =pod
 4410: 
 4411: =back
 4412: 
 4413: =cut
 4414: 
 4415: # ------------------------------------------------------------------ File Types
 4416: sub fileextensions {
 4417:     return sort(keys(%fe));
 4418: }
 4419: 
 4420: # ----------------------------------------------------------- Display Languages
 4421: # returns a hash with all desired display languages
 4422: #
 4423: 
 4424: sub display_languages {
 4425:     my %languages=();
 4426:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4427: 	$languages{$lang}=1;
 4428:     }
 4429:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4430:     if ($env{'form.displaylanguage'}) {
 4431: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4432: 	    $languages{$lang}=1;
 4433:         }
 4434:     }
 4435:     return %languages;
 4436: }
 4437: 
 4438: sub languages {
 4439:     my ($possible_langs) = @_;
 4440:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4441:     if (!ref($possible_langs)) {
 4442: 	if( wantarray ) {
 4443: 	    return @preferred_langs;
 4444: 	} else {
 4445: 	    return $preferred_langs[0];
 4446: 	}
 4447:     }
 4448:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4449:     my @preferred_possibilities;
 4450:     foreach my $preferred_lang (@preferred_langs) {
 4451: 	if (exists($possibilities{$preferred_lang})) {
 4452: 	    push(@preferred_possibilities, $preferred_lang);
 4453: 	}
 4454:     }
 4455:     if( wantarray ) {
 4456: 	return @preferred_possibilities;
 4457:     }
 4458:     return $preferred_possibilities[0];
 4459: }
 4460: 
 4461: sub user_lang {
 4462:     my ($touname,$toudom,$fromcid) = @_;
 4463:     my @userlangs;
 4464:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4465:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4466:                     $env{'course.'.$fromcid.'.languages'}));
 4467:     } else {
 4468:         my %langhash = &getlangs($touname,$toudom);
 4469:         if ($langhash{'languages'} ne '') {
 4470:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4471:         } else {
 4472:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4473:             if ($domdefs{'lang_def'} ne '') {
 4474:                 @userlangs = ($domdefs{'lang_def'});
 4475:             }
 4476:         }
 4477:     }
 4478:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4479:     my $user_lh = Apache::localize->get_handle(@languages);
 4480:     return $user_lh;
 4481: }
 4482: 
 4483: 
 4484: ###############################################################
 4485: ##               Student Answer Attempts                     ##
 4486: ###############################################################
 4487: 
 4488: =pod
 4489: 
 4490: =head1 Alternate Problem Views
 4491: 
 4492: =over 4
 4493: 
 4494: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4495:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4496: 
 4497: Return string with previous attempt on problem. Arguments:
 4498: 
 4499: =over 4
 4500: 
 4501: =item * $symb: Problem, including path
 4502: 
 4503: =item * $username: username of the desired student
 4504: 
 4505: =item * $domain: domain of the desired student
 4506: 
 4507: =item * $course: Course ID
 4508: 
 4509: =item * $getattempt: Leave blank for all attempts, otherwise put
 4510:     something
 4511: 
 4512: =item * $regexp: if string matches this regexp, the string will be
 4513:     sent to $gradesub
 4514: 
 4515: =item * $gradesub: routine that processes the string if it matches $regexp
 4516: 
 4517: =item * $usec: section of the desired student
 4518: 
 4519: =item * $identifier: counter for student (multiple students one problem) or 
 4520:     problem (one student; whole sequence).
 4521: 
 4522: =back
 4523: 
 4524: The output string is a table containing all desired attempts, if any.
 4525: 
 4526: =cut
 4527: 
 4528: sub get_previous_attempt {
 4529:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4530:   my $prevattempts='';
 4531:   no strict 'refs';
 4532:   if ($symb) {
 4533:     my (%returnhash)=
 4534:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4535:     if ($returnhash{'version'}) {
 4536:       my %lasthash=();
 4537:       my $version;
 4538:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4539:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4540:             if ($key =~ /\.rawrndseed$/) {
 4541:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4542:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4543:             } else {
 4544:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4545:             }
 4546:         }
 4547:       }
 4548:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4549:       $prevattempts.='<th>'.&mt('History').'</th>';
 4550:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4551:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4552:       foreach my $key (sort(keys(%lasthash))) {
 4553: 	my ($ign,@parts) = split(/\./,$key);
 4554: 	if ($#parts > 0) {
 4555: 	  my $data=$parts[-1];
 4556:           next if ($data eq 'foilorder');
 4557: 	  pop(@parts);
 4558:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4559:           if ($data eq 'type') {
 4560:               unless ($showsurv) {
 4561:                   my $id = join(',',@parts);
 4562:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4563:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4564:                       $lasthidden{$ign.'.'.$id} = 1;
 4565:                   }
 4566:               }
 4567:               if ($identifier ne '') {
 4568:                   my $id = join(',',@parts);
 4569:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4570:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4571:                       $hidestatus{$ign.'.'.$id} = 1;
 4572:                   }
 4573:               }
 4574:           } elsif ($data eq 'regrader') {
 4575:               if (($identifier ne '') && (@parts)) {
 4576:                   my $id = join(',',@parts);
 4577:                   $regraded{$ign.'.'.$id} = 1;
 4578:               }
 4579:           } 
 4580: 	} else {
 4581: 	  if ($#parts == 0) {
 4582: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4583: 	  } else {
 4584: 	    $prevattempts.='<th>'.$ign.'</th>';
 4585: 	  }
 4586: 	}
 4587:       }
 4588:       $prevattempts.=&end_data_table_header_row();
 4589:       if ($getattempt eq '') {
 4590:         my (%solved,%resets,%probstatus);
 4591:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4592:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4593:                 foreach my $id (keys(%regraded)) {
 4594:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4595:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4596:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4597:                         push(@{$resets{$id}},$version);
 4598:                     }
 4599:                 }
 4600:             }
 4601:         }
 4602: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4603:             my (@hidden,@unsolved);
 4604:             if (%typeparts) {
 4605:                 foreach my $id (keys(%typeparts)) {
 4606:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4607:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4608:                         push(@hidden,$id);
 4609:                     } elsif ($identifier ne '') {
 4610:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4611:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4612:                                 ($hidestatus{$id})) {
 4613:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4614:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4615:                                 push(@{$solved{$id}},$version);
 4616:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4617:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4618:                                 my $skip;
 4619:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4620:                                     foreach my $reset (@{$resets{$id}}) {
 4621:                                         if ($reset > $solved{$id}[-1]) {
 4622:                                             $skip=1;
 4623:                                             last;
 4624:                                         }
 4625:                                     }
 4626:                                 }
 4627:                                 unless ($skip) {
 4628:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4629:                                     push(@unsolved,$partslist);
 4630:                                 }
 4631:                             }
 4632:                         }
 4633:                     }
 4634:                 }
 4635:             }
 4636:             $prevattempts.=&start_data_table_row().
 4637:                            '<td>'.&mt('Transaction [_1]',$version);
 4638:             if (@unsolved) {
 4639:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4640:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4641:                                  &mt('Hide').'</label></span>';
 4642:             }
 4643:             $prevattempts .= '</td>';
 4644:             if (@hidden) {
 4645:                 foreach my $key (sort(keys(%lasthash))) {
 4646:                     next if ($key =~ /\.foilorder$/);
 4647:                     my $hide;
 4648:                     foreach my $id (@hidden) {
 4649:                         if ($key =~ /^\Q$id\E/) {
 4650:                             $hide = 1;
 4651:                             last;
 4652:                         }
 4653:                     }
 4654:                     if ($hide) {
 4655:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4656:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4657:                             my $value = &format_previous_attempt_value($key,
 4658:                                              $returnhash{$version.':'.$key});
 4659:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4660:                         } else {
 4661:                             $prevattempts.='<td>&nbsp;</td>';
 4662:                         }
 4663:                     } else {
 4664:                         if ($key =~ /\./) {
 4665:                             my $value = $returnhash{$version.':'.$key};
 4666:                             if ($key =~ /\.rndseed$/) {
 4667:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4668:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4669:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4670:                                 }
 4671:                             }
 4672:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4673:                                            '&nbsp;</td>';
 4674:                         } else {
 4675:                             $prevattempts.='<td>&nbsp;</td>';
 4676:                         }
 4677:                     }
 4678:                 }
 4679:             } else {
 4680: 	        foreach my $key (sort(keys(%lasthash))) {
 4681:                     next if ($key =~ /\.foilorder$/);
 4682:                     my $value = $returnhash{$version.':'.$key};
 4683:                     if ($key =~ /\.rndseed$/) {
 4684:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4685:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4686:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4687:                         }
 4688:                     }
 4689:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4690:                                    '&nbsp;</td>';
 4691: 	        }
 4692:             }
 4693: 	    $prevattempts.=&end_data_table_row();
 4694: 	 }
 4695:       }
 4696:       my @currhidden = keys(%lasthidden);
 4697:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4698:       foreach my $key (sort(keys(%lasthash))) {
 4699:           next if ($key =~ /\.foilorder$/);
 4700:           if (%typeparts) {
 4701:               my $hidden;
 4702:               foreach my $id (@currhidden) {
 4703:                   if ($key =~ /^\Q$id\E/) {
 4704:                       $hidden = 1;
 4705:                       last;
 4706:                   }
 4707:               }
 4708:               if ($hidden) {
 4709:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4710:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4711:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4712:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4713:                           $value = &$gradesub($value);
 4714:                       }
 4715:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4716:                   } else {
 4717:                       $prevattempts.='<td>&nbsp;</td>';
 4718:                   }
 4719:               } else {
 4720:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4721:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4722:                       $value = &$gradesub($value);
 4723:                   }
 4724:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4725:               }
 4726:           } else {
 4727: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4728: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4729:                   $value = &$gradesub($value);
 4730:               }
 4731: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4732:           }
 4733:       }
 4734:       $prevattempts.= &end_data_table_row().&end_data_table();
 4735:     } else {
 4736:       my $msg;
 4737:       if ($symb =~ /ext\.tool$/) {
 4738:           $msg = &mt('No grade passed back.');
 4739:       } else {
 4740:           $msg = &mt('Nothing submitted - no attempts.');
 4741:       }
 4742:       $prevattempts=
 4743: 	  &start_data_table().&start_data_table_row().
 4744: 	  '<td>'.$msg.'</td>'.
 4745: 	  &end_data_table_row().&end_data_table();
 4746:     }
 4747:   } else {
 4748:     $prevattempts=
 4749: 	  &start_data_table().&start_data_table_row().
 4750: 	  '<td>'.&mt('No data.').'</td>'.
 4751: 	  &end_data_table_row().&end_data_table();
 4752:   }
 4753: }
 4754: 
 4755: sub format_previous_attempt_value {
 4756:     my ($key,$value) = @_;
 4757:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4758:         $value = &Apache::lonlocal::locallocaltime($value);
 4759:     } elsif (ref($value) eq 'ARRAY') {
 4760:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4761:     } elsif ($key =~ /answerstring$/) {
 4762:         my %answers = &Apache::lonnet::str2hash($value);
 4763:         my @answer = %answers;
 4764:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4765:         my @anskeys = sort(keys(%answers));
 4766:         if (@anskeys == 1) {
 4767:             my $answer = $answers{$anskeys[0]};
 4768:             if ($answer =~ m{\0}) {
 4769:                 $answer =~ s{\0}{,}g;
 4770:             }
 4771:             my $tag_internal_answer_name = 'INTERNAL';
 4772:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4773:                 $value = $answer; 
 4774:             } else {
 4775:                 $value = $anskeys[0].'='.$answer;
 4776:             }
 4777:         } else {
 4778:             foreach my $ans (@anskeys) {
 4779:                 my $answer = $answers{$ans};
 4780:                 if ($answer =~ m{\0}) {
 4781:                     $answer =~ s{\0}{,}g;
 4782:                 }
 4783:                 $value .=  $ans.'='.$answer.'<br />';;
 4784:             } 
 4785:         }
 4786:     } else {
 4787:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4788:     }
 4789:     return $value;
 4790: }
 4791: 
 4792: 
 4793: sub relative_to_absolute {
 4794:     my ($url,$output)=@_;
 4795:     my $parser=HTML::TokeParser->new(\$output);
 4796:     my $token;
 4797:     my $thisdir=$url;
 4798:     my @rlinks=();
 4799:     while ($token=$parser->get_token) {
 4800: 	if ($token->[0] eq 'S') {
 4801: 	    if ($token->[1] eq 'a') {
 4802: 		if ($token->[2]->{'href'}) {
 4803: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4804: 		}
 4805: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4806: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4807: 	    } elsif ($token->[1] eq 'base') {
 4808: 		$thisdir=$token->[2]->{'href'};
 4809: 	    }
 4810: 	}
 4811:     }
 4812:     $thisdir=~s-/[^/]*$--;
 4813:     foreach my $link (@rlinks) {
 4814: 	unless (($link=~/^https?\:\/\//i) ||
 4815: 		($link=~/^\//) ||
 4816: 		($link=~/^javascript:/i) ||
 4817: 		($link=~/^mailto:/i) ||
 4818: 		($link=~/^\#/)) {
 4819: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4820: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4821: 	}
 4822:     }
 4823: # -------------------------------------------------- Deal with Applet codebases
 4824:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4825:     return $output;
 4826: }
 4827: 
 4828: =pod
 4829: 
 4830: =item * &get_student_view()
 4831: 
 4832: show a snapshot of what student was looking at
 4833: 
 4834: =cut
 4835: 
 4836: sub get_student_view {
 4837:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4838:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4839:   my (%form);
 4840:   my @elements=('symb','courseid','domain','username');
 4841:   foreach my $element (@elements) {
 4842:       $form{'grade_'.$element}=eval '$'.$element #'
 4843:   }
 4844:   if (defined($moreenv)) {
 4845:       %form=(%form,%{$moreenv});
 4846:   }
 4847:   if (defined($target)) { $form{'grade_target'} = $target; }
 4848:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4849:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 4850:       $feedurl =~ s{^/adm/wrapper}{};
 4851:   }
 4852:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4853:   $userview=~s/\<body[^\>]*\>//gi;
 4854:   $userview=~s/\<\/body\>//gi;
 4855:   $userview=~s/\<html\>//gi;
 4856:   $userview=~s/\<\/html\>//gi;
 4857:   $userview=~s/\<head\>//gi;
 4858:   $userview=~s/\<\/head\>//gi;
 4859:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4860:   $userview=&relative_to_absolute($feedurl,$userview);
 4861:   if (wantarray) {
 4862:      return ($userview,$response);
 4863:   } else {
 4864:      return $userview;
 4865:   }
 4866: }
 4867: 
 4868: sub get_student_view_with_retries {
 4869:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4870: 
 4871:     my $ok = 0;                 # True if we got a good response.
 4872:     my $content;
 4873:     my $response;
 4874: 
 4875:     # Try to get the student_view done. within the retries count:
 4876:     
 4877:     do {
 4878:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4879:          $ok      = $response->is_success;
 4880:          if (!$ok) {
 4881:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4882:          }
 4883:          $retries--;
 4884:     } while (!$ok && ($retries > 0));
 4885:     
 4886:     if (!$ok) {
 4887:        $content = '';          # On error return an empty content.
 4888:     }
 4889:     if (wantarray) {
 4890:        return ($content, $response);
 4891:     } else {
 4892:        return $content;
 4893:     }
 4894: }
 4895: 
 4896: sub css_links {
 4897:     my ($currsymb,$level) = @_;
 4898:     my ($links,@symbs,%cssrefs,%httpref);
 4899:     if ($level eq 'map') {
 4900:         my $navmap = Apache::lonnavmaps::navmap->new();
 4901:         if (ref($navmap)) {
 4902:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4903:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4904:             foreach my $res (@resources) {
 4905:                 if (ref($res) && $res->symb()) {
 4906:                     push(@symbs,$res->symb());
 4907:                 }
 4908:             }
 4909:         }
 4910:     } else {
 4911:         @symbs = ($currsymb);
 4912:     }
 4913:     foreach my $symb (@symbs) {
 4914:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4915:         if ($css_href =~ /\S/) {
 4916:             unless ($css_href =~ m{https?://}) {
 4917:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4918:                 my $proburl =  &Apache::lonnet::clutter($url);
 4919:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4920:                 unless ($css_href =~ m{^/}) {
 4921:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4922:                 }
 4923:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4924:                     unless (($httpref{'httpref.'.$css_href}) ||
 4925:                             (&Apache::lonnet::is_on_map($css_href))) {
 4926:                         my $thisurl = $proburl;
 4927:                         if ($env{'httpref.'.$proburl}) {
 4928:                             $thisurl = $env{'httpref.'.$proburl};
 4929:                         }
 4930:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4931:                     }
 4932:                 }
 4933:             }
 4934:             $cssrefs{$css_href} = 1;
 4935:         }
 4936:     }
 4937:     if (keys(%httpref)) {
 4938:         &Apache::lonnet::appenv(\%httpref);
 4939:     }
 4940:     if (keys(%cssrefs)) {
 4941:         foreach my $css_href (keys(%cssrefs)) {
 4942:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4943:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4944:         }
 4945:     }
 4946:     return $links;
 4947: }
 4948: 
 4949: =pod
 4950: 
 4951: =item * &get_student_answers() 
 4952: 
 4953: show a snapshot of how student was answering problem
 4954: 
 4955: =cut
 4956: 
 4957: sub get_student_answers {
 4958:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4959:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4960:   my (%moreenv);
 4961:   my @elements=('symb','courseid','domain','username');
 4962:   foreach my $element (@elements) {
 4963:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4964:   }
 4965:   $moreenv{'grade_target'}='answer';
 4966:   %moreenv=(%form,%moreenv);
 4967:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4968:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4969:   return $userview;
 4970: }
 4971: 
 4972: =pod
 4973: 
 4974: =item * &submlink()
 4975: 
 4976: Inputs: $text $uname $udom $symb $target
 4977: 
 4978: Returns: A link to grades.pm such as to see the SUBM view of a student
 4979: 
 4980: =cut
 4981: 
 4982: ###############################################
 4983: sub submlink {
 4984:     my ($text,$uname,$udom,$symb,$target)=@_;
 4985:     if (!($uname && $udom)) {
 4986: 	(my $cursymb, my $courseid,$udom,$uname)=
 4987: 	    &Apache::lonnet::whichuser($symb);
 4988: 	if (!$symb) { $symb=$cursymb; }
 4989:     }
 4990:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4991:     $symb=&escape($symb);
 4992:     if ($target) { $target=" target=\"$target\""; }
 4993:     return
 4994:         '<a href="/adm/grades?command=submission'.
 4995:         '&amp;symb='.$symb.
 4996:         '&amp;student='.$uname.
 4997:         '&amp;userdom='.$udom.'"'.
 4998:         $target.'>'.$text.'</a>';
 4999: }
 5000: ##############################################
 5001: 
 5002: =pod
 5003: 
 5004: =item * &pgrdlink()
 5005: 
 5006: Inputs: $text $uname $udom $symb $target
 5007: 
 5008: Returns: A link to grades.pm such as to see the PGRD view of a student
 5009: 
 5010: =cut
 5011: 
 5012: ###############################################
 5013: sub pgrdlink {
 5014:     my $link=&submlink(@_);
 5015:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5016:     return $link;
 5017: }
 5018: ##############################################
 5019: 
 5020: =pod
 5021: 
 5022: =item * &pprmlink()
 5023: 
 5024: Inputs: $text $uname $udom $symb $target
 5025: 
 5026: Returns: A link to parmset.pm such as to see the PPRM view of a
 5027: student and a specific resource
 5028: 
 5029: =cut
 5030: 
 5031: ###############################################
 5032: sub pprmlink {
 5033:     my ($text,$uname,$udom,$symb,$target)=@_;
 5034:     if (!($uname && $udom)) {
 5035: 	(my $cursymb, my $courseid,$udom,$uname)=
 5036: 	    &Apache::lonnet::whichuser($symb);
 5037: 	if (!$symb) { $symb=$cursymb; }
 5038:     }
 5039:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5040:     $symb=&escape($symb);
 5041:     if ($target) { $target="target=\"$target\""; }
 5042:     return '<a href="/adm/parmset?command=set&amp;'.
 5043: 	'symb='.$symb.'&amp;uname='.$uname.
 5044: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5045: }
 5046: ##############################################
 5047: 
 5048: =pod
 5049: 
 5050: =back
 5051: 
 5052: =cut
 5053: 
 5054: ###############################################
 5055: 
 5056: 
 5057: sub timehash {
 5058:     my ($thistime) = @_;
 5059:     my $timezone = &Apache::lonlocal::gettimezone();
 5060:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5061:                      ->set_time_zone($timezone);
 5062:     my $wday = $dt->day_of_week();
 5063:     if ($wday == 7) { $wday = 0; }
 5064:     return ( 'second' => $dt->second(),
 5065:              'minute' => $dt->minute(),
 5066:              'hour'   => $dt->hour(),
 5067:              'day'     => $dt->day_of_month(),
 5068:              'month'   => $dt->month(),
 5069:              'year'    => $dt->year(),
 5070:              'weekday' => $wday,
 5071:              'dayyear' => $dt->day_of_year(),
 5072:              'dlsav'   => $dt->is_dst() );
 5073: }
 5074: 
 5075: sub utc_string {
 5076:     my ($date)=@_;
 5077:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5078: }
 5079: 
 5080: sub maketime {
 5081:     my %th=@_;
 5082:     my ($epoch_time,$timezone,$dt);
 5083:     $timezone = &Apache::lonlocal::gettimezone();
 5084:     eval {
 5085:         $dt = DateTime->new( year   => $th{'year'},
 5086:                              month  => $th{'month'},
 5087:                              day    => $th{'day'},
 5088:                              hour   => $th{'hour'},
 5089:                              minute => $th{'minute'},
 5090:                              second => $th{'second'},
 5091:                              time_zone => $timezone,
 5092:                          );
 5093:     };
 5094:     if (!$@) {
 5095:         $epoch_time = $dt->epoch;
 5096:         if ($epoch_time) {
 5097:             return $epoch_time;
 5098:         }
 5099:     }
 5100:     return POSIX::mktime(
 5101:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5102:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5103: }
 5104: 
 5105: #########################################
 5106: 
 5107: sub findallcourses {
 5108:     my ($roles,$uname,$udom) = @_;
 5109:     my %roles;
 5110:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5111:     my %courses;
 5112:     my $now=time;
 5113:     if (!defined($uname)) {
 5114:         $uname = $env{'user.name'};
 5115:     }
 5116:     if (!defined($udom)) {
 5117:         $udom = $env{'user.domain'};
 5118:     }
 5119:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5120:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5121:         if (!%roles) {
 5122:             %roles = (
 5123:                        cc => 1,
 5124:                        co => 1,
 5125:                        in => 1,
 5126:                        ep => 1,
 5127:                        ta => 1,
 5128:                        cr => 1,
 5129:                        st => 1,
 5130:              );
 5131:         }
 5132:         foreach my $entry (keys(%roleshash)) {
 5133:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5134:             if ($trole =~ /^cr/) { 
 5135:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5136:             } else {
 5137:                 next if (!exists($roles{$trole}));
 5138:             }
 5139:             if ($tend) {
 5140:                 next if ($tend < $now);
 5141:             }
 5142:             if ($tstart) {
 5143:                 next if ($tstart > $now);
 5144:             }
 5145:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5146:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5147:             my $value = $trole.'/'.$cdom.'/';
 5148:             if ($secpart eq '') {
 5149:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5150:                 $sec = 'none';
 5151:                 $value .= $cnum.'/';
 5152:             } else {
 5153:                 $cnum = $cnumpart;
 5154:                 ($sec,$role) = split(/_/,$secpart);
 5155:                 $value .= $cnum.'/'.$sec;
 5156:             }
 5157:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5158:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5159:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5160:                 }
 5161:             } else {
 5162:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5163:             }
 5164:         }
 5165:     } else {
 5166:         foreach my $key (keys(%env)) {
 5167: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5168:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5169: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5170: 	        next if ($role eq 'ca' || $role eq 'aa');
 5171: 	        next if (%roles && !exists($roles{$role}));
 5172: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5173:                 my $active=1;
 5174:                 if ($starttime) {
 5175: 		    if ($now<$starttime) { $active=0; }
 5176:                 }
 5177:                 if ($endtime) {
 5178:                     if ($now>$endtime) { $active=0; }
 5179:                 }
 5180:                 if ($active) {
 5181:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5182:                     if ($sec eq '') {
 5183:                         $sec = 'none';
 5184:                     } else {
 5185:                         $value .= $sec;
 5186:                     }
 5187:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5188:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5189:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5190:                         }
 5191:                     } else {
 5192:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5193:                     }
 5194:                 }
 5195:             }
 5196:         }
 5197:     }
 5198:     return %courses;
 5199: }
 5200: 
 5201: ###############################################
 5202: 
 5203: sub blockcheck {
 5204:     my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5205: 
 5206:     if (defined($udom) && defined($uname)) {
 5207:         # If uname and udom are for a course, check for blocks in the course.
 5208:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5209:             my ($startblock,$endblock,$triggerblock) =
 5210:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5211:             return ($startblock,$endblock,$triggerblock);
 5212:         }
 5213:     } else {
 5214:         $udom = $env{'user.domain'};
 5215:         $uname = $env{'user.name'};
 5216:     }
 5217: 
 5218:     my $startblock = 0;
 5219:     my $endblock = 0;
 5220:     my $triggerblock = '';
 5221:     my %live_courses = &findallcourses(undef,$uname,$udom);
 5222: 
 5223:     # If uname is for a user, and activity is course-specific, i.e.,
 5224:     # boards, chat or groups, check for blocking in current course only.
 5225: 
 5226:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5227:          $activity eq 'groups' || $activity eq 'printout' ||
 5228:          $activity eq 'search' || $activity eq 'reinit' ||
 5229:          $activity eq 'alert') &&
 5230:         ($env{'request.course.id'})) {
 5231:         foreach my $key (keys(%live_courses)) {
 5232:             if ($key ne $env{'request.course.id'}) {
 5233:                 delete($live_courses{$key});
 5234:             }
 5235:         }
 5236:     }
 5237: 
 5238:     my $otheruser = 0;
 5239:     my %own_courses;
 5240:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5241:         # Resource belongs to user other than current user.
 5242:         $otheruser = 1;
 5243:         # Gather courses for current user
 5244:         %own_courses = 
 5245:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5246:     }
 5247: 
 5248:     # Gather active course roles - course coordinator, instructor, 
 5249:     # exam proctor, ta, student, or custom role.
 5250: 
 5251:     foreach my $course (keys(%live_courses)) {
 5252:         my ($cdom,$cnum);
 5253:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5254:             $cdom = $env{'course.'.$course.'.domain'};
 5255:             $cnum = $env{'course.'.$course.'.num'};
 5256:         } else {
 5257:             ($cdom,$cnum) = split(/_/,$course); 
 5258:         }
 5259:         my $no_ownblock = 0;
 5260:         my $no_userblock = 0;
 5261:         if ($otheruser && $activity ne 'com') {
 5262:             # Check if current user has 'evb' priv for this
 5263:             if (defined($own_courses{$course})) {
 5264:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5265:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5266:                     if ($sec ne 'none') {
 5267:                         $checkrole .= '/'.$sec;
 5268:                     }
 5269:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5270:                         $no_ownblock = 1;
 5271:                         last;
 5272:                     }
 5273:                 }
 5274:             }
 5275:             # if they have 'evb' priv and are currently not playing student
 5276:             next if (($no_ownblock) &&
 5277:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5278:         }
 5279:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5280:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5281:             if ($sec ne 'none') {
 5282:                 $checkrole .= '/'.$sec;
 5283:             }
 5284:             if ($otheruser) {
 5285:                 # Resource belongs to user other than current user.
 5286:                 # Assemble privs for that user, and check for 'evb' priv.
 5287:                 my (%allroles,%userroles);
 5288:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5289:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5290:                         my ($trole,$tdom,$tnum,$tsec);
 5291:                         if ($entry =~ /^cr/) {
 5292:                             ($trole,$tdom,$tnum,$tsec) = 
 5293:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5294:                         } else {
 5295:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5296:                         }
 5297:                         my ($spec,$area,$trest);
 5298:                         $area = '/'.$tdom.'/'.$tnum;
 5299:                         $trest = $tnum;
 5300:                         if ($tsec ne '') {
 5301:                             $area .= '/'.$tsec;
 5302:                             $trest .= '/'.$tsec;
 5303:                         }
 5304:                         $spec = $trole.'.'.$area;
 5305:                         if ($trole =~ /^cr/) {
 5306:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5307:                                                               $tdom,$spec,$trest,$area);
 5308:                         } else {
 5309:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5310:                                                                 $tdom,$spec,$trest,$area);
 5311:                         }
 5312:                     }
 5313:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5314:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5315:                         if ($1) {
 5316:                             $no_userblock = 1;
 5317:                             last;
 5318:                         }
 5319:                     }
 5320:                 }
 5321:             } else {
 5322:                 # Resource belongs to current user
 5323:                 # Check for 'evb' priv via lonnet::allowed().
 5324:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5325:                     $no_ownblock = 1;
 5326:                     last;
 5327:                 }
 5328:             }
 5329:         }
 5330:         # if they have the evb priv and are currently not playing student
 5331:         next if (($no_ownblock) &&
 5332:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5333:         next if ($no_userblock);
 5334: 
 5335:         # Retrieve blocking times and identity of blocker for course
 5336:         # of specified user, unless user has 'evb' privilege.
 5337: 
 5338:         my ($start,$end,$trigger) = 
 5339:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5340:         if (($start != 0) && 
 5341:             (($startblock == 0) || ($startblock > $start))) {
 5342:             $startblock = $start;
 5343:             if ($trigger ne '') {
 5344:                 $triggerblock = $trigger;
 5345:             }
 5346:         }
 5347:         if (($end != 0)  &&
 5348:             (($endblock == 0) || ($endblock < $end))) {
 5349:             $endblock = $end;
 5350:             if ($trigger ne '') {
 5351:                 $triggerblock = $trigger;
 5352:             }
 5353:         }
 5354:     }
 5355:     return ($startblock,$endblock,$triggerblock);
 5356: }
 5357: 
 5358: sub get_blocks {
 5359:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5360:     my $startblock = 0;
 5361:     my $endblock = 0;
 5362:     my $triggerblock = '';
 5363:     my $course = $cdom.'_'.$cnum;
 5364:     $setters->{$course} = {};
 5365:     $setters->{$course}{'staff'} = [];
 5366:     $setters->{$course}{'times'} = [];
 5367:     $setters->{$course}{'triggers'} = [];
 5368:     my (@blockers,%triggered);
 5369:     my $now = time;
 5370:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5371:     if ($activity eq 'docs') {
 5372:         my ($blocked,$nosymbcache,$noenccheck);
 5373:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5374:             $blocked = 1;
 5375:             $nosymbcache = 1;
 5376:             $noenccheck = 1;
 5377:         }
 5378:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5379:         foreach my $block (@blockers) {
 5380:             if ($block =~ /^firstaccess____(.+)$/) {
 5381:                 my $item = $1;
 5382:                 my $type = 'map';
 5383:                 my $timersymb = $item;
 5384:                 if ($item eq 'course') {
 5385:                     $type = 'course';
 5386:                 } elsif ($item =~ /___\d+___/) {
 5387:                     $type = 'resource';
 5388:                 } else {
 5389:                     $timersymb = &Apache::lonnet::symbread($item);
 5390:                 }
 5391:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5392:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5393:                 $triggered{$block} = {
 5394:                                        start => $start,
 5395:                                        end   => $end,
 5396:                                        type  => $type,
 5397:                                      };
 5398:             }
 5399:         }
 5400:     } else {
 5401:         foreach my $block (keys(%commblocks)) {
 5402:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5403:                 my ($start,$end) = ($1,$2);
 5404:                 if ($start <= time && $end >= time) {
 5405:                     if (ref($commblocks{$block}) eq 'HASH') {
 5406:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5407:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5408:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5409:                                     push(@blockers,$block);
 5410:                                 }
 5411:                             }
 5412:                         }
 5413:                     }
 5414:                 }
 5415:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5416:                 my $item = $1;
 5417:                 my $timersymb = $item; 
 5418:                 my $type = 'map';
 5419:                 if ($item eq 'course') {
 5420:                     $type = 'course';
 5421:                 } elsif ($item =~ /___\d+___/) {
 5422:                     $type = 'resource';
 5423:                 } else {
 5424:                     $timersymb = &Apache::lonnet::symbread($item);
 5425:                 }
 5426:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5427:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5428:                 if ($start && $end) {
 5429:                     if (($start <= time) && ($end >= time)) {
 5430:                         if (ref($commblocks{$block}) eq 'HASH') {
 5431:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5432:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5433:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5434:                                         push(@blockers,$block);
 5435:                                         $triggered{$block} = {
 5436:                                                                start => $start,
 5437:                                                                end   => $end,
 5438:                                                                type  => $type,
 5439:                                                              };
 5440:                                     }
 5441:                                 }
 5442:                             }
 5443:                         }
 5444:                     }
 5445:                 }
 5446:             }
 5447:         }
 5448:     }
 5449:     foreach my $blocker (@blockers) {
 5450:         my ($staff_name,$staff_dom,$title,$blocks) =
 5451:             &parse_block_record($commblocks{$blocker});
 5452:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5453:         my ($start,$end,$triggertype);
 5454:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5455:             ($start,$end) = ($1,$2);
 5456:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5457:             $start = $triggered{$blocker}{'start'};
 5458:             $end = $triggered{$blocker}{'end'};
 5459:             $triggertype = $triggered{$blocker}{'type'};
 5460:         }
 5461:         if ($start) {
 5462:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5463:             if ($triggertype) {
 5464:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5465:             } else {
 5466:                 push(@{$$setters{$course}{'triggers'}},0);
 5467:             }
 5468:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5469:                 $startblock = $start;
 5470:                 if ($triggertype) {
 5471:                     $triggerblock = $blocker;
 5472:                 }
 5473:             }
 5474:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5475:                $endblock = $end;
 5476:                if ($triggertype) {
 5477:                    $triggerblock = $blocker;
 5478:                }
 5479:             }
 5480:         }
 5481:     }
 5482:     return ($startblock,$endblock,$triggerblock);
 5483: }
 5484: 
 5485: sub parse_block_record {
 5486:     my ($record) = @_;
 5487:     my ($setuname,$setudom,$title,$blocks);
 5488:     if (ref($record) eq 'HASH') {
 5489:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5490:         $title = &unescape($record->{'event'});
 5491:         $blocks = $record->{'blocks'};
 5492:     } else {
 5493:         my @data = split(/:/,$record,3);
 5494:         if (scalar(@data) eq 2) {
 5495:             $title = $data[1];
 5496:             ($setuname,$setudom) = split(/@/,$data[0]);
 5497:         } else {
 5498:             ($setuname,$setudom,$title) = @data;
 5499:         }
 5500:         $blocks = { 'com' => 'on' };
 5501:     }
 5502:     return ($setuname,$setudom,$title,$blocks);
 5503: }
 5504: 
 5505: sub blocking_status {
 5506:     my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5507:     my %setters;
 5508: 
 5509: # check for active blocking
 5510:     my ($startblock,$endblock,$triggerblock) = 
 5511:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
 5512:     my $blocked = 0;
 5513:     if ($startblock && $endblock) {
 5514:         $blocked = 1;
 5515:     }
 5516: 
 5517: # caller just wants to know whether a block is active
 5518:     if (!wantarray) { return $blocked; }
 5519: 
 5520: # build a link to a popup window containing the details
 5521:     my $querystring  = "?activity=$activity";
 5522: # $uname and $udom decide whose portfolio the user is trying to look at
 5523:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5524:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5525:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5526:     } elsif ($activity eq 'docs') {
 5527:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5528:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5529:         if ($symb) {
 5530:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5531:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5532:         }
 5533:     }
 5534: 
 5535:     my $output .= <<'END_MYBLOCK';
 5536: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5537:     var options = "width=" + w + ",height=" + h + ",";
 5538:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5539:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5540:     var newWin = window.open(url, wdwName, options);
 5541:     newWin.focus();
 5542: }
 5543: END_MYBLOCK
 5544: 
 5545:     $output = Apache::lonhtmlcommon::scripttag($output);
 5546:   
 5547:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5548:     my $text = &mt('Communication Blocked');
 5549:     my $class = 'LC_comblock';
 5550:     if ($activity eq 'docs') {
 5551:         $text = &mt('Content Access Blocked');
 5552:         $class = '';
 5553:     } elsif ($activity eq 'printout') {
 5554:         $text = &mt('Printing Blocked');
 5555:     } elsif ($activity eq 'passwd') {
 5556:         $text = &mt('Password Changing Blocked');
 5557:     } elsif ($activity eq 'grades') {
 5558:         $text = &mt('Gradebook Blocked');
 5559:     } elsif ($activity eq 'search') {
 5560:         $text = &mt('Search Blocked');
 5561:     } elsif ($activity eq 'alert') {
 5562:         $text = &mt('Checking Critical Messages Blocked');
 5563:     } elsif ($activity eq 'reinit') {
 5564:         $text = &mt('Checking Course Update Blocked');
 5565:     }
 5566:     $output .= <<"END_BLOCK";
 5567: <div class='$class'>
 5568:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5569:   title='$text'>
 5570:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5571:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5572:   title='$text'>$text</a>
 5573: </div>
 5574: 
 5575: END_BLOCK
 5576: 
 5577:     return ($blocked, $output);
 5578: }
 5579: 
 5580: ###############################################
 5581: 
 5582: sub check_ip_acc {
 5583:     my ($acc,$clientip)=@_;
 5584:     &Apache::lonxml::debug("acc is $acc");
 5585:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5586:         return 1;
 5587:     }
 5588:     my ($ip,$allowed);
 5589:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5590:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5591:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5592:     } else {
 5593:         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
 5594:     }
 5595: 
 5596:     my $name;
 5597:     my %access = (
 5598:                      allowfrom => 1,
 5599:                      denyfrom  => 0,
 5600:                  );
 5601:     my @allows;
 5602:     my @denies;
 5603:     foreach my $item (split(',',$acc)) {
 5604:         $item =~ s/^\s*//;
 5605:         $item =~ s/\s*$//;
 5606:         my $pattern;
 5607:         if ($item =~ /^\!(.+)$/) {
 5608:             push(@denies,$1);
 5609:         } else {
 5610:             push(@allows,$item);
 5611:         }
 5612:    }
 5613:    my $numdenies = scalar(@denies);
 5614:    my $numallows = scalar(@allows);
 5615:    my $count = 0;
 5616:    foreach my $pattern (@denies,@allows) {
 5617:         $count ++; 
 5618:         my $acctype = 'allowfrom';
 5619:         if ($count <= $numdenies) {
 5620:             $acctype = 'denyfrom';
 5621:         }
 5622:         if ($pattern =~ /\*$/) {
 5623:             #35.8.*
 5624:             $pattern=~s/\*//;
 5625:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5626:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5627:             #35.8.3.[34-56]
 5628:             my $low=$2;
 5629:             my $high=$3;
 5630:             $pattern=$1;
 5631:             if ($ip =~ /^\Q$pattern\E/) {
 5632:                 my $last=(split(/\./,$ip))[3];
 5633:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5634:             }
 5635:         } elsif ($pattern =~ /^\*/) {
 5636:             #*.msu.edu
 5637:             $pattern=~s/\*//;
 5638:             if (!defined($name)) {
 5639:                 use Socket;
 5640:                 my $netaddr=inet_aton($ip);
 5641:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5642:             }
 5643:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5644:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5645:             #127.0.0.1
 5646:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5647:         } else {
 5648:             #some.name.com
 5649:             if (!defined($name)) {
 5650:                 use Socket;
 5651:                 my $netaddr=inet_aton($ip);
 5652:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5653:             }
 5654:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5655:         }
 5656:         if ($allowed =~ /^(0|1)$/) { last; }
 5657:     }
 5658:     if ($allowed eq '') {
 5659:         if ($numdenies && !$numallows) {
 5660:             $allowed = 1;
 5661:         } else {
 5662:             $allowed = 0;
 5663:         }
 5664:     }
 5665:     return $allowed;
 5666: }
 5667: 
 5668: ###############################################
 5669: 
 5670: =pod
 5671: 
 5672: =head1 Domain Template Functions
 5673: 
 5674: =over 4
 5675: 
 5676: =item * &determinedomain()
 5677: 
 5678: Inputs: $domain (usually will be undef)
 5679: 
 5680: Returns: Determines which domain should be used for designs
 5681: 
 5682: =cut
 5683: 
 5684: ###############################################
 5685: sub determinedomain {
 5686:     my $domain=shift;
 5687:     if (! $domain) {
 5688:         # Determine domain if we have not been given one
 5689:         $domain = &Apache::lonnet::default_login_domain();
 5690:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5691:         if ($env{'request.role.domain'}) { 
 5692:             $domain=$env{'request.role.domain'}; 
 5693:         }
 5694:     }
 5695:     return $domain;
 5696: }
 5697: ###############################################
 5698: 
 5699: sub devalidate_domconfig_cache {
 5700:     my ($udom)=@_;
 5701:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5702: }
 5703: 
 5704: # ---------------------- Get domain configuration for a domain
 5705: sub get_domainconf {
 5706:     my ($udom) = @_;
 5707:     my $cachetime=1800;
 5708:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5709:     if (defined($cached)) { return %{$result}; }
 5710: 
 5711:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5712: 					     ['login','rolecolors','autoenroll'],$udom);
 5713:     my (%designhash,%legacy);
 5714:     if (keys(%domconfig) > 0) {
 5715:         if (ref($domconfig{'login'}) eq 'HASH') {
 5716:             if (keys(%{$domconfig{'login'}})) {
 5717:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5718:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5719:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5720:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5721:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5722:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5723:                                         if ($key eq 'loginvia') {
 5724:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5725:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5726:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5727:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5728: 
 5729:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5730:                                                 } else {
 5731:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5732:                                                 }
 5733:                                             }
 5734:                                         } elsif ($key eq 'headtag') {
 5735:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5736:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5737:                                             }
 5738:                                         }
 5739:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5740:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5741:                                         }
 5742:                                     }
 5743:                                 }
 5744:                             }
 5745:                         } else {
 5746:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5747:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5748:                                     $domconfig{'login'}{$key}{$img};
 5749:                             }
 5750:                         }
 5751:                     } else {
 5752:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5753:                     }
 5754:                 }
 5755:             } else {
 5756:                 $legacy{'login'} = 1;
 5757:             }
 5758:         } else {
 5759:             $legacy{'login'} = 1;
 5760:         }
 5761:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5762:             if (keys(%{$domconfig{'rolecolors'}})) {
 5763:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5764:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5765:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5766:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5767:                         }
 5768:                     }
 5769:                 }
 5770:             } else {
 5771:                 $legacy{'rolecolors'} = 1;
 5772:             }
 5773:         } else {
 5774:             $legacy{'rolecolors'} = 1;
 5775:         }
 5776:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5777:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5778:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5779:             }
 5780:         }
 5781:         if (keys(%legacy) > 0) {
 5782:             my %legacyhash = &get_legacy_domconf($udom);
 5783:             foreach my $item (keys(%legacyhash)) {
 5784:                 if ($item =~ /^\Q$udom\E\.login/) {
 5785:                     if ($legacy{'login'}) { 
 5786:                         $designhash{$item} = $legacyhash{$item};
 5787:                     }
 5788:                 } else {
 5789:                     if ($legacy{'rolecolors'}) {
 5790:                         $designhash{$item} = $legacyhash{$item};
 5791:                     }
 5792:                 }
 5793:             }
 5794:         }
 5795:     } else {
 5796:         %designhash = &get_legacy_domconf($udom); 
 5797:     }
 5798:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5799: 				  $cachetime);
 5800:     return %designhash;
 5801: }
 5802: 
 5803: sub get_legacy_domconf {
 5804:     my ($udom) = @_;
 5805:     my %legacyhash;
 5806:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5807:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5808:     if (-e $designfile) {
 5809:         if ( open (my $fh,'<',$designfile) ) {
 5810:             while (my $line = <$fh>) {
 5811:                 next if ($line =~ /^\#/);
 5812:                 chomp($line);
 5813:                 my ($key,$val)=(split(/\=/,$line));
 5814:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5815:             }
 5816:             close($fh);
 5817:         }
 5818:     }
 5819:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5820:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5821:     }
 5822:     return %legacyhash;
 5823: }
 5824: 
 5825: =pod
 5826: 
 5827: =item * &domainlogo()
 5828: 
 5829: Inputs: $domain (usually will be undef)
 5830: 
 5831: Returns: A link to a domain logo, if the domain logo exists.
 5832: If the domain logo does not exist, a description of the domain.
 5833: 
 5834: =cut
 5835: 
 5836: ###############################################
 5837: sub domainlogo {
 5838:     my $domain = &determinedomain(shift);
 5839:     my %designhash = &get_domainconf($domain);    
 5840:     # See if there is a logo
 5841:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5842:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5843:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5844: 	    if ($imgsrc =~ m{^/res/}) {
 5845: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5846: 		&Apache::lonnet::repcopy($local_name);
 5847: 	    }
 5848: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5849:         } 
 5850:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5851:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5852:         return &Apache::lonnet::domain($domain,'description');
 5853:     } else {
 5854:         return '';
 5855:     }
 5856: }
 5857: ##############################################
 5858: 
 5859: =pod
 5860: 
 5861: =item * &designparm()
 5862: 
 5863: Inputs: $which parameter; $domain (usually will be undef)
 5864: 
 5865: Returns: value of designparamter $which
 5866: 
 5867: =cut
 5868: 
 5869: 
 5870: ##############################################
 5871: sub designparm {
 5872:     my ($which,$domain)=@_;
 5873:     if (exists($env{'environment.color.'.$which})) {
 5874:         return $env{'environment.color.'.$which};
 5875:     }
 5876:     $domain=&determinedomain($domain);
 5877:     my %domdesign;
 5878:     unless ($domain eq 'public') {
 5879:         %domdesign = &get_domainconf($domain);
 5880:     }
 5881:     my $output;
 5882:     if ($domdesign{$domain.'.'.$which} ne '') {
 5883:         $output = $domdesign{$domain.'.'.$which};
 5884:     } else {
 5885:         $output = $defaultdesign{$which};
 5886:     }
 5887:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5888:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5889:         if ($output =~ m{^/(adm|res)/}) {
 5890:             if ($output =~ m{^/res/}) {
 5891:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5892:                 &Apache::lonnet::repcopy($local_name);
 5893:             }
 5894:             $output = &lonhttpdurl($output);
 5895:         }
 5896:     }
 5897:     return $output;
 5898: }
 5899: 
 5900: ##############################################
 5901: =pod
 5902: 
 5903: =item * &authorspace()
 5904: 
 5905: Inputs: $url (usually will be undef).
 5906: 
 5907: Returns: Path to Authoring Space containing the resource or 
 5908:          directory being viewed (or for which action is being taken). 
 5909:          If $url is provided, and begins /priv/<domain>/<uname>
 5910:          the path will be that portion of the $context argument.
 5911:          Otherwise the path will be for the author space of the current
 5912:          user when the current role is author, or for that of the 
 5913:          co-author/assistant co-author space when the current role 
 5914:          is co-author or assistant co-author.
 5915: 
 5916: =cut
 5917: 
 5918: sub authorspace {
 5919:     my ($url) = @_;
 5920:     if ($url ne '') {
 5921:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5922:            return $1;
 5923:         }
 5924:     }
 5925:     my $caname = '';
 5926:     my $cadom = '';
 5927:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5928:         ($cadom,$caname) =
 5929:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5930:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5931:         $caname = $env{'user.name'};
 5932:         $cadom = $env{'user.domain'};
 5933:     }
 5934:     if (($caname ne '') && ($cadom ne '')) {
 5935:         return "/priv/$cadom/$caname/";
 5936:     }
 5937:     return;
 5938: }
 5939: 
 5940: ##############################################
 5941: =pod
 5942: 
 5943: =item * &head_subbox()
 5944: 
 5945: Inputs: $content (contains HTML code with page functions, etc.)
 5946: 
 5947: Returns: HTML div with $content
 5948:          To be included in page header
 5949: 
 5950: =cut
 5951: 
 5952: sub head_subbox {
 5953:     my ($content)=@_;
 5954:     my $output =
 5955:         '<div class="LC_head_subbox">'
 5956:        .$content
 5957:        .'</div>'
 5958: }
 5959: 
 5960: ##############################################
 5961: =pod
 5962: 
 5963: =item * &CSTR_pageheader()
 5964: 
 5965: Input: (optional) filename from which breadcrumb trail is built.
 5966:        In most cases no input as needed, as $env{'request.filename'}
 5967:        is appropriate for use in building the breadcrumb trail.
 5968: 
 5969: Returns: HTML div with CSTR path and recent box
 5970:          To be included on Authoring Space pages
 5971: 
 5972: =cut
 5973: 
 5974: sub CSTR_pageheader {
 5975:     my ($trailfile) = @_;
 5976:     if ($trailfile eq '') {
 5977:         $trailfile = $env{'request.filename'};
 5978:     }
 5979: 
 5980: # this is for resources; directories have customtitle, and crumbs
 5981: # and select recent are created in lonpubdir.pm
 5982: 
 5983:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5984:     my ($udom,$uname,$thisdisfn)=
 5985:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5986:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5987:     $formaction =~ s{/+}{/}g;
 5988: 
 5989:     my $parentpath = '';
 5990:     my $lastitem = '';
 5991:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5992:         $parentpath = $1;
 5993:         $lastitem = $2;
 5994:     } else {
 5995:         $lastitem = $thisdisfn;
 5996:     }
 5997: 
 5998:     my ($crsauthor,$title);
 5999:     if (($env{'request.course.id'}) &&
 6000:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6001:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6002:         $crsauthor = 1;
 6003:         $title = &mt('Course Authoring Space');
 6004:     } else {
 6005:         $title = &mt('Authoring Space');
 6006:     }
 6007: 
 6008:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
 6009:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6010:         $target = '';
 6011:         $crumbtarget = '';
 6012:     }
 6013: 
 6014:     my $output =
 6015:          '<div>'
 6016:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6017:         .'<b>'.$title.'</b> '
 6018:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6019:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6020: 
 6021:     if ($lastitem) {
 6022:         $output .=
 6023:              '<span class="LC_filename">'
 6024:             .$lastitem
 6025:             .'</span>';
 6026:     }
 6027: 
 6028:     if ($crsauthor) {
 6029:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 6030:     } else {
 6031:         $output .=
 6032:              '<br />'
 6033:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6034:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6035:             .'</form>'
 6036:             .&Apache::lonmenu::constspaceform();
 6037:     }
 6038:     $output .= '</div>';
 6039: 
 6040:     return $output;
 6041: }
 6042: 
 6043: ###############################################
 6044: ###############################################
 6045: 
 6046: =pod
 6047: 
 6048: =back
 6049: 
 6050: =head1 HTML Helpers
 6051: 
 6052: =over 4
 6053: 
 6054: =item * &bodytag()
 6055: 
 6056: Returns a uniform header for LON-CAPA web pages.
 6057: 
 6058: Inputs: 
 6059: 
 6060: =over 4
 6061: 
 6062: =item * $title, A title to be displayed on the page.
 6063: 
 6064: =item * $function, the current role (can be undef).
 6065: 
 6066: =item * $addentries, extra parameters for the <body> tag.
 6067: 
 6068: =item * $bodyonly, if defined, only return the <body> tag.
 6069: 
 6070: =item * $domain, if defined, force a given domain.
 6071: 
 6072: =item * $forcereg, if page should register as content page (relevant for 
 6073:             text interface only)
 6074: 
 6075: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6076:                      navigational links
 6077: 
 6078: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6079: 
 6080: =item * $args, optional argument valid values are
 6081:             no_auto_mt_title -> prevents &mt()ing the title arg
 6082:             use_absolute     -> for external resource or syllabus, this will
 6083:                                 contain https://<hostname> if server uses
 6084:                                 https (as per hosts.tab), but request is for http
 6085:             hostname         -> hostname, from $r->hostname().
 6086: 
 6087: =item * $advtoolsref, optional argument, ref to an array containing
 6088:             inlineremote items to be added in "Functions" menu below
 6089:             breadcrumbs.
 6090: 
 6091: =item * $ltiscope, optional argument, will be one of: resource, map or
 6092:             course, if LON-CAPA is in LTI Provider context. Value is
 6093:             the scope of use, i.e., launch was for access to a single, a map
 6094:             or the entire course.
 6095: 
 6096: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6097:             context, this will contain the URL for the landing item in
 6098:             the course, after launch from an LTI Consumer
 6099: 
 6100: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6101:             context, this will contain a reference to hash of items
 6102:             to be included in the page header and/or inline menu.
 6103: 
 6104: =back
 6105: 
 6106: Returns: A uniform header for LON-CAPA web pages.  
 6107: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6108: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6109: other decorations will be returned.
 6110: 
 6111: =cut
 6112: 
 6113: sub bodytag {
 6114:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6115:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
 6116: 
 6117:     my $public;
 6118:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6119:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6120:         $public = 1;
 6121:     }
 6122:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6123:     my $httphost = $args->{'use_absolute'};
 6124:     my $hostname = $args->{'hostname'};
 6125: 
 6126:     $function = &get_users_function() if (!$function);
 6127:     my $img =    &designparm($function.'.img',$domain);
 6128:     my $font =   &designparm($function.'.font',$domain);
 6129:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6130: 
 6131:     my %design = ( 'style'   => 'margin-top: 0',
 6132: 		   'bgcolor' => $pgbg,
 6133: 		   'text'    => $font,
 6134:                    'alink'   => &designparm($function.'.alink',$domain),
 6135: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6136: 		   'link'    => &designparm($function.'.link',$domain),);
 6137:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6138: 
 6139:  # role and realm
 6140:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6141:     if ($realm) {
 6142:         $realm = '/'.$realm;
 6143:     }
 6144:     if ($role  eq 'ca') {
 6145:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6146:         $realm = &plainname($rname,$rdom);
 6147:     } 
 6148: # realm
 6149:     if ($env{'request.course.id'}) {
 6150:         if ($env{'request.role'} !~ /^cr/) {
 6151:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6152:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6153:             if ($env{'request.role.desc'}) {
 6154:                 $role = $env{'request.role.desc'};
 6155:             } else {
 6156:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6157:             }
 6158:         } else {
 6159:             $role = (split(/\//,$role,4))[-1]; 
 6160:         }
 6161:         if ($env{'request.course.sec'}) {
 6162:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 6163:         }   
 6164: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 6165:     } else {
 6166:         $role = &Apache::lonnet::plaintext($role);
 6167:     }
 6168: 
 6169:     if (!$realm) { $realm='&nbsp;'; }
 6170: 
 6171:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6172: 
 6173: # construct main body tag
 6174:     my $bodytag = "<body $extra_body_attr>".
 6175: 	&Apache::lontexconvert::init_math_support();
 6176: 
 6177:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6178: 
 6179:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6180:         return $bodytag;
 6181:     }
 6182: 
 6183:     if ($public) {
 6184: 	undef($role);
 6185:     }
 6186: 
 6187:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 6188:         if (ref($ltimenu) eq 'HASH') {
 6189:             unless ($ltimenu->{'role'}) {
 6190:                 undef($role);
 6191:             }
 6192:             unless ($ltimenu->{'coursetitle'}) {
 6193:                 $realm='&nbsp;';
 6194:             }
 6195:         }
 6196:     }
 6197: 
 6198:     my $titleinfo = '<h1>'.$title.'</h1>';
 6199:     #
 6200:     # Extra info if you are the DC
 6201:     my $dc_info = '';
 6202:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 6203:                         $env{'course.'.$env{'request.course.id'}.
 6204:                                  '.domain'}.'/'})) {
 6205:         my $cid = $env{'request.course.id'};
 6206:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6207:         $dc_info =~ s/\s+$//;
 6208:     }
 6209: 
 6210:     my $crstype;
 6211:     if ($env{'request.course.id'}) {
 6212:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 6213:     } elsif ($args->{'crstype'}) {
 6214:         $crstype = $args->{'crstype'};
 6215:     }
 6216:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6217:         undef($role);
 6218:     } else {
 6219:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6220:     }
 6221: 
 6222:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6223: 
 6224:         #    if ($env{'request.state'} eq 'construct') {
 6225:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6226:         #    }
 6227: 
 6228:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6229:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6230: 
 6231:         unless ($args->{'no_primary_menu'}) {
 6232:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
 6233: 
 6234:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6235:                 if ($dc_info) {
 6236:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6237:                 }
 6238:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6239:                                <em>$realm</em> $dc_info</div>|;
 6240:                 return $bodytag;
 6241:             }
 6242: 
 6243:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6244:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6245:             }
 6246: 
 6247:             $bodytag .= $right;
 6248: 
 6249:             if ($dc_info) {
 6250:                 $dc_info = &dc_courseid_toggle($dc_info);
 6251:             }
 6252:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6253:         }
 6254: 
 6255:         #if directed to not display the secondary menu, don't.  
 6256:         if ($args->{'no_secondary_menu'}) {
 6257:             return $bodytag;
 6258:         }
 6259:         #don't show menus for public users
 6260:         if (!$public){
 6261:             unless ($args->{'no_inline_menu'}) {
 6262:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6263:                                                             $args->{'no_primary_menu'});
 6264:             }
 6265:             $bodytag .= Apache::lonmenu::serverform();
 6266:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6267:             if ($env{'request.state'} eq 'construct') {
 6268:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6269:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
 6270:             } elsif ($forcereg) {
 6271:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6272:                                                             $args->{'group'},
 6273:                                                             $args->{'hide_buttons'},
 6274:                                                             $hostname,$ltiscope,$ltiuri);
 6275:             } else {
 6276:                 $bodytag .= 
 6277:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6278:                                                         $forcereg,$args->{'group'},
 6279:                                                         $args->{'bread_crumbs'},
 6280:                                                         $advtoolsref,'',$hostname);
 6281:             }
 6282:         }else{
 6283:             # this is to seperate menu from content when there's no secondary
 6284:             # menu. Especially needed for public accessible ressources.
 6285:             $bodytag .= '<hr style="clear:both" />';
 6286:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6287:         }
 6288: 
 6289:         return $bodytag;
 6290: }
 6291: 
 6292: sub dc_courseid_toggle {
 6293:     my ($dc_info) = @_;
 6294:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6295:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6296:            &mt('(More ...)').'</a></span>'.
 6297:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6298: }
 6299: 
 6300: sub make_attr_string {
 6301:     my ($register,$attr_ref) = @_;
 6302: 
 6303:     if ($attr_ref && !ref($attr_ref)) {
 6304: 	die("addentries Must be a hash ref ".
 6305: 	    join(':',caller(1))." ".
 6306: 	    join(':',caller(0))." ");
 6307:     }
 6308: 
 6309:     if ($register) {
 6310: 	my ($on_load,$on_unload);
 6311: 	foreach my $key (keys(%{$attr_ref})) {
 6312: 	    if      (lc($key) eq 'onload') {
 6313: 		$on_load.=$attr_ref->{$key}.';';
 6314: 		delete($attr_ref->{$key});
 6315: 
 6316: 	    } elsif (lc($key) eq 'onunload') {
 6317: 		$on_unload.=$attr_ref->{$key}.';';
 6318: 		delete($attr_ref->{$key});
 6319: 	    }
 6320: 	}
 6321: 	$attr_ref->{'onload'}  = $on_load;
 6322: 	$attr_ref->{'onunload'}= $on_unload;
 6323:     }
 6324: 
 6325:     my $attr_string;
 6326:     foreach my $attr (sort(keys(%$attr_ref))) {
 6327: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6328:     }
 6329:     return $attr_string;
 6330: }
 6331: 
 6332: 
 6333: ###############################################
 6334: ###############################################
 6335: 
 6336: =pod
 6337: 
 6338: =item * &endbodytag()
 6339: 
 6340: Returns a uniform footer for LON-CAPA web pages.
 6341: 
 6342: Inputs: 1 - optional reference to an args hash
 6343: If in the hash, key for noredirectlink has a value which evaluates to true,
 6344: a 'Continue' link is not displayed if the page contains an
 6345: internal redirect in the <head></head> section,
 6346: i.e., $env{'internal.head.redirect'} exists   
 6347: 
 6348: =cut
 6349: 
 6350: sub endbodytag {
 6351:     my ($args) = @_;
 6352:     my $endbodytag;
 6353:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6354:         $endbodytag='</body>';
 6355:     }
 6356:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6357:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6358: 	    $endbodytag=
 6359: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6360: 	        &mt('Continue').'</a>'.
 6361: 	        $endbodytag;
 6362:         }
 6363:     }
 6364:     return $endbodytag;
 6365: }
 6366: 
 6367: =pod
 6368: 
 6369: =item * &standard_css()
 6370: 
 6371: Returns a style sheet
 6372: 
 6373: Inputs: (all optional)
 6374:             domain         -> force to color decorate a page for a specific
 6375:                                domain
 6376:             function       -> force usage of a specific rolish color scheme
 6377:             bgcolor        -> override the default page bgcolor
 6378: 
 6379: =cut
 6380: 
 6381: sub standard_css {
 6382:     my ($function,$domain,$bgcolor) = @_;
 6383:     $function  = &get_users_function() if (!$function);
 6384:     my $img    = &designparm($function.'.img',   $domain);
 6385:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6386:     my $font   = &designparm($function.'.font',  $domain);
 6387:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6388: #second colour for later usage
 6389:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6390:     my $pgbg_or_bgcolor =
 6391: 	         $bgcolor ||
 6392: 	         &designparm($function.'.pgbg',  $domain);
 6393:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6394:     my $alink  = &designparm($function.'.alink', $domain);
 6395:     my $vlink  = &designparm($function.'.vlink', $domain);
 6396:     my $link   = &designparm($function.'.link',  $domain);
 6397: 
 6398:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6399:     my $mono                 = 'monospace';
 6400:     my $data_table_head      = $sidebg;
 6401:     my $data_table_light     = '#FAFAFA';
 6402:     my $data_table_dark      = '#E0E0E0';
 6403:     my $data_table_darker    = '#CCCCCC';
 6404:     my $data_table_highlight = '#FFFF00';
 6405:     my $mail_new             = '#FFBB77';
 6406:     my $mail_new_hover       = '#DD9955';
 6407:     my $mail_read            = '#BBBB77';
 6408:     my $mail_read_hover      = '#999944';
 6409:     my $mail_replied         = '#AAAA88';
 6410:     my $mail_replied_hover   = '#888855';
 6411:     my $mail_other           = '#99BBBB';
 6412:     my $mail_other_hover     = '#669999';
 6413:     my $table_header         = '#DDDDDD';
 6414:     my $feedback_link_bg     = '#BBBBBB';
 6415:     my $lg_border_color      = '#C8C8C8';
 6416:     my $button_hover         = '#BF2317';
 6417: 
 6418:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6419:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6420:                                              : '0 3px 0 4px';
 6421: 
 6422: 
 6423:     return <<END;
 6424: 
 6425: /* needed for iframe to allow 100% height in FF */
 6426: body, html { 
 6427:     margin: 0;
 6428:     padding: 0 0.5%;
 6429:     height: 99%; /* to avoid scrollbars */
 6430: }
 6431: 
 6432: body {
 6433:   font-family: $sans;
 6434:   line-height:130%;
 6435:   font-size:0.83em;
 6436:   color:$font;
 6437: }
 6438: 
 6439: a:focus,
 6440: a:focus img {
 6441:   color: red;
 6442: }
 6443: 
 6444: form, .inline {
 6445:   display: inline;
 6446: }
 6447: 
 6448: .LC_right {
 6449:   text-align:right;
 6450: }
 6451: 
 6452: .LC_middle {
 6453:   vertical-align:middle;
 6454: }
 6455: 
 6456: .LC_floatleft {
 6457:   float: left;
 6458: }
 6459: 
 6460: .LC_floatright {
 6461:   float: right;
 6462: }
 6463: 
 6464: .LC_400Box {
 6465:   width:400px;
 6466: }
 6467: 
 6468: .LC_iframecontainer {
 6469:     width: 98%;
 6470:     margin: 0;
 6471:     position: fixed;
 6472:     top: 8.5em;
 6473:     bottom: 0;
 6474: }
 6475: 
 6476: .LC_iframecontainer iframe{
 6477:     border: none;
 6478:     width: 100%;
 6479:     height: 100%;
 6480: }
 6481: 
 6482: .LC_filename {
 6483:   font-family: $mono;
 6484:   white-space:pre;
 6485:   font-size: 120%;
 6486: }
 6487: 
 6488: .LC_fileicon {
 6489:   border: none;
 6490:   height: 1.3em;
 6491:   vertical-align: text-bottom;
 6492:   margin-right: 0.3em;
 6493:   text-decoration:none;
 6494: }
 6495: 
 6496: .LC_setting {
 6497:   text-decoration:underline;
 6498: }
 6499: 
 6500: .LC_error {
 6501:   color: red;
 6502: }
 6503: 
 6504: .LC_warning {
 6505:   color: darkorange;
 6506: }
 6507: 
 6508: .LC_diff_removed {
 6509:   color: red;
 6510: }
 6511: 
 6512: .LC_info,
 6513: .LC_success,
 6514: .LC_diff_added {
 6515:   color: green;
 6516: }
 6517: 
 6518: div.LC_confirm_box {
 6519:   background-color: #FAFAFA;
 6520:   border: 1px solid $lg_border_color;
 6521:   margin-right: 0;
 6522:   padding: 5px;
 6523: }
 6524: 
 6525: div.LC_confirm_box .LC_error img,
 6526: div.LC_confirm_box .LC_success img {
 6527:   vertical-align: middle;
 6528: }
 6529: 
 6530: .LC_maxwidth {
 6531:   max-width: 100%;
 6532:   height: auto;
 6533: }
 6534: 
 6535: .LC_textsize_mobile {
 6536:   \@media only screen and (max-device-width: 480px) {
 6537:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6538:   }
 6539: }
 6540: 
 6541: .LC_icon {
 6542:   border: none;
 6543:   vertical-align: middle;
 6544: }
 6545: 
 6546: .LC_docs_spacer {
 6547:   width: 25px;
 6548:   height: 1px;
 6549:   border: none;
 6550: }
 6551: 
 6552: .LC_internal_info {
 6553:   color: #999999;
 6554: }
 6555: 
 6556: .LC_discussion {
 6557:   background: $data_table_dark;
 6558:   border: 1px solid black;
 6559:   margin: 2px;
 6560: }
 6561: 
 6562: .LC_disc_action_left {
 6563:   background: $sidebg;
 6564:   text-align: left;
 6565:   padding: 4px;
 6566:   margin: 2px;
 6567: }
 6568: 
 6569: .LC_disc_action_right {
 6570:   background: $sidebg;
 6571:   text-align: right;
 6572:   padding: 4px;
 6573:   margin: 2px;
 6574: }
 6575: 
 6576: .LC_disc_new_item {
 6577:   background: white;
 6578:   border: 2px solid red;
 6579:   margin: 4px;
 6580:   padding: 4px;
 6581: }
 6582: 
 6583: .LC_disc_old_item {
 6584:   background: white;
 6585:   margin: 4px;
 6586:   padding: 4px;
 6587: }
 6588: 
 6589: table.LC_pastsubmission {
 6590:   border: 1px solid black;
 6591:   margin: 2px;
 6592: }
 6593: 
 6594: table#LC_menubuttons {
 6595:   width: 100%;
 6596:   background: $pgbg;
 6597:   border: 2px;
 6598:   border-collapse: separate;
 6599:   padding: 0;
 6600: }
 6601: 
 6602: table#LC_title_bar a {
 6603:   color: $fontmenu;
 6604: }
 6605: 
 6606: table#LC_title_bar {
 6607:   clear: both;
 6608:   display: none;
 6609: }
 6610: 
 6611: table#LC_title_bar,
 6612: table.LC_breadcrumbs, /* obsolete? */
 6613: table#LC_title_bar.LC_with_remote {
 6614:   width: 100%;
 6615:   border-color: $pgbg;
 6616:   border-style: solid;
 6617:   border-width: $border;
 6618:   background: $pgbg;
 6619:   color: $fontmenu;
 6620:   border-collapse: collapse;
 6621:   padding: 0;
 6622:   margin: 0;
 6623: }
 6624: 
 6625: ul.LC_breadcrumb_tools_outerlist {
 6626:     margin: 0;
 6627:     padding: 0;
 6628:     position: relative;
 6629:     list-style: none;
 6630: }
 6631: ul.LC_breadcrumb_tools_outerlist li {
 6632:     display: inline;
 6633: }
 6634: 
 6635: .LC_breadcrumb_tools_navigation {
 6636:     padding: 0;
 6637:     margin: 0;
 6638:     float: left;
 6639: }
 6640: .LC_breadcrumb_tools_tools {
 6641:     padding: 0;
 6642:     margin: 0;
 6643:     float: right;
 6644: }
 6645: 
 6646: .LC_placement_prog {
 6647:     padding-right: 20px;
 6648:     font-weight: bold;
 6649:     font-size: 90%;
 6650: }
 6651: 
 6652: table#LC_title_bar td {
 6653:   background: $tabbg;
 6654: }
 6655: 
 6656: table#LC_menubuttons img {
 6657:   border: none;
 6658: }
 6659: 
 6660: .LC_breadcrumbs_component {
 6661:   float: right;
 6662:   margin: 0 1em;
 6663: }
 6664: .LC_breadcrumbs_component img {
 6665:   vertical-align: middle;
 6666: }
 6667: 
 6668: .LC_breadcrumbs_hoverable {
 6669:   background: $sidebg;
 6670: }
 6671: 
 6672: td.LC_table_cell_checkbox {
 6673:   text-align: center;
 6674: }
 6675: 
 6676: .LC_fontsize_small {
 6677:   font-size: 70%;
 6678: }
 6679: 
 6680: #LC_breadcrumbs {
 6681:   clear:both;
 6682:   background: $sidebg;
 6683:   border-bottom: 1px solid $lg_border_color;
 6684:   line-height: 2.5em;
 6685:   overflow: hidden;
 6686:   margin: 0;
 6687:   padding: 0;
 6688:   text-align: left;
 6689: }
 6690: 
 6691: .LC_head_subbox, .LC_actionbox {
 6692:   clear:both;
 6693:   background: #F8F8F8; /* $sidebg; */
 6694:   border: 1px solid $sidebg;
 6695:   margin: 0 0 10px 0;
 6696:   padding: 3px;
 6697:   text-align: left;
 6698: }
 6699: 
 6700: .LC_fontsize_medium {
 6701:   font-size: 85%;
 6702: }
 6703: 
 6704: .LC_fontsize_large {
 6705:   font-size: 120%;
 6706: }
 6707: 
 6708: .LC_menubuttons_inline_text {
 6709:   color: $font;
 6710:   font-size: 90%;
 6711:   padding-left:3px;
 6712: }
 6713: 
 6714: .LC_menubuttons_inline_text img{
 6715:   vertical-align: middle;
 6716: }
 6717: 
 6718: li.LC_menubuttons_inline_text img {
 6719:   cursor:pointer;
 6720:   text-decoration: none;
 6721: }
 6722: 
 6723: .LC_menubuttons_link {
 6724:   text-decoration: none;
 6725: }
 6726: 
 6727: .LC_menubuttons_category {
 6728:   color: $font;
 6729:   background: $pgbg;
 6730:   font-size: larger;
 6731:   font-weight: bold;
 6732: }
 6733: 
 6734: td.LC_menubuttons_text {
 6735:   color: $font;
 6736: }
 6737: 
 6738: .LC_current_location {
 6739:   background: $tabbg;
 6740: }
 6741: 
 6742: td.LC_zero_height {
 6743:   line-height: 0; 
 6744:   cellpadding: 0;
 6745: }
 6746: 
 6747: table.LC_data_table {
 6748:   border: 1px solid #000000;
 6749:   border-collapse: separate;
 6750:   border-spacing: 1px;
 6751:   background: $pgbg;
 6752: }
 6753: 
 6754: .LC_data_table_dense {
 6755:   font-size: small;
 6756: }
 6757: 
 6758: table.LC_nested_outer {
 6759:   border: 1px solid #000000;
 6760:   border-collapse: collapse;
 6761:   border-spacing: 0;
 6762:   width: 100%;
 6763: }
 6764: 
 6765: table.LC_innerpickbox,
 6766: table.LC_nested {
 6767:   border: none;
 6768:   border-collapse: collapse;
 6769:   border-spacing: 0;
 6770:   width: 100%;
 6771: }
 6772: 
 6773: table.LC_data_table tr th,
 6774: table.LC_calendar tr th,
 6775: table.LC_prior_tries tr th,
 6776: table.LC_innerpickbox tr th {
 6777:   font-weight: bold;
 6778:   background-color: $data_table_head;
 6779:   color:$fontmenu;
 6780:   font-size:90%;
 6781: }
 6782: 
 6783: table.LC_innerpickbox tr th,
 6784: table.LC_innerpickbox tr td {
 6785:   vertical-align: top;
 6786: }
 6787: 
 6788: table.LC_data_table tr.LC_info_row > td {
 6789:   background-color: #CCCCCC;
 6790:   font-weight: bold;
 6791:   text-align: left;
 6792: }
 6793: 
 6794: table.LC_data_table tr.LC_odd_row > td {
 6795:   background-color: $data_table_light;
 6796:   padding: 2px;
 6797:   vertical-align: top;
 6798: }
 6799: 
 6800: table.LC_pick_box tr > td.LC_odd_row {
 6801:   background-color: $data_table_light;
 6802:   vertical-align: top;
 6803: }
 6804: 
 6805: table.LC_data_table tr.LC_even_row > td {
 6806:   background-color: $data_table_dark;
 6807:   padding: 2px;
 6808:   vertical-align: top;
 6809: }
 6810: 
 6811: table.LC_pick_box tr > td.LC_even_row {
 6812:   background-color: $data_table_dark;
 6813:   vertical-align: top;
 6814: }
 6815: 
 6816: table.LC_data_table tr.LC_data_table_highlight td {
 6817:   background-color: $data_table_darker;
 6818: }
 6819: 
 6820: table.LC_data_table tr td.LC_leftcol_header {
 6821:   background-color: $data_table_head;
 6822:   font-weight: bold;
 6823: }
 6824: 
 6825: table.LC_data_table tr.LC_empty_row td,
 6826: table.LC_nested tr.LC_empty_row td {
 6827:   font-weight: bold;
 6828:   font-style: italic;
 6829:   text-align: center;
 6830:   padding: 8px;
 6831: }
 6832: 
 6833: table.LC_data_table tr.LC_empty_row td,
 6834: table.LC_data_table tr.LC_footer_row td {
 6835:   background-color: $sidebg;
 6836: }
 6837: 
 6838: table.LC_nested tr.LC_empty_row td {
 6839:   background-color: #FFFFFF;
 6840: }
 6841: 
 6842: table.LC_caption {
 6843: }
 6844: 
 6845: table.LC_nested tr.LC_empty_row td {
 6846:   padding: 4ex
 6847: }
 6848: 
 6849: table.LC_nested_outer tr th {
 6850:   font-weight: bold;
 6851:   color:$fontmenu;
 6852:   background-color: $data_table_head;
 6853:   font-size: small;
 6854:   border-bottom: 1px solid #000000;
 6855: }
 6856: 
 6857: table.LC_nested_outer tr td.LC_subheader {
 6858:   background-color: $data_table_head;
 6859:   font-weight: bold;
 6860:   font-size: small;
 6861:   border-bottom: 1px solid #000000;
 6862:   text-align: right;
 6863: }
 6864: 
 6865: table.LC_nested tr.LC_info_row td {
 6866:   background-color: #CCCCCC;
 6867:   font-weight: bold;
 6868:   font-size: small;
 6869:   text-align: center;
 6870: }
 6871: 
 6872: table.LC_nested tr.LC_info_row td.LC_left_item,
 6873: table.LC_nested_outer tr th.LC_left_item {
 6874:   text-align: left;
 6875: }
 6876: 
 6877: table.LC_nested td {
 6878:   background-color: #FFFFFF;
 6879:   font-size: small;
 6880: }
 6881: 
 6882: table.LC_nested_outer tr th.LC_right_item,
 6883: table.LC_nested tr.LC_info_row td.LC_right_item,
 6884: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6885: table.LC_nested tr td.LC_right_item {
 6886:   text-align: right;
 6887: }
 6888: 
 6889: table.LC_nested tr.LC_odd_row td {
 6890:   background-color: #EEEEEE;
 6891: }
 6892: 
 6893: table.LC_createuser {
 6894: }
 6895: 
 6896: table.LC_createuser tr.LC_section_row td {
 6897:   font-size: small;
 6898: }
 6899: 
 6900: table.LC_createuser tr.LC_info_row td  {
 6901:   background-color: #CCCCCC;
 6902:   font-weight: bold;
 6903:   text-align: center;
 6904: }
 6905: 
 6906: table.LC_calendar {
 6907:   border: 1px solid #000000;
 6908:   border-collapse: collapse;
 6909:   width: 98%;
 6910: }
 6911: 
 6912: table.LC_calendar_pickdate {
 6913:   font-size: xx-small;
 6914: }
 6915: 
 6916: table.LC_calendar tr td {
 6917:   border: 1px solid #000000;
 6918:   vertical-align: top;
 6919:   width: 14%;
 6920: }
 6921: 
 6922: table.LC_calendar tr td.LC_calendar_day_empty {
 6923:   background-color: $data_table_dark;
 6924: }
 6925: 
 6926: table.LC_calendar tr td.LC_calendar_day_current {
 6927:   background-color: $data_table_highlight;
 6928: }
 6929: 
 6930: table.LC_data_table tr td.LC_mail_new {
 6931:   background-color: $mail_new;
 6932: }
 6933: 
 6934: table.LC_data_table tr.LC_mail_new:hover {
 6935:   background-color: $mail_new_hover;
 6936: }
 6937: 
 6938: table.LC_data_table tr td.LC_mail_read {
 6939:   background-color: $mail_read;
 6940: }
 6941: 
 6942: /*
 6943: table.LC_data_table tr.LC_mail_read:hover {
 6944:   background-color: $mail_read_hover;
 6945: }
 6946: */
 6947: 
 6948: table.LC_data_table tr td.LC_mail_replied {
 6949:   background-color: $mail_replied;
 6950: }
 6951: 
 6952: /*
 6953: table.LC_data_table tr.LC_mail_replied:hover {
 6954:   background-color: $mail_replied_hover;
 6955: }
 6956: */
 6957: 
 6958: table.LC_data_table tr td.LC_mail_other {
 6959:   background-color: $mail_other;
 6960: }
 6961: 
 6962: /*
 6963: table.LC_data_table tr.LC_mail_other:hover {
 6964:   background-color: $mail_other_hover;
 6965: }
 6966: */
 6967: 
 6968: table.LC_data_table tr > td.LC_browser_file,
 6969: table.LC_data_table tr > td.LC_browser_file_published {
 6970:   background: #AAEE77;
 6971: }
 6972: 
 6973: table.LC_data_table tr > td.LC_browser_file_locked,
 6974: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6975:   background: #FFAA99;
 6976: }
 6977: 
 6978: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6979:   background: #888888;
 6980: }
 6981: 
 6982: table.LC_data_table tr > td.LC_browser_file_modified,
 6983: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6984:   background: #F8F866;
 6985: }
 6986: 
 6987: table.LC_data_table tr.LC_browser_folder > td {
 6988:   background: #E0E8FF;
 6989: }
 6990: 
 6991: table.LC_data_table tr > td.LC_roles_is {
 6992:   /* background: #77FF77; */
 6993: }
 6994: 
 6995: table.LC_data_table tr > td.LC_roles_future {
 6996:   border-right: 8px solid #FFFF77;
 6997: }
 6998: 
 6999: table.LC_data_table tr > td.LC_roles_will {
 7000:   border-right: 8px solid #FFAA77;
 7001: }
 7002: 
 7003: table.LC_data_table tr > td.LC_roles_expired {
 7004:   border-right: 8px solid #FF7777;
 7005: }
 7006: 
 7007: table.LC_data_table tr > td.LC_roles_will_not {
 7008:   border-right: 8px solid #AAFF77;
 7009: }
 7010: 
 7011: table.LC_data_table tr > td.LC_roles_selected {
 7012:   border-right: 8px solid #11CC55;
 7013: }
 7014: 
 7015: span.LC_current_location {
 7016:   font-size:larger;
 7017:   background: $pgbg;
 7018: }
 7019: 
 7020: span.LC_current_nav_location {
 7021:   font-weight:bold;
 7022:   background: $sidebg;
 7023: }
 7024: 
 7025: span.LC_parm_menu_item {
 7026:   font-size: larger;
 7027: }
 7028: 
 7029: span.LC_parm_scope_all {
 7030:   color: red;
 7031: }
 7032: 
 7033: span.LC_parm_scope_folder {
 7034:   color: green;
 7035: }
 7036: 
 7037: span.LC_parm_scope_resource {
 7038:   color: orange;
 7039: }
 7040: 
 7041: span.LC_parm_part {
 7042:   color: blue;
 7043: }
 7044: 
 7045: span.LC_parm_folder,
 7046: span.LC_parm_symb {
 7047:   font-size: x-small;
 7048:   font-family: $mono;
 7049:   color: #AAAAAA;
 7050: }
 7051: 
 7052: ul.LC_parm_parmlist li {
 7053:   display: inline-block;
 7054:   padding: 0.3em 0.8em;
 7055:   vertical-align: top;
 7056:   width: 150px;
 7057:   border-top:1px solid $lg_border_color;
 7058: }
 7059: 
 7060: td.LC_parm_overview_level_menu,
 7061: td.LC_parm_overview_map_menu,
 7062: td.LC_parm_overview_parm_selectors,
 7063: td.LC_parm_overview_restrictions  {
 7064:   border: 1px solid black;
 7065:   border-collapse: collapse;
 7066: }
 7067: 
 7068: span.LC_parm_recursive,
 7069: td.LC_parm_recursive {
 7070:   font-weight: bold;
 7071:   font-size: smaller;
 7072: }
 7073: 
 7074: table.LC_parm_overview_restrictions td {
 7075:   border-width: 1px 4px 1px 4px;
 7076:   border-style: solid;
 7077:   border-color: $pgbg;
 7078:   text-align: center;
 7079: }
 7080: 
 7081: table.LC_parm_overview_restrictions th {
 7082:   background: $tabbg;
 7083:   border-width: 1px 4px 1px 4px;
 7084:   border-style: solid;
 7085:   border-color: $pgbg;
 7086: }
 7087: 
 7088: table#LC_helpmenu {
 7089:   border: none;
 7090:   height: 55px;
 7091:   border-spacing: 0;
 7092: }
 7093: 
 7094: table#LC_helpmenu fieldset legend {
 7095:   font-size: larger;
 7096: }
 7097: 
 7098: table#LC_helpmenu_links {
 7099:   width: 100%;
 7100:   border: 1px solid black;
 7101:   background: $pgbg;
 7102:   padding: 0;
 7103:   border-spacing: 1px;
 7104: }
 7105: 
 7106: table#LC_helpmenu_links tr td {
 7107:   padding: 1px;
 7108:   background: $tabbg;
 7109:   text-align: center;
 7110:   font-weight: bold;
 7111: }
 7112: 
 7113: table#LC_helpmenu_links a:link,
 7114: table#LC_helpmenu_links a:visited,
 7115: table#LC_helpmenu_links a:active {
 7116:   text-decoration: none;
 7117:   color: $font;
 7118: }
 7119: 
 7120: table#LC_helpmenu_links a:hover {
 7121:   text-decoration: underline;
 7122:   color: $vlink;
 7123: }
 7124: 
 7125: .LC_chrt_popup_exists {
 7126:   border: 1px solid #339933;
 7127:   margin: -1px;
 7128: }
 7129: 
 7130: .LC_chrt_popup_up {
 7131:   border: 1px solid yellow;
 7132:   margin: -1px;
 7133: }
 7134: 
 7135: .LC_chrt_popup {
 7136:   border: 1px solid #8888FF;
 7137:   background: #CCCCFF;
 7138: }
 7139: 
 7140: table.LC_pick_box {
 7141:   border-collapse: separate;
 7142:   background: white;
 7143:   border: 1px solid black;
 7144:   border-spacing: 1px;
 7145: }
 7146: 
 7147: table.LC_pick_box td.LC_pick_box_title {
 7148:   background: $sidebg;
 7149:   font-weight: bold;
 7150:   text-align: left;
 7151:   vertical-align: top;
 7152:   width: 184px;
 7153:   padding: 8px;
 7154: }
 7155: 
 7156: table.LC_pick_box td.LC_pick_box_value {
 7157:   text-align: left;
 7158:   padding: 8px;
 7159: }
 7160: 
 7161: table.LC_pick_box td.LC_pick_box_select {
 7162:   text-align: left;
 7163:   padding: 8px;
 7164: }
 7165: 
 7166: table.LC_pick_box td.LC_pick_box_separator {
 7167:   padding: 0;
 7168:   height: 1px;
 7169:   background: black;
 7170: }
 7171: 
 7172: table.LC_pick_box td.LC_pick_box_submit {
 7173:   text-align: right;
 7174: }
 7175: 
 7176: table.LC_pick_box td.LC_evenrow_value {
 7177:   text-align: left;
 7178:   padding: 8px;
 7179:   background-color: $data_table_light;
 7180: }
 7181: 
 7182: table.LC_pick_box td.LC_oddrow_value {
 7183:   text-align: left;
 7184:   padding: 8px;
 7185:   background-color: $data_table_light;
 7186: }
 7187: 
 7188: span.LC_helpform_receipt_cat {
 7189:   font-weight: bold;
 7190: }
 7191: 
 7192: table.LC_group_priv_box {
 7193:   background: white;
 7194:   border: 1px solid black;
 7195:   border-spacing: 1px;
 7196: }
 7197: 
 7198: table.LC_group_priv_box td.LC_pick_box_title {
 7199:   background: $tabbg;
 7200:   font-weight: bold;
 7201:   text-align: right;
 7202:   width: 184px;
 7203: }
 7204: 
 7205: table.LC_group_priv_box td.LC_groups_fixed {
 7206:   background: $data_table_light;
 7207:   text-align: center;
 7208: }
 7209: 
 7210: table.LC_group_priv_box td.LC_groups_optional {
 7211:   background: $data_table_dark;
 7212:   text-align: center;
 7213: }
 7214: 
 7215: table.LC_group_priv_box td.LC_groups_functionality {
 7216:   background: $data_table_darker;
 7217:   text-align: center;
 7218:   font-weight: bold;
 7219: }
 7220: 
 7221: table.LC_group_priv td {
 7222:   text-align: left;
 7223:   padding: 0;
 7224: }
 7225: 
 7226: .LC_navbuttons {
 7227:   margin: 2ex 0ex 2ex 0ex;
 7228: }
 7229: 
 7230: .LC_topic_bar {
 7231:   font-weight: bold;
 7232:   background: $tabbg;
 7233:   margin: 1em 0em 1em 2em;
 7234:   padding: 3px;
 7235:   font-size: 1.2em;
 7236: }
 7237: 
 7238: .LC_topic_bar span {
 7239:   left: 0.5em;
 7240:   position: absolute;
 7241:   vertical-align: middle;
 7242:   font-size: 1.2em;
 7243: }
 7244: 
 7245: table.LC_course_group_status {
 7246:   margin: 20px;
 7247: }
 7248: 
 7249: table.LC_status_selector td {
 7250:   vertical-align: top;
 7251:   text-align: center;
 7252:   padding: 4px;
 7253: }
 7254: 
 7255: div.LC_feedback_link {
 7256:   clear: both;
 7257:   background: $sidebg;
 7258:   width: 100%;
 7259:   padding-bottom: 10px;
 7260:   border: 1px $tabbg solid;
 7261:   height: 22px;
 7262:   line-height: 22px;
 7263:   padding-top: 5px;
 7264: }
 7265: 
 7266: div.LC_feedback_link img {
 7267:   height: 22px;
 7268:   vertical-align:middle;
 7269: }
 7270: 
 7271: div.LC_feedback_link a {
 7272:   text-decoration: none;
 7273: }
 7274: 
 7275: div.LC_comblock {
 7276:   display:inline;
 7277:   color:$font;
 7278:   font-size:90%;
 7279: }
 7280: 
 7281: div.LC_feedback_link div.LC_comblock {
 7282:   padding-left:5px;
 7283: }
 7284: 
 7285: div.LC_feedback_link div.LC_comblock a {
 7286:   color:$font;
 7287: }
 7288: 
 7289: span.LC_feedback_link {
 7290:   /* background: $feedback_link_bg; */
 7291:   font-size: larger;
 7292: }
 7293: 
 7294: span.LC_message_link {
 7295:   /* background: $feedback_link_bg; */
 7296:   font-size: larger;
 7297:   position: absolute;
 7298:   right: 1em;
 7299: }
 7300: 
 7301: table.LC_prior_tries {
 7302:   border: 1px solid #000000;
 7303:   border-collapse: separate;
 7304:   border-spacing: 1px;
 7305: }
 7306: 
 7307: table.LC_prior_tries td {
 7308:   padding: 2px;
 7309: }
 7310: 
 7311: .LC_answer_correct {
 7312:   background: lightgreen;
 7313:   color: darkgreen;
 7314:   padding: 6px;
 7315: }
 7316: 
 7317: .LC_answer_charged_try {
 7318:   background: #FFAAAA;
 7319:   color: darkred;
 7320:   padding: 6px;
 7321: }
 7322: 
 7323: .LC_answer_not_charged_try,
 7324: .LC_answer_no_grade,
 7325: .LC_answer_late {
 7326:   background: lightyellow;
 7327:   color: black;
 7328:   padding: 6px;
 7329: }
 7330: 
 7331: .LC_answer_previous {
 7332:   background: lightblue;
 7333:   color: darkblue;
 7334:   padding: 6px;
 7335: }
 7336: 
 7337: .LC_answer_no_message {
 7338:   background: #FFFFFF;
 7339:   color: black;
 7340:   padding: 6px;
 7341: }
 7342: 
 7343: .LC_answer_unknown,
 7344: .LC_answer_warning {
 7345:   background: orange;
 7346:   color: black;
 7347:   padding: 6px;
 7348: }
 7349: 
 7350: span.LC_prior_numerical,
 7351: span.LC_prior_string,
 7352: span.LC_prior_custom,
 7353: span.LC_prior_reaction,
 7354: span.LC_prior_math {
 7355:   font-family: $mono;
 7356:   white-space: pre;
 7357: }
 7358: 
 7359: span.LC_prior_string {
 7360:   font-family: $mono;
 7361:   white-space: pre;
 7362: }
 7363: 
 7364: table.LC_prior_option {
 7365:   width: 100%;
 7366:   border-collapse: collapse;
 7367: }
 7368: 
 7369: table.LC_prior_rank,
 7370: table.LC_prior_match {
 7371:   border-collapse: collapse;
 7372: }
 7373: 
 7374: table.LC_prior_option tr td,
 7375: table.LC_prior_rank tr td,
 7376: table.LC_prior_match tr td {
 7377:   border: 1px solid #000000;
 7378: }
 7379: 
 7380: .LC_nobreak {
 7381:   white-space: nowrap;
 7382: }
 7383: 
 7384: span.LC_cusr_emph {
 7385:   font-style: italic;
 7386: }
 7387: 
 7388: span.LC_cusr_subheading {
 7389:   font-weight: normal;
 7390:   font-size: 85%;
 7391: }
 7392: 
 7393: div.LC_docs_entry_move {
 7394:   border: 1px solid #BBBBBB;
 7395:   background: #DDDDDD;
 7396:   width: 22px;
 7397:   padding: 1px;
 7398:   margin: 0;
 7399: }
 7400: 
 7401: table.LC_data_table tr > td.LC_docs_entry_commands,
 7402: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7403:   font-size: x-small;
 7404: }
 7405: 
 7406: .LC_docs_entry_parameter {
 7407:   white-space: nowrap;
 7408: }
 7409: 
 7410: .LC_docs_copy {
 7411:   color: #000099;
 7412: }
 7413: 
 7414: .LC_docs_cut {
 7415:   color: #550044;
 7416: }
 7417: 
 7418: .LC_docs_rename {
 7419:   color: #009900;
 7420: }
 7421: 
 7422: .LC_docs_remove {
 7423:   color: #990000;
 7424: }
 7425: 
 7426: .LC_docs_alias {
 7427:   color: #440055;  
 7428: }
 7429: 
 7430: .LC_domprefs_email,
 7431: .LC_docs_alias_name,
 7432: .LC_docs_reinit_warn,
 7433: .LC_docs_ext_edit {
 7434:   font-size: x-small;
 7435: }
 7436: 
 7437: table.LC_docs_adddocs td,
 7438: table.LC_docs_adddocs th {
 7439:   border: 1px solid #BBBBBB;
 7440:   padding: 4px;
 7441:   background: #DDDDDD;
 7442: }
 7443: 
 7444: table.LC_sty_begin {
 7445:   background: #BBFFBB;
 7446: }
 7447: 
 7448: table.LC_sty_end {
 7449:   background: #FFBBBB;
 7450: }
 7451: 
 7452: table.LC_double_column {
 7453:   border-width: 0;
 7454:   border-collapse: collapse;
 7455:   width: 100%;
 7456:   padding: 2px;
 7457: }
 7458: 
 7459: table.LC_double_column tr td.LC_left_col {
 7460:   top: 2px;
 7461:   left: 2px;
 7462:   width: 47%;
 7463:   vertical-align: top;
 7464: }
 7465: 
 7466: table.LC_double_column tr td.LC_right_col {
 7467:   top: 2px;
 7468:   right: 2px;
 7469:   width: 47%;
 7470:   vertical-align: top;
 7471: }
 7472: 
 7473: div.LC_left_float {
 7474:   float: left;
 7475:   padding-right: 5%;
 7476:   padding-bottom: 4px;
 7477: }
 7478: 
 7479: div.LC_clear_float_header {
 7480:   padding-bottom: 2px;
 7481: }
 7482: 
 7483: div.LC_clear_float_footer {
 7484:   padding-top: 10px;
 7485:   clear: both;
 7486: }
 7487: 
 7488: div.LC_grade_show_user {
 7489: /*  border-left: 5px solid $sidebg; */
 7490:   border-top: 5px solid #000000;
 7491:   margin: 50px 0 0 0;
 7492:   padding: 15px 0 5px 10px;
 7493: }
 7494: 
 7495: div.LC_grade_show_user_odd_row {
 7496: /*  border-left: 5px solid #000000; */
 7497: }
 7498: 
 7499: div.LC_grade_show_user div.LC_Box {
 7500:   margin-right: 50px;
 7501: }
 7502: 
 7503: div.LC_grade_submissions,
 7504: div.LC_grade_message_center,
 7505: div.LC_grade_info_links {
 7506:   margin: 5px;
 7507:   width: 99%;
 7508:   background: #FFFFFF;
 7509: }
 7510: 
 7511: div.LC_grade_submissions_header,
 7512: div.LC_grade_message_center_header {
 7513:   font-weight: bold;
 7514:   font-size: large;
 7515: }
 7516: 
 7517: div.LC_grade_submissions_body,
 7518: div.LC_grade_message_center_body {
 7519:   border: 1px solid black;
 7520:   width: 99%;
 7521:   background: #FFFFFF;
 7522: }
 7523: 
 7524: table.LC_scantron_action {
 7525:   width: 100%;
 7526: }
 7527: 
 7528: table.LC_scantron_action tr th {
 7529:   font-weight:bold;
 7530:   font-style:normal;
 7531: }
 7532: 
 7533: .LC_edit_problem_header,
 7534: div.LC_edit_problem_footer {
 7535:   font-weight: normal;
 7536:   font-size:  medium;
 7537:   margin: 2px;
 7538:   background-color: $sidebg;
 7539: }
 7540: 
 7541: div.LC_edit_problem_header,
 7542: div.LC_edit_problem_header div,
 7543: div.LC_edit_problem_footer,
 7544: div.LC_edit_problem_footer div,
 7545: div.LC_edit_problem_editxml_header,
 7546: div.LC_edit_problem_editxml_header div {
 7547:   z-index: 100;
 7548: }
 7549: 
 7550: div.LC_edit_problem_header_title {
 7551:   font-weight: bold;
 7552:   font-size: larger;
 7553:   background: $tabbg;
 7554:   padding: 3px;
 7555:   margin: 0 0 5px 0;
 7556: }
 7557: 
 7558: table.LC_edit_problem_header_title {
 7559:   width: 100%;
 7560:   background: $tabbg;
 7561: }
 7562: 
 7563: div.LC_edit_actionbar {
 7564:     background-color: $sidebg;
 7565:     margin: 0;
 7566:     padding: 0;
 7567:     line-height: 200%;
 7568: }
 7569: 
 7570: div.LC_edit_actionbar div{
 7571:     padding: 0;
 7572:     margin: 0;
 7573:     display: inline-block;
 7574: }
 7575: 
 7576: .LC_edit_opt {
 7577:   padding-left: 1em;
 7578:   white-space: nowrap;
 7579: }
 7580: 
 7581: .LC_edit_problem_latexhelper{
 7582:     text-align: right;
 7583: }
 7584: 
 7585: #LC_edit_problem_colorful div{
 7586:     margin-left: 40px;
 7587: }
 7588: 
 7589: #LC_edit_problem_codemirror div{
 7590:     margin-left: 0px;
 7591: }
 7592: 
 7593: img.stift {
 7594:   border-width: 0;
 7595:   vertical-align: middle;
 7596: }
 7597: 
 7598: table td.LC_mainmenu_col_fieldset {
 7599:   vertical-align: top;
 7600: }
 7601: 
 7602: div.LC_createcourse {
 7603:   margin: 10px 10px 10px 10px;
 7604: }
 7605: 
 7606: .LC_dccid {
 7607:   float: right;
 7608:   margin: 0.2em 0 0 0;
 7609:   padding: 0;
 7610:   font-size: 90%;
 7611:   display:none;
 7612: }
 7613: 
 7614: ol.LC_primary_menu a:hover,
 7615: ol#LC_MenuBreadcrumbs a:hover,
 7616: ol#LC_PathBreadcrumbs a:hover,
 7617: ul#LC_secondary_menu a:hover,
 7618: .LC_FormSectionClearButton input:hover
 7619: ul.LC_TabContent   li:hover a {
 7620:   color:$button_hover;
 7621:   text-decoration:none;
 7622: }
 7623: 
 7624: h1 {
 7625:   padding: 0;
 7626:   line-height:130%;
 7627: }
 7628: 
 7629: h2,
 7630: h3,
 7631: h4,
 7632: h5,
 7633: h6 {
 7634:   margin: 5px 0 5px 0;
 7635:   padding: 0;
 7636:   line-height:130%;
 7637: }
 7638: 
 7639: .LC_hcell {
 7640:   padding:3px 15px 3px 15px;
 7641:   margin: 0;
 7642:   background-color:$tabbg;
 7643:   color:$fontmenu;
 7644:   border-bottom:solid 1px $lg_border_color;
 7645: }
 7646: 
 7647: .LC_Box > .LC_hcell {
 7648:   margin: 0 -10px 10px -10px;
 7649: }
 7650: 
 7651: .LC_noBorder {
 7652:   border: 0;
 7653: }
 7654: 
 7655: .LC_FormSectionClearButton input {
 7656:   background-color:transparent;
 7657:   border: none;
 7658:   cursor:pointer;
 7659:   text-decoration:underline;
 7660: }
 7661: 
 7662: .LC_help_open_topic {
 7663:   color: #FFFFFF;
 7664:   background-color: #EEEEFF;
 7665:   margin: 1px;
 7666:   padding: 4px;
 7667:   border: 1px solid #000033;
 7668:   white-space: nowrap;
 7669:   /* vertical-align: middle; */
 7670: }
 7671: 
 7672: dl,
 7673: ul,
 7674: div,
 7675: fieldset {
 7676:   margin: 10px 10px 10px 0;
 7677:   /* overflow: hidden; */
 7678: }
 7679: 
 7680: article.geogebraweb div {
 7681:     margin: 0;
 7682: }
 7683: 
 7684: fieldset > legend {
 7685:   font-weight: bold;
 7686:   padding: 0 5px 0 5px;
 7687: }
 7688: 
 7689: #LC_nav_bar {
 7690:   float: left;
 7691:   background-color: $pgbg_or_bgcolor;
 7692:   margin: 0 0 2px 0;
 7693: }
 7694: 
 7695: #LC_realm {
 7696:   margin: 0.2em 0 0 0;
 7697:   padding: 0;
 7698:   font-weight: bold;
 7699:   text-align: center;
 7700:   background-color: $pgbg_or_bgcolor;
 7701: }
 7702: 
 7703: #LC_nav_bar em {
 7704:   font-weight: bold;
 7705:   font-style: normal;
 7706: }
 7707: 
 7708: ol.LC_primary_menu {
 7709:   margin: 0;
 7710:   padding: 0;
 7711: }
 7712: 
 7713: ol#LC_PathBreadcrumbs {
 7714:   margin: 0;
 7715: }
 7716: 
 7717: ol.LC_primary_menu li {
 7718:   color: RGB(80, 80, 80);
 7719:   vertical-align: middle;
 7720:   text-align: left;
 7721:   list-style: none;
 7722:   position: relative;
 7723:   float: left;
 7724:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7725:   line-height: 1.5em;
 7726: }
 7727: 
 7728: ol.LC_primary_menu li a,
 7729: ol.LC_primary_menu li p {
 7730:   display: block;
 7731:   margin: 0;
 7732:   padding: 0 5px 0 10px;
 7733:   text-decoration: none;
 7734: }
 7735: 
 7736: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7737:   display: inline-block;
 7738:   width: 95%;
 7739:   text-align: left;
 7740: }
 7741: 
 7742: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7743:   display: inline-block;	
 7744:   width: 5%;
 7745:   float: right;
 7746:   text-align: right;
 7747:   font-size: 70%;
 7748: }
 7749: 
 7750: ol.LC_primary_menu ul {
 7751:   display: none;
 7752:   width: 15em;
 7753:   background-color: $data_table_light;
 7754:   position: absolute;
 7755:   top: 100%;
 7756: }
 7757: 
 7758: ol.LC_primary_menu ul ul {
 7759:   left: 100%;
 7760:   top: 0;
 7761: }
 7762: 
 7763: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7764:   display: block;
 7765:   position: absolute;
 7766:   margin: 0;
 7767:   padding: 0;
 7768:   z-index: 2;
 7769: }
 7770: 
 7771: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7772: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7773:   font-size: 90%;
 7774:   vertical-align: top;
 7775:   float: none;
 7776:   border-left: 1px solid black;
 7777:   border-right: 1px solid black;
 7778: /* A dark bottom border to visualize different menu options; 
 7779: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7780:   border-bottom: 1px solid $data_table_dark; 
 7781: }
 7782: 
 7783: ol.LC_primary_menu li li p:hover {
 7784:   color:$button_hover;
 7785:   text-decoration:none;
 7786:   background-color:$data_table_dark;
 7787: }
 7788: 
 7789: ol.LC_primary_menu li li a:hover {
 7790:    color:$button_hover;
 7791:    background-color:$data_table_dark;
 7792: }
 7793: 
 7794: /* Font-size equal to the size of the predecessors*/
 7795: ol.LC_primary_menu li:hover li li {
 7796:   font-size: 100%;
 7797: }
 7798: 
 7799: ol.LC_primary_menu li img {
 7800:   vertical-align: bottom;
 7801:   height: 1.1em;
 7802:   margin: 0.2em 0 0 0;
 7803: }
 7804: 
 7805: ol.LC_primary_menu a {
 7806:   color: RGB(80, 80, 80);
 7807:   text-decoration: none;
 7808: }
 7809: 
 7810: ol.LC_primary_menu a.LC_new_message {
 7811:   font-weight:bold;
 7812:   color: darkred;
 7813: }
 7814: 
 7815: ol.LC_docs_parameters {
 7816:   margin-left: 0;
 7817:   padding: 0;
 7818:   list-style: none;
 7819: }
 7820: 
 7821: ol.LC_docs_parameters li {
 7822:   margin: 0;
 7823:   padding-right: 20px;
 7824:   display: inline;
 7825: }
 7826: 
 7827: ol.LC_docs_parameters li:before {
 7828:   content: "\\002022 \\0020";
 7829: }
 7830: 
 7831: li.LC_docs_parameters_title {
 7832:   font-weight: bold;
 7833: }
 7834: 
 7835: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7836:   content: "";
 7837: }
 7838: 
 7839: ul#LC_secondary_menu {
 7840:   clear: right;
 7841:   color: $fontmenu;
 7842:   background: $tabbg;
 7843:   list-style: none;
 7844:   padding: 0;
 7845:   margin: 0;
 7846:   width: 100%;
 7847:   text-align: left;
 7848:   float: left;
 7849: }
 7850: 
 7851: ul#LC_secondary_menu li {
 7852:   font-weight: bold;
 7853:   line-height: 1.8em;
 7854:   border-right: 1px solid black;
 7855:   float: left;
 7856: }
 7857: 
 7858: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7859:   background-color: $data_table_light;
 7860: }
 7861: 
 7862: ul#LC_secondary_menu li a {
 7863:   padding: 0 0.8em;
 7864: }
 7865: 
 7866: ul#LC_secondary_menu li ul {
 7867:   display: none;
 7868: }
 7869: 
 7870: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7871:   display: block;
 7872:   position: absolute;
 7873:   margin: 0;
 7874:   padding: 0;
 7875:   list-style:none;
 7876:   float: none;
 7877:   background-color: $data_table_light;
 7878:   z-index: 2;
 7879:   margin-left: -1px;
 7880: }
 7881: 
 7882: ul#LC_secondary_menu li ul li {
 7883:   font-size: 90%;
 7884:   vertical-align: top;
 7885:   border-left: 1px solid black;
 7886:   border-right: 1px solid black;
 7887:   background-color: $data_table_light;
 7888:   list-style:none;
 7889:   float: none;
 7890: }
 7891: 
 7892: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7893:   background-color: $data_table_dark;
 7894: }
 7895: 
 7896: ul.LC_TabContent {
 7897:   display:block;
 7898:   background: $sidebg;
 7899:   border-bottom: solid 1px $lg_border_color;
 7900:   list-style:none;
 7901:   margin: -1px -10px 0 -10px;
 7902:   padding: 0;
 7903: }
 7904: 
 7905: ul.LC_TabContent li,
 7906: ul.LC_TabContentBigger li {
 7907:   float:left;
 7908: }
 7909: 
 7910: ul#LC_secondary_menu li a {
 7911:   color: $fontmenu;
 7912:   text-decoration: none;
 7913: }
 7914: 
 7915: ul.LC_TabContent {
 7916:   min-height:20px;
 7917: }
 7918: 
 7919: ul.LC_TabContent li {
 7920:   vertical-align:middle;
 7921:   padding: 0 16px 0 10px;
 7922:   background-color:$tabbg;
 7923:   border-bottom:solid 1px $lg_border_color;
 7924:   border-left: solid 1px $font;
 7925: }
 7926: 
 7927: ul.LC_TabContent .right {
 7928:   float:right;
 7929: }
 7930: 
 7931: ul.LC_TabContent li a,
 7932: ul.LC_TabContent li {
 7933:   color:rgb(47,47,47);
 7934:   text-decoration:none;
 7935:   font-size:95%;
 7936:   font-weight:bold;
 7937:   min-height:20px;
 7938: }
 7939: 
 7940: ul.LC_TabContent li a:hover,
 7941: ul.LC_TabContent li a:focus {
 7942:   color: $button_hover;
 7943:   background:none;
 7944:   outline:none;
 7945: }
 7946: 
 7947: ul.LC_TabContent li:hover {
 7948:   color: $button_hover;
 7949:   cursor:pointer;
 7950: }
 7951: 
 7952: ul.LC_TabContent li.active {
 7953:   color: $font;
 7954:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7955:   border-bottom:solid 1px #FFFFFF;
 7956:   cursor: default;
 7957: }
 7958: 
 7959: ul.LC_TabContent li.active a {
 7960:   color:$font;
 7961:   background:#FFFFFF;
 7962:   outline: none;
 7963: }
 7964: 
 7965: ul.LC_TabContent li.goback {
 7966:   float: left;
 7967:   border-left: none;
 7968: }
 7969: 
 7970: #maincoursedoc {
 7971:   clear:both;
 7972: }
 7973: 
 7974: ul.LC_TabContentBigger {
 7975:   display:block;
 7976:   list-style:none;
 7977:   padding: 0;
 7978: }
 7979: 
 7980: ul.LC_TabContentBigger li {
 7981:   vertical-align:bottom;
 7982:   height: 30px;
 7983:   font-size:110%;
 7984:   font-weight:bold;
 7985:   color: #737373;
 7986: }
 7987: 
 7988: ul.LC_TabContentBigger li.active {
 7989:   position: relative;
 7990:   top: 1px;
 7991: }
 7992: 
 7993: ul.LC_TabContentBigger li a {
 7994:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7995:   height: 30px;
 7996:   line-height: 30px;
 7997:   text-align: center;
 7998:   display: block;
 7999:   text-decoration: none;
 8000:   outline: none;  
 8001: }
 8002: 
 8003: ul.LC_TabContentBigger li.active a {
 8004:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8005:   color:$font;
 8006: }
 8007: 
 8008: ul.LC_TabContentBigger li b {
 8009:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8010:   display: block;
 8011:   float: left;
 8012:   padding: 0 30px;
 8013:   border-bottom: 1px solid $lg_border_color;
 8014: }
 8015: 
 8016: ul.LC_TabContentBigger li:hover b {
 8017:   color:$button_hover;
 8018: }
 8019: 
 8020: ul.LC_TabContentBigger li.active b {
 8021:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8022:   color:$font;
 8023:   border: 0;
 8024: }
 8025: 
 8026: 
 8027: ul.LC_CourseBreadcrumbs {
 8028:   background: $sidebg;
 8029:   height: 2em;
 8030:   padding-left: 10px;
 8031:   margin: 0;
 8032:   list-style-position: inside;
 8033: }
 8034: 
 8035: ol#LC_MenuBreadcrumbs,
 8036: ol#LC_PathBreadcrumbs {
 8037:   padding-left: 10px;
 8038:   margin: 0;
 8039:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8040: }
 8041: 
 8042: ol#LC_MenuBreadcrumbs li,
 8043: ol#LC_PathBreadcrumbs li,
 8044: ul.LC_CourseBreadcrumbs li {
 8045:   display: inline;
 8046:   white-space: normal;  
 8047: }
 8048: 
 8049: ol#LC_MenuBreadcrumbs li a,
 8050: ul.LC_CourseBreadcrumbs li a {
 8051:   text-decoration: none;
 8052:   font-size:90%;
 8053: }
 8054: 
 8055: ol#LC_MenuBreadcrumbs h1 {
 8056:   display: inline;
 8057:   font-size: 90%;
 8058:   line-height: 2.5em;
 8059:   margin: 0;
 8060:   padding: 0;
 8061: }
 8062: 
 8063: ol#LC_PathBreadcrumbs li a {
 8064:   text-decoration:none;
 8065:   font-size:100%;
 8066:   font-weight:bold;
 8067: }
 8068: 
 8069: .LC_Box {
 8070:   border: solid 1px $lg_border_color;
 8071:   padding: 0 10px 10px 10px;
 8072: }
 8073: 
 8074: .LC_DocsBox {
 8075:   border: solid 1px $lg_border_color;
 8076:   padding: 0 0 10px 10px;
 8077: }
 8078: 
 8079: .LC_AboutMe_Image {
 8080:   float:left;
 8081:   margin-right:10px;
 8082: }
 8083: 
 8084: .LC_Clear_AboutMe_Image {
 8085:   clear:left;
 8086: }
 8087: 
 8088: dl.LC_ListStyleClean dt {
 8089:   padding-right: 5px;
 8090:   display: table-header-group;
 8091: }
 8092: 
 8093: dl.LC_ListStyleClean dd {
 8094:   display: table-row;
 8095: }
 8096: 
 8097: .LC_ListStyleClean,
 8098: .LC_ListStyleSimple,
 8099: .LC_ListStyleNormal,
 8100: .LC_ListStyleSpecial {
 8101:   /* display:block; */
 8102:   list-style-position: inside;
 8103:   list-style-type: none;
 8104:   overflow: hidden;
 8105:   padding: 0;
 8106: }
 8107: 
 8108: .LC_ListStyleSimple li,
 8109: .LC_ListStyleSimple dd,
 8110: .LC_ListStyleNormal li,
 8111: .LC_ListStyleNormal dd,
 8112: .LC_ListStyleSpecial li,
 8113: .LC_ListStyleSpecial dd {
 8114:   margin: 0;
 8115:   padding: 5px 5px 5px 10px;
 8116:   clear: both;
 8117: }
 8118: 
 8119: .LC_ListStyleClean li,
 8120: .LC_ListStyleClean dd {
 8121:   padding-top: 0;
 8122:   padding-bottom: 0;
 8123: }
 8124: 
 8125: .LC_ListStyleSimple dd,
 8126: .LC_ListStyleSimple li {
 8127:   border-bottom: solid 1px $lg_border_color;
 8128: }
 8129: 
 8130: .LC_ListStyleSpecial li,
 8131: .LC_ListStyleSpecial dd {
 8132:   list-style-type: none;
 8133:   background-color: RGB(220, 220, 220);
 8134:   margin-bottom: 4px;
 8135: }
 8136: 
 8137: table.LC_SimpleTable {
 8138:   margin:5px;
 8139:   border:solid 1px $lg_border_color;
 8140: }
 8141: 
 8142: table.LC_SimpleTable tr {
 8143:   padding: 0;
 8144:   border:solid 1px $lg_border_color;
 8145: }
 8146: 
 8147: table.LC_SimpleTable thead {
 8148:   background:rgb(220,220,220);
 8149: }
 8150: 
 8151: div.LC_columnSection {
 8152:   display: block;
 8153:   clear: both;
 8154:   overflow: hidden;
 8155:   margin: 0;
 8156: }
 8157: 
 8158: div.LC_columnSection>* {
 8159:   float: left;
 8160:   margin: 10px 20px 10px 0;
 8161:   overflow:hidden;
 8162: }
 8163: 
 8164: table em {
 8165:   font-weight: bold;
 8166:   font-style: normal;
 8167: }
 8168: 
 8169: table.LC_tableBrowseRes,
 8170: table.LC_tableOfContent {
 8171:   border:none;
 8172:   border-spacing: 1px;
 8173:   padding: 3px;
 8174:   background-color: #FFFFFF;
 8175:   font-size: 90%;
 8176: }
 8177: 
 8178: table.LC_tableOfContent {
 8179:   border-collapse: collapse;
 8180: }
 8181: 
 8182: table.LC_tableBrowseRes a,
 8183: table.LC_tableOfContent a {
 8184:   background-color: transparent;
 8185:   text-decoration: none;
 8186: }
 8187: 
 8188: table.LC_tableOfContent img {
 8189:   border: none;
 8190:   height: 1.3em;
 8191:   vertical-align: text-bottom;
 8192:   margin-right: 0.3em;
 8193: }
 8194: 
 8195: a#LC_content_toolbar_firsthomework {
 8196:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8197: }
 8198: 
 8199: a#LC_content_toolbar_everything {
 8200:   background-image:url(/res/adm/pages/show-all.gif);
 8201: }
 8202: 
 8203: a#LC_content_toolbar_uncompleted {
 8204:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8205: }
 8206: 
 8207: #LC_content_toolbar_clearbubbles {
 8208:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8209: }
 8210: 
 8211: a#LC_content_toolbar_changefolder {
 8212:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8213: }
 8214: 
 8215: a#LC_content_toolbar_changefolder_toggled {
 8216:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8217: }
 8218: 
 8219: a#LC_content_toolbar_edittoplevel {
 8220:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8221: }
 8222: 
 8223: ul#LC_toolbar li a:hover {
 8224:   background-position: bottom center;
 8225: }
 8226: 
 8227: ul#LC_toolbar {
 8228:   padding: 0;
 8229:   margin: 2px;
 8230:   list-style:none;
 8231:   position:relative;
 8232:   background-color:white;
 8233:   overflow: auto;
 8234: }
 8235: 
 8236: ul#LC_toolbar li {
 8237:   border:1px solid white;
 8238:   padding: 0;
 8239:   margin: 0;
 8240:   float: left;
 8241:   display:inline;
 8242:   vertical-align:middle;
 8243:   white-space: nowrap;
 8244: }
 8245: 
 8246: 
 8247: a.LC_toolbarItem {
 8248:   display:block;
 8249:   padding: 0;
 8250:   margin: 0;
 8251:   height: 32px;
 8252:   width: 32px;
 8253:   color:white;
 8254:   border: none;
 8255:   background-repeat:no-repeat;
 8256:   background-color:transparent;
 8257: }
 8258: 
 8259: ul.LC_funclist {
 8260:     margin: 0;
 8261:     padding: 0.5em 1em 0.5em 0;
 8262: }
 8263: 
 8264: ul.LC_funclist > li:first-child {
 8265:     font-weight:bold; 
 8266:     margin-left:0.8em;
 8267: }
 8268: 
 8269: ul.LC_funclist + ul.LC_funclist {
 8270:     /* 
 8271:        left border as a seperator if we have more than
 8272:        one list 
 8273:     */
 8274:     border-left: 1px solid $sidebg;
 8275:     /* 
 8276:        this hides the left border behind the border of the 
 8277:        outer box if element is wrapped to the next 'line' 
 8278:     */
 8279:     margin-left: -1px;
 8280: }
 8281: 
 8282: ul.LC_funclist li {
 8283:   display: inline;
 8284:   white-space: nowrap;
 8285:   margin: 0 0 0 25px;
 8286:   line-height: 150%;
 8287: }
 8288: 
 8289: .LC_hidden {
 8290:   display: none;
 8291: }
 8292: 
 8293: .LCmodal-overlay {
 8294: 		position:fixed;
 8295: 		top:0;
 8296: 		right:0;
 8297: 		bottom:0;
 8298: 		left:0;
 8299: 		height:100%;
 8300: 		width:100%;
 8301: 		margin:0;
 8302: 		padding:0;
 8303: 		background:#999;
 8304: 		opacity:.75;
 8305: 		filter: alpha(opacity=75);
 8306: 		-moz-opacity: 0.75;
 8307: 		z-index:101;
 8308: }
 8309: 
 8310: * html .LCmodal-overlay {   
 8311: 		position: absolute;
 8312: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8313: }
 8314: 
 8315: .LCmodal-window {
 8316: 		position:fixed;
 8317: 		top:50%;
 8318: 		left:50%;
 8319: 		margin:0;
 8320: 		padding:0;
 8321: 		z-index:102;
 8322: 	}
 8323: 
 8324: * html .LCmodal-window {
 8325: 		position:absolute;
 8326: }
 8327: 
 8328: .LCclose-window {
 8329: 		position:absolute;
 8330: 		width:32px;
 8331: 		height:32px;
 8332: 		right:8px;
 8333: 		top:8px;
 8334: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8335: 		text-indent:-99999px;
 8336: 		overflow:hidden;
 8337: 		cursor:pointer;
 8338: }
 8339: 
 8340: pre.LC_wordwrap {
 8341:   white-space: pre-wrap;
 8342:   white-space: -moz-pre-wrap;
 8343:   white-space: -pre-wrap;
 8344:   white-space: -o-pre-wrap;
 8345:   word-wrap: break-word;
 8346: }
 8347: 
 8348: /*
 8349:   styles used for response display
 8350: */
 8351: div.LC_radiofoil, div.LC_rankfoil {
 8352:   margin: .5em 0em .5em 0em;
 8353: }
 8354: table.LC_itemgroup {
 8355:   margin-top: 1em;
 8356: }
 8357: 
 8358: /*
 8359:   styles used by TTH when "Default set of options to pass to tth/m
 8360:   when converting TeX" in course settings has been set
 8361: 
 8362:   option passed: -t
 8363: 
 8364: */
 8365: 
 8366: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8367: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8368: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8369: td div.norm {line-height:normal;}
 8370: 
 8371: /*
 8372:   option passed -y3
 8373: */
 8374: 
 8375: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8376: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8377: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8378: 
 8379: /*
 8380:   sections with roles, for content only
 8381: */
 8382: section[class^="role-"] {
 8383:   padding-left: 10px;
 8384:   padding-right: 5px;
 8385:   margin-top: 8px;
 8386:   margin-bottom: 8px;
 8387:   border: 1px solid #2A4;
 8388:   border-radius: 5px;
 8389:   box-shadow: 0px 1px 1px #BBB;
 8390: }
 8391: section[class^="role-"]>h1 {
 8392:   position: relative;
 8393:   margin: 0px;
 8394:   padding-top: 10px;
 8395:   padding-left: 40px;
 8396: }
 8397: section[class^="role-"]>h1:before {
 8398:   position: absolute;
 8399:   left: -5px;
 8400:   top: 5px;
 8401: }
 8402: section.role-activity>h1:before {
 8403:   content:url('/adm/daxe/images/section_icons/activity.png');
 8404: }
 8405: section.role-advice>h1:before {
 8406:   content:url('/adm/daxe/images/section_icons/advice.png');
 8407: }
 8408: section.role-bibliography>h1:before {
 8409:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8410: }
 8411: section.role-citation>h1:before {
 8412:   content:url('/adm/daxe/images/section_icons/citation.png');
 8413: }
 8414: section.role-conclusion>h1:before {
 8415:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8416: }
 8417: section.role-definition>h1:before {
 8418:   content:url('/adm/daxe/images/section_icons/definition.png');
 8419: }
 8420: section.role-demonstration>h1:before {
 8421:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8422: }
 8423: section.role-example>h1:before {
 8424:   content:url('/adm/daxe/images/section_icons/example.png');
 8425: }
 8426: section.role-explanation>h1:before {
 8427:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8428: }
 8429: section.role-introduction>h1:before {
 8430:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8431: }
 8432: section.role-method>h1:before {
 8433:   content:url('/adm/daxe/images/section_icons/method.png');
 8434: }
 8435: section.role-more_information>h1:before {
 8436:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8437: }
 8438: section.role-objectives>h1:before {
 8439:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8440: }
 8441: section.role-prerequisites>h1:before {
 8442:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8443: }
 8444: section.role-remark>h1:before {
 8445:   content:url('/adm/daxe/images/section_icons/remark.png');
 8446: }
 8447: section.role-reminder>h1:before {
 8448:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8449: }
 8450: section.role-summary>h1:before {
 8451:   content:url('/adm/daxe/images/section_icons/summary.png');
 8452: }
 8453: section.role-syntax>h1:before {
 8454:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8455: }
 8456: section.role-warning>h1:before {
 8457:   content:url('/adm/daxe/images/section_icons/warning.png');
 8458: }
 8459: 
 8460: #LC_minitab_header {
 8461:   float:left;
 8462:   width:100%;
 8463:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8464:   font-size:93%;
 8465:   line-height:normal;
 8466:   margin: 0.5em 0 0.5em 0;
 8467: }
 8468: #LC_minitab_header ul {
 8469:   margin:0;
 8470:   padding:10px 10px 0;
 8471:   list-style:none;
 8472: }
 8473: #LC_minitab_header li {
 8474:   float:left;
 8475:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8476:   margin:0;
 8477:   padding:0 0 0 9px;
 8478: }
 8479: #LC_minitab_header a {
 8480:   display:block;
 8481:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8482:   padding:5px 15px 4px 6px;
 8483: }
 8484: #LC_minitab_header #LC_current_minitab {
 8485:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8486: }
 8487: #LC_minitab_header #LC_current_minitab a {
 8488:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8489:   padding-bottom:5px;
 8490: }
 8491: 
 8492: 
 8493: END
 8494: }
 8495: 
 8496: =pod
 8497: 
 8498: =item * &headtag()
 8499: 
 8500: Returns a uniform footer for LON-CAPA web pages.
 8501: 
 8502: Inputs: $title - optional title for the head
 8503:         $head_extra - optional extra HTML to put inside the <head>
 8504:         $args - optional arguments
 8505:             force_register - if is true call registerurl so the remote is 
 8506:                              informed
 8507:             redirect       -> array ref of
 8508:                                    1- seconds before redirect occurs
 8509:                                    2- url to redirect to
 8510:                                    3- whether the side effect should occur
 8511:                            (side effect of setting 
 8512:                                $env{'internal.head.redirect'} to the url 
 8513:                                redirected too)
 8514:             domain         -> force to color decorate a page for a specific
 8515:                                domain
 8516:             function       -> force usage of a specific rolish color scheme
 8517:             bgcolor        -> override the default page bgcolor
 8518:             no_auto_mt_title
 8519:                            -> prevent &mt()ing the title arg
 8520: 
 8521: =cut
 8522: 
 8523: sub headtag {
 8524:     my ($title,$head_extra,$args) = @_;
 8525:     
 8526:     my $function = $args->{'function'} || &get_users_function();
 8527:     my $domain   = $args->{'domain'}   || &determinedomain();
 8528:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8529:     my $httphost = $args->{'use_absolute'};
 8530:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8531: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8532: 		   #time(),
 8533: 		   $env{'environment.color.timestamp'},
 8534: 		   $function,$domain,$bgcolor);
 8535: 
 8536:     $url = '/adm/css/'.&escape($url).'.css';
 8537: 
 8538:     my $result =
 8539: 	'<head>'.
 8540: 	&font_settings($args);
 8541: 
 8542:     my $inhibitprint;
 8543:     if ($args->{'print_suppress'}) {
 8544:         $inhibitprint = &print_suppression();
 8545:     }
 8546: 
 8547:     if (!$args->{'frameset'}) {
 8548: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8549:     }
 8550:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8551:         $result .= Apache::lonxml::display_title();
 8552:     }
 8553:     if (!$args->{'no_nav_bar'} 
 8554: 	&& !$args->{'only_body'}
 8555: 	&& !$args->{'frameset'}) {
 8556: 	$result .= &help_menu_js($httphost);
 8557:         $result.=&modal_window();
 8558:         $result.=&togglebox_script();
 8559:         $result.=&wishlist_window();
 8560:         $result.=&LCprogressbarUpdate_script();
 8561:     } else {
 8562:         if ($args->{'add_modal'}) {
 8563:            $result.=&modal_window();
 8564:         }
 8565:         if ($args->{'add_wishlist'}) {
 8566:            $result.=&wishlist_window();
 8567:         }
 8568:         if ($args->{'add_togglebox'}) {
 8569:            $result.=&togglebox_script();
 8570:         }
 8571:         if ($args->{'add_progressbar'}) {
 8572:            $result.=&LCprogressbarUpdate_script();
 8573:         }
 8574:     }
 8575:     if (ref($args->{'redirect'})) {
 8576: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8577: 	$url = &Apache::lonenc::check_encrypt($url);
 8578: 	if (!$inhibit_continue) {
 8579: 	    $env{'internal.head.redirect'} = $url;
 8580: 	}
 8581: 	$result.=<<ADDMETA
 8582: <meta http-equiv="pragma" content="no-cache" />
 8583: <meta http-equiv="Refresh" content="$time; url=$url" />
 8584: ADDMETA
 8585:     } else {
 8586:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8587:             my $requrl = $env{'request.uri'};
 8588:             if ($requrl eq '') {
 8589:                 $requrl = $ENV{'REQUEST_URI'};
 8590:                 $requrl =~ s/\?.+$//;
 8591:             }
 8592:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8593:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8594:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8595:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8596:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8597:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8598:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8599:                     my $offload;
 8600:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8601:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8602:                             $offload = 1;
 8603:                         }
 8604:                     }
 8605:                     unless ($offload) {
 8606:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8607:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8608:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8609:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8610:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8611:                                         $offload = 1;
 8612:                                         $dom_in_use = $env{'user.domain'};
 8613:                                     }
 8614:                                 }
 8615:                             }
 8616:                         }
 8617:                     }
 8618:                     if ($offload) {
 8619:                         my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8620:                         if (($newserver) && ($newserver ne $lonhost)) {
 8621:                             my $numsec = 5;
 8622:                             my $timeout = $numsec * 1000;
 8623:                             my ($newurl,$locknum,%locks,$msg);
 8624:                             if ($env{'request.role.adv'}) {
 8625:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8626:                             }
 8627:                             my $disable_submit = 0;
 8628:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8629:                                 $disable_submit = 1;
 8630:                             }
 8631:                             if ($locknum) {
 8632:                                 my @lockinfo = sort(values(%locks));
 8633:                                 $msg = &mt('Once the following tasks are complete: ')."\n".
 8634:                                        join(", ",sort(values(%locks)))."\n";
 8635:                                 if (&show_course()) {
 8636:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8637:                                 } else {
 8638:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8639:                                 }
 8640:                             } else {
 8641:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8642:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8643:                                 }
 8644:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8645:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8646:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8647:                                     $newurl .= '&role='.$env{'request.role'};
 8648:                                 }
 8649:                                 if ($env{'request.symb'}) {
 8650:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8651:                                     if ($shownsymb =~ m{^/enc/}) {
 8652:                                         my $reqdmajor = 2;
 8653:                                         my $reqdminor = 11;
 8654:                                         my $reqdsubminor = 3;
 8655:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8656:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8657:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8658:                                         if (($major eq '' && $minor eq '') ||
 8659:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8660:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8661:                                              ($reqdsubminor > $subminor))))) {
 8662:                                             undef($shownsymb);
 8663:                                         }
 8664:                                     }
 8665:                                     if ($shownsymb) {
 8666:                                         &js_escape(\$shownsymb);
 8667:                                         $newurl .= '&symb='.$shownsymb;
 8668:                                     }
 8669:                                 } else {
 8670:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8671:                                     &js_escape(\$shownurl);
 8672:                                     $newurl .= '&origurl='.$shownurl;
 8673:                                 }
 8674:                             }
 8675:                             &js_escape(\$msg);
 8676:                             $result.=<<OFFLOAD
 8677: <meta http-equiv="pragma" content="no-cache" />
 8678: <script type="text/javascript">
 8679: // <![CDATA[
 8680: function LC_Offload_Now() {
 8681:     var dest = "$newurl";
 8682:     if (dest != '') {
 8683:         window.location.href="$newurl";
 8684:     }
 8685: }
 8686: \$(document).ready(function () {
 8687:     window.alert('$msg');
 8688:     if ($disable_submit) {
 8689:         \$(".LC_hwk_submit").prop("disabled", true);
 8690:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8691:     }
 8692:     setTimeout('LC_Offload_Now()', $timeout);
 8693: });
 8694: // ]]>
 8695: </script>
 8696: OFFLOAD
 8697:                         }
 8698:                     }
 8699:                 }
 8700:             }
 8701:         }
 8702:     }
 8703:     if (!defined($title)) {
 8704: 	$title = 'The LearningOnline Network with CAPA';
 8705:     }
 8706:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8707:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8708: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8709:     if (!$args->{'frameset'}) {
 8710:         $result .= ' /';
 8711:     }
 8712:     $result .= '>' 
 8713:         .$inhibitprint
 8714: 	.$head_extra;
 8715:     my $clientmobile;
 8716:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8717:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8718:     } else {
 8719:         $clientmobile = $env{'browser.mobile'};
 8720:     }
 8721:     if ($clientmobile) {
 8722:         $result .= '
 8723: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8724: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8725:     }
 8726:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8727:     return $result.'</head>';
 8728: }
 8729: 
 8730: =pod
 8731: 
 8732: =item * &font_settings()
 8733: 
 8734: Returns neccessary <meta> to set the proper encoding
 8735: 
 8736: Inputs: optional reference to HASH -- $args passed to &headtag()
 8737: 
 8738: =cut
 8739: 
 8740: sub font_settings {
 8741:     my ($args) = @_;
 8742:     my $headerstring='';
 8743:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8744:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8745:         $headerstring.=
 8746:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8747:         if (!$args->{'frameset'}) {
 8748: 	    $headerstring.= ' /';
 8749:         }
 8750: 	$headerstring .= '>'."\n";
 8751:     }
 8752:     return $headerstring;
 8753: }
 8754: 
 8755: =pod
 8756: 
 8757: =item * &print_suppression()
 8758: 
 8759: In course context returns css which causes the body to be blank when media="print",
 8760: if printout generation is unavailable for the current resource.
 8761: 
 8762: This could be because:
 8763: 
 8764: (a) printstartdate is in the future
 8765: 
 8766: (b) printenddate is in the past
 8767: 
 8768: (c) there is an active exam block with "printout"
 8769: functionality blocked
 8770: 
 8771: Users with pav, pfo or evb privileges are exempt.
 8772: 
 8773: Inputs: none
 8774: 
 8775: =cut
 8776: 
 8777: 
 8778: sub print_suppression {
 8779:     my $noprint;
 8780:     if ($env{'request.course.id'}) {
 8781:         my $scope = $env{'request.course.id'};
 8782:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8783:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8784:             return;
 8785:         }
 8786:         if ($env{'request.course.sec'} ne '') {
 8787:             $scope .= "/$env{'request.course.sec'}";
 8788:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8789:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8790:                 return;
 8791:             }
 8792:         }
 8793:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8794:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8795:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8796:         if ($blocked) {
 8797:             my $checkrole = "cm./$cdom/$cnum";
 8798:             if ($env{'request.course.sec'} ne '') {
 8799:                 $checkrole .= "/$env{'request.course.sec'}";
 8800:             }
 8801:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8802:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8803:                 $noprint = 1;
 8804:             }
 8805:         }
 8806:         unless ($noprint) {
 8807:             my $symb = &Apache::lonnet::symbread();
 8808:             if ($symb ne '') {
 8809:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8810:                 if (ref($navmap)) {
 8811:                     my $res = $navmap->getBySymb($symb);
 8812:                     if (ref($res)) {
 8813:                         if (!$res->resprintable()) {
 8814:                             $noprint = 1;
 8815:                         }
 8816:                     }
 8817:                 }
 8818:             }
 8819:         }
 8820:         if ($noprint) {
 8821:             return <<"ENDSTYLE";
 8822: <style type="text/css" media="print">
 8823:     body { display:none }
 8824: </style>
 8825: ENDSTYLE
 8826:         }
 8827:     }
 8828:     return;
 8829: }
 8830: 
 8831: =pod
 8832: 
 8833: =item * &xml_begin()
 8834: 
 8835: Returns the needed doctype and <html>
 8836: 
 8837: Inputs: none
 8838: 
 8839: =cut
 8840: 
 8841: sub xml_begin {
 8842:     my ($is_frameset) = @_;
 8843:     my $output='';
 8844: 
 8845:     if ($env{'browser.mathml'}) {
 8846: 	$output='<?xml version="1.0"?>'
 8847:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8848: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8849:             
 8850: #	    .'<!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">] >'
 8851: 	    .'<!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">'
 8852:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8853: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8854:     } elsif ($is_frameset) {
 8855:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8856:                 '<html>'."\n";
 8857:     } else {
 8858: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8859:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8860:     }
 8861:     return $output;
 8862: }
 8863: 
 8864: =pod
 8865: 
 8866: =item * &start_page()
 8867: 
 8868: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8869: 
 8870: Inputs:
 8871: 
 8872: =over 4
 8873: 
 8874: $title - optional title for the page
 8875: 
 8876: $head_extra - optional extra HTML to incude inside the <head>
 8877: 
 8878: $args - additional optional args supported are:
 8879: 
 8880: =over 8
 8881: 
 8882:              only_body      -> is true will set &bodytag() onlybodytag
 8883:                                     arg on
 8884:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8885:              add_entries    -> additional attributes to add to the  <body>
 8886:              domain         -> force to color decorate a page for a 
 8887:                                     specific domain
 8888:              function       -> force usage of a specific rolish color
 8889:                                     scheme
 8890:              redirect       -> see &headtag()
 8891:              bgcolor        -> override the default page bg color
 8892:              js_ready       -> return a string ready for being used in 
 8893:                                     a javascript writeln
 8894:              html_encode    -> return a string ready for being used in 
 8895:                                     a html attribute
 8896:              force_register -> if is true will turn on the &bodytag()
 8897:                                     $forcereg arg
 8898:              frameset       -> if true will start with a <frameset>
 8899:                                     rather than <body>
 8900:              skip_phases    -> hash ref of 
 8901:                                     head -> skip the <html><head> generation
 8902:                                     body -> skip all <body> generation
 8903:              no_auto_mt_title -> prevent &mt()ing the title arg
 8904:              bread_crumbs ->             Array containing breadcrumbs
 8905:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8906:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8907:                                     to lonhtmlcommon::breadcrumbs
 8908:              group          -> includes the current group, if page is for a 
 8909:                                specific group
 8910:              use_absolute   -> for request for external resource or syllabus, this
 8911:                                will contain https://<hostname> if server uses
 8912:                                https (as per hosts.tab), but request is for http
 8913:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8914: 
 8915: =back
 8916: 
 8917: =back
 8918: 
 8919: =cut
 8920: 
 8921: sub start_page {
 8922:     my ($title,$head_extra,$args) = @_;
 8923:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8924: 
 8925:     $env{'internal.start_page'}++;
 8926:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
 8927: 
 8928:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8929:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8930:     }
 8931: 
 8932:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8933:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8934:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8935:                 $args->{'no_primary_menu'} = 1;
 8936:             }
 8937:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8938:                 $args->{'no_inline_menu'} = 1;
 8939:             }
 8940:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8941:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8942:             }
 8943:         } else {
 8944:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8945:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8946:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8947:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8948:                     $args->{'no_primary_menu'} = 1;
 8949:                 }
 8950:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8951:                     $args->{'no_inline_menu'} = 1;
 8952:                 }
 8953:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8954:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8955:                 }
 8956:             }
 8957:         }
 8958:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8959:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8960:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8961:     }
 8962:     
 8963:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8964: 	if ($args->{'frameset'}) {
 8965: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8966: 						$args->{'add_entries'});
 8967: 	    $result .= "\n<frameset $attr_string>\n";
 8968:         } else {
 8969:             $result .=
 8970:                 &bodytag($title, 
 8971:                          $args->{'function'},       $args->{'add_entries'},
 8972:                          $args->{'only_body'},      $args->{'domain'},
 8973:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8974:                          $args->{'bgcolor'},        $args,
 8975:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
 8976:         }
 8977:     }
 8978: 
 8979:     if ($args->{'js_ready'}) {
 8980: 		$result = &js_ready($result);
 8981:     }
 8982:     if ($args->{'html_encode'}) {
 8983: 		$result = &html_encode($result);
 8984:     }
 8985: 
 8986:     # Preparation for new and consistent functionlist at top of screen
 8987:     # if ($args->{'functionlist'}) {
 8988:     #            $result .= &build_functionlist();
 8989:     #}
 8990: 
 8991:     # Don't add anything more if only_body wanted or in const space
 8992:     return $result if    $args->{'only_body'} 
 8993:                       || $env{'request.state'} eq 'construct';
 8994: 
 8995:     #Breadcrumbs
 8996:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8997: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8998: 		#if any br links exists, add them to the breadcrumbs
 8999: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9000: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9001: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9002: 			}
 9003: 		}
 9004:                 # if @advtools array contains items add then to the breadcrumbs
 9005:                 if (@advtools > 0) {
 9006:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9007:                 }
 9008:                 my $menulink;
 9009:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9010:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9011:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9012:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9013:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9014:                      (!$env{'request.role.adv'}))) {
 9015:                     $menulink = 0;
 9016:                 } else {
 9017:                     undef($menulink);
 9018:                 }
 9019: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9020: 		if(exists($args->{'bread_crumbs_component'})){
 9021: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9022:                 } else {
 9023: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9024: 		}
 9025:     }
 9026:     return $result;
 9027: }
 9028: 
 9029: sub end_page {
 9030:     my ($args) = @_;
 9031:     $env{'internal.end_page'}++;
 9032:     my $result;
 9033:     if ($args->{'discussion'}) {
 9034: 	my ($target,$parser);
 9035: 	if (ref($args->{'discussion'})) {
 9036: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9037: 				$args->{'discussion'}{'parser'});
 9038: 	}
 9039: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9040:     }
 9041:     if ($args->{'frameset'}) {
 9042: 	$result .= '</frameset>';
 9043:     } else {
 9044: 	$result .= &endbodytag($args);
 9045:     }
 9046:     unless ($args->{'notbody'}) {
 9047:         $result .= "\n</html>";
 9048:     }
 9049: 
 9050:     if ($args->{'js_ready'}) {
 9051: 	$result = &js_ready($result);
 9052:     }
 9053: 
 9054:     if ($args->{'html_encode'}) {
 9055: 	$result = &html_encode($result);
 9056:     }
 9057: 
 9058:     return $result;
 9059: }
 9060: 
 9061: sub wishlist_window {
 9062:     return(<<'ENDWISHLIST');
 9063: <script type="text/javascript">
 9064: // <![CDATA[
 9065: // <!-- BEGIN LON-CAPA Internal
 9066: function set_wishlistlink(title, path) {
 9067:     if (!title) {
 9068:         title = document.title;
 9069:         title = title.replace(/^LON-CAPA /,'');
 9070:     }
 9071:     title = encodeURIComponent(title);
 9072:     title = title.replace("'","\\\'");
 9073:     if (!path) {
 9074:         path = location.pathname;
 9075:     }
 9076:     path = encodeURIComponent(path);
 9077:     path = path.replace("'","\\\'");
 9078:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9079:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9080: }
 9081: // END LON-CAPA Internal -->
 9082: // ]]>
 9083: </script>
 9084: ENDWISHLIST
 9085: }
 9086: 
 9087: sub modal_window {
 9088:     return(<<'ENDMODAL');
 9089: <script type="text/javascript">
 9090: // <![CDATA[
 9091: // <!-- BEGIN LON-CAPA Internal
 9092: var modalWindow = {
 9093: 	parent:"body",
 9094: 	windowId:null,
 9095: 	content:null,
 9096: 	width:null,
 9097: 	height:null,
 9098: 	close:function()
 9099: 	{
 9100: 	        $(".LCmodal-window").remove();
 9101: 	        $(".LCmodal-overlay").remove();
 9102: 	},
 9103: 	open:function()
 9104: 	{
 9105: 		var modal = "";
 9106: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9107: 		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;\">";
 9108: 		modal += this.content;
 9109: 		modal += "</div>";	
 9110: 
 9111: 		$(this.parent).append(modal);
 9112: 
 9113: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9114: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9115: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9116: 	}
 9117: };
 9118: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9119: 	{
 9120:                 source = source.replace(/'/g,"&#39;");
 9121: 		modalWindow.windowId = "myModal";
 9122: 		modalWindow.width = width;
 9123: 		modalWindow.height = height;
 9124: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9125: 		modalWindow.open();
 9126: 	};
 9127: // END LON-CAPA Internal -->
 9128: // ]]>
 9129: </script>
 9130: ENDMODAL
 9131: }
 9132: 
 9133: sub modal_link {
 9134:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9135:     unless ($width) { $width=480; }
 9136:     unless ($height) { $height=400; }
 9137:     unless ($scrolling) { $scrolling='yes'; }
 9138:     unless ($transparency) { $transparency='true'; }
 9139: 
 9140:     my $target_attr;
 9141:     if (defined($target)) {
 9142:         $target_attr = 'target="'.$target.'"';
 9143:     }
 9144:     return <<"ENDLINK";
 9145: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9146: ENDLINK
 9147: }
 9148: 
 9149: sub modal_adhoc_script {
 9150:     my ($funcname,$width,$height,$content)=@_;
 9151:     return (<<ENDADHOC);
 9152: <script type="text/javascript">
 9153: // <![CDATA[
 9154:         var $funcname = function()
 9155:         {
 9156:                 modalWindow.windowId = "myModal";
 9157:                 modalWindow.width = $width;
 9158:                 modalWindow.height = $height;
 9159:                 modalWindow.content = '$content';
 9160:                 modalWindow.open();
 9161:         };  
 9162: // ]]>
 9163: </script>
 9164: ENDADHOC
 9165: }
 9166: 
 9167: sub modal_adhoc_inner {
 9168:     my ($funcname,$width,$height,$content)=@_;
 9169:     my $innerwidth=$width-20;
 9170:     $content=&js_ready(
 9171:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9172:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9173:                  $content.
 9174:                  &end_scrollbox().
 9175:                  &end_page()
 9176:              );
 9177:     return &modal_adhoc_script($funcname,$width,$height,$content);
 9178: }
 9179: 
 9180: sub modal_adhoc_window {
 9181:     my ($funcname,$width,$height,$content,$linktext)=@_;
 9182:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 9183:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9184: }
 9185: 
 9186: sub modal_adhoc_launch {
 9187:     my ($funcname,$width,$height,$content)=@_;
 9188:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9189: <script type="text/javascript">
 9190: // <![CDATA[
 9191: $funcname();
 9192: // ]]>
 9193: </script>
 9194: ENDLAUNCH
 9195: }
 9196: 
 9197: sub modal_adhoc_close {
 9198:     return (<<ENDCLOSE);
 9199: <script type="text/javascript">
 9200: // <![CDATA[
 9201: modalWindow.close();
 9202: // ]]>
 9203: </script>
 9204: ENDCLOSE
 9205: }
 9206: 
 9207: sub togglebox_script {
 9208:    return(<<ENDTOGGLE);
 9209: <script type="text/javascript"> 
 9210: // <![CDATA[
 9211: function LCtoggleDisplay(id,hidetext,showtext) {
 9212:    link = document.getElementById(id + "link").childNodes[0];
 9213:    with (document.getElementById(id).style) {
 9214:       if (display == "none" ) {
 9215:           display = "inline";
 9216:           link.nodeValue = hidetext;
 9217:         } else {
 9218:           display = "none";
 9219:           link.nodeValue = showtext;
 9220:        }
 9221:    }
 9222: }
 9223: // ]]>
 9224: </script>
 9225: ENDTOGGLE
 9226: }
 9227: 
 9228: sub start_togglebox {
 9229:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9230:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9231:     unless ($showtext) { $showtext=&mt('show'); }
 9232:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9233:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9234:     return &start_data_table().
 9235:            &start_data_table_header_row().
 9236:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9237:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9238:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9239:            &end_data_table_header_row().
 9240:            '<tr id="'.$id.'" style="display:none""><td>';
 9241: }
 9242: 
 9243: sub end_togglebox {
 9244:     return '</td></tr>'.&end_data_table();
 9245: }
 9246: 
 9247: sub LCprogressbar_script {
 9248:    my ($id,$number_to_do)=@_;
 9249:    if ($number_to_do) {
 9250:        return(<<ENDPROGRESS);
 9251: <script type="text/javascript">
 9252: // <![CDATA[
 9253: \$('#progressbar$id').progressbar({
 9254:   value: 0,
 9255:   change: function(event, ui) {
 9256:     var newVal = \$(this).progressbar('option', 'value');
 9257:     \$('.pblabel', this).text(LCprogressTxt);
 9258:   }
 9259: });
 9260: // ]]>
 9261: </script>
 9262: ENDPROGRESS
 9263:    } else {
 9264:        return(<<ENDPROGRESS);
 9265: <script type="text/javascript">
 9266: // <![CDATA[
 9267: \$('#progressbar$id').progressbar({
 9268:   value: false,
 9269:   create: function(event, ui) {
 9270:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9271:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9272:   }
 9273: });
 9274: // ]]>
 9275: </script>
 9276: ENDPROGRESS
 9277:    }
 9278: }
 9279: 
 9280: sub LCprogressbarUpdate_script {
 9281:    return(<<ENDPROGRESSUPDATE);
 9282: <style type="text/css">
 9283: .ui-progressbar { position:relative; }
 9284: .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%; }
 9285: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9286: </style>
 9287: <script type="text/javascript">
 9288: // <![CDATA[
 9289: var LCprogressTxt='---';
 9290: 
 9291: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9292:    LCprogressTxt=progresstext;
 9293:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9294:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9295:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9296:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9297:    } else {
 9298:        \$('#progressbar'+id).progressbar('value',percent);
 9299:    }
 9300: }
 9301: // ]]>
 9302: </script>
 9303: ENDPROGRESSUPDATE
 9304: }
 9305: 
 9306: my $LClastpercent;
 9307: my $LCidcnt;
 9308: my $LCcurrentid;
 9309: 
 9310: sub LCprogressbar {
 9311:     my ($r,$number_to_do,$preamble)=@_;
 9312:     $LClastpercent=0;
 9313:     $LCidcnt++;
 9314:     $LCcurrentid=$$.'_'.$LCidcnt;
 9315:     my ($starting,$content);
 9316:     if ($number_to_do) {
 9317:         $starting=&mt('Starting');
 9318:         $content=(<<ENDPROGBAR);
 9319: $preamble
 9320:   <div id="progressbar$LCcurrentid">
 9321:     <span class="pblabel">$starting</span>
 9322:   </div>
 9323: ENDPROGBAR
 9324:     } else {
 9325:         $starting=&mt('Loading...');
 9326:         $LClastpercent='false';
 9327:         $content=(<<ENDPROGBAR);
 9328: $preamble
 9329:   <div id="progressbar$LCcurrentid">
 9330:       <div class="progress-label">$starting</div>
 9331:   </div>
 9332: ENDPROGBAR
 9333:     }
 9334:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9335: }
 9336: 
 9337: sub LCprogressbarUpdate {
 9338:     my ($r,$val,$text,$number_to_do)=@_;
 9339:     if ($number_to_do) {
 9340:         unless ($val) { 
 9341:             if ($LClastpercent) {
 9342:                 $val=$LClastpercent;
 9343:             } else {
 9344:                 $val=0;
 9345:             }
 9346:         }
 9347:         if ($val<0) { $val=0; }
 9348:         if ($val>100) { $val=0; }
 9349:         $LClastpercent=$val;
 9350:         unless ($text) { $text=$val.'%'; }
 9351:     } else {
 9352:         $val = 'false';
 9353:     }
 9354:     $text=&js_ready($text);
 9355:     &r_print($r,<<ENDUPDATE);
 9356: <script type="text/javascript">
 9357: // <![CDATA[
 9358: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9359: // ]]>
 9360: </script>
 9361: ENDUPDATE
 9362: }
 9363: 
 9364: sub LCprogressbarClose {
 9365:     my ($r)=@_;
 9366:     $LClastpercent=0;
 9367:     &r_print($r,<<ENDCLOSE);
 9368: <script type="text/javascript">
 9369: // <![CDATA[
 9370: \$("#progressbar$LCcurrentid").hide('slow'); 
 9371: // ]]>
 9372: </script>
 9373: ENDCLOSE
 9374: }
 9375: 
 9376: sub r_print {
 9377:     my ($r,$to_print)=@_;
 9378:     if ($r) {
 9379:       $r->print($to_print);
 9380:       $r->rflush();
 9381:     } else {
 9382:       print($to_print);
 9383:     }
 9384: }
 9385: 
 9386: sub html_encode {
 9387:     my ($result) = @_;
 9388: 
 9389:     $result = &HTML::Entities::encode($result,'<>&"');
 9390:     
 9391:     return $result;
 9392: }
 9393: 
 9394: sub js_ready {
 9395:     my ($result) = @_;
 9396: 
 9397:     $result =~ s/[\n\r]/ /xmsg;
 9398:     $result =~ s/\\/\\\\/xmsg;
 9399:     $result =~ s/'/\\'/xmsg;
 9400:     $result =~ s{</}{<\\/}xmsg;
 9401:     
 9402:     return $result;
 9403: }
 9404: 
 9405: sub validate_page {
 9406:     if (  exists($env{'internal.start_page'})
 9407: 	  &&     $env{'internal.start_page'} > 1) {
 9408: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9409: 				 $env{'internal.start_page'}.' '.
 9410: 				 $ENV{'request.filename'});
 9411:     }
 9412:     if (  exists($env{'internal.end_page'})
 9413: 	  &&     $env{'internal.end_page'} > 1) {
 9414: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9415: 				 $env{'internal.end_page'}.' '.
 9416: 				 $env{'request.filename'});
 9417:     }
 9418:     if (     exists($env{'internal.start_page'})
 9419: 	&& ! exists($env{'internal.end_page'})) {
 9420: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9421: 				 $env{'request.filename'});
 9422:     }
 9423:     if (   ! exists($env{'internal.start_page'})
 9424: 	&&   exists($env{'internal.end_page'})) {
 9425: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9426: 				 $env{'request.filename'});
 9427:     }
 9428: }
 9429: 
 9430: 
 9431: sub start_scrollbox {
 9432:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9433:     unless ($outerwidth) { $outerwidth='520px'; }
 9434:     unless ($width) { $width='500px'; }
 9435:     unless ($height) { $height='200px'; }
 9436:     my ($table_id,$div_id,$tdcol);
 9437:     if ($id ne '') {
 9438:         $table_id = ' id="table_'.$id.'"';
 9439:         $div_id = ' id="div_'.$id.'"';
 9440:     }
 9441:     if ($bgcolor ne '') {
 9442:         $tdcol = "background-color: $bgcolor;";
 9443:     }
 9444:     my $nicescroll_js;
 9445:     if ($env{'browser.mobile'}) {
 9446:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9447:     }
 9448:     return <<"END";
 9449: $nicescroll_js
 9450: 
 9451: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9452: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9453: END
 9454: }
 9455: 
 9456: sub end_scrollbox {
 9457:     return '</div></td></tr></table>';
 9458: }
 9459: 
 9460: sub nicescroll_javascript {
 9461:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9462:     my %options;
 9463:     if (ref($cursor) eq 'HASH') {
 9464:         %options = %{$cursor};
 9465:     }
 9466:     unless ($options{'railalign'} =~ /^left|right$/) {
 9467:         $options{'railalign'} = 'left';
 9468:     }
 9469:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9470:         my $function  = &get_users_function();
 9471:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9472:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9473:             $options{'cursorcolor'} = '#00F';
 9474:         }
 9475:     }
 9476:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9477:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9478:             $options{'cursoropacity'}='1.0';
 9479:         }
 9480:     } else {
 9481:         $options{'cursoropacity'}='1.0';
 9482:     }
 9483:     if ($options{'cursorfixedheight'} eq 'none') {
 9484:         delete($options{'cursorfixedheight'});
 9485:     } else {
 9486:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9487:     }
 9488:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9489:         delete($options{'railoffset'});
 9490:     }
 9491:     my @niceoptions;
 9492:     while (my($key,$value) = each(%options)) {
 9493:         if ($value =~ /^\{.+\}$/) {
 9494:             push(@niceoptions,$key.':'.$value);
 9495:         } else {
 9496:             push(@niceoptions,$key.':"'.$value.'"');
 9497:         }
 9498:     }
 9499:     my $nicescroll_js = '
 9500: $(document).ready(
 9501:       function() {
 9502:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9503:       }
 9504: );
 9505: ';
 9506:     if ($framecheck) {
 9507:         $nicescroll_js .= '
 9508: function expand_div(caller) {
 9509:     if (top === self) {
 9510:         document.getElementById("'.$id.'").style.width = "auto";
 9511:         document.getElementById("'.$id.'").style.height = "auto";
 9512:     } else {
 9513:         try {
 9514:             if (parent.frames) {
 9515:                 if (parent.frames.length > 1) {
 9516:                     var framesrc = parent.frames[1].location.href;
 9517:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9518:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9519:                         document.getElementById("'.$id.'").style.width = "auto";
 9520:                         document.getElementById("'.$id.'").style.height = "auto";
 9521:                     }
 9522:                 }
 9523:             }
 9524:         } catch (e) {
 9525:             return;
 9526:         }
 9527:     }
 9528:     return;
 9529: }
 9530: ';
 9531:     }
 9532:     if ($needjsready) {
 9533:         $nicescroll_js = '
 9534: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9535:     } else {
 9536:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9537:     }
 9538:     return $nicescroll_js;
 9539: }
 9540: 
 9541: sub simple_error_page {
 9542:     my ($r,$title,$msg,$args) = @_;
 9543:     my %displayargs;
 9544:     if (ref($args) eq 'HASH') {
 9545:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9546:         if ($args->{'only_body'}) {
 9547:             $displayargs{'only_body'} = 1;
 9548:         }
 9549:         if ($args->{'no_nav_bar'}) {
 9550:             $displayargs{'no_nav_bar'} = 1;
 9551:         }
 9552:     } else {
 9553:         $msg = &mt($msg);
 9554:     }
 9555: 
 9556:     my $page =
 9557: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9558: 	'<p class="LC_error">'.$msg.'</p>'.
 9559: 	&Apache::loncommon::end_page();
 9560:     if (ref($r)) {
 9561: 	$r->print($page);
 9562: 	return;
 9563:     }
 9564:     return $page;
 9565: }
 9566: 
 9567: {
 9568:     my @row_count;
 9569: 
 9570:     sub start_data_table_count {
 9571:         unshift(@row_count, 0);
 9572:         return;
 9573:     }
 9574: 
 9575:     sub end_data_table_count {
 9576:         shift(@row_count);
 9577:         return;
 9578:     }
 9579: 
 9580:     sub start_data_table {
 9581: 	my ($add_class,$id) = @_;
 9582: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9583:         my $table_id;
 9584:         if (defined($id)) {
 9585:             $table_id = ' id="'.$id.'"';
 9586:         }
 9587: 	&start_data_table_count();
 9588: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9589:     }
 9590: 
 9591:     sub end_data_table {
 9592: 	&end_data_table_count();
 9593: 	return '</table>'."\n";;
 9594:     }
 9595: 
 9596:     sub start_data_table_row {
 9597: 	my ($add_class, $id) = @_;
 9598: 	$row_count[0]++;
 9599: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9600: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9601:         $id = (' id="'.$id.'"') unless ($id eq '');
 9602:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9603:     }
 9604:     
 9605:     sub continue_data_table_row {
 9606: 	my ($add_class, $id) = @_;
 9607: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9608: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9609:         $id = (' id="'.$id.'"') unless ($id eq '');
 9610:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9611:     }
 9612: 
 9613:     sub end_data_table_row {
 9614: 	return '</tr>'."\n";;
 9615:     }
 9616: 
 9617:     sub start_data_table_empty_row {
 9618: #	$row_count[0]++;
 9619: 	return  '<tr class="LC_empty_row" >'."\n";;
 9620:     }
 9621: 
 9622:     sub end_data_table_empty_row {
 9623: 	return '</tr>'."\n";;
 9624:     }
 9625: 
 9626:     sub start_data_table_header_row {
 9627: 	return  '<tr class="LC_header_row">'."\n";;
 9628:     }
 9629: 
 9630:     sub end_data_table_header_row {
 9631: 	return '</tr>'."\n";;
 9632:     }
 9633: 
 9634:     sub data_table_caption {
 9635:         my $caption = shift;
 9636:         return "<caption class=\"LC_caption\">$caption</caption>";
 9637:     }
 9638: }
 9639: 
 9640: =pod
 9641: 
 9642: =item * &inhibit_menu_check($arg)
 9643: 
 9644: Checks for a inhibitmenu state and generates output to preserve it
 9645: 
 9646: Inputs:         $arg - can be any of
 9647:                      - undef - in which case the return value is a string 
 9648:                                to add  into arguments list of a uri
 9649:                      - 'input' - in which case the return value is a HTML
 9650:                                  <form> <input> field of type hidden to
 9651:                                  preserve the value
 9652:                      - a url - in which case the return value is the url with
 9653:                                the neccesary cgi args added to preserve the
 9654:                                inhibitmenu state
 9655:                      - a ref to a url - no return value, but the string is
 9656:                                         updated to include the neccessary cgi
 9657:                                         args to preserve the inhibitmenu state
 9658: 
 9659: =cut
 9660: 
 9661: sub inhibit_menu_check {
 9662:     my ($arg) = @_;
 9663:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9664:     if ($arg eq 'input') {
 9665: 	if ($env{'form.inhibitmenu'}) {
 9666: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9667: 	} else {
 9668: 	    return
 9669: 	}
 9670:     }
 9671:     if ($env{'form.inhibitmenu'}) {
 9672: 	if (ref($arg)) {
 9673: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9674: 	} elsif ($arg eq '') {
 9675: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9676: 	} else {
 9677: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9678: 	}
 9679:     }
 9680:     if (!ref($arg)) {
 9681: 	return $arg;
 9682:     }
 9683: }
 9684: 
 9685: ###############################################
 9686: 
 9687: =pod
 9688: 
 9689: =back
 9690: 
 9691: =head1 User Information Routines
 9692: 
 9693: =over 4
 9694: 
 9695: =item * &get_users_function()
 9696: 
 9697: Used by &bodytag to determine the current users primary role.
 9698: Returns either 'student','coordinator','admin', or 'author'.
 9699: 
 9700: =cut
 9701: 
 9702: ###############################################
 9703: sub get_users_function {
 9704:     my $function = 'norole';
 9705:     if ($env{'request.role'}=~/^(st)/) {
 9706:         $function='student';
 9707:     }
 9708:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9709:         $function='coordinator';
 9710:     }
 9711:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9712:         $function='admin';
 9713:     }
 9714:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9715:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9716:         $function='author';
 9717:     }
 9718:     return $function;
 9719: }
 9720: 
 9721: ###############################################
 9722: 
 9723: =pod
 9724: 
 9725: =item * &show_course()
 9726: 
 9727: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9728: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9729: 
 9730: Inputs:
 9731: None
 9732: 
 9733: Outputs:
 9734: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9735: 
 9736: =cut
 9737: 
 9738: ###############################################
 9739: sub show_course {
 9740:     my $course = !$env{'user.adv'};
 9741:     if (!$env{'user.adv'}) {
 9742:         foreach my $env (keys(%env)) {
 9743:             next if ($env !~ m/^user\.priv\./);
 9744:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9745:                 $course = 0;
 9746:                 last;
 9747:             }
 9748:         }
 9749:     }
 9750:     return $course;
 9751: }
 9752: 
 9753: ###############################################
 9754: 
 9755: =pod
 9756: 
 9757: =item * &check_user_status()
 9758: 
 9759: Determines current status of supplied role for a
 9760: specific user. Roles can be active, previous or future.
 9761: 
 9762: Inputs: 
 9763: user's domain, user's username, course's domain,
 9764: course's number, optional section ID.
 9765: 
 9766: Outputs:
 9767: role status: active, previous or future. 
 9768: 
 9769: =cut
 9770: 
 9771: sub check_user_status {
 9772:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9773:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9774:     my @uroles = keys(%userinfo);
 9775:     my $srchstr;
 9776:     my $active_chk = 'none';
 9777:     my $now = time;
 9778:     if (@uroles > 0) {
 9779:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9780:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9781:         } else {
 9782:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9783:         }
 9784:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9785:             my $role_end = 0;
 9786:             my $role_start = 0;
 9787:             $active_chk = 'active';
 9788:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9789:                 $role_end = $1;
 9790:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9791:                     $role_start = $1;
 9792:                 }
 9793:             }
 9794:             if ($role_start > 0) {
 9795:                 if ($now < $role_start) {
 9796:                     $active_chk = 'future';
 9797:                 }
 9798:             }
 9799:             if ($role_end > 0) {
 9800:                 if ($now > $role_end) {
 9801:                     $active_chk = 'previous';
 9802:                 }
 9803:             }
 9804:         }
 9805:     }
 9806:     return $active_chk;
 9807: }
 9808: 
 9809: ###############################################
 9810: 
 9811: =pod
 9812: 
 9813: =item * &get_sections()
 9814: 
 9815: Determines all the sections for a course including
 9816: sections with students and sections containing other roles.
 9817: Incoming parameters: 
 9818: 
 9819: 1. domain
 9820: 2. course number 
 9821: 3. reference to array containing roles for which sections should 
 9822: be gathered (optional).
 9823: 4. reference to array containing status types for which sections 
 9824: should be gathered (optional).
 9825: 
 9826: If the third argument is undefined, sections are gathered for any role. 
 9827: If the fourth argument is undefined, sections are gathered for any status.
 9828: Permissible values are 'active' or 'future' or 'previous'.
 9829:  
 9830: Returns section hash (keys are section IDs, values are
 9831: number of users in each section), subject to the
 9832: optional roles filter, optional status filter 
 9833: 
 9834: =cut
 9835: 
 9836: ###############################################
 9837: sub get_sections {
 9838:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9839:     if (!defined($cdom) || !defined($cnum)) {
 9840:         my $cid =  $env{'request.course.id'};
 9841: 
 9842: 	return if (!defined($cid));
 9843: 
 9844:         $cdom = $env{'course.'.$cid.'.domain'};
 9845:         $cnum = $env{'course.'.$cid.'.num'};
 9846:     }
 9847: 
 9848:     my %sectioncount;
 9849:     my $now = time;
 9850: 
 9851:     my $check_students = 1;
 9852:     my $only_students = 0;
 9853:     if (ref($possible_roles) eq 'ARRAY') {
 9854:         if (grep(/^st$/,@{$possible_roles})) {
 9855:             if (@{$possible_roles} == 1) {
 9856:                 $only_students = 1;
 9857:             }
 9858:         } else {
 9859:             $check_students = 0;
 9860:         }
 9861:     }
 9862: 
 9863:     if ($check_students) { 
 9864: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9865: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9866: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9867:         my $start_index = &Apache::loncoursedata::CL_START();
 9868:         my $end_index = &Apache::loncoursedata::CL_END();
 9869:         my $status;
 9870: 	while (my ($student,$data) = each(%$classlist)) {
 9871: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9872: 				                     $data->[$status_index],
 9873:                                                      $data->[$start_index],
 9874:                                                      $data->[$end_index]);
 9875:             if ($stu_status eq 'Active') {
 9876:                 $status = 'active';
 9877:             } elsif ($end < $now) {
 9878:                 $status = 'previous';
 9879:             } elsif ($start > $now) {
 9880:                 $status = 'future';
 9881:             } 
 9882: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9883:                 if ((!defined($possible_status)) || (($status ne '') && 
 9884:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9885: 		    $sectioncount{$section}++;
 9886:                 }
 9887: 	    }
 9888: 	}
 9889:     }
 9890:     if ($only_students) {
 9891:         return %sectioncount;
 9892:     }
 9893:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9894:     foreach my $user (sort(keys(%courseroles))) {
 9895: 	if ($user !~ /^(\w{2})/) { next; }
 9896: 	my ($role) = ($user =~ /^(\w{2})/);
 9897: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9898: 	my ($section,$status);
 9899: 	if ($role eq 'cr' &&
 9900: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9901: 	    $section=$1;
 9902: 	}
 9903: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9904: 	if (!defined($section) || $section eq '-1') { next; }
 9905:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9906:         if ($end == -1 && $start == -1) {
 9907:             next; #deleted role
 9908:         }
 9909:         if (!defined($possible_status)) { 
 9910:             $sectioncount{$section}++;
 9911:         } else {
 9912:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9913:                 $status = 'active';
 9914:             } elsif ($end < $now) {
 9915:                 $status = 'future';
 9916:             } elsif ($start > $now) {
 9917:                 $status = 'previous';
 9918:             }
 9919:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9920:                 $sectioncount{$section}++;
 9921:             }
 9922:         }
 9923:     }
 9924:     return %sectioncount;
 9925: }
 9926: 
 9927: ###############################################
 9928: 
 9929: =pod
 9930: 
 9931: =item * &get_course_users()
 9932: 
 9933: Retrieves usernames:domains for users in the specified course
 9934: with specific role(s), and access status. 
 9935: 
 9936: Incoming parameters:
 9937: 1. course domain
 9938: 2. course number
 9939: 3. access status: users must have - either active, 
 9940: previous, future, or all.
 9941: 4. reference to array of permissible roles
 9942: 5. reference to array of section restrictions (optional)
 9943: 6. reference to results object (hash of hashes).
 9944: 7. reference to optional userdata hash
 9945: 8. reference to optional statushash
 9946: 9. flag if privileged users (except those set to unhide in
 9947:    course settings) should be excluded    
 9948: Keys of top level results hash are roles.
 9949: Keys of inner hashes are username:domain, with 
 9950: values set to access type.
 9951: Optional userdata hash returns an array with arguments in the 
 9952: same order as loncoursedata::get_classlist() for student data.
 9953: 
 9954: Optional statushash returns
 9955: 
 9956: Entries for end, start, section and status are blank because
 9957: of the possibility of multiple values for non-student roles.
 9958: 
 9959: =cut
 9960: 
 9961: ###############################################
 9962: 
 9963: sub get_course_users {
 9964:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9965:     my %idx = ();
 9966:     my %seclists;
 9967: 
 9968:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9969:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9970:     $idx{end} = &Apache::loncoursedata::CL_END();
 9971:     $idx{start} = &Apache::loncoursedata::CL_START();
 9972:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9973:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9974:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9975:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9976: 
 9977:     if (grep(/^st$/,@{$roles})) {
 9978:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9979:         my $now = time;
 9980:         foreach my $student (keys(%{$classlist})) {
 9981:             my $match = 0;
 9982:             my $secmatch = 0;
 9983:             my $section = $$classlist{$student}[$idx{section}];
 9984:             my $status = $$classlist{$student}[$idx{status}];
 9985:             if ($section eq '') {
 9986:                 $section = 'none';
 9987:             }
 9988:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9989:                 if (grep(/^all$/,@{$sections})) {
 9990:                     $secmatch = 1;
 9991:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9992:                     if (grep(/^none$/,@{$sections})) {
 9993:                         $secmatch = 1;
 9994:                     }
 9995:                 } else {  
 9996: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9997: 		        $secmatch = 1;
 9998:                     }
 9999: 		}
10000:                 if (!$secmatch) {
10001:                     next;
10002:                 }
10003:             }
10004:             if (defined($$types{'active'})) {
10005:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10006:                     push(@{$$users{st}{$student}},'active');
10007:                     $match = 1;
10008:                 }
10009:             }
10010:             if (defined($$types{'previous'})) {
10011:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10012:                     push(@{$$users{st}{$student}},'previous');
10013:                     $match = 1;
10014:                 }
10015:             }
10016:             if (defined($$types{'future'})) {
10017:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10018:                     push(@{$$users{st}{$student}},'future');
10019:                     $match = 1;
10020:                 }
10021:             }
10022:             if ($match) {
10023:                 push(@{$seclists{$student}},$section);
10024:                 if (ref($userdata) eq 'HASH') {
10025:                     $$userdata{$student} = $$classlist{$student};
10026:                 }
10027:                 if (ref($statushash) eq 'HASH') {
10028:                     $statushash->{$student}{'st'}{$section} = $status;
10029:                 }
10030:             }
10031:         }
10032:     }
10033:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10034:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10035:         my $now = time;
10036:         my %displaystatus = ( previous => 'Expired',
10037:                               active   => 'Active',
10038:                               future   => 'Future',
10039:                             );
10040:         my (%nothide,@possdoms);
10041:         if ($hidepriv) {
10042:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10043:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10044:                 if ($user !~ /:/) {
10045:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10046:                 } else {
10047:                     $nothide{$user} = 1;
10048:                 }
10049:             }
10050:             my @possdoms = ($cdom);
10051:             if ($coursehash{'checkforpriv'}) {
10052:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10053:             }
10054:         }
10055:         foreach my $person (sort(keys(%coursepersonnel))) {
10056:             my $match = 0;
10057:             my $secmatch = 0;
10058:             my $status;
10059:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10060:             $user =~ s/:$//;
10061:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10062:             if ($end == -1 || $start == -1) {
10063:                 next;
10064:             }
10065:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10066:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10067:                 my ($uname,$udom) = split(/:/,$user);
10068:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10069:                     if (grep(/^all$/,@{$sections})) {
10070:                         $secmatch = 1;
10071:                     } elsif ($usec eq '') {
10072:                         if (grep(/^none$/,@{$sections})) {
10073:                             $secmatch = 1;
10074:                         }
10075:                     } else {
10076:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10077:                             $secmatch = 1;
10078:                         }
10079:                     }
10080:                     if (!$secmatch) {
10081:                         next;
10082:                     }
10083:                 }
10084:                 if ($usec eq '') {
10085:                     $usec = 'none';
10086:                 }
10087:                 if ($uname ne '' && $udom ne '') {
10088:                     if ($hidepriv) {
10089:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10090:                             (!$nothide{$uname.':'.$udom})) {
10091:                             next;
10092:                         }
10093:                     }
10094:                     if ($end > 0 && $end < $now) {
10095:                         $status = 'previous';
10096:                     } elsif ($start > $now) {
10097:                         $status = 'future';
10098:                     } else {
10099:                         $status = 'active';
10100:                     }
10101:                     foreach my $type (keys(%{$types})) { 
10102:                         if ($status eq $type) {
10103:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10104:                                 push(@{$$users{$role}{$user}},$type);
10105:                             }
10106:                             $match = 1;
10107:                         }
10108:                     }
10109:                     if (($match) && (ref($userdata) eq 'HASH')) {
10110:                         if (!exists($$userdata{$uname.':'.$udom})) {
10111: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10112:                         }
10113:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10114:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10115:                         }
10116:                         if (ref($statushash) eq 'HASH') {
10117:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10118:                         }
10119:                     }
10120:                 }
10121:             }
10122:         }
10123:         if (grep(/^ow$/,@{$roles})) {
10124:             if ((defined($cdom)) && (defined($cnum))) {
10125:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10126:                 if ( defined($csettings{'internal.courseowner'}) ) {
10127:                     my $owner = $csettings{'internal.courseowner'};
10128:                     next if ($owner eq '');
10129:                     my ($ownername,$ownerdom);
10130:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10131:                         $ownername = $1;
10132:                         $ownerdom = $2;
10133:                     } else {
10134:                         $ownername = $owner;
10135:                         $ownerdom = $cdom;
10136:                         $owner = $ownername.':'.$ownerdom;
10137:                     }
10138:                     @{$$users{'ow'}{$owner}} = 'any';
10139:                     if (defined($userdata) && 
10140: 			!exists($$userdata{$owner})) {
10141: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10142:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10143:                             push(@{$seclists{$owner}},'none');
10144:                         }
10145:                         if (ref($statushash) eq 'HASH') {
10146:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10147:                         }
10148: 		    }
10149:                 }
10150:             }
10151:         }
10152:         foreach my $user (keys(%seclists)) {
10153:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10154:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10155:         }
10156:     }
10157:     return;
10158: }
10159: 
10160: sub get_user_info {
10161:     my ($udom,$uname,$idx,$userdata) = @_;
10162:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10163: 	&plainname($uname,$udom,'lastname');
10164:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10165:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10166:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10167:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10168:     return;
10169: }
10170: 
10171: ###############################################
10172: 
10173: =pod
10174: 
10175: =item * &get_user_quota()
10176: 
10177: Retrieves quota assigned for storage of user files.
10178: Default is to report quota for portfolio files.
10179: 
10180: Incoming parameters:
10181: 1. user's username
10182: 2. user's domain
10183: 3. quota name - portfolio, author, or course
10184:    (if no quota name provided, defaults to portfolio).
10185: 4. crstype - official, unofficial, textbook, placement or community, 
10186:    if quota name is course
10187: 
10188: Returns:
10189: 1. Disk quota (in MB) assigned to student.
10190: 2. (Optional) Type of setting: custom or default
10191:    (individually assigned or default for user's 
10192:    institutional status).
10193: 3. (Optional) - User's institutional status (e.g., faculty, staff
10194:    or student - types as defined in localenroll::inst_usertypes 
10195:    for user's domain, which determines default quota for user.
10196: 4. (Optional) - Default quota which would apply to the user.
10197: 
10198: If a value has been stored in the user's environment, 
10199: it will return that, otherwise it returns the maximal default
10200: defined for the user's institutional status(es) in the domain.
10201: 
10202: =cut
10203: 
10204: ###############################################
10205: 
10206: 
10207: sub get_user_quota {
10208:     my ($uname,$udom,$quotaname,$crstype) = @_;
10209:     my ($quota,$quotatype,$settingstatus,$defquota);
10210:     if (!defined($udom)) {
10211:         $udom = $env{'user.domain'};
10212:     }
10213:     if (!defined($uname)) {
10214:         $uname = $env{'user.name'};
10215:     }
10216:     if (($udom eq '' || $uname eq '') ||
10217:         ($udom eq 'public') && ($uname eq 'public')) {
10218:         $quota = 0;
10219:         $quotatype = 'default';
10220:         $defquota = 0; 
10221:     } else {
10222:         my $inststatus;
10223:         if ($quotaname eq 'course') {
10224:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10225:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10226:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10227:             } else {
10228:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10229:                 $quota = $cenv{'internal.uploadquota'};
10230:             }
10231:         } else {
10232:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10233:                 if ($quotaname eq 'author') {
10234:                     $quota = $env{'environment.authorquota'};
10235:                 } else {
10236:                     $quota = $env{'environment.portfolioquota'};
10237:                 }
10238:                 $inststatus = $env{'environment.inststatus'};
10239:             } else {
10240:                 my %userenv = 
10241:                     &Apache::lonnet::get('environment',['portfolioquota',
10242:                                          'authorquota','inststatus'],$udom,$uname);
10243:                 my ($tmp) = keys(%userenv);
10244:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10245:                     if ($quotaname eq 'author') {
10246:                         $quota = $userenv{'authorquota'};
10247:                     } else {
10248:                         $quota = $userenv{'portfolioquota'};
10249:                     }
10250:                     $inststatus = $userenv{'inststatus'};
10251:                 } else {
10252:                     undef(%userenv);
10253:                 }
10254:             }
10255:         }
10256:         if ($quota eq '' || wantarray) {
10257:             if ($quotaname eq 'course') {
10258:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10259:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10260:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10261:                     ($crstype eq 'placement')) { 
10262:                     $defquota = $domdefs{$crstype.'quota'};
10263:                 }
10264:                 if ($defquota eq '') {
10265:                     $defquota = 500;
10266:                 }
10267:             } else {
10268:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10269:             }
10270:             if ($quota eq '') {
10271:                 $quota = $defquota;
10272:                 $quotatype = 'default';
10273:             } else {
10274:                 $quotatype = 'custom';
10275:             }
10276:         }
10277:     }
10278:     if (wantarray) {
10279:         return ($quota,$quotatype,$settingstatus,$defquota);
10280:     } else {
10281:         return $quota;
10282:     }
10283: }
10284: 
10285: ###############################################
10286: 
10287: =pod
10288: 
10289: =item * &default_quota()
10290: 
10291: Retrieves default quota assigned for storage of user portfolio files,
10292: given an (optional) user's institutional status.
10293: 
10294: Incoming parameters:
10295: 
10296: 1. domain
10297: 2. (Optional) institutional status(es).  This is a : separated list of 
10298:    status types (e.g., faculty, staff, student etc.)
10299:    which apply to the user for whom the default is being retrieved.
10300:    If the institutional status string in undefined, the domain
10301:    default quota will be returned.
10302: 3.  quota name - portfolio, author, or course
10303:    (if no quota name provided, defaults to portfolio).
10304: 
10305: Returns:
10306: 
10307: 1. Default disk quota (in MB) for user portfolios in the domain.
10308: 2. (Optional) institutional type which determined the value of the
10309:    default quota.
10310: 
10311: If a value has been stored in the domain's configuration db,
10312: it will return that, otherwise it returns 20 (for backwards 
10313: compatibility with domains which have not set up a configuration
10314: db file; the original statically defined portfolio quota was 20 MB). 
10315: 
10316: If the user's status includes multiple types (e.g., staff and student),
10317: the largest default quota which applies to the user determines the
10318: default quota returned.
10319: 
10320: =cut
10321: 
10322: ###############################################
10323: 
10324: 
10325: sub default_quota {
10326:     my ($udom,$inststatus,$quotaname) = @_;
10327:     my ($defquota,$settingstatus);
10328:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10329:                                             ['quotas'],$udom);
10330:     my $key = 'defaultquota';
10331:     if ($quotaname eq 'author') {
10332:         $key = 'authorquota';
10333:     }
10334:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10335:         if ($inststatus ne '') {
10336:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10337:             foreach my $item (@statuses) {
10338:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10339:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10340:                         if ($defquota eq '') {
10341:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10342:                             $settingstatus = $item;
10343:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10344:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10345:                             $settingstatus = $item;
10346:                         }
10347:                     }
10348:                 } elsif ($key eq 'defaultquota') {
10349:                     if ($quotahash{'quotas'}{$item} ne '') {
10350:                         if ($defquota eq '') {
10351:                             $defquota = $quotahash{'quotas'}{$item};
10352:                             $settingstatus = $item;
10353:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10354:                             $defquota = $quotahash{'quotas'}{$item};
10355:                             $settingstatus = $item;
10356:                         }
10357:                     }
10358:                 }
10359:             }
10360:         }
10361:         if ($defquota eq '') {
10362:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10363:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10364:             } elsif ($key eq 'defaultquota') {
10365:                 $defquota = $quotahash{'quotas'}{'default'};
10366:             }
10367:             $settingstatus = 'default';
10368:             if ($defquota eq '') {
10369:                 if ($quotaname eq 'author') {
10370:                     $defquota = 500;
10371:                 }
10372:             }
10373:         }
10374:     } else {
10375:         $settingstatus = 'default';
10376:         if ($quotaname eq 'author') {
10377:             $defquota = 500;
10378:         } else {
10379:             $defquota = 20;
10380:         }
10381:     }
10382:     if (wantarray) {
10383:         return ($defquota,$settingstatus);
10384:     } else {
10385:         return $defquota;
10386:     }
10387: }
10388: 
10389: ###############################################
10390: 
10391: =pod
10392: 
10393: =item * &excess_filesize_warning()
10394: 
10395: Returns warning message if upload of file to authoring space, or copying
10396: of existing file within authoring space will cause quota for the authoring
10397: space to be exceeded.
10398: 
10399: Same, if upload of a file directly to a course/community via Course Editor
10400: will cause quota for uploaded content for the course to be exceeded.
10401: 
10402: Inputs: 7 
10403: 1. username or coursenum
10404: 2. domain
10405: 3. context ('author' or 'course')
10406: 4. filename of file for which action is being requested
10407: 5. filesize (kB) of file
10408: 6. action being taken: copy or upload.
10409: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10410: 
10411: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10412:          otherwise return null.
10413: 
10414: =back
10415: 
10416: =cut
10417: 
10418: sub excess_filesize_warning {
10419:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10420:     my $current_disk_usage = 0;
10421:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10422:     if ($context eq 'author') {
10423:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10424:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10425:     } else {
10426:         foreach my $subdir ('docs','supplemental') {
10427:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10428:         }
10429:     }
10430:     $disk_quota = int($disk_quota * 1000);
10431:     if (($current_disk_usage + $filesize) > $disk_quota) {
10432:         return '<p class="LC_warning">'.
10433:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10434:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10435:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10436:                             $disk_quota,$current_disk_usage).
10437:                '</p>';
10438:     }
10439:     return;
10440: }
10441: 
10442: ###############################################
10443: 
10444: 
10445: 
10446: 
10447: sub get_secgrprole_info {
10448:     my ($cdom,$cnum,$needroles,$type)  = @_;
10449:     my %sections_count = &get_sections($cdom,$cnum);
10450:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10451:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10452:     my @groups = sort(keys(%curr_groups));
10453:     my $allroles = [];
10454:     my $rolehash;
10455:     my $accesshash = {
10456:                      active => 'Currently has access',
10457:                      future => 'Will have future access',
10458:                      previous => 'Previously had access',
10459:                   };
10460:     if ($needroles) {
10461:         $rolehash = {'all' => 'all'};
10462:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10463: 	if (&Apache::lonnet::error(%user_roles)) {
10464: 	    undef(%user_roles);
10465: 	}
10466:         foreach my $item (keys(%user_roles)) {
10467:             my ($role)=split(/\:/,$item,2);
10468:             if ($role eq 'cr') { next; }
10469:             if ($role =~ /^cr/) {
10470:                 $$rolehash{$role} = (split('/',$role))[3];
10471:             } else {
10472:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10473:             }
10474:         }
10475:         foreach my $key (sort(keys(%{$rolehash}))) {
10476:             push(@{$allroles},$key);
10477:         }
10478:         push (@{$allroles},'st');
10479:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10480:     }
10481:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10482: }
10483: 
10484: sub user_picker {
10485:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10486:     my $currdom = $dom;
10487:     my @alldoms = &Apache::lonnet::all_domains();
10488:     if (@alldoms == 1) {
10489:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10490:                                                ['directorysrch'],$alldoms[0]);
10491:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10492:         my $showdom = $domdesc;
10493:         if ($showdom eq '') {
10494:             $showdom = $dom;
10495:         }
10496:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10497:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10498:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10499:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10500:             }
10501:         }
10502:     }
10503:     my %curr_selected = (
10504:                         srchin => 'dom',
10505:                         srchby => 'lastname',
10506:                       );
10507:     my $srchterm;
10508:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10509:         if ($srch->{'srchby'} ne '') {
10510:             $curr_selected{'srchby'} = $srch->{'srchby'};
10511:         }
10512:         if ($srch->{'srchin'} ne '') {
10513:             $curr_selected{'srchin'} = $srch->{'srchin'};
10514:         }
10515:         if ($srch->{'srchtype'} ne '') {
10516:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10517:         }
10518:         if ($srch->{'srchdomain'} ne '') {
10519:             $currdom = $srch->{'srchdomain'};
10520:         }
10521:         $srchterm = $srch->{'srchterm'};
10522:     }
10523:     my %html_lt=&Apache::lonlocal::texthash(
10524:                     'usr'       => 'Search criteria',
10525:                     'doma'      => 'Domain/institution to search',
10526:                     'uname'     => 'username',
10527:                     'lastname'  => 'last name',
10528:                     'lastfirst' => 'last name, first name',
10529:                     'crs'       => 'in this course',
10530:                     'dom'       => 'in selected LON-CAPA domain', 
10531:                     'alc'       => 'all LON-CAPA',
10532:                     'instd'     => 'in institutional directory for selected domain',
10533:                     'exact'     => 'is',
10534:                     'contains'  => 'contains',
10535:                     'begins'    => 'begins with',
10536:                                        );
10537:     my %js_lt=&Apache::lonlocal::texthash(
10538:                     'youm'      => "You must include some text to search for.",
10539:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10540:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10541:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10542:                     'ymcd'      => "You must choose a domain when using a domain search.",
10543:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10544:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10545:                      'thfo'     => "The following need to be corrected before the search can be run:",
10546:                                        );
10547:     &html_escape(\%html_lt);
10548:     &js_escape(\%js_lt);
10549:     my $domform;
10550:     my $allow_blank = 1;
10551:     if ($fixeddom) {
10552:         $allow_blank = 0;
10553:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10554:     } else {
10555:         my $defdom = $env{'request.role.domain'};
10556:         my ($trusted,$untrusted);
10557:         if (($context eq 'requestcrs') || ($context eq 'course')) {
10558:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10559:         } elsif ($context eq 'author') {
10560:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10561:         } elsif ($context eq 'domain') {
10562:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10563:         }
10564:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10565:     }
10566:     my $srchinsel = ' <select name="srchin">';
10567: 
10568:     my @srchins = ('crs','dom','alc','instd');
10569: 
10570:     foreach my $option (@srchins) {
10571:         # FIXME 'alc' option unavailable until 
10572:         #       loncreateuser::print_user_query_page()
10573:         #       has been completed.
10574:         next if ($option eq 'alc');
10575:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10576:         next if ($option eq 'crs' && !$env{'request.course.id'});
10577:         next if (($option eq 'instd') && ($noinstd));
10578:         if ($curr_selected{'srchin'} eq $option) {
10579:             $srchinsel .= ' 
10580:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10581:         } else {
10582:             $srchinsel .= '
10583:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10584:         }
10585:     }
10586:     $srchinsel .= "\n  </select>\n";
10587: 
10588:     my $srchbysel =  ' <select name="srchby">';
10589:     foreach my $option ('lastname','lastfirst','uname') {
10590:         if ($curr_selected{'srchby'} eq $option) {
10591:             $srchbysel .= '
10592:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10593:         } else {
10594:             $srchbysel .= '
10595:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10596:          }
10597:     }
10598:     $srchbysel .= "\n  </select>\n";
10599: 
10600:     my $srchtypesel = ' <select name="srchtype">';
10601:     foreach my $option ('begins','contains','exact') {
10602:         if ($curr_selected{'srchtype'} eq $option) {
10603:             $srchtypesel .= '
10604:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10605:         } else {
10606:             $srchtypesel .= '
10607:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10608:         }
10609:     }
10610:     $srchtypesel .= "\n  </select>\n";
10611: 
10612:     my ($newuserscript,$new_user_create);
10613:     my $context_dom = $env{'request.role.domain'};
10614:     if ($context eq 'requestcrs') {
10615:         if ($env{'form.coursedom'} ne '') { 
10616:             $context_dom = $env{'form.coursedom'};
10617:         }
10618:     }
10619:     if ($forcenewuser) {
10620:         if (ref($srch) eq 'HASH') {
10621:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10622:                 if ($cancreate) {
10623:                     $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>';
10624:                 } else {
10625:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10626:                     my %usertypetext = (
10627:                         official   => 'institutional',
10628:                         unofficial => 'non-institutional',
10629:                     );
10630:                     $new_user_create = '<p class="LC_warning">'
10631:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10632:                                       .' '
10633:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10634:                                           ,'<a href="'.$helplink.'">','</a>')
10635:                                       .'</p><br />';
10636:                 }
10637:             }
10638:         }
10639: 
10640:         $newuserscript = <<"ENDSCRIPT";
10641: 
10642: function setSearch(createnew,callingForm) {
10643:     if (createnew == 1) {
10644:         for (var i=0; i<callingForm.srchby.length; i++) {
10645:             if (callingForm.srchby.options[i].value == 'uname') {
10646:                 callingForm.srchby.selectedIndex = i;
10647:             }
10648:         }
10649:         for (var i=0; i<callingForm.srchin.length; i++) {
10650:             if ( callingForm.srchin.options[i].value == 'dom') {
10651: 		callingForm.srchin.selectedIndex = i;
10652:             }
10653:         }
10654:         for (var i=0; i<callingForm.srchtype.length; i++) {
10655:             if (callingForm.srchtype.options[i].value == 'exact') {
10656:                 callingForm.srchtype.selectedIndex = i;
10657:             }
10658:         }
10659:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10660:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10661:                 callingForm.srchdomain.selectedIndex = i;
10662:             }
10663:         }
10664:     }
10665: }
10666: ENDSCRIPT
10667: 
10668:     }
10669: 
10670:     my $output = <<"END_BLOCK";
10671: <script type="text/javascript">
10672: // <![CDATA[
10673: function validateEntry(callingForm) {
10674: 
10675:     var checkok = 1;
10676:     var srchin;
10677:     for (var i=0; i<callingForm.srchin.length; i++) {
10678: 	if ( callingForm.srchin[i].checked ) {
10679: 	    srchin = callingForm.srchin[i].value;
10680: 	}
10681:     }
10682: 
10683:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10684:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10685:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10686:     var srchterm =  callingForm.srchterm.value;
10687:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10688:     var msg = "";
10689: 
10690:     if (srchterm == "") {
10691:         checkok = 0;
10692:         msg += "$js_lt{'youm'}\\n";
10693:     }
10694: 
10695:     if (srchtype== 'begins') {
10696:         if (srchterm.length < 2) {
10697:             checkok = 0;
10698:             msg += "$js_lt{'thte'}\\n";
10699:         }
10700:     }
10701: 
10702:     if (srchtype== 'contains') {
10703:         if (srchterm.length < 3) {
10704:             checkok = 0;
10705:             msg += "$js_lt{'thet'}\\n";
10706:         }
10707:     }
10708:     if (srchin == 'instd') {
10709:         if (srchdomain == '') {
10710:             checkok = 0;
10711:             msg += "$js_lt{'yomc'}\\n";
10712:         }
10713:     }
10714:     if (srchin == 'dom') {
10715:         if (srchdomain == '') {
10716:             checkok = 0;
10717:             msg += "$js_lt{'ymcd'}\\n";
10718:         }
10719:     }
10720:     if (srchby == 'lastfirst') {
10721:         if (srchterm.indexOf(",") == -1) {
10722:             checkok = 0;
10723:             msg += "$js_lt{'whus'}\\n";
10724:         }
10725:         if (srchterm.indexOf(",") == srchterm.length -1) {
10726:             checkok = 0;
10727:             msg += "$js_lt{'whse'}\\n";
10728:         }
10729:     }
10730:     if (checkok == 0) {
10731:         alert("$js_lt{'thfo'}\\n"+msg);
10732:         return;
10733:     }
10734:     if (checkok == 1) {
10735:         callingForm.submit();
10736:     }
10737: }
10738: 
10739: $newuserscript
10740: 
10741: // ]]>
10742: </script>
10743: 
10744: $new_user_create
10745: 
10746: END_BLOCK
10747: 
10748:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10749:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10750:                $domform.
10751:                &Apache::lonhtmlcommon::row_closure().
10752:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10753:                $srchbysel.
10754:                $srchtypesel. 
10755:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10756:                $srchinsel.
10757:                &Apache::lonhtmlcommon::row_closure(1). 
10758:                &Apache::lonhtmlcommon::end_pick_box().
10759:                '<br />';
10760:     return ($output,1);
10761: }
10762: 
10763: sub user_rule_check {
10764:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10765:     my ($response,%inst_response);
10766:     if (ref($usershash) eq 'HASH') {
10767:         if (keys(%{$usershash}) > 1) {
10768:             my (%by_username,%by_id,%userdoms);
10769:             my $checkid; 
10770:             if (ref($checks) eq 'HASH') {
10771:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10772:                     $checkid = 1;
10773:                 }
10774:             }
10775:             foreach my $user (keys(%{$usershash})) {
10776:                 my ($uname,$udom) = split(/:/,$user);
10777:                 if ($checkid) {
10778:                     if (ref($usershash->{$user}) eq 'HASH') {
10779:                         if ($usershash->{$user}->{'id'} ne '') {
10780:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10781:                             $userdoms{$udom} = 1;
10782:                             if (ref($inst_results) eq 'HASH') {
10783:                                 $inst_results->{$uname.':'.$udom} = {};
10784:                             }
10785:                         }
10786:                     }
10787:                 } else {
10788:                     $by_username{$udom}{$uname} = 1;
10789:                     $userdoms{$udom} = 1;
10790:                     if (ref($inst_results) eq 'HASH') {
10791:                         $inst_results->{$uname.':'.$udom} = {};
10792:                     }
10793:                 }
10794:             }
10795:             foreach my $udom (keys(%userdoms)) {
10796:                 if (!$got_rules->{$udom}) {
10797:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10798:                                                              ['usercreation'],$udom);
10799:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10800:                         foreach my $item ('username','id') {
10801:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10802:                                 $$curr_rules{$udom}{$item} =
10803:                                     $domconfig{'usercreation'}{$item.'_rule'};
10804:                             }
10805:                         }
10806:                     }
10807:                     $got_rules->{$udom} = 1;
10808:                 }
10809:             }
10810:             if ($checkid) {
10811:                 foreach my $udom (keys(%by_id)) {
10812:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10813:                     if ($outcome eq 'ok') {
10814:                         foreach my $id (keys(%{$by_id{$udom}})) {
10815:                             my $uname = $by_id{$udom}{$id};
10816:                             $inst_response{$uname.':'.$udom} = $outcome;
10817:                         }
10818:                         if (ref($results) eq 'HASH') {
10819:                             foreach my $uname (keys(%{$results})) {
10820:                                 if (exists($inst_response{$uname.':'.$udom})) {
10821:                                     $inst_response{$uname.':'.$udom} = $outcome;
10822:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10823:                                 }
10824:                             }
10825:                         }
10826:                     }
10827:                 }
10828:             } else {
10829:                 foreach my $udom (keys(%by_username)) {
10830:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10831:                     if ($outcome eq 'ok') {
10832:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10833:                             $inst_response{$uname.':'.$udom} = $outcome;
10834:                         }
10835:                         if (ref($results) eq 'HASH') {
10836:                             foreach my $uname (keys(%{$results})) {
10837:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10838:                             }
10839:                         }
10840:                     }
10841:                 }
10842:             }
10843:         } elsif (keys(%{$usershash}) == 1) {
10844:             my $user = (keys(%{$usershash}))[0];
10845:             my ($uname,$udom) = split(/:/,$user);
10846:             if (($udom ne '') && ($uname ne '')) {
10847:                 if (ref($usershash->{$user}) eq 'HASH') {
10848:                     if (ref($checks) eq 'HASH') {
10849:                         if (defined($checks->{'username'})) {
10850:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10851:                                 &Apache::lonnet::get_instuser($udom,$uname);
10852:                         } elsif (defined($checks->{'id'})) {
10853:                             if ($usershash->{$user}->{'id'} ne '') {
10854:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10855:                                     &Apache::lonnet::get_instuser($udom,undef,
10856:                                                                   $usershash->{$user}->{'id'});
10857:                             } else {
10858:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10859:                                     &Apache::lonnet::get_instuser($udom,$uname);
10860:                             }
10861:                         }
10862:                     } else {
10863:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10864:                             &Apache::lonnet::get_instuser($udom,$uname);
10865:                        return;
10866:                     }
10867:                     if (!$got_rules->{$udom}) {
10868:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10869:                                                                  ['usercreation'],$udom);
10870:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10871:                             foreach my $item ('username','id') {
10872:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10873:                                    $$curr_rules{$udom}{$item} = 
10874:                                        $domconfig{'usercreation'}{$item.'_rule'};
10875:                                 }
10876:                             }
10877:                         }
10878:                         $got_rules->{$udom} = 1;
10879:                     }
10880:                 }
10881:             } else {
10882:                 return;
10883:             }
10884:         } else {
10885:             return;
10886:         }
10887:         foreach my $user (keys(%{$usershash})) {
10888:             my ($uname,$udom) = split(/:/,$user);
10889:             next if (($udom eq '') || ($uname eq ''));
10890:             my $id;
10891:             if (ref($inst_results) eq 'HASH') {
10892:                 if (ref($inst_results->{$user}) eq 'HASH') {
10893:                     $id = $inst_results->{$user}->{'id'};
10894:                 }
10895:             }
10896:             if ($id eq '') { 
10897:                 if (ref($usershash->{$user})) {
10898:                     $id = $usershash->{$user}->{'id'};
10899:                 }
10900:             }
10901:             foreach my $item (keys(%{$checks})) {
10902:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10903:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10904:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10905:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10906:                                                                              $$curr_rules{$udom}{$item});
10907:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10908:                                 if ($rule_check{$rule}) {
10909:                                     $$rulematch{$user}{$item} = $rule;
10910:                                     if ($inst_response{$user} eq 'ok') {
10911:                                         if (ref($inst_results) eq 'HASH') {
10912:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10913:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10914:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10915:                                                 } elsif ($item eq 'id') {
10916:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10917:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10918:                                                     }
10919:                                                 }
10920:                                             }
10921:                                         }
10922:                                     }
10923:                                     last;
10924:                                 }
10925:                             }
10926:                         }
10927:                     }
10928:                 }
10929:             }
10930:         }
10931:     }
10932:     return;
10933: }
10934: 
10935: sub user_rule_formats {
10936:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10937:     my %text = ( 
10938:                  'username' => 'Usernames',
10939:                  'id'       => 'IDs',
10940:                );
10941:     my $output;
10942:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10943:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10944:         if (@{$ruleorder} > 0) {
10945:             $output = '<br />'.
10946:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10947:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10948:                       ' <ul>';
10949:             foreach my $rule (@{$ruleorder}) {
10950:                 if (ref($curr_rules) eq 'ARRAY') {
10951:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10952:                         if (ref($rules->{$rule}) eq 'HASH') {
10953:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10954:                                         $rules->{$rule}{'desc'}.'</li>';
10955:                         }
10956:                     }
10957:                 }
10958:             }
10959:             $output .= '</ul>';
10960:         }
10961:     }
10962:     return $output;
10963: }
10964: 
10965: sub instrule_disallow_msg {
10966:     my ($checkitem,$domdesc,$count,$mode) = @_;
10967:     my $response;
10968:     my %text = (
10969:                   item   => 'username',
10970:                   items  => 'usernames',
10971:                   match  => 'matches',
10972:                   do     => 'does',
10973:                   action => 'a username',
10974:                   one    => 'one',
10975:                );
10976:     if ($count > 1) {
10977:         $text{'item'} = 'usernames';
10978:         $text{'match'} ='match';
10979:         $text{'do'} = 'do';
10980:         $text{'action'} = 'usernames',
10981:         $text{'one'} = 'ones';
10982:     }
10983:     if ($checkitem eq 'id') {
10984:         $text{'items'} = 'IDs';
10985:         $text{'item'} = 'ID';
10986:         $text{'action'} = 'an ID';
10987:         if ($count > 1) {
10988:             $text{'item'} = 'IDs';
10989:             $text{'action'} = 'IDs';
10990:         }
10991:     }
10992:     $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 />';
10993:     if ($mode eq 'upload') {
10994:         if ($checkitem eq 'username') {
10995:             $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'}.");
10996:         } elsif ($checkitem eq 'id') {
10997:             $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.");
10998:         }
10999:     } elsif ($mode eq 'selfcreate') {
11000:         if ($checkitem eq 'id') {
11001:             $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.");
11002:         }
11003:     } else {
11004:         if ($checkitem eq 'username') {
11005:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11006:         } elsif ($checkitem eq 'id') {
11007:             $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.");
11008:         }
11009:     }
11010:     return $response;
11011: }
11012: 
11013: sub personal_data_fieldtitles {
11014:     my %fieldtitles = &Apache::lonlocal::texthash (
11015:                         id => 'Student/Employee ID',
11016:                         permanentemail => 'E-mail address',
11017:                         lastname => 'Last Name',
11018:                         firstname => 'First Name',
11019:                         middlename => 'Middle Name',
11020:                         generation => 'Generation',
11021:                         gen => 'Generation',
11022:                         inststatus => 'Affiliation',
11023:                    );
11024:     return %fieldtitles;
11025: }
11026: 
11027: sub sorted_inst_types {
11028:     my ($dom) = @_;
11029:     my ($usertypes,$order);
11030:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11031:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11032:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11033:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11034:     } else {
11035:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11036:     }
11037:     my $othertitle = &mt('All users');
11038:     if ($env{'request.course.id'}) {
11039:         $othertitle  = &mt('Any users');
11040:     }
11041:     my @types;
11042:     if (ref($order) eq 'ARRAY') {
11043:         @types = @{$order};
11044:     }
11045:     if (@types == 0) {
11046:         if (ref($usertypes) eq 'HASH') {
11047:             @types = sort(keys(%{$usertypes}));
11048:         }
11049:     }
11050:     if (keys(%{$usertypes}) > 0) {
11051:         $othertitle = &mt('Other users');
11052:     }
11053:     return ($othertitle,$usertypes,\@types);
11054: }
11055: 
11056: sub get_institutional_codes {
11057:     my ($settings,$allcourses,$LC_code) = @_;
11058: # Get complete list of course sections to update
11059:     my @currsections = ();
11060:     my @currxlists = ();
11061:     my $coursecode = $$settings{'internal.coursecode'};
11062: 
11063:     if ($$settings{'internal.sectionnums'} ne '') {
11064:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11065:     }
11066: 
11067:     if ($$settings{'internal.crosslistings'} ne '') {
11068:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11069:     }
11070: 
11071:     if (@currxlists > 0) {
11072:         foreach (@currxlists) {
11073:             if (m/^([^:]+):(\w*)$/) {
11074:                 unless (grep/^$1$/,@{$allcourses}) {
11075:                     push(@{$allcourses},$1);
11076:                     $$LC_code{$1} = $2;
11077:                 }
11078:             }
11079:         }
11080:     }
11081:  
11082:     if (@currsections > 0) {
11083:         foreach (@currsections) {
11084:             if (m/^(\w+):(\w*)$/) {
11085:                 my $sec = $coursecode.$1;
11086:                 my $lc_sec = $2;
11087:                 unless (grep/^$sec$/,@{$allcourses}) {
11088:                     push(@{$allcourses},$sec);
11089:                     $$LC_code{$sec} = $lc_sec;
11090:                 }
11091:             }
11092:         }
11093:     }
11094:     return;
11095: }
11096: 
11097: sub get_standard_codeitems {
11098:     return ('Year','Semester','Department','Number','Section');
11099: }
11100: 
11101: =pod
11102: 
11103: =head1 Slot Helpers
11104: 
11105: =over 4
11106: 
11107: =item * sorted_slots()
11108: 
11109: Sorts an array of slot names in order of an optional sort key,
11110: default sort is by slot start time (earliest first). 
11111: 
11112: Inputs:
11113: 
11114: =over 4
11115: 
11116: slotsarr  - Reference to array of unsorted slot names.
11117: 
11118: slots     - Reference to hash of hash, where outer hash keys are slot names.
11119: 
11120: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11121: 
11122: =back
11123: 
11124: Returns:
11125: 
11126: =over 4
11127: 
11128: sorted   - An array of slot names sorted by a specified sort key 
11129:            (default sort key is start time of the slot).
11130: 
11131: =back
11132: 
11133: =cut
11134: 
11135: 
11136: sub sorted_slots {
11137:     my ($slotsarr,$slots,$sortkey) = @_;
11138:     if ($sortkey eq '') {
11139:         $sortkey = 'starttime';
11140:     }
11141:     my @sorted;
11142:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11143:         @sorted =
11144:             sort {
11145:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11146:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11147:                      }
11148:                      if (ref($slots->{$a})) { return -1;}
11149:                      if (ref($slots->{$b})) { return 1;}
11150:                      return 0;
11151:                  } @{$slotsarr};
11152:     }
11153:     return @sorted;
11154: }
11155: 
11156: =pod
11157: 
11158: =item * get_future_slots()
11159: 
11160: Inputs:
11161: 
11162: =over 4
11163: 
11164: cnum - course number
11165: 
11166: cdom - course domain
11167: 
11168: now - current UNIX time
11169: 
11170: symb - optional symb
11171: 
11172: =back
11173: 
11174: Returns:
11175: 
11176: =over 4
11177: 
11178: sorted_reservable - ref to array of student_schedulable slots currently 
11179:                     reservable, ordered by end date of reservation period.
11180: 
11181: reservable_now - ref to hash of student_schedulable slots currently
11182:                  reservable.
11183: 
11184:     Keys in inner hash are:
11185:     (a) symb: either blank or symb to which slot use is restricted.
11186:     (b) endreserve: end date of reservation period.
11187:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11188:         selected.
11189: 
11190: sorted_future - ref to array of student_schedulable slots reservable in
11191:                 the future, ordered by start date of reservation period.
11192: 
11193: future_reservable - ref to hash of student_schedulable slots reservable
11194:                     in the future.
11195: 
11196:     Keys in inner hash are:
11197:     (a) symb: either blank or symb to which slot use is restricted.
11198:     (b) startreserve: start date of reservation period.
11199:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11200:         selected.
11201: 
11202: =back
11203: 
11204: =cut
11205: 
11206: sub get_future_slots {
11207:     my ($cnum,$cdom,$now,$symb) = @_;
11208:     my $map;
11209:     if ($symb) {
11210:         ($map) = &Apache::lonnet::decode_symb($symb);
11211:     }
11212:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11213:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11214:     foreach my $slot (keys(%slots)) {
11215:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11216:         if ($symb) {
11217:             if ($slots{$slot}->{'symb'} ne '') {
11218:                 my $canuse;
11219:                 my %oksymbs;
11220:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11221:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11222:                 if ($oksymbs{$symb}) {
11223:                     $canuse = 1;
11224:                 } else {
11225:                     foreach my $item (@slotsymbs) {
11226:                         if ($item =~ /\.(page|sequence)$/) {
11227:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11228:                             if (($map ne '') && ($map eq $sloturl)) {
11229:                                 $canuse = 1;
11230:                                 last;
11231:                             }
11232:                         }
11233:                     }
11234:                 }
11235:                 next unless ($canuse);
11236:             }
11237:         }
11238:         if (($slots{$slot}->{'starttime'} > $now) &&
11239:             ($slots{$slot}->{'endtime'} > $now)) {
11240:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11241:                 my $userallowed = 0;
11242:                 if ($slots{$slot}->{'allowedsections'}) {
11243:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11244:                     if (!defined($env{'request.role.sec'})
11245:                         && grep(/^No section assigned$/,@allowed_sec)) {
11246:                         $userallowed=1;
11247:                     } else {
11248:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11249:                             $userallowed=1;
11250:                         }
11251:                     }
11252:                     unless ($userallowed) {
11253:                         if (defined($env{'request.course.groups'})) {
11254:                             my @groups = split(/:/,$env{'request.course.groups'});
11255:                             foreach my $group (@groups) {
11256:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11257:                                     $userallowed=1;
11258:                                     last;
11259:                                 }
11260:                             }
11261:                         }
11262:                     }
11263:                 }
11264:                 if ($slots{$slot}->{'allowedusers'}) {
11265:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11266:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11267:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11268:                         $userallowed = 1;
11269:                     }
11270:                 }
11271:                 next unless($userallowed);
11272:             }
11273:             my $startreserve = $slots{$slot}->{'startreserve'};
11274:             my $endreserve = $slots{$slot}->{'endreserve'};
11275:             my $symb = $slots{$slot}->{'symb'};
11276:             my $uniqueperiod;
11277:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11278:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11279:             }
11280:             if (($startreserve < $now) &&
11281:                 (!$endreserve || $endreserve > $now)) {
11282:                 my $lastres = $endreserve;
11283:                 if (!$lastres) {
11284:                     $lastres = $slots{$slot}->{'starttime'};
11285:                 }
11286:                 $reservable_now{$slot} = {
11287:                                            symb       => $symb,
11288:                                            endreserve => $lastres,
11289:                                            uniqueperiod => $uniqueperiod,
11290:                                          };
11291:             } elsif (($startreserve > $now) &&
11292:                      (!$endreserve || $endreserve > $startreserve)) {
11293:                 $future_reservable{$slot} = {
11294:                                               symb         => $symb,
11295:                                               startreserve => $startreserve,
11296:                                               uniqueperiod => $uniqueperiod,
11297:                                             };
11298:             }
11299:         }
11300:     }
11301:     my @unsorted_reservable = keys(%reservable_now);
11302:     if (@unsorted_reservable > 0) {
11303:         @sorted_reservable = 
11304:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11305:     }
11306:     my @unsorted_future = keys(%future_reservable);
11307:     if (@unsorted_future > 0) {
11308:         @sorted_future =
11309:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11310:     }
11311:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11312: }
11313: 
11314: =pod
11315: 
11316: =back
11317: 
11318: =head1 HTTP Helpers
11319: 
11320: =over 4
11321: 
11322: =item * &get_unprocessed_cgi($query,$possible_names)
11323: 
11324: Modify the %env hash to contain unprocessed CGI form parameters held in
11325: $query.  The parameters listed in $possible_names (an array reference),
11326: will be set in $env{'form.name'} if they do not already exist.
11327: 
11328: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11329: $possible_names is an ref to an array of form element names.  As an example:
11330: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11331: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11332: 
11333: =cut
11334: 
11335: sub get_unprocessed_cgi {
11336:   my ($query,$possible_names)= @_;
11337:   # $Apache::lonxml::debug=1;
11338:   foreach my $pair (split(/&/,$query)) {
11339:     my ($name, $value) = split(/=/,$pair);
11340:     $name = &unescape($name);
11341:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11342:       $value =~ tr/+/ /;
11343:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11344:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11345:     }
11346:   }
11347: }
11348: 
11349: =pod
11350: 
11351: =item * &cacheheader() 
11352: 
11353: returns cache-controlling header code
11354: 
11355: =cut
11356: 
11357: sub cacheheader {
11358:     unless ($env{'request.method'} eq 'GET') { return ''; }
11359:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11360:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11361:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11362:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11363:     return $output;
11364: }
11365: 
11366: =pod
11367: 
11368: =item * &no_cache($r) 
11369: 
11370: specifies header code to not have cache
11371: 
11372: =cut
11373: 
11374: sub no_cache {
11375:     my ($r) = @_;
11376:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11377: 	$env{'request.method'} ne 'GET') { return ''; }
11378:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11379:     $r->no_cache(1);
11380:     $r->header_out("Expires" => $date);
11381:     $r->header_out("Pragma" => "no-cache");
11382: }
11383: 
11384: sub content_type {
11385:     my ($r,$type,$charset) = @_;
11386:     if ($r) {
11387: 	#  Note that printout.pl calls this with undef for $r.
11388: 	&no_cache($r);
11389:     }
11390:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11391:     unless ($charset) {
11392: 	$charset=&Apache::lonlocal::current_encoding;
11393:     }
11394:     if ($charset) { $type.='; charset='.$charset; }
11395:     if ($r) {
11396: 	$r->content_type($type);
11397:     } else {
11398: 	print("Content-type: $type\n\n");
11399:     }
11400: }
11401: 
11402: =pod
11403: 
11404: =item * &add_to_env($name,$value) 
11405: 
11406: adds $name to the %env hash with value
11407: $value, if $name already exists, the entry is converted to an array
11408: reference and $value is added to the array.
11409: 
11410: =cut
11411: 
11412: sub add_to_env {
11413:   my ($name,$value)=@_;
11414:   if (defined($env{$name})) {
11415:     if (ref($env{$name})) {
11416:       #already have multiple values
11417:       push(@{ $env{$name} },$value);
11418:     } else {
11419:       #first time seeing multiple values, convert hash entry to an arrayref
11420:       my $first=$env{$name};
11421:       undef($env{$name});
11422:       push(@{ $env{$name} },$first,$value);
11423:     }
11424:   } else {
11425:     $env{$name}=$value;
11426:   }
11427: }
11428: 
11429: =pod
11430: 
11431: =item * &get_env_multiple($name) 
11432: 
11433: gets $name from the %env hash, it seemlessly handles the cases where multiple
11434: values may be defined and end up as an array ref.
11435: 
11436: returns an array of values
11437: 
11438: =cut
11439: 
11440: sub get_env_multiple {
11441:     my ($name) = @_;
11442:     my @values;
11443:     if (defined($env{$name})) {
11444:         # exists is it an array
11445:         if (ref($env{$name})) {
11446:             @values=@{ $env{$name} };
11447:         } else {
11448:             $values[0]=$env{$name};
11449:         }
11450:     }
11451:     return(@values);
11452: }
11453: 
11454: # Looks at given dependencies, and returns something depending on the context.
11455: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11456: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11457: # For all other contexts, returns ($output, $counter, $numpathchg).
11458: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11459: # $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.
11460: # $numpathchg: integer with the number of cleaned up dependency paths.
11461: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11462: # \%mapping: hash reference clean path -> original path for all dependencies.
11463: # @param {string} actionurl - The path to the handler, indicative of the context.
11464: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11465: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11466: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11467: # @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)
11468: # @return {Array} - array depending on the context (not a reference)
11469: sub ask_for_embedded_content {
11470:     # NOTE: documentation was added afterwards, it could be wrong
11471:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11472:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11473:         %currsubfile,%unused,$rem);
11474:     my $counter = 0;
11475:     my $numnew = 0;
11476:     my $numremref = 0;
11477:     my $numinvalid = 0;
11478:     my $numpathchg = 0;
11479:     my $numexisting = 0;
11480:     my $numunused = 0;
11481:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11482:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11483:     my $heading = &mt('Upload embedded files');
11484:     my $buttontext = &mt('Upload');
11485: 
11486:     # fills these variables based on the context:
11487:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11488:     # $path, $fileloc, $title, $rem, $filename
11489:     if ($env{'request.course.id'}) {
11490:         if ($actionurl eq '/adm/dependencies') {
11491:             $navmap = Apache::lonnavmaps::navmap->new();
11492:         }
11493:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11494:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11495:     }
11496:     if (($actionurl eq '/adm/portfolio') || 
11497:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11498:         my $current_path='/';
11499:         if ($env{'form.currentpath'}) {
11500:             $current_path = $env{'form.currentpath'};
11501:         }
11502:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11503:             $udom = $cdom;
11504:             $uname = $cnum;
11505:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11506:         } else {
11507:             $udom = $env{'user.domain'};
11508:             $uname = $env{'user.name'};
11509:             $url = '/userfiles/portfolio';
11510:         }
11511:         $toplevel = $url.'/';
11512:         $url .= $current_path;
11513:         $getpropath = 1;
11514:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11515:              ($actionurl eq '/adm/imsimport')) { 
11516:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11517:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11518:         $toplevel = $url;
11519:         if ($rest ne '') {
11520:             $url .= $rest;
11521:         }
11522:     } elsif ($actionurl eq '/adm/coursedocs') {
11523:         if (ref($args) eq 'HASH') {
11524:             $url = $args->{'docs_url'};
11525:             $toplevel = $url;
11526:             if ($args->{'context'} eq 'paste') {
11527:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11528:                 ($path) = 
11529:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11530:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11531:                 $fileloc =~ s{^/}{};
11532:             }
11533:         }
11534:     } elsif ($actionurl eq '/adm/dependencies')  {
11535:         if ($env{'request.course.id'} ne '') {
11536:             if (ref($args) eq 'HASH') {
11537:                 $url = $args->{'docs_url'};
11538:                 $title = $args->{'docs_title'};
11539:                 $toplevel = $url; 
11540:                 unless ($toplevel =~ m{^/}) {
11541:                     $toplevel = "/$url";
11542:                 }
11543:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11544:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11545:                     $path = $1;
11546:                 } else {
11547:                     ($path) =
11548:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11549:                 }
11550:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11551:                     $fileloc = $toplevel;
11552:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11553:                     my ($udom,$uname,$fname) =
11554:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11555:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11556:                 } else {
11557:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11558:                 }
11559:                 $fileloc =~ s{^/}{};
11560:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11561:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11562:             }
11563:         }
11564:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11565:         $udom = $cdom;
11566:         $uname = $cnum;
11567:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11568:         $toplevel = $url;
11569:         $path = $url;
11570:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11571:         $fileloc =~ s{^/}{};
11572:     }
11573:     
11574:     # parses the dependency paths to get some info
11575:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11576:     # $newfiles: hash URL -> 1 for new files or external URLs
11577:     # (will be completed later)
11578:     # $mapping:
11579:     #   for external URLs: external URL -> external URL
11580:     #   for relative paths: clean path -> original path
11581:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11582:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11583:     foreach my $file (keys(%{$allfiles})) {
11584:         my $embed_file;
11585:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11586:             $embed_file = $1;
11587:         } else {
11588:             $embed_file = $file;
11589:         }
11590:         my ($absolutepath,$cleaned_file);
11591:         if ($embed_file =~ m{^\w+://}) {
11592:             $cleaned_file = $embed_file;
11593:             $newfiles{$cleaned_file} = 1;
11594:             $mapping{$cleaned_file} = $embed_file;
11595:         } else {
11596:             $cleaned_file = &clean_path($embed_file);
11597:             if ($embed_file =~ m{^/}) {
11598:                 $absolutepath = $embed_file;
11599:             }
11600:             if ($cleaned_file =~ m{/}) {
11601:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11602:                 $path = &check_for_traversal($path,$url,$toplevel);
11603:                 my $item = $fname;
11604:                 if ($path ne '') {
11605:                     $item = $path.'/'.$fname;
11606:                     $subdependencies{$path}{$fname} = 1;
11607:                 } else {
11608:                     $dependencies{$item} = 1;
11609:                 }
11610:                 if ($absolutepath) {
11611:                     $mapping{$item} = $absolutepath;
11612:                 } else {
11613:                     $mapping{$item} = $embed_file;
11614:                 }
11615:             } else {
11616:                 $dependencies{$embed_file} = 1;
11617:                 if ($absolutepath) {
11618:                     $mapping{$cleaned_file} = $absolutepath;
11619:                 } else {
11620:                     $mapping{$cleaned_file} = $embed_file;
11621:                 }
11622:             }
11623:         }
11624:     }
11625:     
11626:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11627:     # and lists
11628:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11629:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11630:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11631:     #                                    the path had to be cleaned up
11632:     # $existing: hash clean path -> 1 if the file exists
11633:     # $numexisting: number of keys in $existing
11634:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11635:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11636:     #                                      dependency subdirectories that are
11637:     #                                      not listed as dependencies, with some exceptions using $rem
11638:     my $dirptr = 16384;
11639:     foreach my $path (keys(%subdependencies)) {
11640:         $currsubfile{$path} = {};
11641:         if (($actionurl eq '/adm/portfolio') || 
11642:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11643:             my ($sublistref,$listerror) =
11644:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11645:             if (ref($sublistref) eq 'ARRAY') {
11646:                 foreach my $line (@{$sublistref}) {
11647:                     my ($file_name,$rest) = split(/\&/,$line,2);
11648:                     $currsubfile{$path}{$file_name} = 1;
11649:                 }
11650:             }
11651:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11652:             if (opendir(my $dir,$url.'/'.$path)) {
11653:                 my @subdir_list = grep(!/^\./,readdir($dir));
11654:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11655:             }
11656:         } elsif (($actionurl eq '/adm/dependencies') ||
11657:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11658:                   ($args->{'context'} eq 'paste')) ||
11659:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11660:             if ($env{'request.course.id'} ne '') {
11661:                 my $dir;
11662:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11663:                     $dir = $fileloc;
11664:                 } else {
11665:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11666:                 }
11667:                 if ($dir ne '') {
11668:                     my ($sublistref,$listerror) =
11669:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11670:                     if (ref($sublistref) eq 'ARRAY') {
11671:                         foreach my $line (@{$sublistref}) {
11672:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11673:                                 undef,$mtime)=split(/\&/,$line,12);
11674:                             unless (($testdir&$dirptr) ||
11675:                                     ($file_name =~ /^\.\.?$/)) {
11676:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11677:                             }
11678:                         }
11679:                     }
11680:                 }
11681:             }
11682:         }
11683:         foreach my $file (keys(%{$subdependencies{$path}})) {
11684:             if (exists($currsubfile{$path}{$file})) {
11685:                 my $item = $path.'/'.$file;
11686:                 unless ($mapping{$item} eq $item) {
11687:                     $pathchanges{$item} = 1;
11688:                 }
11689:                 $existing{$item} = 1;
11690:                 $numexisting ++;
11691:             } else {
11692:                 $newfiles{$path.'/'.$file} = 1;
11693:             }
11694:         }
11695:         if ($actionurl eq '/adm/dependencies') {
11696:             foreach my $path (keys(%currsubfile)) {
11697:                 if (ref($currsubfile{$path}) eq 'HASH') {
11698:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11699:                          unless ($subdependencies{$path}{$file}) {
11700:                              next if (($rem ne '') &&
11701:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11702:                                        (ref($navmap) &&
11703:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11704:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11705:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11706:                              $unused{$path.'/'.$file} = 1; 
11707:                          }
11708:                     }
11709:                 }
11710:             }
11711:         }
11712:     }
11713:     
11714:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11715:     # for files in $url or $fileloc (target directory) in some contexts
11716:     my %currfile;
11717:     if (($actionurl eq '/adm/portfolio') ||
11718:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11719:         my ($dirlistref,$listerror) =
11720:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11721:         if (ref($dirlistref) eq 'ARRAY') {
11722:             foreach my $line (@{$dirlistref}) {
11723:                 my ($file_name,$rest) = split(/\&/,$line,2);
11724:                 $currfile{$file_name} = 1;
11725:             }
11726:         }
11727:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11728:         if (opendir(my $dir,$url)) {
11729:             my @dir_list = grep(!/^\./,readdir($dir));
11730:             map {$currfile{$_} = 1;} @dir_list;
11731:         }
11732:     } elsif (($actionurl eq '/adm/dependencies') ||
11733:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11734:               ($args->{'context'} eq 'paste')) ||
11735:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11736:         if ($env{'request.course.id'} ne '') {
11737:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11738:             if ($dir ne '') {
11739:                 my ($dirlistref,$listerror) =
11740:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11741:                 if (ref($dirlistref) eq 'ARRAY') {
11742:                     foreach my $line (@{$dirlistref}) {
11743:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11744:                             $size,undef,$mtime)=split(/\&/,$line,12);
11745:                         unless (($testdir&$dirptr) ||
11746:                                 ($file_name =~ /^\.\.?$/)) {
11747:                             $currfile{$file_name} = [$size,$mtime];
11748:                         }
11749:                     }
11750:                 }
11751:             }
11752:         }
11753:     }
11754:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11755:     # are not in subdirectories, using $currfile
11756:     foreach my $file (keys(%dependencies)) {
11757:         if (exists($currfile{$file})) {
11758:             unless ($mapping{$file} eq $file) {
11759:                 $pathchanges{$file} = 1;
11760:             }
11761:             $existing{$file} = 1;
11762:             $numexisting ++;
11763:         } else {
11764:             $newfiles{$file} = 1;
11765:         }
11766:     }
11767:     foreach my $file (keys(%currfile)) {
11768:         unless (($file eq $filename) ||
11769:                 ($file eq $filename.'.bak') ||
11770:                 ($dependencies{$file})) {
11771:             if ($actionurl eq '/adm/dependencies') {
11772:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11773:                     next if (($rem ne '') &&
11774:                              (($env{"httpref.$rem".$file} ne '') ||
11775:                               (ref($navmap) &&
11776:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11777:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11778:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11779:                 }
11780:             }
11781:             $unused{$file} = 1;
11782:         }
11783:     }
11784:     
11785:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11786:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11787:         ($args->{'context'} eq 'paste')) {
11788:         $counter = scalar(keys(%existing));
11789:         $numpathchg = scalar(keys(%pathchanges));
11790:         return ($output,$counter,$numpathchg,\%existing);
11791:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11792:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11793:         $counter = scalar(keys(%existing));
11794:         $numpathchg = scalar(keys(%pathchanges));
11795:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11796:     }
11797:     
11798:     # returns HTML otherwise, with dependency results and to ask for more uploads
11799:     
11800:     # $upload_output: missing dependencies (with upload form)
11801:     # $modify_output: uploaded dependencies (in use)
11802:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11803:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11804:         if ($actionurl eq '/adm/dependencies') {
11805:             next if ($embed_file =~ m{^\w+://});
11806:         }
11807:         $upload_output .= &start_data_table_row().
11808:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11809:                           '<span class="LC_filename">'.$embed_file.'</span>';
11810:         unless ($mapping{$embed_file} eq $embed_file) {
11811:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11812:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11813:         }
11814:         $upload_output .= '</td>';
11815:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11816:             $upload_output.='<td align="right">'.
11817:                             '<span class="LC_info LC_fontsize_medium">'.
11818:                             &mt("URL points to web address").'</span>';
11819:             $numremref++;
11820:         } elsif ($args->{'error_on_invalid_names'}
11821:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11822:             $upload_output.='<td align="right"><span class="LC_warning">'.
11823:                             &mt('Invalid characters').'</span>';
11824:             $numinvalid++;
11825:         } else {
11826:             $upload_output .= '<td>'.
11827:                               &embedded_file_element('upload_embedded',$counter,
11828:                                                      $embed_file,\%mapping,
11829:                                                      $allfiles,$codebase,'upload');
11830:             $counter ++;
11831:             $numnew ++;
11832:         }
11833:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11834:     }
11835:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11836:         if ($actionurl eq '/adm/dependencies') {
11837:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11838:             $modify_output .= &start_data_table_row().
11839:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11840:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11841:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11842:                               '<td>'.$size.'</td>'.
11843:                               '<td>'.$mtime.'</td>'.
11844:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11845:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11846:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11847:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11848:                               &embedded_file_element('upload_embedded',$counter,
11849:                                                      $embed_file,\%mapping,
11850:                                                      $allfiles,$codebase,'modify').
11851:                               '</div></td>'.
11852:                               &end_data_table_row()."\n";
11853:             $counter ++;
11854:         } else {
11855:             $upload_output .= &start_data_table_row().
11856:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11857:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11858:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11859:                               &Apache::loncommon::end_data_table_row()."\n";
11860:         }
11861:     }
11862:     my $delidx = $counter;
11863:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11864:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11865:         $delete_output .= &start_data_table_row().
11866:                           '<td><img src="'.&icon($oldfile).'" />'.
11867:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11868:                           '<td>'.$size.'</td>'.
11869:                           '<td>'.$mtime.'</td>'.
11870:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11871:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11872:                           &embedded_file_element('upload_embedded',$delidx,
11873:                                                  $oldfile,\%mapping,$allfiles,
11874:                                                  $codebase,'delete').'</td>'.
11875:                           &end_data_table_row()."\n"; 
11876:         $numunused ++;
11877:         $delidx ++;
11878:     }
11879:     if ($upload_output) {
11880:         $upload_output = &start_data_table().
11881:                          $upload_output.
11882:                          &end_data_table()."\n";
11883:     }
11884:     if ($modify_output) {
11885:         $modify_output = &start_data_table().
11886:                          &start_data_table_header_row().
11887:                          '<th>'.&mt('File').'</th>'.
11888:                          '<th>'.&mt('Size (KB)').'</th>'.
11889:                          '<th>'.&mt('Modified').'</th>'.
11890:                          '<th>'.&mt('Upload replacement?').'</th>'.
11891:                          &end_data_table_header_row().
11892:                          $modify_output.
11893:                          &end_data_table()."\n";
11894:     }
11895:     if ($delete_output) {
11896:         $delete_output = &start_data_table().
11897:                          &start_data_table_header_row().
11898:                          '<th>'.&mt('File').'</th>'.
11899:                          '<th>'.&mt('Size (KB)').'</th>'.
11900:                          '<th>'.&mt('Modified').'</th>'.
11901:                          '<th>'.&mt('Delete?').'</th>'.
11902:                          &end_data_table_header_row().
11903:                          $delete_output.
11904:                          &end_data_table()."\n";
11905:     }
11906:     my $applies = 0;
11907:     if ($numremref) {
11908:         $applies ++;
11909:     }
11910:     if ($numinvalid) {
11911:         $applies ++;
11912:     }
11913:     if ($numexisting) {
11914:         $applies ++;
11915:     }
11916:     if ($counter || $numunused) {
11917:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11918:                   ' method="post" enctype="multipart/form-data">'."\n".
11919:                   $state.'<h3>'.$heading.'</h3>'; 
11920:         if ($actionurl eq '/adm/dependencies') {
11921:             if ($numnew) {
11922:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11923:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11924:                            $upload_output.'<br />'."\n";
11925:             }
11926:             if ($numexisting) {
11927:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11928:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11929:                            $modify_output.'<br />'."\n";
11930:                            $buttontext = &mt('Save changes');
11931:             }
11932:             if ($numunused) {
11933:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11934:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11935:                            $delete_output.'<br />'."\n";
11936:                            $buttontext = &mt('Save changes');
11937:             }
11938:         } else {
11939:             $output .= $upload_output.'<br />'."\n";
11940:         }
11941:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11942:                    $counter.'" />'."\n";
11943:         if ($actionurl eq '/adm/dependencies') { 
11944:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11945:                        $numnew.'" />'."\n";
11946:         } elsif ($actionurl eq '') {
11947:             $output .=  '<input type="hidden" name="phase" value="three" />';
11948:         }
11949:     } elsif ($applies) {
11950:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11951:         if ($applies > 1) {
11952:             $output .=  
11953:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11954:             if ($numremref) {
11955:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11956:             }
11957:             if ($numinvalid) {
11958:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11959:             }
11960:             if ($numexisting) {
11961:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11962:             }
11963:             $output .= '</ul><br />';
11964:         } elsif ($numremref) {
11965:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11966:         } elsif ($numinvalid) {
11967:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11968:         } elsif ($numexisting) {
11969:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11970:         }
11971:         $output .= $upload_output.'<br />';
11972:     }
11973:     my ($pathchange_output,$chgcount);
11974:     $chgcount = $counter;
11975:     if (keys(%pathchanges) > 0) {
11976:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11977:             if ($counter) {
11978:                 $output .= &embedded_file_element('pathchange',$chgcount,
11979:                                                   $embed_file,\%mapping,
11980:                                                   $allfiles,$codebase,'change');
11981:             } else {
11982:                 $pathchange_output .= 
11983:                     &start_data_table_row().
11984:                     '<td><input type ="checkbox" name="namechange" value="'.
11985:                     $chgcount.'" checked="checked" /></td>'.
11986:                     '<td>'.$mapping{$embed_file}.'</td>'.
11987:                     '<td>'.$embed_file.
11988:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11989:                                            \%mapping,$allfiles,$codebase,'change').
11990:                     '</td>'.&end_data_table_row();
11991:             }
11992:             $numpathchg ++;
11993:             $chgcount ++;
11994:         }
11995:     }
11996:     if (($counter) || ($numunused)) {
11997:         if ($numpathchg) {
11998:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11999:                        $numpathchg.'" />'."\n";
12000:         }
12001:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12002:             ($actionurl eq '/adm/imsimport')) {
12003:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12004:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12005:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12006:         } elsif ($actionurl eq '/adm/dependencies') {
12007:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12008:         }
12009:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12010:     } elsif ($numpathchg) {
12011:         my %pathchange = ();
12012:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12013:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12014:             $output .= '<p>'.&mt('or').'</p>'; 
12015:         }
12016:     }
12017:     return ($output,$counter,$numpathchg);
12018: }
12019: 
12020: =pod
12021: 
12022: =item * clean_path($name)
12023: 
12024: Performs clean-up of directories, subdirectories and filename in an
12025: embedded object, referenced in an HTML file which is being uploaded
12026: to a course or portfolio, where 
12027: "Upload embedded images/multimedia files if HTML file" checkbox was
12028: checked.
12029: 
12030: Clean-up is similar to replacements in lonnet::clean_filename()
12031: except each / between sub-directory and next level is preserved.
12032: 
12033: =cut
12034: 
12035: sub clean_path {
12036:     my ($embed_file) = @_;
12037:     $embed_file =~s{^/+}{};
12038:     my @contents;
12039:     if ($embed_file =~ m{/}) {
12040:         @contents = split(/\//,$embed_file);
12041:     } else {
12042:         @contents = ($embed_file);
12043:     }
12044:     my $lastidx = scalar(@contents)-1;
12045:     for (my $i=0; $i<=$lastidx; $i++) { 
12046:         $contents[$i]=~s{\\}{/}g;
12047:         $contents[$i]=~s/\s+/\_/g;
12048:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12049:         if ($i == $lastidx) {
12050:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12051:         }
12052:     }
12053:     if ($lastidx > 0) {
12054:         return join('/',@contents);
12055:     } else {
12056:         return $contents[0];
12057:     }
12058: }
12059: 
12060: sub embedded_file_element {
12061:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12062:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12063:                    (ref($codebase) eq 'HASH'));
12064:     my $output;
12065:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12066:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12067:     }
12068:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12069:                &escape($embed_file).'" />';
12070:     unless (($context eq 'upload_embedded') && 
12071:             ($mapping->{$embed_file} eq $embed_file)) {
12072:         $output .='
12073:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12074:     }
12075:     my $attrib;
12076:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12077:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12078:     }
12079:     $output .=
12080:         "\n\t\t".
12081:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12082:         $attrib.'" />';
12083:     if (exists($codebase->{$mapping->{$embed_file}})) {
12084:         $output .=
12085:             "\n\t\t".
12086:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12087:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12088:     }
12089:     return $output;
12090: }
12091: 
12092: sub get_dependency_details {
12093:     my ($currfile,$currsubfile,$embed_file) = @_;
12094:     my ($size,$mtime,$showsize,$showmtime);
12095:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12096:         if ($embed_file =~ m{/}) {
12097:             my ($path,$fname) = split(/\//,$embed_file);
12098:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12099:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12100:             }
12101:         } else {
12102:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12103:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12104:             }
12105:         }
12106:         $showsize = $size/1024.0;
12107:         $showsize = sprintf("%.1f",$showsize);
12108:         if ($mtime > 0) {
12109:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12110:         }
12111:     }
12112:     return ($showsize,$showmtime);
12113: }
12114: 
12115: sub ask_embedded_js {
12116:     return <<"END";
12117: <script type="text/javascript"">
12118: // <![CDATA[
12119: function toggleBrowse(counter) {
12120:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12121:     var fileid = document.getElementById('embedded_item_'+counter);
12122:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12123:     if (chkboxid.checked == true) {
12124:         uploaddivid.style.display='block';
12125:     } else {
12126:         uploaddivid.style.display='none';
12127:         fileid.value = '';
12128:     }
12129: }
12130: // ]]>
12131: </script>
12132: 
12133: END
12134: }
12135: 
12136: sub upload_embedded {
12137:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12138:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12139:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12140:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12141:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12142:         my $orig_uploaded_filename =
12143:             $env{'form.embedded_item_'.$i.'.filename'};
12144:         foreach my $type ('orig','ref','attrib','codebase') {
12145:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12146:                 $env{'form.embedded_'.$type.'_'.$i} =
12147:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12148:             }
12149:         }
12150:         my ($path,$fname) =
12151:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12152:         # no path, whole string is fname
12153:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12154:         $fname = &Apache::lonnet::clean_filename($fname);
12155:         # See if there is anything left
12156:         next if ($fname eq '');
12157: 
12158:         # Check if file already exists as a file or directory.
12159:         my ($state,$msg);
12160:         if ($context eq 'portfolio') {
12161:             my $port_path = $dirpath;
12162:             if ($group ne '') {
12163:                 $port_path = "groups/$group/$port_path";
12164:             }
12165:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12166:                                               $fname,$group,'embedded_item_'.$i,
12167:                                               $dir_root,$port_path,$disk_quota,
12168:                                               $current_disk_usage,$uname,$udom);
12169:             if ($state eq 'will_exceed_quota'
12170:                 || $state eq 'file_locked') {
12171:                 $output .= $msg;
12172:                 next;
12173:             }
12174:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12175:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12176:             if ($state eq 'exists') {
12177:                 $output .= $msg;
12178:                 next;
12179:             }
12180:         }
12181:         # Check if extension is valid
12182:         if (($fname =~ /\.(\w+)$/) &&
12183:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12184:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12185:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12186:             next;
12187:         } elsif (($fname =~ /\.(\w+)$/) &&
12188:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12189:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12190:             next;
12191:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12192:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12193:             next;
12194:         }
12195:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12196:         my $subdir = $path;
12197:         $subdir =~ s{/+$}{};
12198:         if ($context eq 'portfolio') {
12199:             my $result;
12200:             if ($state eq 'existingfile') {
12201:                 $result=
12202:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12203:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12204:             } else {
12205:                 $result=
12206:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12207:                                                     $dirpath.
12208:                                                     $env{'form.currentpath'}.$subdir);
12209:                 if ($result !~ m|^/uploaded/|) {
12210:                     $output .= '<span class="LC_error">'
12211:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12212:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12213:                                .'</span><br />';
12214:                     next;
12215:                 } else {
12216:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12217:                                $path.$fname.'</span>').'<br />';     
12218:                 }
12219:             }
12220:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12221:             my $extendedsubdir = $dirpath.'/'.$subdir;
12222:             $extendedsubdir =~ s{/+$}{};
12223:             my $result =
12224:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12225:             if ($result !~ m|^/uploaded/|) {
12226:                 $output .= '<span class="LC_error">'
12227:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12228:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12229:                            .'</span><br />';
12230:                     next;
12231:             } else {
12232:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12233:                            $path.$fname.'</span>').'<br />';
12234:                 if ($context eq 'syllabus') {
12235:                     &Apache::lonnet::make_public_indefinitely($result);
12236:                 }
12237:             }
12238:         } else {
12239: # Save the file
12240:             my $target = $env{'form.embedded_item_'.$i};
12241:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12242:             my $dest = $fullpath.$fname;
12243:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12244:             my @parts=split(/\//,"$dirpath/$path");
12245:             my $count;
12246:             my $filepath = $dir_root;
12247:             foreach my $subdir (@parts) {
12248:                 $filepath .= "/$subdir";
12249:                 if (!-e $filepath) {
12250:                     mkdir($filepath,0770);
12251:                 }
12252:             }
12253:             my $fh;
12254:             if (!open($fh,'>'.$dest)) {
12255:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12256:                 $output .= '<span class="LC_error">'.
12257:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12258:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12259:                            '</span><br />';
12260:             } else {
12261:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12262:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12263:                     $output .= '<span class="LC_error">'.
12264:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12265:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12266:                               '</span><br />';
12267:                 } else {
12268:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12269:                                $url.'</span>').'<br />';
12270:                     unless ($context eq 'testbank') {
12271:                         $footer .= &mt('View embedded file: [_1]',
12272:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12273:                     }
12274:                 }
12275:                 close($fh);
12276:             }
12277:         }
12278:         if ($env{'form.embedded_ref_'.$i}) {
12279:             $pathchange{$i} = 1;
12280:         }
12281:     }
12282:     if ($output) {
12283:         $output = '<p>'.$output.'</p>';
12284:     }
12285:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12286:     $returnflag = 'ok';
12287:     my $numpathchgs = scalar(keys(%pathchange));
12288:     if ($numpathchgs > 0) {
12289:         if ($context eq 'portfolio') {
12290:             $output .= '<p>'.&mt('or').'</p>';
12291:         } elsif ($context eq 'testbank') {
12292:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12293:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12294:             $returnflag = 'modify_orightml';
12295:         }
12296:     }
12297:     return ($output.$footer,$returnflag,$numpathchgs);
12298: }
12299: 
12300: sub modify_html_form {
12301:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12302:     my $end = 0;
12303:     my $modifyform;
12304:     if ($context eq 'upload_embedded') {
12305:         return unless (ref($pathchange) eq 'HASH');
12306:         if ($env{'form.number_embedded_items'}) {
12307:             $end += $env{'form.number_embedded_items'};
12308:         }
12309:         if ($env{'form.number_pathchange_items'}) {
12310:             $end += $env{'form.number_pathchange_items'};
12311:         }
12312:         if ($end) {
12313:             for (my $i=0; $i<$end; $i++) {
12314:                 if ($i < $env{'form.number_embedded_items'}) {
12315:                     next unless($pathchange->{$i});
12316:                 }
12317:                 $modifyform .=
12318:                     &start_data_table_row().
12319:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12320:                     'checked="checked" /></td>'.
12321:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12322:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12323:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12324:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12325:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12326:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12327:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12328:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12329:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12330:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12331:                     &end_data_table_row();
12332:             }
12333:         }
12334:     } else {
12335:         $modifyform = $pathchgtable;
12336:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12337:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12338:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12339:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12340:         }
12341:     }
12342:     if ($modifyform) {
12343:         if ($actionurl eq '/adm/dependencies') {
12344:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12345:         }
12346:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12347:                '<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".
12348:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12349:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12350:                '</ol></p>'."\n".'<p>'.
12351:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12352:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12353:                &start_data_table()."\n".
12354:                &start_data_table_header_row().
12355:                '<th>'.&mt('Change?').'</th>'.
12356:                '<th>'.&mt('Current reference').'</th>'.
12357:                '<th>'.&mt('Required reference').'</th>'.
12358:                &end_data_table_header_row()."\n".
12359:                $modifyform.
12360:                &end_data_table().'<br />'."\n".$hiddenstate.
12361:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12362:                '</form>'."\n";
12363:     }
12364:     return;
12365: }
12366: 
12367: sub modify_html_refs {
12368:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12369:     my $container;
12370:     if ($context eq 'portfolio') {
12371:         $container = $env{'form.container'};
12372:     } elsif ($context eq 'coursedoc') {
12373:         $container = $env{'form.primaryurl'};
12374:     } elsif ($context eq 'manage_dependencies') {
12375:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12376:         $container = "/$container";
12377:     } elsif ($context eq 'syllabus') {
12378:         $container = $url;
12379:     } else {
12380:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12381:     }
12382:     my (%allfiles,%codebase,$output,$content);
12383:     my @changes = &get_env_multiple('form.namechange');
12384:     unless ((@changes > 0) || ($context eq 'syllabus')) {
12385:         if (wantarray) {
12386:             return ('',0,0); 
12387:         } else {
12388:             return;
12389:         }
12390:     }
12391:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12392:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12393:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12394:             if (wantarray) {
12395:                 return ('',0,0);
12396:             } else {
12397:                 return;
12398:             }
12399:         } 
12400:         $content = &Apache::lonnet::getfile($container);
12401:         if ($content eq '-1') {
12402:             if (wantarray) {
12403:                 return ('',0,0);
12404:             } else {
12405:                 return;
12406:             }
12407:         }
12408:     } else {
12409:         unless ($container =~ /^\Q$dir_root\E/) {
12410:             if (wantarray) {
12411:                 return ('',0,0);
12412:             } else {
12413:                 return;
12414:             }
12415:         } 
12416:         if (open(my $fh,'<',$container)) {
12417:             $content = join('', <$fh>);
12418:             close($fh);
12419:         } else {
12420:             if (wantarray) {
12421:                 return ('',0,0);
12422:             } else {
12423:                 return;
12424:             }
12425:         }
12426:     }
12427:     my ($count,$codebasecount) = (0,0);
12428:     my $mm = new File::MMagic;
12429:     my $mime_type = $mm->checktype_contents($content);
12430:     if ($mime_type eq 'text/html') {
12431:         my $parse_result = 
12432:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12433:                                                     \%codebase,\$content);
12434:         if ($parse_result eq 'ok') {
12435:             foreach my $i (@changes) {
12436:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12437:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12438:                 if ($allfiles{$ref}) {
12439:                     my $newname =  $orig;
12440:                     my ($attrib_regexp,$codebase);
12441:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12442:                     if ($attrib_regexp =~ /:/) {
12443:                         $attrib_regexp =~ s/\:/|/g;
12444:                     }
12445:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12446:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12447:                         $count += $numchg;
12448:                         $allfiles{$newname} = $allfiles{$ref};
12449:                         delete($allfiles{$ref});
12450:                     }
12451:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12452:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12453:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12454:                         $codebasecount ++;
12455:                     }
12456:                 }
12457:             }
12458:             my $skiprewrites;
12459:             if ($count || $codebasecount) {
12460:                 my $saveresult;
12461:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12462:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12463:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12464:                     if ($url eq $container) {
12465:                         my ($fname) = ($container =~ m{/([^/]+)$});
12466:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12467:                                             $count,'<span class="LC_filename">'.
12468:                                             $fname.'</span>').'</p>';
12469:                     } else {
12470:                          $output = '<p class="LC_error">'.
12471:                                    &mt('Error: update failed for: [_1].',
12472:                                    '<span class="LC_filename">'.
12473:                                    $container.'</span>').'</p>';
12474:                     }
12475:                     if ($context eq 'syllabus') {
12476:                         unless ($saveresult eq 'ok') {
12477:                             $skiprewrites = 1;
12478:                         }
12479:                     }
12480:                 } else {
12481:                     if (open(my $fh,'>',$container)) {
12482:                         print $fh $content;
12483:                         close($fh);
12484:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12485:                                   $count,'<span class="LC_filename">'.
12486:                                   $container.'</span>').'</p>';
12487:                     } else {
12488:                          $output = '<p class="LC_error">'.
12489:                                    &mt('Error: could not update [_1].',
12490:                                    '<span class="LC_filename">'.
12491:                                    $container.'</span>').'</p>';
12492:                     }
12493:                 }
12494:             }
12495:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12496:                 my ($actionurl,$state);
12497:                 $actionurl = "/public/$udom/$uname/syllabus";
12498:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12499:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12500:                                               \%codebase,
12501:                                               {'context' => 'rewrites',
12502:                                                'ignore_remote_references' => 1,});
12503:                 if (ref($mapping) eq 'HASH') {
12504:                     my $rewrites = 0;
12505:                     foreach my $key (keys(%{$mapping})) {
12506:                         next if ($key =~ m{^https?://});
12507:                         my $ref = $mapping->{$key};
12508:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12509:                         my $attrib;
12510:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12511:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12512:                         }
12513:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12514:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12515:                             $rewrites += $numchg;
12516:                         }
12517:                     }
12518:                     if ($rewrites) {
12519:                         my $saveresult; 
12520:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12521:                         if ($url eq $container) {
12522:                             my ($fname) = ($container =~ m{/([^/]+)$});
12523:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12524:                                             $count,'<span class="LC_filename">'.
12525:                                             $fname.'</span>').'</p>';
12526:                         } else {
12527:                             $output .= '<p class="LC_error">'.
12528:                                        &mt('Error: could not update links in [_1].',
12529:                                        '<span class="LC_filename">'.
12530:                                        $container.'</span>').'</p>';
12531: 
12532:                         }
12533:                     }
12534:                 }
12535:             }
12536:         } else {
12537:             &logthis('Failed to parse '.$container.
12538:                      ' to modify references: '.$parse_result);
12539:         }
12540:     }
12541:     if (wantarray) {
12542:         return ($output,$count,$codebasecount);
12543:     } else {
12544:         return $output;
12545:     }
12546: }
12547: 
12548: sub check_for_existing {
12549:     my ($path,$fname,$element) = @_;
12550:     my ($state,$msg);
12551:     if (-d $path.'/'.$fname) {
12552:         $state = 'exists';
12553:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12554:     } elsif (-e $path.'/'.$fname) {
12555:         $state = 'exists';
12556:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12557:     }
12558:     if ($state eq 'exists') {
12559:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12560:     }
12561:     return ($state,$msg);
12562: }
12563: 
12564: sub check_for_upload {
12565:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12566:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12567:     my $filesize = length($env{'form.'.$element});
12568:     if (!$filesize) {
12569:         my $msg = '<span class="LC_error">'.
12570:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12571:                       '<span class="LC_filename">'.$fname.'</span>',
12572:                       $filesize).'<br />'.
12573:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12574:                   '</span>';
12575:         return ('zero_bytes',$msg);
12576:     }
12577:     $filesize =  $filesize/1000; #express in k (1024?)
12578:     my $getpropath = 1;
12579:     my ($dirlistref,$listerror) =
12580:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12581:     my $found_file = 0;
12582:     my $locked_file = 0;
12583:     my @lockers;
12584:     my $navmap;
12585:     if ($env{'request.course.id'}) {
12586:         $navmap = Apache::lonnavmaps::navmap->new();
12587:     }
12588:     if (ref($dirlistref) eq 'ARRAY') {
12589:         foreach my $line (@{$dirlistref}) {
12590:             my ($file_name,$rest)=split(/\&/,$line,2);
12591:             if ($file_name eq $fname){
12592:                 $file_name = $path.$file_name;
12593:                 if ($group ne '') {
12594:                     $file_name = $group.$file_name;
12595:                 }
12596:                 $found_file = 1;
12597:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12598:                     foreach my $lock (@lockers) {
12599:                         if (ref($lock) eq 'ARRAY') {
12600:                             my ($symb,$crsid) = @{$lock};
12601:                             if ($crsid eq $env{'request.course.id'}) {
12602:                                 if (ref($navmap)) {
12603:                                     my $res = $navmap->getBySymb($symb);
12604:                                     foreach my $part (@{$res->parts()}) { 
12605:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12606:                                         unless (($slot_status == $res->RESERVED) ||
12607:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12608:                                             $locked_file = 1;
12609:                                         }
12610:                                     }
12611:                                 } else {
12612:                                     $locked_file = 1;
12613:                                 }
12614:                             } else {
12615:                                 $locked_file = 1;
12616:                             }
12617:                         }
12618:                    }
12619:                 } else {
12620:                     my @info = split(/\&/,$rest);
12621:                     my $currsize = $info[6]/1000;
12622:                     if ($currsize < $filesize) {
12623:                         my $extra = $filesize - $currsize;
12624:                         if (($current_disk_usage + $extra) > $disk_quota) {
12625:                             my $msg = '<p class="LC_warning">'.
12626:                                       &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.',
12627:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12628:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12629:                                                    $disk_quota,$current_disk_usage).'</p>';
12630:                             return ('will_exceed_quota',$msg);
12631:                         }
12632:                     }
12633:                 }
12634:             }
12635:         }
12636:     }
12637:     if (($current_disk_usage + $filesize) > $disk_quota){
12638:         my $msg = '<p class="LC_warning">'.
12639:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12640:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12641:         return ('will_exceed_quota',$msg);
12642:     } elsif ($found_file) {
12643:         if ($locked_file) {
12644:             my $msg = '<p class="LC_warning">';
12645:             $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>');
12646:             $msg .= '</p>';
12647:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12648:             return ('file_locked',$msg);
12649:         } else {
12650:             my $msg = '<p class="LC_error">';
12651:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12652:             $msg .= '</p>';
12653:             return ('existingfile',$msg);
12654:         }
12655:     }
12656: }
12657: 
12658: sub check_for_traversal {
12659:     my ($path,$url,$toplevel) = @_;
12660:     my @parts=split(/\//,$path);
12661:     my $cleanpath;
12662:     my $fullpath = $url;
12663:     for (my $i=0;$i<@parts;$i++) {
12664:         next if ($parts[$i] eq '.');
12665:         if ($parts[$i] eq '..') {
12666:             $fullpath =~ s{([^/]+/)$}{};
12667:         } else {
12668:             $fullpath .= $parts[$i].'/';
12669:         }
12670:     }
12671:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12672:         $cleanpath = $1;
12673:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12674:         my $curr_toprel = $1;
12675:         my @parts = split(/\//,$curr_toprel);
12676:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12677:         my @urlparts = split(/\//,$url_toprel);
12678:         my $doubledots;
12679:         my $startdiff = -1;
12680:         for (my $i=0; $i<@urlparts; $i++) {
12681:             if ($startdiff == -1) {
12682:                 unless ($urlparts[$i] eq $parts[$i]) {
12683:                     $startdiff = $i;
12684:                     $doubledots .= '../';
12685:                 }
12686:             } else {
12687:                 $doubledots .= '../';
12688:             }
12689:         }
12690:         if ($startdiff > -1) {
12691:             $cleanpath = $doubledots;
12692:             for (my $i=$startdiff; $i<@parts; $i++) {
12693:                 $cleanpath .= $parts[$i].'/';
12694:             }
12695:         }
12696:     }
12697:     $cleanpath =~ s{(/)$}{};
12698:     return $cleanpath;
12699: }
12700: 
12701: sub is_archive_file {
12702:     my ($mimetype) = @_;
12703:     if (($mimetype eq 'application/octet-stream') ||
12704:         ($mimetype eq 'application/x-stuffit') ||
12705:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12706:         return 1;
12707:     }
12708:     return;
12709: }
12710: 
12711: sub decompress_form {
12712:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12713:     my %lt = &Apache::lonlocal::texthash (
12714:         this => 'This file is an archive file.',
12715:         camt => 'This file is a Camtasia archive file.',
12716:         itsc => 'Its contents are as follows:',
12717:         youm => 'You may wish to extract its contents.',
12718:         extr => 'Extract contents',
12719:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12720:         proa => 'Process automatically?',
12721:         yes  => 'Yes',
12722:         no   => 'No',
12723:         fold => 'Title for folder containing movie',
12724:         movi => 'Title for page containing embedded movie', 
12725:     );
12726:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12727:     my ($is_camtasia,$topdir,%toplevel,@paths);
12728:     my $info = &list_archive_contents($fileloc,\@paths);
12729:     if (@paths) {
12730:         foreach my $path (@paths) {
12731:             $path =~ s{^/}{};
12732:             if ($path =~ m{^([^/]+)/$}) {
12733:                 $topdir = $1;
12734:             }
12735:             if ($path =~ m{^([^/]+)/}) {
12736:                 $toplevel{$1} = $path;
12737:             } else {
12738:                 $toplevel{$path} = $path;
12739:             }
12740:         }
12741:     }
12742:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12743:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12744:                         "$topdir/media/",
12745:                         "$topdir/media/$topdir.mp4",
12746:                         "$topdir/media/FirstFrame.png",
12747:                         "$topdir/media/player.swf",
12748:                         "$topdir/media/swfobject.js",
12749:                         "$topdir/media/expressInstall.swf");
12750:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12751:                          "$topdir/$topdir.mp4",
12752:                          "$topdir/$topdir\_config.xml",
12753:                          "$topdir/$topdir\_controller.swf",
12754:                          "$topdir/$topdir\_embed.css",
12755:                          "$topdir/$topdir\_First_Frame.png",
12756:                          "$topdir/$topdir\_player.html",
12757:                          "$topdir/$topdir\_Thumbnails.png",
12758:                          "$topdir/playerProductInstall.swf",
12759:                          "$topdir/scripts/",
12760:                          "$topdir/scripts/config_xml.js",
12761:                          "$topdir/scripts/handlebars.js",
12762:                          "$topdir/scripts/jquery-1.7.1.min.js",
12763:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12764:                          "$topdir/scripts/modernizr.js",
12765:                          "$topdir/scripts/player-min.js",
12766:                          "$topdir/scripts/swfobject.js",
12767:                          "$topdir/skins/",
12768:                          "$topdir/skins/configuration_express.xml",
12769:                          "$topdir/skins/express_show/",
12770:                          "$topdir/skins/express_show/player-min.css",
12771:                          "$topdir/skins/express_show/spritesheet.png");
12772:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12773:                          "$topdir/$topdir.mp4",
12774:                          "$topdir/$topdir\_config.xml",
12775:                          "$topdir/$topdir\_controller.swf",
12776:                          "$topdir/$topdir\_embed.css",
12777:                          "$topdir/$topdir\_First_Frame.png",
12778:                          "$topdir/$topdir\_player.html",
12779:                          "$topdir/$topdir\_Thumbnails.png",
12780:                          "$topdir/playerProductInstall.swf",
12781:                          "$topdir/scripts/",
12782:                          "$topdir/scripts/config_xml.js",
12783:                          "$topdir/scripts/techsmith-smart-player.min.js",
12784:                          "$topdir/skins/",
12785:                          "$topdir/skins/configuration_express.xml",
12786:                          "$topdir/skins/express_show/",
12787:                          "$topdir/skins/express_show/spritesheet.min.css",
12788:                          "$topdir/skins/express_show/spritesheet.png",
12789:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12790:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12791:         if (@diffs == 0) {
12792:             $is_camtasia = 6;
12793:         } else {
12794:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12795:             if (@diffs == 0) {
12796:                 $is_camtasia = 8;
12797:             } else {
12798:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12799:                 if (@diffs == 0) {
12800:                     $is_camtasia = 8;
12801:                 }
12802:             }
12803:         }
12804:     }
12805:     my $output;
12806:     if ($is_camtasia) {
12807:         $output = <<"ENDCAM";
12808: <script type="text/javascript" language="Javascript">
12809: // <![CDATA[
12810: 
12811: function camtasiaToggle() {
12812:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12813:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12814:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12815:                 document.getElementById('camtasia_titles').style.display='block';
12816:             } else {
12817:                 document.getElementById('camtasia_titles').style.display='none';
12818:             }
12819:         }
12820:     }
12821:     return;
12822: }
12823: 
12824: // ]]>
12825: </script>
12826: <p>$lt{'camt'}</p>
12827: ENDCAM
12828:     } else {
12829:         $output = '<p>'.$lt{'this'};
12830:         if ($info eq '') {
12831:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12832:         } else {
12833:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12834:                        '<div><pre>'.$info.'</pre></div>';
12835:         }
12836:     }
12837:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12838:     my $duplicates;
12839:     my $num = 0;
12840:     if (ref($dirlist) eq 'ARRAY') {
12841:         foreach my $item (@{$dirlist}) {
12842:             if (ref($item) eq 'ARRAY') {
12843:                 if (exists($toplevel{$item->[0]})) {
12844:                     $duplicates .= 
12845:                         &start_data_table_row().
12846:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12847:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12848:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12849:                         'value="1" />'.&mt('Yes').'</label>'.
12850:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12851:                         '<td>'.$item->[0].'</td>';
12852:                     if ($item->[2]) {
12853:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12854:                     } else {
12855:                         $duplicates .= '<td>'.&mt('File').'</td>';
12856:                     }
12857:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12858:                                    '<td>'.
12859:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12860:                                    '</td>'.
12861:                                    &end_data_table_row();
12862:                     $num ++;
12863:                 }
12864:             }
12865:         }
12866:     }
12867:     my $itemcount;
12868:     if (@paths > 0) {
12869:         $itemcount = scalar(@paths);
12870:     } else {
12871:         $itemcount = 1;
12872:     }
12873:     if ($is_camtasia) {
12874:         $output .= $lt{'auto'}.'<br />'.
12875:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12876:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12877:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12878:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12879:                    $lt{'no'}.'</label></span><br />'.
12880:                    '<div id="camtasia_titles" style="display:block">'.
12881:                    &Apache::lonhtmlcommon::start_pick_box().
12882:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12883:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12884:                    &Apache::lonhtmlcommon::row_closure().
12885:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12886:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12887:                    &Apache::lonhtmlcommon::row_closure(1).
12888:                    &Apache::lonhtmlcommon::end_pick_box().
12889:                    '</div>';
12890:     }
12891:     $output .= 
12892:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12893:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12894:         "\n";
12895:     if ($duplicates ne '') {
12896:         $output .= '<p><span class="LC_warning">'.
12897:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12898:                    &start_data_table().
12899:                    &start_data_table_header_row().
12900:                    '<th>'.&mt('Overwrite?').'</th>'.
12901:                    '<th>'.&mt('Name').'</th>'.
12902:                    '<th>'.&mt('Type').'</th>'.
12903:                    '<th>'.&mt('Size').'</th>'.
12904:                    '<th>'.&mt('Last modified').'</th>'.
12905:                    &end_data_table_header_row().
12906:                    $duplicates.
12907:                    &end_data_table().
12908:                    '</p>';
12909:     }
12910:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12911:     if (ref($hiddenelements) eq 'HASH') {
12912:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12913:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12914:         }
12915:     }
12916:     $output .= <<"END";
12917: <br />
12918: <input type="submit" name="decompress" value="$lt{'extr'}" />
12919: </form>
12920: $noextract
12921: END
12922:     return $output;
12923: }
12924: 
12925: sub decompression_utility {
12926:     my ($program) = @_;
12927:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12928:     my $location;
12929:     if (grep(/^\Q$program\E$/,@utilities)) { 
12930:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12931:                          '/usr/sbin/') {
12932:             if (-x $dir.$program) {
12933:                 $location = $dir.$program;
12934:                 last;
12935:             }
12936:         }
12937:     }
12938:     return $location;
12939: }
12940: 
12941: sub list_archive_contents {
12942:     my ($file,$pathsref) = @_;
12943:     my (@cmd,$output);
12944:     my $needsregexp;
12945:     if ($file =~ /\.zip$/) {
12946:         @cmd = (&decompression_utility('unzip'),"-l");
12947:         $needsregexp = 1;
12948:     } elsif (($file =~ m/\.tar\.gz$/) ||
12949:              ($file =~ /\.tgz$/)) {
12950:         @cmd = (&decompression_utility('tar'),"-ztf");
12951:     } elsif ($file =~ /\.tar\.bz2$/) {
12952:         @cmd = (&decompression_utility('tar'),"-jtf");
12953:     } elsif ($file =~ m|\.tar$|) {
12954:         @cmd = (&decompression_utility('tar'),"-tf");
12955:     }
12956:     if (@cmd) {
12957:         undef($!);
12958:         undef($@);
12959:         if (open(my $fh,"-|", @cmd, $file)) {
12960:             while (my $line = <$fh>) {
12961:                 $output .= $line;
12962:                 chomp($line);
12963:                 my $item;
12964:                 if ($needsregexp) {
12965:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12966:                 } else {
12967:                     $item = $line;
12968:                 }
12969:                 if ($item ne '') {
12970:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12971:                         push(@{$pathsref},$item);
12972:                     } 
12973:                 }
12974:             }
12975:             close($fh);
12976:         }
12977:     }
12978:     return $output;
12979: }
12980: 
12981: sub decompress_uploaded_file {
12982:     my ($file,$dir) = @_;
12983:     &Apache::lonnet::appenv({'cgi.file' => $file});
12984:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12985:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12986:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12987:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12988:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12989:     my $decompressed = $env{'cgi.decompressed'};
12990:     &Apache::lonnet::delenv('cgi.file');
12991:     &Apache::lonnet::delenv('cgi.dir');
12992:     &Apache::lonnet::delenv('cgi.decompressed');
12993:     return ($decompressed,$result);
12994: }
12995: 
12996: sub process_decompression {
12997:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12998:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12999:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13000:                &mt('Unexpected file path.').'</p>'."\n";
13001:     }
13002:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13003:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13004:                &mt('Unexpected course context.').'</p>'."\n";
13005:     }
13006:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13007:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13008:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13009:     }
13010:     my ($dir,$error,$warning,$output);
13011:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13012:         $error = &mt('Filename not a supported archive file type.').
13013:                  '<br />'.&mt('Filename should end with one of: [_1].',
13014:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13015:     } else {
13016:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13017:         if ($docuhome eq 'no_host') {
13018:             $error = &mt('Could not determine home server for course.');
13019:         } else {
13020:             my @ids=&Apache::lonnet::current_machine_ids();
13021:             my $currdir = "$dir_root/$destination";
13022:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13023:                 $dir = &LONCAPA::propath($docudom,$docuname).
13024:                        "$dir_root/$destination";
13025:             } else {
13026:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13027:                        "$dir_root/$docudom/$docuname/$destination";
13028:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13029:                     $error = &mt('Archive file not found.');
13030:                 }
13031:             }
13032:             my (@to_overwrite,@to_skip);
13033:             if ($env{'form.archive_overwrite_total'} > 0) {
13034:                 my $total = $env{'form.archive_overwrite_total'};
13035:                 for (my $i=0; $i<$total; $i++) {
13036:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13037:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13038:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13039:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13040:                     }
13041:                 }
13042:             }
13043:             my $numskip = scalar(@to_skip);
13044:             my $numoverwrite = scalar(@to_overwrite);
13045:             if (($numskip) && (!$numoverwrite)) { 
13046:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13047:             } elsif ($dir eq '') {
13048:                 $error = &mt('Directory containing archive file unavailable.');
13049:             } elsif (!$error) {
13050:                 my ($decompressed,$display);
13051:                 if (($numskip) || ($numoverwrite)) {
13052:                     my $tempdir = time.'_'.$$.int(rand(10000));
13053:                     mkdir("$dir/$tempdir",0755);
13054:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13055:                         ($decompressed,$display) = 
13056:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13057:                         foreach my $item (@to_skip) {
13058:                             if (($item ne '') && ($item !~ /\.\./)) {
13059:                                 if (-f "$dir/$tempdir/$item") { 
13060:                                     unlink("$dir/$tempdir/$item");
13061:                                 } elsif (-d "$dir/$tempdir/$item") {
13062:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13063:                                 }
13064:                             }
13065:                         }
13066:                         foreach my $item (@to_overwrite) {
13067:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13068:                                 if (($item ne '') && ($item !~ /\.\./)) {
13069:                                     if (-f "$dir/$item") {
13070:                                         unlink("$dir/$item");
13071:                                     } elsif (-d "$dir/$item") {
13072:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13073:                                     }
13074:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13075:                                 }
13076:                             }
13077:                         }
13078:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13079:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13080:                         }
13081:                     }
13082:                 } else {
13083:                     ($decompressed,$display) = 
13084:                         &decompress_uploaded_file($file,$dir);
13085:                 }
13086:                 if ($decompressed eq 'ok') {
13087:                     $output = '<p class="LC_info">'.
13088:                               &mt('Files extracted successfully from archive.').
13089:                               '</p>'."\n";
13090:                     my ($warning,$result,@contents);
13091:                     my ($newdirlistref,$newlisterror) =
13092:                         &Apache::lonnet::dirlist($currdir,$docudom,
13093:                                                  $docuname,1);
13094:                     my (%is_dir,%changes,@newitems);
13095:                     my $dirptr = 16384;
13096:                     if (ref($newdirlistref) eq 'ARRAY') {
13097:                         foreach my $dir_line (@{$newdirlistref}) {
13098:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13099:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13100:                                 push(@newitems,$item);
13101:                                 if ($dirptr&$testdir) {
13102:                                     $is_dir{$item} = 1;
13103:                                 }
13104:                                 $changes{$item} = 1;
13105:                             }
13106:                         }
13107:                     }
13108:                     if (keys(%changes) > 0) {
13109:                         foreach my $item (sort(@newitems)) {
13110:                             if ($changes{$item}) {
13111:                                 push(@contents,$item);
13112:                             }
13113:                         }
13114:                     }
13115:                     if (@contents > 0) {
13116:                         my $wantform;
13117:                         unless ($env{'form.autoextract_camtasia'}) {
13118:                             $wantform = 1;
13119:                         }
13120:                         my (%children,%parent,%dirorder,%titles);
13121:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13122:                                                                 $currdir,\%is_dir,
13123:                                                                 \%children,\%parent,
13124:                                                                 \@contents,\%dirorder,
13125:                                                                 \%titles,$wantform);
13126:                         if ($datatable ne '') {
13127:                             $output .= &archive_options_form('decompressed',$datatable,
13128:                                                              $count,$hiddenelem);
13129:                             my $startcount = 6;
13130:                             $output .= &archive_javascript($startcount,$count,
13131:                                                            \%titles,\%children);
13132:                         }
13133:                         if ($env{'form.autoextract_camtasia'}) {
13134:                             my $version = $env{'form.autoextract_camtasia'};
13135:                             my %displayed;
13136:                             my $total = 1;
13137:                             $env{'form.archive_directory'} = [];
13138:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13139:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13140:                                 $path =~ s{/$}{};
13141:                                 my $item;
13142:                                 if ($path ne '') {
13143:                                     $item = "$path/$titles{$i}";
13144:                                 } else {
13145:                                     $item = $titles{$i};
13146:                                 }
13147:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13148:                                 if ($item eq $contents[0]) {
13149:                                     push(@{$env{'form.archive_directory'}},$i);
13150:                                     $env{'form.archive_'.$i} = 'display';
13151:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13152:                                     $displayed{'folder'} = $i;
13153:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13154:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13155:                                     $env{'form.archive_'.$i} = 'display';
13156:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13157:                                     $displayed{'web'} = $i;
13158:                                 } else {
13159:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13160:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13161:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13162:                                         push(@{$env{'form.archive_directory'}},$i);
13163:                                     }
13164:                                     $env{'form.archive_'.$i} = 'dependency';
13165:                                 }
13166:                                 $total ++;
13167:                             }
13168:                             for (my $i=1; $i<$total; $i++) {
13169:                                 next if ($i == $displayed{'web'});
13170:                                 next if ($i == $displayed{'folder'});
13171:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13172:                             }
13173:                             $env{'form.phase'} = 'decompress_cleanup';
13174:                             $env{'form.archivedelete'} = 1;
13175:                             $env{'form.archive_count'} = $total-1;
13176:                             $output .=
13177:                                 &process_extracted_files('coursedocs',$docudom,
13178:                                                          $docuname,$destination,
13179:                                                          $dir_root,$hiddenelem);
13180:                         }
13181:                     } else {
13182:                         $warning = &mt('No new items extracted from archive file.');
13183:                     }
13184:                 } else {
13185:                     $output = $display;
13186:                     $error = &mt('An error occurred during extraction from the archive file.');
13187:                 }
13188:             }
13189:         }
13190:     }
13191:     if ($error) {
13192:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13193:                    $error.'</p>'."\n";
13194:     }
13195:     if ($warning) {
13196:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13197:     }
13198:     return $output;
13199: }
13200: 
13201: sub get_extracted {
13202:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13203:         $titles,$wantform) = @_;
13204:     my $count = 0;
13205:     my $depth = 0;
13206:     my $datatable;
13207:     my @hierarchy;
13208:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13209:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13210:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13211:     foreach my $item (@{$contents}) {
13212:         $count ++;
13213:         @{$dirorder->{$count}} = @hierarchy;
13214:         $titles->{$count} = $item;
13215:         &archive_hierarchy($depth,$count,$parent,$children);
13216:         if ($wantform) {
13217:             $datatable .= &archive_row($is_dir->{$item},$item,
13218:                                        $currdir,$depth,$count);
13219:         }
13220:         if ($is_dir->{$item}) {
13221:             $depth ++;
13222:             push(@hierarchy,$count);
13223:             $parent->{$depth} = $count;
13224:             $datatable .=
13225:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13226:                                            \$depth,\$count,\@hierarchy,$dirorder,
13227:                                            $children,$parent,$titles,$wantform);
13228:             $depth --;
13229:             pop(@hierarchy);
13230:         }
13231:     }
13232:     return ($count,$datatable);
13233: }
13234: 
13235: sub recurse_extracted_archive {
13236:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13237:         $children,$parent,$titles,$wantform) = @_;
13238:     my $result='';
13239:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13240:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13241:             (ref($dirorder) eq 'HASH')) {
13242:         return $result;
13243:     }
13244:     my $dirptr = 16384;
13245:     my ($newdirlistref,$newlisterror) =
13246:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13247:     if (ref($newdirlistref) eq 'ARRAY') {
13248:         foreach my $dir_line (@{$newdirlistref}) {
13249:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13250:             unless ($item =~ /^\.+$/) {
13251:                 $$count ++;
13252:                 @{$dirorder->{$$count}} = @{$hierarchy};
13253:                 $titles->{$$count} = $item;
13254:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13255: 
13256:                 my $is_dir;
13257:                 if ($dirptr&$testdir) {
13258:                     $is_dir = 1;
13259:                 }
13260:                 if ($wantform) {
13261:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13262:                 }
13263:                 if ($is_dir) {
13264:                     $$depth ++;
13265:                     push(@{$hierarchy},$$count);
13266:                     $parent->{$$depth} = $$count;
13267:                     $result .=
13268:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13269:                                                    $docuname,$depth,$count,
13270:                                                    $hierarchy,$dirorder,$children,
13271:                                                    $parent,$titles,$wantform);
13272:                     $$depth --;
13273:                     pop(@{$hierarchy});
13274:                 }
13275:             }
13276:         }
13277:     }
13278:     return $result;
13279: }
13280: 
13281: sub archive_hierarchy {
13282:     my ($depth,$count,$parent,$children) =@_;
13283:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13284:         if (exists($parent->{$depth})) {
13285:              $children->{$parent->{$depth}} .= $count.':';
13286:         }
13287:     }
13288:     return;
13289: }
13290: 
13291: sub archive_row {
13292:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13293:     my ($name) = ($item =~ m{([^/]+)$});
13294:     my %choices = &Apache::lonlocal::texthash (
13295:                                        'display'    => 'Add as file',
13296:                                        'dependency' => 'Include as dependency',
13297:                                        'discard'    => 'Discard',
13298:                                       );
13299:     if ($is_dir) {
13300:         $choices{'display'} = &mt('Add as folder'); 
13301:     }
13302:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13303:     my $offset = 0;
13304:     foreach my $action ('display','dependency','discard') {
13305:         $offset ++;
13306:         if ($action ne 'display') {
13307:             $offset ++;
13308:         }  
13309:         $output .= '<td><span class="LC_nobreak">'.
13310:                    '<label><input type="radio" name="archive_'.$count.
13311:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13312:         my $text = $choices{$action};
13313:         if ($is_dir) {
13314:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13315:             if ($action eq 'display') {
13316:                 $text = &mt('Add as folder');
13317:             }
13318:         } else {
13319:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13320: 
13321:         }
13322:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13323:         if ($action eq 'dependency') {
13324:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13325:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13326:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13327:                        '<option value=""></option>'."\n".
13328:                        '</select>'."\n".
13329:                        '</div>';
13330:         } elsif ($action eq 'display') {
13331:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13332:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13333:                        '</div>';
13334:         }
13335:         $output .= '</td>';
13336:     }
13337:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13338:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13339:     for (my $i=0; $i<$depth; $i++) {
13340:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13341:     }
13342:     if ($is_dir) {
13343:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13344:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13345:     } else {
13346:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13347:     }
13348:     $output .= '&nbsp;'.$name.'</td>'."\n".
13349:                &end_data_table_row();
13350:     return $output;
13351: }
13352: 
13353: sub archive_options_form {
13354:     my ($form,$display,$count,$hiddenelem) = @_;
13355:     my %lt = &Apache::lonlocal::texthash(
13356:                perm => 'Permanently remove archive file?',
13357:                hows => 'How should each extracted item be incorporated in the course?',
13358:                cont => 'Content actions for all',
13359:                addf => 'Add as folder/file',
13360:                incd => 'Include as dependency for a displayed file',
13361:                disc => 'Discard',
13362:                no   => 'No',
13363:                yes  => 'Yes',
13364:                save => 'Save',
13365:     );
13366:     my $output = <<"END";
13367: <form name="$form" method="post" action="">
13368: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13369: <label>
13370:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13371: </label>
13372: &nbsp;
13373: <label>
13374:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13375: </span>
13376: </p>
13377: <input type="hidden" name="phase" value="decompress_cleanup" />
13378: <br />$lt{'hows'}
13379: <div class="LC_columnSection">
13380:   <fieldset>
13381:     <legend>$lt{'cont'}</legend>
13382:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13383:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13384:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13385:   </fieldset>
13386: </div>
13387: END
13388:     return $output.
13389:            &start_data_table()."\n".
13390:            $display."\n".
13391:            &end_data_table()."\n".
13392:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13393:            $hiddenelem.
13394:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13395:            '</form>';
13396: }
13397: 
13398: sub archive_javascript {
13399:     my ($startcount,$numitems,$titles,$children) = @_;
13400:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13401:     my $maintitle = $env{'form.comment'};
13402:     my $scripttag = <<START;
13403: <script type="text/javascript">
13404: // <![CDATA[
13405: 
13406: function checkAll(form,prefix) {
13407:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13408:     for (var i=0; i < form.elements.length; i++) {
13409:         var id = form.elements[i].id;
13410:         if ((id != '') && (id != undefined)) {
13411:             if (idstr.test(id)) {
13412:                 if (form.elements[i].type == 'radio') {
13413:                     form.elements[i].checked = true;
13414:                     var nostart = i-$startcount;
13415:                     var offset = nostart%7;
13416:                     var count = (nostart-offset)/7;    
13417:                     dependencyCheck(form,count,offset);
13418:                 }
13419:             }
13420:         }
13421:     }
13422: }
13423: 
13424: function propagateCheck(form,count) {
13425:     if (count > 0) {
13426:         var startelement = $startcount + ((count-1) * 7);
13427:         for (var j=1; j<6; j++) {
13428:             if ((j != 2) && (j != 4)) {
13429:                 var item = startelement + j; 
13430:                 if (form.elements[item].type == 'radio') {
13431:                     if (form.elements[item].checked) {
13432:                         containerCheck(form,count,j);
13433:                         break;
13434:                     }
13435:                 }
13436:             }
13437:         }
13438:     }
13439: }
13440: 
13441: numitems = $numitems
13442: var titles = new Array(numitems);
13443: var parents = new Array(numitems);
13444: for (var i=0; i<numitems; i++) {
13445:     parents[i] = new Array;
13446: }
13447: var maintitle = '$maintitle';
13448: 
13449: START
13450: 
13451:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13452:         my @contents = split(/:/,$children->{$container});
13453:         for (my $i=0; $i<@contents; $i ++) {
13454:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13455:         }
13456:     }
13457: 
13458:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13459:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13460:     }
13461: 
13462:     $scripttag .= <<END;
13463: 
13464: function containerCheck(form,count,offset) {
13465:     if (count > 0) {
13466:         dependencyCheck(form,count,offset);
13467:         var item = (offset+$startcount)+7*(count-1);
13468:         form.elements[item].checked = true;
13469:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13470:             if (parents[count].length > 0) {
13471:                 for (var j=0; j<parents[count].length; j++) {
13472:                     containerCheck(form,parents[count][j],offset);
13473:                 }
13474:             }
13475:         }
13476:     }
13477: }
13478: 
13479: function dependencyCheck(form,count,offset) {
13480:     if (count > 0) {
13481:         var chosen = (offset+$startcount)+7*(count-1);
13482:         var depitem = $startcount + ((count-1) * 7) + 4;
13483:         var currtype = form.elements[depitem].type;
13484:         if (form.elements[chosen].value == 'dependency') {
13485:             document.getElementById('arc_depon_'+count).style.display='block'; 
13486:             form.elements[depitem].options.length = 0;
13487:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13488:             for (var i=1; i<=numitems; i++) {
13489:                 if (i == count) {
13490:                     continue;
13491:                 }
13492:                 var startelement = $startcount + (i-1) * 7;
13493:                 for (var j=1; j<6; j++) {
13494:                     if ((j != 2) && (j!= 4)) {
13495:                         var item = startelement + j;
13496:                         if (form.elements[item].type == 'radio') {
13497:                             if (form.elements[item].checked) {
13498:                                 if (form.elements[item].value == 'display') {
13499:                                     var n = form.elements[depitem].options.length;
13500:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13501:                                 }
13502:                             }
13503:                         }
13504:                     }
13505:                 }
13506:             }
13507:         } else {
13508:             document.getElementById('arc_depon_'+count).style.display='none';
13509:             form.elements[depitem].options.length = 0;
13510:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13511:         }
13512:         titleCheck(form,count,offset);
13513:     }
13514: }
13515: 
13516: function propagateSelect(form,count,offset) {
13517:     if (count > 0) {
13518:         var item = (1+offset+$startcount)+7*(count-1);
13519:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13520:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13521:             if (parents[count].length > 0) {
13522:                 for (var j=0; j<parents[count].length; j++) {
13523:                     containerSelect(form,parents[count][j],offset,picked);
13524:                 }
13525:             }
13526:         }
13527:     }
13528: }
13529: 
13530: function containerSelect(form,count,offset,picked) {
13531:     if (count > 0) {
13532:         var item = (offset+$startcount)+7*(count-1);
13533:         if (form.elements[item].type == 'radio') {
13534:             if (form.elements[item].value == 'dependency') {
13535:                 if (form.elements[item+1].type == 'select-one') {
13536:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13537:                         if (form.elements[item+1].options[i].value == picked) {
13538:                             form.elements[item+1].selectedIndex = i;
13539:                             break;
13540:                         }
13541:                     }
13542:                 }
13543:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13544:                     if (parents[count].length > 0) {
13545:                         for (var j=0; j<parents[count].length; j++) {
13546:                             containerSelect(form,parents[count][j],offset,picked);
13547:                         }
13548:                     }
13549:                 }
13550:             }
13551:         }
13552:     }
13553: }
13554: 
13555: function titleCheck(form,count,offset) {
13556:     if (count > 0) {
13557:         var chosen = (offset+$startcount)+7*(count-1);
13558:         var depitem = $startcount + ((count-1) * 7) + 2;
13559:         var currtype = form.elements[depitem].type;
13560:         if (form.elements[chosen].value == 'display') {
13561:             document.getElementById('arc_title_'+count).style.display='block';
13562:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13563:                 document.getElementById('archive_title_'+count).value=maintitle;
13564:             }
13565:         } else {
13566:             document.getElementById('arc_title_'+count).style.display='none';
13567:             if (currtype == 'text') { 
13568:                 document.getElementById('archive_title_'+count).value='';
13569:             }
13570:         }
13571:     }
13572:     return;
13573: }
13574: 
13575: // ]]>
13576: </script>
13577: END
13578:     return $scripttag;
13579: }
13580: 
13581: sub process_extracted_files {
13582:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13583:     my $numitems = $env{'form.archive_count'};
13584:     return if ((!$numitems) || ($numitems =~ /\D/));
13585:     my @ids=&Apache::lonnet::current_machine_ids();
13586:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13587:         %folders,%containers,%mapinner,%prompttofetch);
13588:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13589:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13590:         $prefix = &LONCAPA::propath($docudom,$docuname);
13591:         $pathtocheck = "$dir_root/$destination";
13592:         $dir = $dir_root;
13593:         $ishome = 1;
13594:     } else {
13595:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13596:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13597:         $dir = "$dir_root/$docudom/$docuname";
13598:     }
13599:     my $currdir = "$dir_root/$destination";
13600:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13601:     if ($env{'form.folderpath'}) {
13602:         my @items = split('&',$env{'form.folderpath'});
13603:         $folders{'0'} = $items[-2];
13604:         if ($env{'form.folderpath'} =~ /\:1$/) {
13605:             $containers{'0'}='page';
13606:         } else {  
13607:             $containers{'0'}='sequence';
13608:         }
13609:     }
13610:     my @archdirs = &get_env_multiple('form.archive_directory');
13611:     if ($numitems) {
13612:         for (my $i=1; $i<=$numitems; $i++) {
13613:             my $path = $env{'form.archive_content_'.$i};
13614:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13615:                 my $item = $1;
13616:                 $toplevelitems{$item} = $i;
13617:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13618:                     $is_dir{$item} = 1;
13619:                 }
13620:             }
13621:         }
13622:     }
13623:     my ($output,%children,%parent,%titles,%dirorder,$result);
13624:     if (keys(%toplevelitems) > 0) {
13625:         my @contents = sort(keys(%toplevelitems));
13626:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13627:                                            \%parent,\@contents,\%dirorder,\%titles);
13628:     }
13629:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13630:     if ($numitems) {
13631:         for (my $i=1; $i<=$numitems; $i++) {
13632:             next if ($env{'form.archive_'.$i} eq 'dependency');
13633:             my $path = $env{'form.archive_content_'.$i};
13634:             if ($path =~ /^\Q$pathtocheck\E/) {
13635:                 if ($env{'form.archive_'.$i} eq 'discard') {
13636:                     if ($prefix ne '' && $path ne '') {
13637:                         if (-e $prefix.$path) {
13638:                             if ((@archdirs > 0) && 
13639:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13640:                                 $todeletedir{$prefix.$path} = 1;
13641:                             } else {
13642:                                 $todelete{$prefix.$path} = 1;
13643:                             }
13644:                         }
13645:                     }
13646:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13647:                     my ($docstitle,$title,$url,$outer);
13648:                     ($title) = ($path =~ m{/([^/]+)$});
13649:                     $docstitle = $env{'form.archive_title_'.$i};
13650:                     if ($docstitle eq '') {
13651:                         $docstitle = $title;
13652:                     }
13653:                     $outer = 0;
13654:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13655:                         if (@{$dirorder{$i}} > 0) {
13656:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13657:                                 if ($env{'form.archive_'.$item} eq 'display') {
13658:                                     $outer = $item;
13659:                                     last;
13660:                                 }
13661:                             }
13662:                         }
13663:                     }
13664:                     my ($errtext,$fatal) = 
13665:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13666:                                                '/'.$folders{$outer}.'.'.
13667:                                                $containers{$outer});
13668:                     next if ($fatal);
13669:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13670:                         if ($context eq 'coursedocs') {
13671:                             $mapinner{$i} = time;
13672:                             $folders{$i} = 'default_'.$mapinner{$i};
13673:                             $containers{$i} = 'sequence';
13674:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13675:                                       $folders{$i}.'.'.$containers{$i};
13676:                             my $newidx = &LONCAPA::map::getresidx();
13677:                             $LONCAPA::map::resources[$newidx]=
13678:                                 $docstitle.':'.$url.':false:normal:res';
13679:                             push(@LONCAPA::map::order,$newidx);
13680:                             my ($outtext,$errtext) =
13681:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13682:                                                         $docuname.'/'.$folders{$outer}.
13683:                                                         '.'.$containers{$outer},1,1);
13684:                             $newseqid{$i} = $newidx;
13685:                             unless ($errtext) {
13686:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13687:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
13688:                                             '</li>'."\n";
13689:                             }
13690:                         }
13691:                     } else {
13692:                         if ($context eq 'coursedocs') {
13693:                             my $newidx=&LONCAPA::map::getresidx();
13694:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13695:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13696:                                       $title;
13697:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13698:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13699:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13700:                                 }
13701:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13702:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13703:                                 }
13704:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13705:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13706:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13707:                                         unless ($ishome) {
13708:                                             my $fetch = "$newdest{$i}/$title";
13709:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13710:                                             $prompttofetch{$fetch} = 1;
13711:                                         }
13712:                                     }
13713:                                 }
13714:                                 $LONCAPA::map::resources[$newidx]=
13715:                                     $docstitle.':'.$url.':false:normal:res';
13716:                                 push(@LONCAPA::map::order, $newidx);
13717:                                 my ($outtext,$errtext)=
13718:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13719:                                                             $docuname.'/'.$folders{$outer}.
13720:                                                             '.'.$containers{$outer},1,1);
13721:                                 unless ($errtext) {
13722:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13723:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13724:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13725:                                                    '</li>'."\n";
13726:                                     }
13727:                                 }
13728:                             } else {
13729:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13730:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13731:                             }
13732:                         }
13733:                     }
13734:                 }
13735:             } else {
13736:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13737:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
13738:             }
13739:         }
13740:         for (my $i=1; $i<=$numitems; $i++) {
13741:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13742:             my $path = $env{'form.archive_content_'.$i};
13743:             if ($path =~ /^\Q$pathtocheck\E/) {
13744:                 my ($title) = ($path =~ m{/([^/]+)$});
13745:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13746:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13747:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13748:                         my ($itemidx,$fullpath,$relpath);
13749:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13750:                             my $container = $dirorder{$referrer{$i}}->[-1];
13751:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13752:                                 if ($dirorder{$i}->[$j] eq $container) {
13753:                                     $itemidx = $j;
13754:                                 }
13755:                             }
13756:                         }
13757:                         if ($itemidx eq '') {
13758:                             $itemidx =  0;
13759:                         } 
13760:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13761:                             if ($mapinner{$referrer{$i}}) {
13762:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13763:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13764:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13765:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13766:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13767:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13768:                                             if (!-e $fullpath) {
13769:                                                 mkdir($fullpath,0755);
13770:                                             }
13771:                                         }
13772:                                     } else {
13773:                                         last;
13774:                                     }
13775:                                 }
13776:                             }
13777:                         } elsif ($newdest{$referrer{$i}}) {
13778:                             $fullpath = $newdest{$referrer{$i}};
13779:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13780:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13781:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13782:                                     last;
13783:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13784:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13785:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13786:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13787:                                         if (!-e $fullpath) {
13788:                                             mkdir($fullpath,0755);
13789:                                         }
13790:                                     }
13791:                                 } else {
13792:                                     last;
13793:                                 }
13794:                             }
13795:                         }
13796:                         if ($fullpath ne '') {
13797:                             if (-e "$prefix$path") {
13798:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13799:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13800:                                 }
13801:                             }
13802:                             if (-e "$fullpath/$title") {
13803:                                 my $showpath;
13804:                                 if ($relpath ne '') {
13805:                                     $showpath = "$relpath/$title";
13806:                                 } else {
13807:                                     $showpath = "/$title";
13808:                                 } 
13809:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13810:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13811:                                            '</li>'."\n";
13812:                                 unless ($ishome) {
13813:                                     my $fetch = "$fullpath/$title";
13814:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
13815:                                     $prompttofetch{$fetch} = 1;
13816:                                 }
13817:                             }
13818:                         }
13819:                     }
13820:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13821:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13822:                                     &HTML::Entities::encode($path,'<>&"'),
13823:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13824:                                 '<br />';
13825:                 }
13826:             } else {
13827:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13828:                                 &HTML::Entities::encode($path)).'<br />';
13829:             }
13830:         }
13831:         if (keys(%todelete)) {
13832:             foreach my $key (keys(%todelete)) {
13833:                 unlink($key);
13834:             }
13835:         }
13836:         if (keys(%todeletedir)) {
13837:             foreach my $key (keys(%todeletedir)) {
13838:                 rmdir($key);
13839:             }
13840:         }
13841:         foreach my $dir (sort(keys(%is_dir))) {
13842:             if (($pathtocheck ne '') && ($dir ne ''))  {
13843:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13844:             }
13845:         }
13846:         if ($result ne '') {
13847:             $output .= '<ul>'."\n".
13848:                        $result."\n".
13849:                        '</ul>';
13850:         }
13851:         unless ($ishome) {
13852:             my $replicationfail;
13853:             foreach my $item (keys(%prompttofetch)) {
13854:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13855:                 unless ($fetchresult eq 'ok') {
13856:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13857:                 }
13858:             }
13859:             if ($replicationfail) {
13860:                 $output .= '<p class="LC_error">'.
13861:                            &mt('Course home server failed to retrieve:').'<ul>'.
13862:                            $replicationfail.
13863:                            '</ul></p>';
13864:             }
13865:         }
13866:     } else {
13867:         $warning = &mt('No items found in archive.');
13868:     }
13869:     if ($error) {
13870:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13871:                    $error.'</p>'."\n";
13872:     }
13873:     if ($warning) {
13874:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13875:     }
13876:     return $output;
13877: }
13878: 
13879: sub cleanup_empty_dirs {
13880:     my ($path) = @_;
13881:     if (($path ne '') && (-d $path)) {
13882:         if (opendir(my $dirh,$path)) {
13883:             my @dircontents = grep(!/^\./,readdir($dirh));
13884:             my $numitems = 0;
13885:             foreach my $item (@dircontents) {
13886:                 if (-d "$path/$item") {
13887:                     &cleanup_empty_dirs("$path/$item");
13888:                     if (-e "$path/$item") {
13889:                         $numitems ++;
13890:                     }
13891:                 } else {
13892:                     $numitems ++;
13893:                 }
13894:             }
13895:             if ($numitems == 0) {
13896:                 rmdir($path);
13897:             }
13898:             closedir($dirh);
13899:         }
13900:     }
13901:     return;
13902: }
13903: 
13904: =pod
13905: 
13906: =item * &get_folder_hierarchy()
13907: 
13908: Provides hierarchy of names of folders/sub-folders containing the current
13909: item,
13910: 
13911: Inputs: 3
13912:      - $navmap - navmaps object
13913: 
13914:      - $map - url for map (either the trigger itself, or map containing
13915:                            the resource, which is the trigger).
13916: 
13917:      - $showitem - 1 => show title for map itself; 0 => do not show.
13918: 
13919: Outputs: 1 @pathitems - array of folder/subfolder names.
13920: 
13921: =cut
13922: 
13923: sub get_folder_hierarchy {
13924:     my ($navmap,$map,$showitem) = @_;
13925:     my @pathitems;
13926:     if (ref($navmap)) {
13927:         my $mapres = $navmap->getResourceByUrl($map);
13928:         if (ref($mapres)) {
13929:             my $pcslist = $mapres->map_hierarchy();
13930:             if ($pcslist ne '') {
13931:                 my @pcs = split(/,/,$pcslist);
13932:                 foreach my $pc (@pcs) {
13933:                     if ($pc == 1) {
13934:                         push(@pathitems,&mt('Main Content'));
13935:                     } else {
13936:                         my $res = $navmap->getByMapPc($pc);
13937:                         if (ref($res)) {
13938:                             my $title = $res->compTitle();
13939:                             $title =~ s/\W+/_/g;
13940:                             if ($title ne '') {
13941:                                 push(@pathitems,$title);
13942:                             }
13943:                         }
13944:                     }
13945:                 }
13946:             }
13947:             if ($showitem) {
13948:                 if ($mapres->{ID} eq '0.0') {
13949:                     push(@pathitems,&mt('Main Content'));
13950:                 } else {
13951:                     my $maptitle = $mapres->compTitle();
13952:                     $maptitle =~ s/\W+/_/g;
13953:                     if ($maptitle ne '') {
13954:                         push(@pathitems,$maptitle);
13955:                     }
13956:                 }
13957:             }
13958:         }
13959:     }
13960:     return @pathitems;
13961: }
13962: 
13963: =pod
13964: 
13965: =item * &get_turnedin_filepath()
13966: 
13967: Determines path in a user's portfolio file for storage of files uploaded
13968: to a specific essayresponse or dropbox item.
13969: 
13970: Inputs: 3 required + 1 optional.
13971: $symb is symb for resource, $uname and $udom are for current user (required).
13972: $caller is optional (can be "submission", if routine is called when storing
13973: an upoaded file when "Submit Answer" button was pressed).
13974: 
13975: Returns array containing $path and $multiresp. 
13976: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13977: than one file upload item.  Callers of routine should append partid as a 
13978: subdirectory to $path in cases where $multiresp is 1.
13979: 
13980: Called by: homework/essayresponse.pm and homework/structuretags.pm
13981: 
13982: =cut
13983: 
13984: sub get_turnedin_filepath {
13985:     my ($symb,$uname,$udom,$caller) = @_;
13986:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13987:     my $turnindir;
13988:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13989:     $turnindir = $userhash{'turnindir'};
13990:     my ($path,$multiresp);
13991:     if ($turnindir eq '') {
13992:         if ($caller eq 'submission') {
13993:             $turnindir = &mt('turned in');
13994:             $turnindir =~ s/\W+/_/g;
13995:             my %newhash = (
13996:                             'turnindir' => $turnindir,
13997:                           );
13998:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13999:         }
14000:     }
14001:     if ($turnindir ne '') {
14002:         $path = '/'.$turnindir.'/';
14003:         my ($multipart,$turnin,@pathitems);
14004:         my $navmap = Apache::lonnavmaps::navmap->new();
14005:         if (defined($navmap)) {
14006:             my $mapres = $navmap->getResourceByUrl($map);
14007:             if (ref($mapres)) {
14008:                 my $pcslist = $mapres->map_hierarchy();
14009:                 if ($pcslist ne '') {
14010:                     foreach my $pc (split(/,/,$pcslist)) {
14011:                         my $res = $navmap->getByMapPc($pc);
14012:                         if (ref($res)) {
14013:                             my $title = $res->compTitle();
14014:                             $title =~ s/\W+/_/g;
14015:                             if ($title ne '') {
14016:                                 if (($pc > 1) && (length($title) > 12)) {
14017:                                     $title = substr($title,0,12);
14018:                                 }
14019:                                 push(@pathitems,$title);
14020:                             }
14021:                         }
14022:                     }
14023:                 }
14024:                 my $maptitle = $mapres->compTitle();
14025:                 $maptitle =~ s/\W+/_/g;
14026:                 if ($maptitle ne '') {
14027:                     if (length($maptitle) > 12) {
14028:                         $maptitle = substr($maptitle,0,12);
14029:                     }
14030:                     push(@pathitems,$maptitle);
14031:                 }
14032:                 unless ($env{'request.state'} eq 'construct') {
14033:                     my $res = $navmap->getBySymb($symb);
14034:                     if (ref($res)) {
14035:                         my $partlist = $res->parts();
14036:                         my $totaluploads = 0;
14037:                         if (ref($partlist) eq 'ARRAY') {
14038:                             foreach my $part (@{$partlist}) {
14039:                                 my @types = $res->responseType($part);
14040:                                 my @ids = $res->responseIds($part);
14041:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14042:                                     if ($types[$i] eq 'essay') {
14043:                                         my $partid = $part.'_'.$ids[$i];
14044:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14045:                                             $totaluploads ++;
14046:                                         }
14047:                                     }
14048:                                 }
14049:                             }
14050:                             if ($totaluploads > 1) {
14051:                                 $multiresp = 1;
14052:                             }
14053:                         }
14054:                     }
14055:                 }
14056:             } else {
14057:                 return;
14058:             }
14059:         } else {
14060:             return;
14061:         }
14062:         my $restitle=&Apache::lonnet::gettitle($symb);
14063:         $restitle =~ s/\W+/_/g;
14064:         if ($restitle eq '') {
14065:             $restitle = ($resurl =~ m{/[^/]+$});
14066:             if ($restitle eq '') {
14067:                 $restitle = time;
14068:             }
14069:         }
14070:         if (length($restitle) > 12) {
14071:             $restitle = substr($restitle,0,12);
14072:         }
14073:         push(@pathitems,$restitle);
14074:         $path .= join('/',@pathitems);
14075:     }
14076:     return ($path,$multiresp);
14077: }
14078: 
14079: =pod
14080: 
14081: =back
14082: 
14083: =head1 CSV Upload/Handling functions
14084: 
14085: =over 4
14086: 
14087: =item * &upfile_store($r)
14088: 
14089: Store uploaded file, $r should be the HTTP Request object,
14090: needs $env{'form.upfile'}
14091: returns $datatoken to be put into hidden field
14092: 
14093: =cut
14094: 
14095: sub upfile_store {
14096:     my $r=shift;
14097:     $env{'form.upfile'}=~s/\r/\n/gs;
14098:     $env{'form.upfile'}=~s/\f/\n/gs;
14099:     $env{'form.upfile'}=~s/\n+/\n/gs;
14100:     $env{'form.upfile'}=~s/\n+$//gs;
14101: 
14102:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14103:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14104:                                      time.'_'.$$);
14105:     return if ($datatoken eq '');
14106: 
14107:     {
14108:         my $datafile = $r->dir_config('lonDaemons').
14109:                            '/tmp/'.$datatoken.'.tmp';
14110:         if ( open(my $fh,'>',$datafile) ) {
14111:             print $fh $env{'form.upfile'};
14112:             close($fh);
14113:         }
14114:     }
14115:     return $datatoken;
14116: }
14117: 
14118: =pod
14119: 
14120: =item * &load_tmp_file($r,$datatoken)
14121: 
14122: Load uploaded file from tmp, $r should be the HTTP Request object,
14123: $datatoken is the name to assign to the temporary file.
14124: sets $env{'form.upfile'} to the contents of the file
14125: 
14126: =cut
14127: 
14128: sub load_tmp_file {
14129:     my ($r,$datatoken) = @_;
14130:     return if ($datatoken eq '');
14131:     my @studentdata=();
14132:     {
14133:         my $studentfile = $r->dir_config('lonDaemons').
14134:                               '/tmp/'.$datatoken.'.tmp';
14135:         if ( open(my $fh,'<',$studentfile) ) {
14136:             @studentdata=<$fh>;
14137:             close($fh);
14138:         }
14139:     }
14140:     $env{'form.upfile'}=join('',@studentdata);
14141: }
14142: 
14143: sub valid_datatoken {
14144:     my ($datatoken) = @_;
14145:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14146:         return $datatoken;
14147:     }
14148:     return;
14149: }
14150: 
14151: =pod
14152: 
14153: =item * &upfile_record_sep()
14154: 
14155: Separate uploaded file into records
14156: returns array of records,
14157: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14158: 
14159: =cut
14160: 
14161: sub upfile_record_sep {
14162:     if ($env{'form.upfiletype'} eq 'xml') {
14163:     } else {
14164: 	my @records;
14165: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14166: 	    if ($line=~/^\s*$/) { next; }
14167: 	    push(@records,$line);
14168: 	}
14169: 	return @records;
14170:     }
14171: }
14172: 
14173: =pod
14174: 
14175: =item * &record_sep($record)
14176: 
14177: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14178: 
14179: =cut
14180: 
14181: sub takeleft {
14182:     my $index=shift;
14183:     return substr('0000'.$index,-4,4);
14184: }
14185: 
14186: sub record_sep {
14187:     my $record=shift;
14188:     my %components=();
14189:     if ($env{'form.upfiletype'} eq 'xml') {
14190:     } elsif ($env{'form.upfiletype'} eq 'space') {
14191:         my $i=0;
14192:         foreach my $field (split(/\s+/,$record)) {
14193:             $field=~s/^(\"|\')//;
14194:             $field=~s/(\"|\')$//;
14195:             $components{&takeleft($i)}=$field;
14196:             $i++;
14197:         }
14198:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14199:         my $i=0;
14200:         foreach my $field (split(/\t/,$record)) {
14201:             $field=~s/^(\"|\')//;
14202:             $field=~s/(\"|\')$//;
14203:             $components{&takeleft($i)}=$field;
14204:             $i++;
14205:         }
14206:     } else {
14207:         my $separator=',';
14208:         if ($env{'form.upfiletype'} eq 'semisv') {
14209:             $separator=';';
14210:         }
14211:         my $i=0;
14212: # the character we are looking for to indicate the end of a quote or a record 
14213:         my $looking_for=$separator;
14214: # do not add the characters to the fields
14215:         my $ignore=0;
14216: # we just encountered a separator (or the beginning of the record)
14217:         my $just_found_separator=1;
14218: # store the field we are working on here
14219:         my $field='';
14220: # work our way through all characters in record
14221:         foreach my $character ($record=~/(.)/g) {
14222:             if ($character eq $looking_for) {
14223:                if ($character ne $separator) {
14224: # Found the end of a quote, again looking for separator
14225:                   $looking_for=$separator;
14226:                   $ignore=1;
14227:                } else {
14228: # Found a separator, store away what we got
14229:                   $components{&takeleft($i)}=$field;
14230: 	          $i++;
14231:                   $just_found_separator=1;
14232:                   $ignore=0;
14233:                   $field='';
14234:                }
14235:                next;
14236:             }
14237: # single or double quotation marks after a separator indicate beginning of a quote
14238: # we are now looking for the end of the quote and need to ignore separators
14239:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14240:                $looking_for=$character;
14241:                next;
14242:             }
14243: # ignore would be true after we reached the end of a quote
14244:             if ($ignore) { next; }
14245:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14246:             $field.=$character;
14247:             $just_found_separator=0; 
14248:         }
14249: # catch the very last entry, since we never encountered the separator
14250:         $components{&takeleft($i)}=$field;
14251:     }
14252:     return %components;
14253: }
14254: 
14255: ######################################################
14256: ######################################################
14257: 
14258: =pod
14259: 
14260: =item * &upfile_select_html()
14261: 
14262: Return HTML code to select a file from the users machine and specify 
14263: the file type.
14264: 
14265: =cut
14266: 
14267: ######################################################
14268: ######################################################
14269: sub upfile_select_html {
14270:     my %Types = (
14271:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14272:                  semisv => &mt('Semicolon separated values'),
14273:                  space => &mt('Space separated'),
14274:                  tab   => &mt('Tabulator separated'),
14275: #                 xml   => &mt('HTML/XML'),
14276:                  );
14277:     my $Str = '<input type="file" name="upfile" size="50" />'.
14278:         '<br />'.&mt('Type').': <select name="upfiletype">';
14279:     foreach my $type (sort(keys(%Types))) {
14280:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14281:     }
14282:     $Str .= "</select>\n";
14283:     return $Str;
14284: }
14285: 
14286: sub get_samples {
14287:     my ($records,$toget) = @_;
14288:     my @samples=({});
14289:     my $got=0;
14290:     foreach my $rec (@$records) {
14291: 	my %temp = &record_sep($rec);
14292: 	if (! grep(/\S/, values(%temp))) { next; }
14293: 	if (%temp) {
14294: 	    $samples[$got]=\%temp;
14295: 	    $got++;
14296: 	    if ($got == $toget) { last; }
14297: 	}
14298:     }
14299:     return \@samples;
14300: }
14301: 
14302: ######################################################
14303: ######################################################
14304: 
14305: =pod
14306: 
14307: =item * &csv_print_samples($r,$records)
14308: 
14309: Prints a table of sample values from each column uploaded $r is an
14310: Apache Request ref, $records is an arrayref from
14311: &Apache::loncommon::upfile_record_sep
14312: 
14313: =cut
14314: 
14315: ######################################################
14316: ######################################################
14317: sub csv_print_samples {
14318:     my ($r,$records) = @_;
14319:     my $samples = &get_samples($records,5);
14320: 
14321:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14322:               &start_data_table_header_row());
14323:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14324:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14325:     $r->print(&end_data_table_header_row());
14326:     foreach my $hash (@$samples) {
14327: 	$r->print(&start_data_table_row());
14328: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14329: 	    $r->print('<td>');
14330: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14331: 	    $r->print('</td>');
14332: 	}
14333: 	$r->print(&end_data_table_row());
14334:     }
14335:     $r->print(&end_data_table().'<br />'."\n");
14336: }
14337: 
14338: ######################################################
14339: ######################################################
14340: 
14341: =pod
14342: 
14343: =item * &csv_print_select_table($r,$records,$d)
14344: 
14345: Prints a table to create associations between values and table columns.
14346: 
14347: $r is an Apache Request ref,
14348: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14349: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14350: 
14351: =cut
14352: 
14353: ######################################################
14354: ######################################################
14355: sub csv_print_select_table {
14356:     my ($r,$records,$d) = @_;
14357:     my $i=0;
14358:     my $samples = &get_samples($records,1);
14359:     $r->print(&mt('Associate columns with student attributes.')."\n".
14360: 	      &start_data_table().&start_data_table_header_row().
14361:               '<th>'.&mt('Attribute').'</th>'.
14362:               '<th>'.&mt('Column').'</th>'.
14363:               &end_data_table_header_row()."\n");
14364:     foreach my $array_ref (@$d) {
14365: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14366: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14367: 
14368: 	$r->print('<td><select name="f'.$i.'"'.
14369: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14370: 	$r->print('<option value="none"></option>');
14371: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14372: 	    $r->print('<option value="'.$sample.'"'.
14373:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14374:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14375: 	}
14376: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14377: 	$i++;
14378:     }
14379:     $r->print(&end_data_table());
14380:     $i--;
14381:     return $i;
14382: }
14383: 
14384: ######################################################
14385: ######################################################
14386: 
14387: =pod
14388: 
14389: =item * &csv_samples_select_table($r,$records,$d)
14390: 
14391: Prints a table of sample values from the upload and can make associate samples to internal names.
14392: 
14393: $r is an Apache Request ref,
14394: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14395: $d is an array of 2 element arrays (internal name, displayed name)
14396: 
14397: =cut
14398: 
14399: ######################################################
14400: ######################################################
14401: sub csv_samples_select_table {
14402:     my ($r,$records,$d) = @_;
14403:     my $i=0;
14404:     #
14405:     my $max_samples = 5;
14406:     my $samples = &get_samples($records,$max_samples);
14407:     $r->print(&start_data_table().
14408:               &start_data_table_header_row().'<th>'.
14409:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14410:               &end_data_table_header_row());
14411: 
14412:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14413: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14414: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14415: 	foreach my $option (@$d) {
14416: 	    my ($value,$display,$defaultcol)=@{ $option };
14417: 	    $r->print('<option value="'.$value.'"'.
14418:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14419:                       $display.'</option>');
14420: 	}
14421: 	$r->print('</select></td><td>');
14422: 	foreach my $line (0..($max_samples-1)) {
14423: 	    if (defined($samples->[$line]{$key})) { 
14424: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14425: 	    }
14426: 	}
14427: 	$r->print('</td>'.&end_data_table_row());
14428: 	$i++;
14429:     }
14430:     $r->print(&end_data_table());
14431:     $i--;
14432:     return($i);
14433: }
14434: 
14435: ######################################################
14436: ######################################################
14437: 
14438: =pod
14439: 
14440: =item * &clean_excel_name($name)
14441: 
14442: Returns a replacement for $name which does not contain any illegal characters.
14443: 
14444: =cut
14445: 
14446: ######################################################
14447: ######################################################
14448: sub clean_excel_name {
14449:     my ($name) = @_;
14450:     $name =~ s/[:\*\?\/\\]//g;
14451:     if (length($name) > 31) {
14452:         $name = substr($name,0,31);
14453:     }
14454:     return $name;
14455: }
14456: 
14457: =pod
14458: 
14459: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14460: 
14461: Returns either 1 or undef
14462: 
14463: 1 if the part is to be hidden, undef if it is to be shown
14464: 
14465: Arguments are:
14466: 
14467: $id the id of the part to be checked
14468: $symb, optional the symb of the resource to check
14469: $udom, optional the domain of the user to check for
14470: $uname, optional the username of the user to check for
14471: 
14472: =cut
14473: 
14474: sub check_if_partid_hidden {
14475:     my ($id,$symb,$udom,$uname) = @_;
14476:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14477: 					 $symb,$udom,$uname);
14478:     my $truth=1;
14479:     #if the string starts with !, then the list is the list to show not hide
14480:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14481:     my @hiddenlist=split(/,/,$hiddenparts);
14482:     foreach my $checkid (@hiddenlist) {
14483: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14484:     }
14485:     return !$truth;
14486: }
14487: 
14488: 
14489: ############################################################
14490: ############################################################
14491: 
14492: =pod
14493: 
14494: =back 
14495: 
14496: =head1 cgi-bin script and graphing routines
14497: 
14498: =over 4
14499: 
14500: =item * &get_cgi_id()
14501: 
14502: Inputs: none
14503: 
14504: Returns an id which can be used to pass environment variables
14505: to various cgi-bin scripts.  These environment variables will
14506: be removed from the users environment after a given time by
14507: the routine &Apache::lonnet::transfer_profile_to_env.
14508: 
14509: =cut
14510: 
14511: ############################################################
14512: ############################################################
14513: my $uniq=0;
14514: sub get_cgi_id {
14515:     $uniq=($uniq+1)%100000;
14516:     return (time.'_'.$$.'_'.$uniq);
14517: }
14518: 
14519: ############################################################
14520: ############################################################
14521: 
14522: =pod
14523: 
14524: =item * &DrawBarGraph()
14525: 
14526: Facilitates the plotting of data in a (stacked) bar graph.
14527: Puts plot definition data into the users environment in order for 
14528: graph.png to plot it.  Returns an <img> tag for the plot.
14529: The bars on the plot are labeled '1','2',...,'n'.
14530: 
14531: Inputs:
14532: 
14533: =over 4
14534: 
14535: =item $Title: string, the title of the plot
14536: 
14537: =item $xlabel: string, text describing the X-axis of the plot
14538: 
14539: =item $ylabel: string, text describing the Y-axis of the plot
14540: 
14541: =item $Max: scalar, the maximum Y value to use in the plot
14542: If $Max is < any data point, the graph will not be rendered.
14543: 
14544: =item $colors: array ref holding the colors to be used for the data sets when
14545: they are plotted.  If undefined, default values will be used.
14546: 
14547: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14548: 
14549: =item @Values: An array of array references.  Each array reference holds data
14550: to be plotted in a stacked bar chart.
14551: 
14552: =item If the final element of @Values is a hash reference the key/value
14553: pairs will be added to the graph definition.
14554: 
14555: =back
14556: 
14557: Returns:
14558: 
14559: An <img> tag which references graph.png and the appropriate identifying
14560: information for the plot.
14561: 
14562: =cut
14563: 
14564: ############################################################
14565: ############################################################
14566: sub DrawBarGraph {
14567:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14568:     #
14569:     if (! defined($colors)) {
14570:         $colors = ['#33ff00', 
14571:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14572:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14573:                   ]; 
14574:     }
14575:     my $extra_settings = {};
14576:     if (ref($Values[-1]) eq 'HASH') {
14577:         $extra_settings = pop(@Values);
14578:     }
14579:     #
14580:     my $identifier = &get_cgi_id();
14581:     my $id = 'cgi.'.$identifier;        
14582:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14583:         return '';
14584:     }
14585:     #
14586:     my @Labels;
14587:     if (defined($labels)) {
14588:         @Labels = @$labels;
14589:     } else {
14590:         for (my $i=0;$i<@{$Values[0]};$i++) {
14591:             push(@Labels,$i+1);
14592:         }
14593:     }
14594:     #
14595:     my $NumBars = scalar(@{$Values[0]});
14596:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14597:     my %ValuesHash;
14598:     my $NumSets=1;
14599:     foreach my $array (@Values) {
14600:         next if (! ref($array));
14601:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14602:             join(',',@$array);
14603:     }
14604:     #
14605:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14606:     if ($NumBars < 3) {
14607:         $width = 120+$NumBars*32;
14608:         $xskip = 1;
14609:         $bar_width = 30;
14610:     } elsif ($NumBars < 5) {
14611:         $width = 120+$NumBars*20;
14612:         $xskip = 1;
14613:         $bar_width = 20;
14614:     } elsif ($NumBars < 10) {
14615:         $width = 120+$NumBars*15;
14616:         $xskip = 1;
14617:         $bar_width = 15;
14618:     } elsif ($NumBars <= 25) {
14619:         $width = 120+$NumBars*11;
14620:         $xskip = 5;
14621:         $bar_width = 8;
14622:     } elsif ($NumBars <= 50) {
14623:         $width = 120+$NumBars*8;
14624:         $xskip = 5;
14625:         $bar_width = 4;
14626:     } else {
14627:         $width = 120+$NumBars*8;
14628:         $xskip = 5;
14629:         $bar_width = 4;
14630:     }
14631:     #
14632:     $Max = 1 if ($Max < 1);
14633:     if ( int($Max) < $Max ) {
14634:         $Max++;
14635:         $Max = int($Max);
14636:     }
14637:     $Title  = '' if (! defined($Title));
14638:     $xlabel = '' if (! defined($xlabel));
14639:     $ylabel = '' if (! defined($ylabel));
14640:     $ValuesHash{$id.'.title'}    = &escape($Title);
14641:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14642:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14643:     $ValuesHash{$id.'.y_max_value'} = $Max;
14644:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14645:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14646:     $ValuesHash{$id.'.PlotType'} = 'bar';
14647:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14648:     $ValuesHash{$id.'.height'}   = $height;
14649:     $ValuesHash{$id.'.width'}    = $width;
14650:     $ValuesHash{$id.'.xskip'}    = $xskip;
14651:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14652:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14653:     #
14654:     # Deal with other parameters
14655:     while (my ($key,$value) = each(%$extra_settings)) {
14656:         $ValuesHash{$id.'.'.$key} = $value;
14657:     }
14658:     #
14659:     &Apache::lonnet::appenv(\%ValuesHash);
14660:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14661: }
14662: 
14663: ############################################################
14664: ############################################################
14665: 
14666: =pod
14667: 
14668: =item * &DrawXYGraph()
14669: 
14670: Facilitates the plotting of data in an XY graph.
14671: Puts plot definition data into the users environment in order for 
14672: graph.png to plot it.  Returns an <img> tag for the plot.
14673: 
14674: Inputs:
14675: 
14676: =over 4
14677: 
14678: =item $Title: string, the title of the plot
14679: 
14680: =item $xlabel: string, text describing the X-axis of the plot
14681: 
14682: =item $ylabel: string, text describing the Y-axis of the plot
14683: 
14684: =item $Max: scalar, the maximum Y value to use in the plot
14685: If $Max is < any data point, the graph will not be rendered.
14686: 
14687: =item $colors: Array ref containing the hex color codes for the data to be 
14688: plotted in.  If undefined, default values will be used.
14689: 
14690: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14691: 
14692: =item $Ydata: Array ref containing Array refs.  
14693: Each of the contained arrays will be plotted as a separate curve.
14694: 
14695: =item %Values: hash indicating or overriding any default values which are 
14696: passed to graph.png.  
14697: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14698: 
14699: =back
14700: 
14701: Returns:
14702: 
14703: An <img> tag which references graph.png and the appropriate identifying
14704: information for the plot.
14705: 
14706: =cut
14707: 
14708: ############################################################
14709: ############################################################
14710: sub DrawXYGraph {
14711:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14712:     #
14713:     # Create the identifier for the graph
14714:     my $identifier = &get_cgi_id();
14715:     my $id = 'cgi.'.$identifier;
14716:     #
14717:     $Title  = '' if (! defined($Title));
14718:     $xlabel = '' if (! defined($xlabel));
14719:     $ylabel = '' if (! defined($ylabel));
14720:     my %ValuesHash = 
14721:         (
14722:          $id.'.title'  => &escape($Title),
14723:          $id.'.xlabel' => &escape($xlabel),
14724:          $id.'.ylabel' => &escape($ylabel),
14725:          $id.'.y_max_value'=> $Max,
14726:          $id.'.labels'     => join(',',@$Xlabels),
14727:          $id.'.PlotType'   => 'XY',
14728:          );
14729:     #
14730:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14731:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14732:     }
14733:     #
14734:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14735:         return '';
14736:     }
14737:     my $NumSets=1;
14738:     foreach my $array (@{$Ydata}){
14739:         next if (! ref($array));
14740:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14741:     }
14742:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14743:     #
14744:     # Deal with other parameters
14745:     while (my ($key,$value) = each(%Values)) {
14746:         $ValuesHash{$id.'.'.$key} = $value;
14747:     }
14748:     #
14749:     &Apache::lonnet::appenv(\%ValuesHash);
14750:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14751: }
14752: 
14753: ############################################################
14754: ############################################################
14755: 
14756: =pod
14757: 
14758: =item * &DrawXYYGraph()
14759: 
14760: Facilitates the plotting of data in an XY graph with two Y axes.
14761: Puts plot definition data into the users environment in order for 
14762: graph.png to plot it.  Returns an <img> tag for the plot.
14763: 
14764: Inputs:
14765: 
14766: =over 4
14767: 
14768: =item $Title: string, the title of the plot
14769: 
14770: =item $xlabel: string, text describing the X-axis of the plot
14771: 
14772: =item $ylabel: string, text describing the Y-axis of the plot
14773: 
14774: =item $colors: Array ref containing the hex color codes for the data to be 
14775: plotted in.  If undefined, default values will be used.
14776: 
14777: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14778: 
14779: =item $Ydata1: The first data set
14780: 
14781: =item $Min1: The minimum value of the left Y-axis
14782: 
14783: =item $Max1: The maximum value of the left Y-axis
14784: 
14785: =item $Ydata2: The second data set
14786: 
14787: =item $Min2: The minimum value of the right Y-axis
14788: 
14789: =item $Max2: The maximum value of the left Y-axis
14790: 
14791: =item %Values: hash indicating or overriding any default values which are 
14792: passed to graph.png.  
14793: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14794: 
14795: =back
14796: 
14797: Returns:
14798: 
14799: An <img> tag which references graph.png and the appropriate identifying
14800: information for the plot.
14801: 
14802: =cut
14803: 
14804: ############################################################
14805: ############################################################
14806: sub DrawXYYGraph {
14807:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14808:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14809:     #
14810:     # Create the identifier for the graph
14811:     my $identifier = &get_cgi_id();
14812:     my $id = 'cgi.'.$identifier;
14813:     #
14814:     $Title  = '' if (! defined($Title));
14815:     $xlabel = '' if (! defined($xlabel));
14816:     $ylabel = '' if (! defined($ylabel));
14817:     my %ValuesHash = 
14818:         (
14819:          $id.'.title'  => &escape($Title),
14820:          $id.'.xlabel' => &escape($xlabel),
14821:          $id.'.ylabel' => &escape($ylabel),
14822:          $id.'.labels' => join(',',@$Xlabels),
14823:          $id.'.PlotType' => 'XY',
14824:          $id.'.NumSets' => 2,
14825:          $id.'.two_axes' => 1,
14826:          $id.'.y1_max_value' => $Max1,
14827:          $id.'.y1_min_value' => $Min1,
14828:          $id.'.y2_max_value' => $Max2,
14829:          $id.'.y2_min_value' => $Min2,
14830:          );
14831:     #
14832:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14833:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14834:     }
14835:     #
14836:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14837:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14838:         return '';
14839:     }
14840:     my $NumSets=1;
14841:     foreach my $array ($Ydata1,$Ydata2){
14842:         next if (! ref($array));
14843:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14844:     }
14845:     #
14846:     # Deal with other parameters
14847:     while (my ($key,$value) = each(%Values)) {
14848:         $ValuesHash{$id.'.'.$key} = $value;
14849:     }
14850:     #
14851:     &Apache::lonnet::appenv(\%ValuesHash);
14852:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14853: }
14854: 
14855: ############################################################
14856: ############################################################
14857: 
14858: =pod
14859: 
14860: =back 
14861: 
14862: =head1 Statistics helper routines?  
14863: 
14864: Bad place for them but what the hell.
14865: 
14866: =over 4
14867: 
14868: =item * &chartlink()
14869: 
14870: Returns a link to the chart for a specific student.  
14871: 
14872: Inputs:
14873: 
14874: =over 4
14875: 
14876: =item $linktext: The text of the link
14877: 
14878: =item $sname: The students username
14879: 
14880: =item $sdomain: The students domain
14881: 
14882: =back
14883: 
14884: =back
14885: 
14886: =cut
14887: 
14888: ############################################################
14889: ############################################################
14890: sub chartlink {
14891:     my ($linktext, $sname, $sdomain) = @_;
14892:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14893:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14894:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14895:        '">'.$linktext.'</a>';
14896: }
14897: 
14898: #######################################################
14899: #######################################################
14900: 
14901: =pod
14902: 
14903: =head1 Course Environment Routines
14904: 
14905: =over 4
14906: 
14907: =item * &restore_course_settings()
14908: 
14909: =item * &store_course_settings()
14910: 
14911: Restores/Store indicated form parameters from the course environment.
14912: Will not overwrite existing values of the form parameters.
14913: 
14914: Inputs: 
14915: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14916: 
14917: a hash ref describing the data to be stored.  For example:
14918:    
14919: %Save_Parameters = ('Status' => 'scalar',
14920:     'chartoutputmode' => 'scalar',
14921:     'chartoutputdata' => 'scalar',
14922:     'Section' => 'array',
14923:     'Group' => 'array',
14924:     'StudentData' => 'array',
14925:     'Maps' => 'array');
14926: 
14927: Returns: both routines return nothing
14928: 
14929: =back
14930: 
14931: =cut
14932: 
14933: #######################################################
14934: #######################################################
14935: sub store_course_settings {
14936:     return &store_settings($env{'request.course.id'},@_);
14937: }
14938: 
14939: sub store_settings {
14940:     # save to the environment
14941:     # appenv the same items, just to be safe
14942:     my $udom  = $env{'user.domain'};
14943:     my $uname = $env{'user.name'};
14944:     my ($context,$prefix,$Settings) = @_;
14945:     my %SaveHash;
14946:     my %AppHash;
14947:     while (my ($setting,$type) = each(%$Settings)) {
14948:         my $basename = join('.','internal',$context,$prefix,$setting);
14949:         my $envname = 'environment.'.$basename;
14950:         if (exists($env{'form.'.$setting})) {
14951:             # Save this value away
14952:             if ($type eq 'scalar' &&
14953:                 (! exists($env{$envname}) || 
14954:                  $env{$envname} ne $env{'form.'.$setting})) {
14955:                 $SaveHash{$basename} = $env{'form.'.$setting};
14956:                 $AppHash{$envname}   = $env{'form.'.$setting};
14957:             } elsif ($type eq 'array') {
14958:                 my $stored_form;
14959:                 if (ref($env{'form.'.$setting})) {
14960:                     $stored_form = join(',',
14961:                                         map {
14962:                                             &escape($_);
14963:                                         } sort(@{$env{'form.'.$setting}}));
14964:                 } else {
14965:                     $stored_form = 
14966:                         &escape($env{'form.'.$setting});
14967:                 }
14968:                 # Determine if the array contents are the same.
14969:                 if ($stored_form ne $env{$envname}) {
14970:                     $SaveHash{$basename} = $stored_form;
14971:                     $AppHash{$envname}   = $stored_form;
14972:                 }
14973:             }
14974:         }
14975:     }
14976:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14977:                                           $udom,$uname);
14978:     if ($put_result !~ /^(ok|delayed)/) {
14979:         &Apache::lonnet::logthis('unable to save form parameters, '.
14980:                                  'got error:'.$put_result);
14981:     }
14982:     # Make sure these settings stick around in this session, too
14983:     &Apache::lonnet::appenv(\%AppHash);
14984:     return;
14985: }
14986: 
14987: sub restore_course_settings {
14988:     return &restore_settings($env{'request.course.id'},@_);
14989: }
14990: 
14991: sub restore_settings {
14992:     my ($context,$prefix,$Settings) = @_;
14993:     while (my ($setting,$type) = each(%$Settings)) {
14994:         next if (exists($env{'form.'.$setting}));
14995:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14996:             '.'.$setting;
14997:         if (exists($env{$envname})) {
14998:             if ($type eq 'scalar') {
14999:                 $env{'form.'.$setting} = $env{$envname};
15000:             } elsif ($type eq 'array') {
15001:                 $env{'form.'.$setting} = [ 
15002:                                            map { 
15003:                                                &unescape($_); 
15004:                                            } split(',',$env{$envname})
15005:                                            ];
15006:             }
15007:         }
15008:     }
15009: }
15010: 
15011: #######################################################
15012: #######################################################
15013: 
15014: =pod
15015: 
15016: =head1 Domain E-mail Routines  
15017: 
15018: =over 4
15019: 
15020: =item * &build_recipient_list()
15021: 
15022: Build recipient lists for following types of e-mail:
15023: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15024: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15025: module change checking, student/employee ID conflict checks, as
15026: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15027: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15028: 
15029: Inputs:
15030: defmail (scalar - email address of default recipient), 
15031: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15032: requestsmail, updatesmail, or idconflictsmail).
15033: 
15034: defdom (domain for which to retrieve configuration settings),
15035: 
15036: origmail (scalar - email address of recipient from loncapa.conf, 
15037: i.e., predates configuration by DC via domainprefs.pm
15038: 
15039: $requname username of requester (if mailing type is helpdeskmail)
15040: 
15041: $requdom domain of requester (if mailing type is helpdeskmail)
15042: 
15043: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15044: 
15045: 
15046: Returns: comma separated list of addresses to which to send e-mail.
15047: 
15048: =back
15049: 
15050: =cut
15051: 
15052: ############################################################
15053: ############################################################
15054: sub build_recipient_list {
15055:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15056:     my @recipients;
15057:     my ($otheremails,$lastresort,$allbcc,$addtext);
15058:     my %domconfig =
15059:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15060:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15061:         if (exists($domconfig{'contacts'}{$mailing})) {
15062:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15063:                 my @contacts = ('adminemail','supportemail');
15064:                 foreach my $item (@contacts) {
15065:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15066:                         my $addr = $domconfig{'contacts'}{$item}; 
15067:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15068:                             push(@recipients,$addr);
15069:                         }
15070:                     }
15071:                 }
15072:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15073:                 if ($mailing eq 'helpdeskmail') {
15074:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15075:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15076:                         my @ok_bccs;
15077:                         foreach my $bcc (@bccs) {
15078:                             $bcc =~ s/^\s+//g;
15079:                             $bcc =~ s/\s+$//g;
15080:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15081:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15082:                                     push(@ok_bccs,$bcc);
15083:                                 }
15084:                             }
15085:                         }
15086:                         if (@ok_bccs > 0) {
15087:                             $allbcc = join(', ',@ok_bccs);
15088:                         }
15089:                     }
15090:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15091:                 }
15092:             }
15093:         } elsif ($origmail ne '') {
15094:             $lastresort = $origmail;
15095:         }
15096:         if ($mailing eq 'helpdeskmail') {
15097:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15098:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15099:                 my ($inststatus,$inststatus_checked);
15100:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15101:                     ($env{'user.domain'} ne 'public')) {
15102:                     $inststatus_checked = 1;
15103:                     $inststatus = $env{'environment.inststatus'};
15104:                 }
15105:                 unless ($inststatus_checked) {
15106:                     if (($requname ne '') && ($requdom ne '')) {
15107:                         if (($requname =~ /^$match_username$/) &&
15108:                             ($requdom =~ /^$match_domain$/) &&
15109:                             (&Apache::lonnet::domain($requdom))) {
15110:                             my $requhome = &Apache::lonnet::homeserver($requname,
15111:                                                                       $requdom);
15112:                             unless ($requhome eq 'no_host') {
15113:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15114:                                 $inststatus = $userenv{'inststatus'};
15115:                                 $inststatus_checked = 1;
15116:                             }
15117:                         }
15118:                     }
15119:                 }
15120:                 unless ($inststatus_checked) {
15121:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15122:                         my %srch = (srchby     => 'email',
15123:                                     srchdomain => $defdom,
15124:                                     srchterm   => $reqemail,
15125:                                     srchtype   => 'exact');
15126:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15127:                         foreach my $uname (keys(%srch_results)) {
15128:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15129:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15130:                                 $inststatus_checked = 1;
15131:                                 last;
15132:                             }
15133:                         }
15134:                         unless ($inststatus_checked) {
15135:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15136:                             if ($dirsrchres eq 'ok') {
15137:                                 foreach my $uname (keys(%srch_results)) {
15138:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15139:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15140:                                         $inststatus_checked = 1;
15141:                                         last;
15142:                                     }
15143:                                 }
15144:                             }
15145:                         }
15146:                     }
15147:                 }
15148:                 if ($inststatus ne '') {
15149:                     foreach my $status (split(/\:/,$inststatus)) {
15150:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15151:                             my @contacts = ('adminemail','supportemail');
15152:                             foreach my $item (@contacts) {
15153:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15154:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15155:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15156:                                         push(@recipients,$addr);
15157:                                     }
15158:                                 }
15159:                             }
15160:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15161:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15162:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15163:                                 my @ok_bccs;
15164:                                 foreach my $bcc (@bccs) {
15165:                                     $bcc =~ s/^\s+//g;
15166:                                     $bcc =~ s/\s+$//g;
15167:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15168:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15169:                                             push(@ok_bccs,$bcc);
15170:                                         }
15171:                                     }
15172:                                 }
15173:                                 if (@ok_bccs > 0) {
15174:                                     $allbcc = join(', ',@ok_bccs);
15175:                                 }
15176:                             }
15177:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15178:                             last;
15179:                         }
15180:                     }
15181:                 }
15182:             }
15183:         }
15184:     } elsif ($origmail ne '') {
15185:         $lastresort = $origmail;
15186:     }
15187:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15188:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15189:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15190:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15191:             my %what = (
15192:                           perlvar => 1,
15193:                        );
15194:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15195:             if ($primary) {
15196:                 my $gotaddr;
15197:                 my ($result,$returnhash) =
15198:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15199:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15200:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15201:                         $lastresort = $returnhash->{'lonSupportEMail'};
15202:                         $gotaddr = 1;
15203:                     }
15204:                 }
15205:                 unless ($gotaddr) {
15206:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15207:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15208:                     unless ($uintdom eq $intdom) {
15209:                         my %domconfig =
15210:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15211:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15212:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15213:                                 my @contacts = ('adminemail','supportemail');
15214:                                 foreach my $item (@contacts) {
15215:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15216:                                         my $addr = $domconfig{'contacts'}{$item};
15217:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15218:                                             push(@recipients,$addr);
15219:                                         }
15220:                                     }
15221:                                 }
15222:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15223:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15224:                                 }
15225:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15226:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15227:                                     my @ok_bccs;
15228:                                     foreach my $bcc (@bccs) {
15229:                                         $bcc =~ s/^\s+//g;
15230:                                         $bcc =~ s/\s+$//g;
15231:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15232:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15233:                                                 push(@ok_bccs,$bcc);
15234:                                             }
15235:                                         }
15236:                                     }
15237:                                     if (@ok_bccs > 0) {
15238:                                         $allbcc = join(', ',@ok_bccs);
15239:                                     }
15240:                                 }
15241:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15242:                             }
15243:                         }
15244:                     }
15245:                 }
15246:             }
15247:         }
15248:     }
15249:     if (defined($defmail)) {
15250:         if ($defmail ne '') {
15251:             push(@recipients,$defmail);
15252:         }
15253:     }
15254:     if ($otheremails) {
15255:         my @others;
15256:         if ($otheremails =~ /,/) {
15257:             @others = split(/,/,$otheremails);
15258:         } else {
15259:             push(@others,$otheremails);
15260:         }
15261:         foreach my $addr (@others) {
15262:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15263:                 push(@recipients,$addr);
15264:             }
15265:         }
15266:     }
15267:     if ($mailing eq 'helpdeskmail') {
15268:         if ((!@recipients) && ($lastresort ne '')) {
15269:             push(@recipients,$lastresort);
15270:         }
15271:     } elsif ($lastresort ne '') {
15272:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15273:             push(@recipients,$lastresort);
15274:         }
15275:     }
15276:     my $recipientlist = join(',',@recipients);
15277:     if (wantarray) {
15278:         return ($recipientlist,$allbcc,$addtext);
15279:     } else {
15280:         return $recipientlist;
15281:     }
15282: }
15283: 
15284: ############################################################
15285: ############################################################
15286: 
15287: =pod
15288: 
15289: =over 4
15290: 
15291: =item * &mime_email()
15292: 
15293: Sends an email with a possible attachment
15294: 
15295: Inputs:
15296: 
15297: =over 4
15298: 
15299: from -              Sender's email address
15300: 
15301: replyto -           Reply-To email address
15302: 
15303: to -                Email address of recipient
15304: 
15305: subject -           Subject of email
15306: 
15307: body -              Body of email
15308: 
15309: cc_string -         Carbon copy email address
15310: 
15311: bcc -               Blind carbon copy email address
15312: 
15313: attachment_path -   Path of file to be attached
15314: 
15315: file_name -         Name of file to be attached
15316: 
15317: attachment_text -   The body of an attachment of type "TEXT"
15318: 
15319: =back
15320: 
15321: =back
15322: 
15323: =cut
15324: 
15325: ############################################################
15326: ############################################################
15327: 
15328: sub mime_email {
15329:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
15330:         $file_name,$attachment_text) = @_;
15331:  
15332:     my $msg = MIME::Lite->new(
15333:              From    => $from,
15334:              To      => $to,
15335:              Subject => $subject,
15336:              Type    =>'TEXT',
15337:              Data    => $body,
15338:              );
15339:     if ($replyto ne '') {
15340:         $msg->add("Reply-To" => $replyto);
15341:     }
15342:     if ($cc_string ne '') {
15343:         $msg->add("Cc" => $cc_string);
15344:     }
15345:     if ($bcc ne '') {
15346:         $msg->add("Bcc" => $bcc);
15347:     }
15348:     $msg->attr("content-type"         => "text/plain");
15349:     $msg->attr("content-type.charset" => "UTF-8");
15350:     # Attach file if given
15351:     if ($attachment_path) {
15352:         unless ($file_name) {
15353:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15354:         }
15355:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15356:         $msg->attach(Type     => $type,
15357:                      Path     => $attachment_path,
15358:                      Filename => $file_name
15359:                      );
15360:     # Otherwise attach text if given
15361:     } elsif ($attachment_text) {
15362:         $msg->attach(Type => 'TEXT',
15363:                      Data => $attachment_text);
15364:     }
15365:     # Send it
15366:     $msg->send('sendmail');
15367: }
15368: 
15369: ############################################################
15370: ############################################################
15371: 
15372: =pod
15373: 
15374: =head1 Course Catalog Routines
15375: 
15376: =over 4
15377: 
15378: =item * &gather_categories()
15379: 
15380: Converts category definitions - keys of categories hash stored in  
15381: coursecategories in configuration.db on the primary library server in a 
15382: domain - to an array.  Also generates javascript and idx hash used to 
15383: generate Domain Coordinator interface for editing Course Categories.
15384: 
15385: Inputs:
15386: 
15387: categories (reference to hash of category definitions).
15388: 
15389: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15390:       categories and subcategories).
15391: 
15392: idx (reference to hash of counters used in Domain Coordinator interface for 
15393:       editing Course Categories).
15394: 
15395: jsarray (reference to array of categories used to create Javascript arrays for
15396:          Domain Coordinator interface for editing Course Categories).
15397: 
15398: Returns: nothing
15399: 
15400: Side effects: populates cats, idx and jsarray. 
15401: 
15402: =cut
15403: 
15404: sub gather_categories {
15405:     my ($categories,$cats,$idx,$jsarray) = @_;
15406:     my %counters;
15407:     my $num = 0;
15408:     foreach my $item (keys(%{$categories})) {
15409:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15410:         if ($container eq '' && $depth == 0) {
15411:             $cats->[$depth][$categories->{$item}] = $cat;
15412:         } else {
15413:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15414:         }
15415:         my ($escitem,$tail) = split(/:/,$item,2);
15416:         if ($counters{$tail} eq '') {
15417:             $counters{$tail} = $num;
15418:             $num ++;
15419:         }
15420:         if (ref($idx) eq 'HASH') {
15421:             $idx->{$item} = $counters{$tail};
15422:         }
15423:         if (ref($jsarray) eq 'ARRAY') {
15424:             push(@{$jsarray->[$counters{$tail}]},$item);
15425:         }
15426:     }
15427:     return;
15428: }
15429: 
15430: =pod
15431: 
15432: =item * &extract_categories()
15433: 
15434: Used to generate breadcrumb trails for course categories.
15435: 
15436: Inputs:
15437: 
15438: categories (reference to hash of category definitions).
15439: 
15440: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15441:       categories and subcategories).
15442: 
15443: trails (reference to array of breacrumb trails for each category).
15444: 
15445: allitems (reference to hash - key is category key 
15446:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15447: 
15448: idx (reference to hash of counters used in Domain Coordinator interface for
15449:       editing Course Categories).
15450: 
15451: jsarray (reference to array of categories used to create Javascript arrays for
15452:          Domain Coordinator interface for editing Course Categories).
15453: 
15454: subcats (reference to hash of arrays containing all subcategories within each 
15455:          category, -recursive)
15456: 
15457: maxd (reference to hash used to hold max depth for all top-level categories).
15458: 
15459: Returns: nothing
15460: 
15461: Side effects: populates trails and allitems hash references.
15462: 
15463: =cut
15464: 
15465: sub extract_categories {
15466:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15467:     if (ref($categories) eq 'HASH') {
15468:         &gather_categories($categories,$cats,$idx,$jsarray);
15469:         if (ref($cats->[0]) eq 'ARRAY') {
15470:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15471:                 my $name = $cats->[0][$i];
15472:                 my $item = &escape($name).'::0';
15473:                 my $trailstr;
15474:                 if ($name eq 'instcode') {
15475:                     $trailstr = &mt('Official courses (with institutional codes)');
15476:                 } elsif ($name eq 'communities') {
15477:                     $trailstr = &mt('Communities');
15478:                 } elsif ($name eq 'placement') {
15479:                     $trailstr = &mt('Placement Tests');
15480:                 } else {
15481:                     $trailstr = $name;
15482:                 }
15483:                 if ($allitems->{$item} eq '') {
15484:                     push(@{$trails},$trailstr);
15485:                     $allitems->{$item} = scalar(@{$trails})-1;
15486:                 }
15487:                 my @parents = ($name);
15488:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15489:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15490:                         my $category = $cats->[1]{$name}[$j];
15491:                         if (ref($subcats) eq 'HASH') {
15492:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15493:                         }
15494:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15495:                     }
15496:                 } else {
15497:                     if (ref($subcats) eq 'HASH') {
15498:                         $subcats->{$item} = [];
15499:                     }
15500:                     if (ref($maxd) eq 'HASH') {
15501:                         $maxd->{$name} = 1;
15502:                     }
15503:                 }
15504:             }
15505:         }
15506:     }
15507:     return;
15508: }
15509: 
15510: =pod
15511: 
15512: =item * &recurse_categories()
15513: 
15514: Recursively used to generate breadcrumb trails for course categories.
15515: 
15516: Inputs:
15517: 
15518: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15519:       categories and subcategories).
15520: 
15521: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15522: 
15523: category (current course category, for which breadcrumb trail is being generated).
15524: 
15525: trails (reference to array of breadcrumb trails for each category).
15526: 
15527: allitems (reference to hash - key is category key
15528:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15529: 
15530: parents (array containing containers directories for current category, 
15531:          back to top level). 
15532: 
15533: Returns: nothing
15534: 
15535: Side effects: populates trails and allitems hash references
15536: 
15537: =cut
15538: 
15539: sub recurse_categories {
15540:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15541:     my $shallower = $depth - 1;
15542:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15543:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15544:             my $name = $cats->[$depth]{$category}[$k];
15545:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15546:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15547:             if ($allitems->{$item} eq '') {
15548:                 push(@{$trails},$trailstr);
15549:                 $allitems->{$item} = scalar(@{$trails})-1;
15550:             }
15551:             my $deeper = $depth+1;
15552:             push(@{$parents},$category);
15553:             if (ref($subcats) eq 'HASH') {
15554:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15555:                 for (my $j=@{$parents}; $j>=0; $j--) {
15556:                     my $higher;
15557:                     if ($j > 0) {
15558:                         $higher = &escape($parents->[$j]).':'.
15559:                                   &escape($parents->[$j-1]).':'.$j;
15560:                     } else {
15561:                         $higher = &escape($parents->[$j]).'::'.$j;
15562:                     }
15563:                     push(@{$subcats->{$higher}},$subcat);
15564:                 }
15565:             }
15566:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15567:                                 $subcats,$maxd);
15568:             pop(@{$parents});
15569:         }
15570:     } else {
15571:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15572:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15573:         if ($allitems->{$item} eq '') {
15574:             push(@{$trails},$trailstr);
15575:             $allitems->{$item} = scalar(@{$trails})-1;
15576:         }
15577:         if (ref($maxd) eq 'HASH') {
15578:             if ($depth > $maxd->{$parents->[0]}) {
15579:                 $maxd->{$parents->[0]} = $depth;
15580:             }
15581:         }
15582:     }
15583:     return;
15584: }
15585: 
15586: =pod
15587: 
15588: =item * &assign_categories_table()
15589: 
15590: Create a datatable for display of hierarchical categories in a domain,
15591: with checkboxes to allow a course to be categorized. 
15592: 
15593: Inputs:
15594: 
15595: cathash - reference to hash of categories defined for the domain (from
15596:           configuration.db)
15597: 
15598: currcat - scalar with an & separated list of categories assigned to a course. 
15599: 
15600: type    - scalar contains course type (Course or Community).
15601: 
15602: disabled - scalar (optional) contains disabled="disabled" if input elements are
15603:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15604: 
15605: Returns: $output (markup to be displayed) 
15606: 
15607: =cut
15608: 
15609: sub assign_categories_table {
15610:     my ($cathash,$currcat,$type,$disabled) = @_;
15611:     my $output;
15612:     if (ref($cathash) eq 'HASH') {
15613:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15614:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15615:         $maxdepth = scalar(@cats);
15616:         if (@cats > 0) {
15617:             my $itemcount = 0;
15618:             if (ref($cats[0]) eq 'ARRAY') {
15619:                 my @currcategories;
15620:                 if ($currcat ne '') {
15621:                     @currcategories = split('&',$currcat);
15622:                 }
15623:                 my $table;
15624:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15625:                     my $parent = $cats[0][$i];
15626:                     next if ($parent eq 'instcode');
15627:                     if ($type eq 'Community') {
15628:                         next unless ($parent eq 'communities');
15629:                     } elsif ($type eq 'Placement') {
15630:                         next unless ($parent eq 'placement');
15631:                     } else {
15632:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15633:                     }
15634:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15635:                     my $item = &escape($parent).'::0';
15636:                     my $checked = '';
15637:                     if (@currcategories > 0) {
15638:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15639:                             $checked = ' checked="checked"';
15640:                         }
15641:                     }
15642:                     my $parent_title = $parent;
15643:                     if ($parent eq 'communities') {
15644:                         $parent_title = &mt('Communities');
15645:                     } elsif ($parent eq 'placement') {
15646:                         $parent_title = &mt('Placement Tests');
15647:                     }
15648:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15649:                               '<input type="checkbox" name="usecategory" value="'.
15650:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15651:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15652:                     my $depth = 1;
15653:                     push(@path,$parent);
15654:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15655:                     pop(@path);
15656:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15657:                     $itemcount ++;
15658:                 }
15659:                 if ($itemcount) {
15660:                     $output = &Apache::loncommon::start_data_table().
15661:                               $table.
15662:                               &Apache::loncommon::end_data_table();
15663:                 }
15664:             }
15665:         }
15666:     }
15667:     return $output;
15668: }
15669: 
15670: =pod
15671: 
15672: =item * &assign_category_rows()
15673: 
15674: Create a datatable row for display of nested categories in a domain,
15675: with checkboxes to allow a course to be categorized,called recursively.
15676: 
15677: Inputs:
15678: 
15679: itemcount - track row number for alternating colors
15680: 
15681: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15682:       categories and subcategories.
15683: 
15684: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15685: 
15686: parent - parent of current category item
15687: 
15688: path - Array containing all categories back up through the hierarchy from the
15689:        current category to the top level.
15690: 
15691: currcategories - reference to array of current categories assigned to the course
15692: 
15693: disabled - scalar (optional) contains disabled="disabled" if input elements are
15694:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15695: 
15696: Returns: $output (markup to be displayed).
15697: 
15698: =cut
15699: 
15700: sub assign_category_rows {
15701:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15702:     my ($text,$name,$item,$chgstr);
15703:     if (ref($cats) eq 'ARRAY') {
15704:         my $maxdepth = scalar(@{$cats});
15705:         if (ref($cats->[$depth]) eq 'HASH') {
15706:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15707:                 my $numchildren = @{$cats->[$depth]{$parent}};
15708:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15709:                 $text .= '<td><table class="LC_data_table">';
15710:                 for (my $j=0; $j<$numchildren; $j++) {
15711:                     $name = $cats->[$depth]{$parent}[$j];
15712:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15713:                     my $deeper = $depth+1;
15714:                     my $checked = '';
15715:                     if (ref($currcategories) eq 'ARRAY') {
15716:                         if (@{$currcategories} > 0) {
15717:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15718:                                 $checked = ' checked="checked"';
15719:                             }
15720:                         }
15721:                     }
15722:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15723:                              '<input type="checkbox" name="usecategory" value="'.
15724:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15725:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15726:                              '</td><td>';
15727:                     if (ref($path) eq 'ARRAY') {
15728:                         push(@{$path},$name);
15729:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15730:                         pop(@{$path});
15731:                     }
15732:                     $text .= '</td></tr>';
15733:                 }
15734:                 $text .= '</table></td>';
15735:             }
15736:         }
15737:     }
15738:     return $text;
15739: }
15740: 
15741: =pod
15742: 
15743: =back
15744: 
15745: =cut
15746: 
15747: ############################################################
15748: ############################################################
15749: 
15750: 
15751: sub commit_customrole {
15752:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15753:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15754:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15755:                          ($end?', ending '.localtime($end):'').': <b>'.
15756:               &Apache::lonnet::assigncustomrole(
15757:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15758:                  '</b><br />';
15759:     return $output;
15760: }
15761: 
15762: sub commit_standardrole {
15763:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15764:     my ($output,$logmsg,$linefeed);
15765:     if ($context eq 'auto') {
15766:         $linefeed = "\n";
15767:     } else {
15768:         $linefeed = "<br />\n";
15769:     }  
15770:     if ($three eq 'st') {
15771:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15772:                                          $one,$two,$sec,$context,$credits);
15773:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15774:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15775:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15776:         } else {
15777:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15778:                ($start?', '.&mt('starting').' '.localtime($start):'').
15779:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15780:             if ($context eq 'auto') {
15781:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15782:             } else {
15783:                $output .= '<b>'.$result.'</b>'.$linefeed.
15784:                &mt('Add to classlist').': <b>ok</b>';
15785:             }
15786:             $output .= $linefeed;
15787:         }
15788:     } else {
15789:         $output = &mt('Assigning').' '.$three.' in '.$url.
15790:                ($start?', '.&mt('starting').' '.localtime($start):'').
15791:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15792:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15793:         if ($context eq 'auto') {
15794:             $output .= $result.$linefeed;
15795:         } else {
15796:             $output .= '<b>'.$result.'</b>'.$linefeed;
15797:         }
15798:     }
15799:     return $output;
15800: }
15801: 
15802: sub commit_studentrole {
15803:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15804:         $credits) = @_;
15805:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15806:     if ($context eq 'auto') {
15807:         $linefeed = "\n";
15808:     } else {
15809:         $linefeed = '<br />'."\n";
15810:     }
15811:     if (defined($one) && defined($two)) {
15812:         my $cid=$one.'_'.$two;
15813:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15814:         my $secchange = 0;
15815:         my $expire_role_result;
15816:         my $modify_section_result;
15817:         if ($oldsec ne '-1') { 
15818:             if ($oldsec ne $sec) {
15819:                 $secchange = 1;
15820:                 my $now = time;
15821:                 my $uurl='/'.$cid;
15822:                 $uurl=~s/\_/\//g;
15823:                 if ($oldsec) {
15824:                     $uurl.='/'.$oldsec;
15825:                 }
15826:                 $oldsecurl = $uurl;
15827:                 $expire_role_result = 
15828:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15829:                 if ($env{'request.course.sec'} ne '') { 
15830:                     if ($expire_role_result eq 'refused') {
15831:                         my @roles = ('st');
15832:                         my @statuses = ('previous');
15833:                         my @roledoms = ($one);
15834:                         my $withsec = 1;
15835:                         my %roleshash = 
15836:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15837:                                               \@statuses,\@roles,\@roledoms,$withsec);
15838:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15839:                             my ($oldstart,$oldend) = 
15840:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15841:                             if ($oldend > 0 && $oldend <= $now) {
15842:                                 $expire_role_result = 'ok';
15843:                             }
15844:                         }
15845:                     }
15846:                 }
15847:                 $result = $expire_role_result;
15848:             }
15849:         }
15850:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15851:             $modify_section_result = 
15852:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15853:                                                            undef,undef,undef,$sec,
15854:                                                            $end,$start,'','',$cid,
15855:                                                            '',$context,$credits);
15856:             if ($modify_section_result =~ /^ok/) {
15857:                 if ($secchange == 1) {
15858:                     if ($sec eq '') {
15859:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15860:                     } else {
15861:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15862:                     }
15863:                 } elsif ($oldsec eq '-1') {
15864:                     if ($sec eq '') {
15865:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15866:                     } else {
15867:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15868:                     }
15869:                 } else {
15870:                     if ($sec eq '') {
15871:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15872:                     } else {
15873:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15874:                     }
15875:                 }
15876:             } else {
15877:                 if ($secchange) { 
15878:                     $$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;
15879:                 } else {
15880:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15881:                 }
15882:             }
15883:             $result = $modify_section_result;
15884:         } elsif ($secchange == 1) {
15885:             if ($oldsec eq '') {
15886:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15887:             } else {
15888:                 $$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;
15889:             }
15890:             if ($expire_role_result eq 'refused') {
15891:                 my $newsecurl = '/'.$cid;
15892:                 $newsecurl =~ s/\_/\//g;
15893:                 if ($sec ne '') {
15894:                     $newsecurl.='/'.$sec;
15895:                 }
15896:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15897:                     if ($sec eq '') {
15898:                         $$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;
15899:                     } else {
15900:                         $$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;
15901:                     }
15902:                 }
15903:             }
15904:         }
15905:     } else {
15906:         $$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;
15907:         $result = "error: incomplete course id\n";
15908:     }
15909:     return $result;
15910: }
15911: 
15912: sub show_role_extent {
15913:     my ($scope,$context,$role) = @_;
15914:     $scope =~ s{^/}{};
15915:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15916:     push(@courseroles,'co');
15917:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15918:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15919:         $scope =~ s{/}{_};
15920:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15921:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15922:         my ($audom,$auname) = split(/\//,$scope);
15923:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15924:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15925:     } else {
15926:         $scope =~ s{/$}{};
15927:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15928:                    &Apache::lonnet::domain($scope,'description').'</span>');
15929:     }
15930: }
15931: 
15932: ############################################################
15933: ############################################################
15934: 
15935: sub check_clone {
15936:     my ($args,$linefeed) = @_;
15937:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15938:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15939:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15940:     my $clonetitle;
15941:     my @clonemsg;
15942:     my $can_clone = 0;
15943:     my $lctype = lc($args->{'crstype'});
15944:     if ($lctype ne 'community') {
15945:         $lctype = 'course';
15946:     }
15947:     if ($clonehome eq 'no_host') {
15948:         if ($args->{'crstype'} eq 'Community') {
15949:             push(@clonemsg,({
15950:                               mt => 'No new community created.',
15951:                               args => [],
15952:                             },
15953:                             {
15954:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15955:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15956:                             }));
15957:         } else {
15958:             push(@clonemsg,({
15959:                               mt => 'No new course created.',
15960:                               args => [],
15961:                             },
15962:                             {
15963:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15964:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15965:                             }));
15966:         }
15967:     } else {
15968: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15969:         $clonetitle = $clonedesc{'description'};
15970:         if ($args->{'crstype'} eq 'Community') {
15971:             if ($clonedesc{'type'} ne 'Community') {
15972:                 push(@clonemsg,({
15973:                                   mt => 'No new community created.',
15974:                                   args => [],
15975:                                 },
15976:                                 {
15977:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15978:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15979:                                 }));
15980:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15981:             }
15982:         }
15983: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15984:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15985: 	    $can_clone = 1;
15986: 	} else {
15987: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15988: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15989:             if ($clonehash{'cloners'} eq '') {
15990:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15991:                 if ($domdefs{'canclone'}) {
15992:                     unless ($domdefs{'canclone'} eq 'none') {
15993:                         if ($domdefs{'canclone'} eq 'domain') {
15994:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15995:                                 $can_clone = 1;
15996:                             }
15997:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15998:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15999:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16000:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16001:                                 $can_clone = 1;
16002:                             }
16003:                         }
16004:                     }
16005:                 }
16006:             } else {
16007: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16008:                 if (grep(/^\*$/,@cloners)) {
16009:                     $can_clone = 1;
16010:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16011:                     $can_clone = 1;
16012:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16013:                     $can_clone = 1;
16014:                 }
16015:                 unless ($can_clone) {
16016:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16017:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16018:                         my (%gotdomdefaults,%gotcodedefaults);
16019:                         foreach my $cloner (@cloners) {
16020:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16021:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16022:                                 my (%codedefaults,@code_order);
16023:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16024:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16025:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16026:                                     }
16027:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16028:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16029:                                     }
16030:                                 } else {
16031:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16032:                                                                             \%codedefaults,
16033:                                                                             \@code_order);
16034:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16035:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16036:                                 }
16037:                                 if (@code_order > 0) {
16038:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16039:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16040:                                                                                 $args->{'crscode'})) {
16041:                                         $can_clone = 1;
16042:                                         last;
16043:                                     }
16044:                                 }
16045:                             }
16046:                         }
16047:                     }
16048:                 }
16049:             }
16050:             unless ($can_clone) {
16051:                 my $ccrole = 'cc';
16052:                 if ($args->{'crstype'} eq 'Community') {
16053:                     $ccrole = 'co';
16054:                 }
16055: 	        my %roleshash =
16056: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16057: 					          $args->{'ccdomain'},
16058:                                                   'userroles',['active'],[$ccrole],
16059: 					          [$args->{'clonedomain'}]);
16060: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16061:                     $can_clone = 1;
16062:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16063:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16064:                     $can_clone = 1;
16065:                 }
16066:             }
16067:             unless ($can_clone) {
16068:                 if ($args->{'crstype'} eq 'Community') {
16069:                     push(@clonemsg,({
16070:                                       mt => 'No new community created.',
16071:                                       args => [],
16072:                                     },
16073:                                     {
16074:                                       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]).',
16075:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16076:                                     }));
16077:                 } else {
16078:                     push(@clonemsg,({
16079:                                       mt => 'No new course created.',
16080:                                       args => [],
16081:                                     },
16082:                                     {
16083:                                       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]).',
16084:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16085:                                     }));
16086:                 }
16087: 	    }
16088:         }
16089:     }
16090:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16091: }
16092: 
16093: sub construct_course {
16094:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16095:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16096:     my ($outcome,$msgref,$clonemsgref);
16097:     my $linefeed =  '<br />'."\n";
16098:     if ($context eq 'auto') {
16099:         $linefeed = "\n";
16100:     }
16101: 
16102: #
16103: # Are we cloning?
16104: #
16105:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16106:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16107: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16108:         if (!$can_clone) {
16109: 	    return (0,$outcome,$clonemsgref);
16110: 	}
16111:     }
16112: 
16113: #
16114: # Open course
16115: #
16116:     my $showncrstype;
16117:     if ($args->{'crstype'} eq 'Placement') {
16118:         $showncrstype = 'placement test'; 
16119:     } else {  
16120:         $showncrstype = lc($args->{'crstype'});
16121:     }
16122:     my %cenv=();
16123:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16124:                                              $args->{'cdescr'},
16125:                                              $args->{'curl'},
16126:                                              $args->{'course_home'},
16127:                                              $args->{'nonstandard'},
16128:                                              $args->{'crscode'},
16129:                                              $args->{'ccuname'}.':'.
16130:                                              $args->{'ccdomain'},
16131:                                              $args->{'crstype'},
16132:                                              $cnum,$context,$category,
16133:                                              $callercontext);
16134: 
16135:     # Note: The testing routines depend on this being output; see 
16136:     # Utils::Course. This needs to at least be output as a comment
16137:     # if anyone ever decides to not show this, and Utils::Course::new
16138:     # will need to be suitably modified.
16139:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16140:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16141:     } else {
16142:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16143:     }
16144:     if ($$courseid =~ /^error:/) {
16145:         return (0,$outcome,$clonemsgref);
16146:     }
16147: 
16148: #
16149: # Check if created correctly
16150: #
16151:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16152:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16153:     if ($crsuhome eq 'no_host') {
16154:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16155:             $outcome .= &mt_user($user_lh,
16156:                             'Course creation failed, unrecognized course home server.');
16157:         } else {
16158:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16159:         }
16160:         $outcome .= $linefeed;
16161:         return (0,$outcome,$clonemsgref);
16162:     }
16163:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16164: 
16165: #
16166: # Do the cloning
16167: #   
16168:     my @clonemsg;
16169:     if ($can_clone && $cloneid) {
16170:         push(@clonemsg,
16171:                       {
16172:                           mt => 'Created [_1] by cloning from [_2]',
16173:                           args => [$showncrstype,$clonetitle],
16174:                       });
16175: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16176: # Copy all files
16177:         my @info =
16178: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16179: 	                                             $args->{'dateshift'},$args->{'crscode'},
16180:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16181:                                                      $args->{'tinyurls'});
16182:         if (@info) {
16183:             push(@clonemsg,@info);
16184:         }
16185: # Restore URL
16186: 	$cenv{'url'}=$oldcenv{'url'};
16187: # Restore title
16188: 	$cenv{'description'}=$oldcenv{'description'};
16189: # Restore creation date, creator and creation context.
16190:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16191:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16192:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16193: # Mark as cloned
16194: 	$cenv{'clonedfrom'}=$cloneid;
16195: # Need to clone grading mode
16196:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16197:         $cenv{'grading'}=$newenv{'grading'};
16198: # Do not clone these environment entries
16199:         &Apache::lonnet::del('environment',
16200:                   ['default_enrollment_start_date',
16201:                    'default_enrollment_end_date',
16202:                    'question.email',
16203:                    'policy.email',
16204:                    'comment.email',
16205:                    'pch.users.denied',
16206:                    'plc.users.denied',
16207:                    'hidefromcat',
16208:                    'checkforpriv',
16209:                    'categories',
16210:                    'internal.uniquecode'],
16211:                    $$crsudom,$$crsunum);
16212:         if ($args->{'textbook'}) {
16213:             $cenv{'internal.textbook'} = $args->{'textbook'};
16214:         }
16215:     }
16216: 
16217: #
16218: # Set environment (will override cloned, if existing)
16219: #
16220:     my @sections = ();
16221:     my @xlists = ();
16222:     if ($args->{'crstype'}) {
16223:         $cenv{'type'}=$args->{'crstype'};
16224:     }
16225:     if ($args->{'crsid'}) {
16226:         $cenv{'courseid'}=$args->{'crsid'};
16227:     }
16228:     if ($args->{'crscode'}) {
16229:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16230:     }
16231:     if ($args->{'crsquota'} ne '') {
16232:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16233:     } else {
16234:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16235:     }
16236:     if ($args->{'ccuname'}) {
16237:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16238:                                         ':'.$args->{'ccdomain'};
16239:     } else {
16240:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16241:     }
16242:     if ($args->{'defaultcredits'}) {
16243:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16244:     }
16245:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16246:     if ($args->{'crssections'}) {
16247:         $cenv{'internal.sectionnums'} = '';
16248:         if ($args->{'crssections'} =~ m/,/) {
16249:             @sections = split/,/,$args->{'crssections'};
16250:         } else {
16251:             $sections[0] = $args->{'crssections'};
16252:         }
16253:         if (@sections > 0) {
16254:             foreach my $item (@sections) {
16255:                 my ($sec,$gp) = split/:/,$item;
16256:                 my $class = $args->{'crscode'}.$sec;
16257:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16258:                 $cenv{'internal.sectionnums'} .= $item.',';
16259:                 unless ($addcheck eq 'ok') {
16260:                     push(@badclasses,$class);
16261:                 }
16262:             }
16263:             $cenv{'internal.sectionnums'} =~ s/,$//;
16264:         }
16265:     }
16266: # do not hide course coordinator from staff listing, 
16267: # even if privileged
16268:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16269: # add course coordinator's domain to domains to check for privileged users
16270: # if different to course domain
16271:     if ($$crsudom ne $args->{'ccdomain'}) {
16272:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16273:     }
16274: # add crosslistings
16275:     if ($args->{'crsxlist'}) {
16276:         $cenv{'internal.crosslistings'}='';
16277:         if ($args->{'crsxlist'} =~ m/,/) {
16278:             @xlists = split/,/,$args->{'crsxlist'};
16279:         } else {
16280:             $xlists[0] = $args->{'crsxlist'};
16281:         }
16282:         if (@xlists > 0) {
16283:             foreach my $item (@xlists) {
16284:                 my ($xl,$gp) = split/:/,$item;
16285:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16286:                 $cenv{'internal.crosslistings'} .= $item.',';
16287:                 unless ($addcheck eq 'ok') {
16288:                     push(@badclasses,$xl);
16289:                 }
16290:             }
16291:             $cenv{'internal.crosslistings'} =~ s/,$//;
16292:         }
16293:     }
16294:     if ($args->{'autoadds'}) {
16295:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16296:     }
16297:     if ($args->{'autodrops'}) {
16298:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16299:     }
16300: # check for notification of enrollment changes
16301:     my @notified = ();
16302:     if ($args->{'notify_owner'}) {
16303:         if ($args->{'ccuname'} ne '') {
16304:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16305:         }
16306:     }
16307:     if ($args->{'notify_dc'}) {
16308:         if ($uname ne '') { 
16309:             push(@notified,$uname.':'.$udom);
16310:         }
16311:     }
16312:     if (@notified > 0) {
16313:         my $notifylist;
16314:         if (@notified > 1) {
16315:             $notifylist = join(',',@notified);
16316:         } else {
16317:             $notifylist = $notified[0];
16318:         }
16319:         $cenv{'internal.notifylist'} = $notifylist;
16320:     }
16321:     if (@badclasses > 0) {
16322:         my %lt=&Apache::lonlocal::texthash(
16323:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16324:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16325:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16326:         );
16327:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16328:                            &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'};
16329:         if ($context eq 'auto') {
16330:             $outcome .= $badclass_msg.$linefeed;
16331:         } else {
16332:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16333:         }
16334:         foreach my $item (@badclasses) {
16335:             if ($context eq 'auto') {
16336:                 $outcome .= " - $item\n";
16337:             } else {
16338:                 $outcome .= "<li>$item</li>\n";
16339:             }
16340:         }
16341:         if ($context eq 'auto') {
16342:             $outcome .= $linefeed;
16343:         } else {
16344:             $outcome .= "</ul><br /><br /></div>\n";
16345:         } 
16346:     }
16347:     if ($args->{'no_end_date'}) {
16348:         $args->{'endaccess'} = 0;
16349:     }
16350:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16351:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16352:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16353:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16354:     if ($args->{'showphotos'}) {
16355:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16356:     }
16357:     $cenv{'internal.authtype'} = $args->{'authtype'};
16358:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16359:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16360:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16361:             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'); 
16362:             if ($context eq 'auto') {
16363:                 $outcome .= $krb_msg;
16364:             } else {
16365:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16366:             }
16367:             $outcome .= $linefeed;
16368:         }
16369:     }
16370:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16371:        if ($args->{'setpolicy'}) {
16372:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16373:        }
16374:        if ($args->{'setcontent'}) {
16375:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16376:        }
16377:        if ($args->{'setcomment'}) {
16378:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16379:        }
16380:     }
16381:     if ($args->{'reshome'}) {
16382: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16383: 	$cenv{'reshome'}=~s/\/+$/\//;
16384:     }
16385: #
16386: # course has keyed access
16387: #
16388:     if ($args->{'setkeys'}) {
16389:        $cenv{'keyaccess'}='yes';
16390:     }
16391: # if specified, key authority is not course, but user
16392: # only active if keyaccess is yes
16393:     if ($args->{'keyauth'}) {
16394: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16395: 	$user = &LONCAPA::clean_username($user);
16396: 	$domain = &LONCAPA::clean_username($domain);
16397: 	if ($user ne '' && $domain ne '') {
16398: 	    $cenv{'keyauth'}=$user.':'.$domain;
16399: 	}
16400:     }
16401: 
16402: #
16403: #  generate and store uniquecode (available to course requester), if course should have one.
16404: #
16405:     if ($args->{'uniquecode'}) {
16406:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16407:         if ($code) {
16408:             $cenv{'internal.uniquecode'} = $code;
16409:             my %crsinfo =
16410:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16411:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16412:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16413:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16414:             } 
16415:             if (ref($coderef)) {
16416:                 $$coderef = $code;
16417:             }
16418:         }
16419:     }
16420: 
16421:     if ($args->{'disresdis'}) {
16422:         $cenv{'pch.roles.denied'}='st';
16423:     }
16424:     if ($args->{'disablechat'}) {
16425:         $cenv{'plc.roles.denied'}='st';
16426:     }
16427: 
16428:     # Record we've not yet viewed the Course Initialization Helper for this 
16429:     # course
16430:     $cenv{'course.helper.not.run'} = 1;
16431:     #
16432:     # Use new Randomseed
16433:     #
16434:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16435:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16436:     #
16437:     # The encryption code and receipt prefix for this course
16438:     #
16439:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16440:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16441:     #
16442:     # By default, use standard grading
16443:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16444: 
16445:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16446:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16447: #
16448: # Open all assignments
16449: #
16450:     if ($args->{'openall'}) {
16451:        my $opendate = time;
16452:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16453:            $opendate = $args->{'openallfrom'};
16454:        }
16455:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16456:        my %storecontent = ($storeunder         => $opendate,
16457:                            $storeunder.'.type' => 'date_start');
16458:        $outcome .= &mt('All assignments open starting [_1]',
16459:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16460:                    &Apache::lonnet::cput
16461:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16462:    }
16463: #
16464: # Set first page
16465: #
16466:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16467: 	    || ($cloneid)) {
16468: 	use LONCAPA::map;
16469: 	$outcome .= &mt('Setting first resource').': ';
16470: 
16471: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16472:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16473: 
16474:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16475:         my $title; my $url;
16476:         if ($args->{'firstres'} eq 'syl') {
16477: 	    $title=&mt('Syllabus');
16478:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16479:         } else {
16480:             $title=&mt('Table of Contents');
16481:             $url='/adm/navmaps';
16482:         }
16483: 
16484:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16485: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16486: 
16487: 	if ($errtext) { $fatal=2; }
16488:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16489:     }
16490: 
16491: # 
16492: # Set params for Placement Tests
16493: #
16494:     if ($args->{'crstype'} eq 'Placement') {
16495:        my %storecontent; 
16496:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16497:        my %defaults = (
16498:                         buttonshide   => { value => 'yes',
16499:                                            type => 'string_yesno',},
16500:                         type          => { value => 'randomizetry',
16501:                                            type  => 'string_questiontype',},
16502:                         maxtries      => { value => 1,
16503:                                            type => 'int_pos',},
16504:                         problemstatus => { value => 'no',
16505:                                            type  => 'string_problemstatus',},
16506:                       );
16507:        foreach my $key (keys(%defaults)) {
16508:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16509:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16510:        }
16511:        &Apache::lonnet::cput
16512:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
16513:     }
16514: 
16515:     return (1,$outcome,\@clonemsg);
16516: }
16517: 
16518: sub make_unique_code {
16519:     my ($cdom,$cnum) = @_;
16520:     # get lock on uniquecodes db
16521:     my $lockhash = {
16522:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16523:                                                   ':'.$env{'user.domain'},
16524:                    };
16525:     my $tries = 0;
16526:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16527:     my ($code,$error);
16528:   
16529:     while (($gotlock ne 'ok') && ($tries<3)) {
16530:         $tries ++;
16531:         sleep 1;
16532:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16533:     }
16534:     if ($gotlock eq 'ok') {
16535:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16536:         my $gotcode;
16537:         my $attempts = 0;
16538:         while ((!$gotcode) && ($attempts < 100)) {
16539:             $code = &generate_code();
16540:             if (!exists($currcodes{$code})) {
16541:                 $gotcode = 1;
16542:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16543:                     $error = 'nostore';
16544:                 }
16545:             }
16546:             $attempts ++;
16547:         }
16548:         my @del_lock = ($cnum."\0".'uniquecodes');
16549:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16550:     } else {
16551:         $error = 'nolock';
16552:     }
16553:     return ($code,$error);
16554: }
16555: 
16556: sub generate_code {
16557:     my $code;
16558:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16559:     for (my $i=0; $i<6; $i++) {
16560:         my $lettnum = int (rand 2);
16561:         my $item = '';
16562:         if ($lettnum) {
16563:             $item = $letts[int( rand(18) )];
16564:         } else {
16565:             $item = 1+int( rand(8) );
16566:         }
16567:         $code .= $item;
16568:     }
16569:     return $code;
16570: }
16571: 
16572: ############################################################
16573: ############################################################
16574: 
16575: # Community, Course and Placement Test
16576: sub course_type {
16577:     my ($cid) = @_;
16578:     if (!defined($cid)) {
16579:         $cid = $env{'request.course.id'};
16580:     }
16581:     if (defined($env{'course.'.$cid.'.type'})) {
16582:         return $env{'course.'.$cid.'.type'};
16583:     } else {
16584:         return 'Course';
16585:     }
16586: }
16587: 
16588: sub group_term {
16589:     my $crstype = &course_type();
16590:     my %names = (
16591:                   'Course' => 'group',
16592:                   'Community' => 'group',
16593:                   'Placement' => 'group',
16594:                 );
16595:     return $names{$crstype};
16596: }
16597: 
16598: sub course_types {
16599:     my @types = ('official','unofficial','community','textbook','placement','lti');
16600:     my %typename = (
16601:                          official   => 'Official course',
16602:                          unofficial => 'Unofficial course',
16603:                          community  => 'Community',
16604:                          textbook   => 'Textbook course',
16605:                          placement  => 'Placement test',
16606:                          lti        => 'LTI provider',
16607:                    );
16608:     return (\@types,\%typename);
16609: }
16610: 
16611: sub icon {
16612:     my ($file)=@_;
16613:     my $curfext = lc((split(/\./,$file))[-1]);
16614:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16615:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16616:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16617: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16618: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16619: 	            $curfext.".gif") {
16620: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16621: 		$curfext.".gif";
16622: 	}
16623:     }
16624:     return &lonhttpdurl($iconname);
16625: } 
16626: 
16627: sub lonhttpdurl {
16628: #
16629: # Had been used for "small fry" static images on separate port 8080.
16630: # Modify here if lightweight http functionality desired again.
16631: # Currently eliminated due to increasing firewall issues.
16632: #
16633:     my ($url)=@_;
16634:     return $url;
16635: }
16636: 
16637: sub connection_aborted {
16638:     my ($r)=@_;
16639:     $r->print(" ");$r->rflush();
16640:     my $c = $r->connection;
16641:     return $c->aborted();
16642: }
16643: 
16644: #    Escapes strings that may have embedded 's that will be put into
16645: #    strings as 'strings'.
16646: sub escape_single {
16647:     my ($input) = @_;
16648:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16649:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16650:     return $input;
16651: }
16652: 
16653: #  Same as escape_single, but escape's "'s  This 
16654: #  can be used for  "strings"
16655: sub escape_double {
16656:     my ($input) = @_;
16657:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16658:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16659:     return $input;
16660: }
16661:  
16662: #   Escapes the last element of a full URL.
16663: sub escape_url {
16664:     my ($url)   = @_;
16665:     my @urlslices = split(/\//, $url,-1);
16666:     my $lastitem = &escape(pop(@urlslices));
16667:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16668: }
16669: 
16670: sub compare_arrays {
16671:     my ($arrayref1,$arrayref2) = @_;
16672:     my (@difference,%count);
16673:     @difference = ();
16674:     %count = ();
16675:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16676:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16677:         foreach my $element (keys(%count)) {
16678:             if ($count{$element} == 1) {
16679:                 push(@difference,$element);
16680:             }
16681:         }
16682:     }
16683:     return @difference;
16684: }
16685: 
16686: sub lon_status_items {
16687:     my %defaults = (
16688:                      E         => 100,
16689:                      W         => 4,
16690:                      N         => 1,
16691:                      U         => 5,
16692:                      threshold => 200,
16693:                      sysmail   => 2500,
16694:                    );
16695:     my %names = (
16696:                    E => 'Errors',
16697:                    W => 'Warnings',
16698:                    N => 'Notices',
16699:                    U => 'Unsent',
16700:                 );
16701:     return (\%defaults,\%names);
16702: }
16703: 
16704: # -------------------------------------------------------- Initialize user login
16705: sub init_user_environment {
16706:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16707:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16708: 
16709:     my $public=($username eq 'public' && $domain eq 'public');
16710: 
16711:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16712:     my $now=time;
16713: 
16714:     if ($public) {
16715: 	my $max_public=100;
16716: 	my $oldest;
16717: 	my $oldest_time=0;
16718: 	for(my $next=1;$next<=$max_public;$next++) {
16719: 	    if (-e $lonids."/publicuser_$next.id") {
16720: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16721: 		if ($mtime<$oldest_time || !$oldest_time) {
16722: 		    $oldest_time=$mtime;
16723: 		    $oldest=$next;
16724: 		}
16725: 	    } else {
16726: 		$cookie="publicuser_$next";
16727: 		last;
16728: 	    }
16729: 	}
16730: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16731:     } else {
16732: 	# See if old ID present, if so, remove if this isn't a robot,
16733: 	# killing any existing non-robot sessions
16734: 	if (!$args->{'robot'}) {
16735: 	    opendir(DIR,$lonids);
16736: 	    while ($filename=readdir(DIR)) {
16737: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16738:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16739:                             &GDBM_READER(),0640)) {
16740:                         my $linkedfile;
16741:                         if (exists($oldenv{'user.linkedenv'})) {
16742:                             $linkedfile = $oldenv{'user.linkedenv'};
16743:                         }
16744:                         untie(%oldenv);
16745:                         if (unlink("$lonids/$filename")) {
16746:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16747:                                 if (-l "$lonids/$linkedfile.id") {
16748:                                     unlink("$lonids/$linkedfile.id");
16749:                                 }
16750:                             }
16751:                         }
16752:                     } else {
16753:                         unlink($lonids.'/'.$filename);
16754:                     }
16755: 		}
16756: 	    }
16757: 	    closedir(DIR);
16758: # If there is a undeleted lockfile for the user's paste buffer remove it.
16759:             my $namespace = 'nohist_courseeditor';
16760:             my $lockingkey = 'paste'."\0".'locked_num';
16761:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16762:                                                 $domain,$username);
16763:             if (exists($lockhash{$lockingkey})) {
16764:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16765:                 unless ($delresult eq 'ok') {
16766:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16767:                 }
16768:             }
16769: 	}
16770: # Give them a new cookie
16771: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16772: 		                   : $now.$$.int(rand(10000)));
16773: 	$cookie="$username\_$id\_$domain\_$authhost";
16774:     
16775: # Initialize roles
16776: 
16777: 	($userroles,$firstaccenv,$timerintenv) = 
16778:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16779:     }
16780: # ------------------------------------ Check browser type and MathML capability
16781: 
16782:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16783:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16784: 
16785: # ------------------------------------------------------------- Get environment
16786: 
16787:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16788:     my ($tmp) = keys(%userenv);
16789:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16790: 	undef(%userenv);
16791:     }
16792:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16793: 	$form->{'interface'}=$userenv{'interface'};
16794:     }
16795:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16796: 
16797: # --------------- Do not trust query string to be put directly into environment
16798:     foreach my $option ('interface','localpath','localres') {
16799:         $form->{$option}=~s/[\n\r\=]//gs;
16800:     }
16801: # --------------------------------------------------------- Write first profile
16802: 
16803:     {
16804: 	my %initial_env = 
16805: 	    ("user.name"          => $username,
16806: 	     "user.domain"        => $domain,
16807: 	     "user.home"          => $authhost,
16808: 	     "browser.type"       => $clientbrowser,
16809: 	     "browser.version"    => $clientversion,
16810: 	     "browser.mathml"     => $clientmathml,
16811: 	     "browser.unicode"    => $clientunicode,
16812: 	     "browser.os"         => $clientos,
16813:              "browser.mobile"     => $clientmobile,
16814:              "browser.info"       => $clientinfo,
16815:              "browser.osversion"  => $clientosversion,
16816: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16817: 	     "request.course.fn"  => '',
16818: 	     "request.course.uri" => '',
16819: 	     "request.course.sec" => '',
16820: 	     "request.role"       => 'cm',
16821: 	     "request.role.adv"   => $env{'user.adv'},
16822: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16823: 
16824:         if ($form->{'localpath'}) {
16825: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16826: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16827:         }
16828: 	
16829: 	if ($form->{'interface'}) {
16830: 	    $form->{'interface'}=~s/\W//gs;
16831: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16832: 	    $env{'browser.interface'}=$form->{'interface'};
16833: 	}
16834: 
16835:         if ($form->{'iptoken'}) {
16836:             my $lonhost = $r->dir_config('lonHostID');
16837:             $initial_env{"user.noloadbalance"} = $lonhost;
16838:             $env{'user.noloadbalance'} = $lonhost;
16839:         }
16840: 
16841:         if ($form->{'noloadbalance'}) {
16842:             my @hosts = &Apache::lonnet::current_machine_ids();
16843:             my $hosthere = $form->{'noloadbalance'};
16844:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16845:                 $initial_env{"user.noloadbalance"} = $hosthere;
16846:                 $env{'user.noloadbalance'} = $hosthere;
16847:             }
16848:         }
16849: 
16850:         unless ($domain eq 'public') {
16851:             my %is_adv = ( is_adv => $env{'user.adv'} );
16852:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16853: 
16854:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16855:                 $userenv{'availabletools.'.$tool} = 
16856:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16857:                                                       undef,\%userenv,\%domdef,\%is_adv);
16858:             }
16859: 
16860:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
16861:                 $userenv{'canrequest.'.$crstype} =
16862:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16863:                                                       'reload','requestcourses',
16864:                                                       \%userenv,\%domdef,\%is_adv);
16865:             }
16866: 
16867:             $userenv{'canrequest.author'} =
16868:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16869:                                                   'reload','requestauthor',
16870:                                                   \%userenv,\%domdef,\%is_adv);
16871:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16872:                                                  $domain,$username);
16873:             my $reqstatus = $reqauthor{'author_status'};
16874:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16875:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16876:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16877:                                                       $reqauthor{'author'}{'timestamp'};
16878:                 }
16879:             }
16880:             my ($types,$typename) = &course_types();
16881:             if (ref($types) eq 'ARRAY') {
16882:                 my @options = ('approval','validate','autolimit');
16883:                 my $optregex = join('|',@options);
16884:                 my (%willtrust,%trustchecked);
16885:                 foreach my $type (@{$types}) {
16886:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
16887:                     if ($dom_str ne '') {
16888:                         my $updatedstr = '';
16889:                         my @possdomains = split(',',$dom_str);
16890:                         foreach my $entry (@possdomains) {
16891:                             my ($extdom,$extopt) = split(':',$entry);
16892:                             unless ($trustchecked{$extdom}) {
16893:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
16894:                                 $trustchecked{$extdom} = 1;
16895:                             }
16896:                             if ($willtrust{$extdom}) {
16897:                                 $updatedstr .= $entry.',';
16898:                             }
16899:                         }
16900:                         $updatedstr =~ s/,$//;
16901:                         if ($updatedstr) {
16902:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
16903:                         } else {
16904:                             delete($userenv{'reqcrsotherdom.'.$type});
16905:                         }
16906:                     }
16907:                 }
16908:             }
16909:         }
16910: 	$env{'user.environment'} = "$lonids/$cookie.id";
16911: 
16912: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16913: 		 &GDBM_WRCREAT(),0640)) {
16914: 	    &_add_to_env(\%disk_env,\%initial_env);
16915: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16916: 	    &_add_to_env(\%disk_env,$userroles);
16917:             if (ref($firstaccenv) eq 'HASH') {
16918:                 &_add_to_env(\%disk_env,$firstaccenv);
16919:             }
16920:             if (ref($timerintenv) eq 'HASH') {
16921:                 &_add_to_env(\%disk_env,$timerintenv);
16922:             }
16923: 	    if (ref($args->{'extra_env'})) {
16924: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16925: 	    }
16926: 	    untie(%disk_env);
16927: 	} else {
16928: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16929: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16930: 	    return 'error: '.$!;
16931: 	}
16932:     }
16933:     $env{'request.role'}='cm';
16934:     $env{'request.role.adv'}=$env{'user.adv'};
16935:     $env{'browser.type'}=$clientbrowser;
16936: 
16937:     return $cookie;
16938: 
16939: }
16940: 
16941: sub _add_to_env {
16942:     my ($idf,$env_data,$prefix) = @_;
16943:     if (ref($env_data) eq 'HASH') {
16944:         while (my ($key,$value) = each(%$env_data)) {
16945: 	    $idf->{$prefix.$key} = $value;
16946: 	    $env{$prefix.$key}   = $value;
16947:         }
16948:     }
16949: }
16950: 
16951: # --- Get the symbolic name of a problem and the url
16952: sub get_symb {
16953:     my ($request,$silent) = @_;
16954:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16955:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16956:     if ($symb eq '') {
16957:         if (!$silent) {
16958:             if (ref($request)) { 
16959:                 $request->print("Unable to handle ambiguous references:$url:.");
16960:             }
16961:             return ();
16962:         }
16963:     }
16964:     &Apache::lonenc::check_decrypt(\$symb);
16965:     return ($symb);
16966: }
16967: 
16968: # --------------------------------------------------------------Get annotation
16969: 
16970: sub get_annotation {
16971:     my ($symb,$enc) = @_;
16972: 
16973:     my $key = $symb;
16974:     if (!$enc) {
16975:         $key =
16976:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16977:     }
16978:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16979:     return $annotation{$key};
16980: }
16981: 
16982: sub clean_symb {
16983:     my ($symb,$delete_enc) = @_;
16984: 
16985:     &Apache::lonenc::check_decrypt(\$symb);
16986:     my $enc = $env{'request.enc'};
16987:     if ($delete_enc) {
16988:         delete($env{'request.enc'});
16989:     }
16990: 
16991:     return ($symb,$enc);
16992: }
16993: 
16994: ############################################################
16995: ############################################################
16996: 
16997: =pod
16998: 
16999: =head1 Routines for building display used to search for courses
17000: 
17001: 
17002: =over 4
17003: 
17004: =item * &build_filters()
17005: 
17006: Create markup for a table used to set filters to use when selecting
17007: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17008: and quotacheck.pl
17009: 
17010: 
17011: Inputs:
17012: 
17013: filterlist - anonymous array of fields to include as potential filters 
17014: 
17015: crstype - course type
17016: 
17017: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17018:               to pop-open a course selector (will contain "extra element"). 
17019: 
17020: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17021: 
17022: filter - anonymous hash of criteria and their values
17023: 
17024: action - form action
17025: 
17026: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17027: 
17028: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17029: 
17030: cloneruname - username of owner of new course who wants to clone
17031: 
17032: clonerudom - domain of owner of new course who wants to clone
17033: 
17034: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17035: 
17036: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17037: 
17038: codedom - domain
17039: 
17040: formname - value of form element named "form". 
17041: 
17042: fixeddom - domain, if fixed.
17043: 
17044: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17045: 
17046: cnameelement - name of form element in form on opener page which will receive title of selected course 
17047: 
17048: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17049: 
17050: cdomelement - name of form element in form on opener page which will receive domain of selected course
17051: 
17052: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17053: 
17054: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17055: 
17056: clonewarning - warning message about missing information for intended course owner when DC creates a course
17057: 
17058: 
17059: Returns: $output - HTML for display of search criteria, and hidden form elements.
17060: 
17061: 
17062: Side Effects: None
17063: 
17064: =cut
17065: 
17066: # ---------------------------------------------- search for courses based on last activity etc.
17067: 
17068: sub build_filters {
17069:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17070:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17071:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17072:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17073:         $clonetext,$clonewarning) = @_;
17074:     my ($list,$jscript);
17075:     my $onchange = 'javascript:updateFilters(this)';
17076:     my ($domainselectform,$sincefilterform,$createdfilterform,
17077:         $ownerdomselectform,$persondomselectform,$instcodeform,
17078:         $typeselectform,$instcodetitle);
17079:     if ($formname eq '') {
17080:         $formname = $caller;
17081:     }
17082:     foreach my $item (@{$filterlist}) {
17083:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17084:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17085:             if ($item eq 'domainfilter') {
17086:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17087:             } elsif ($item eq 'coursefilter') {
17088:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17089:             } elsif ($item eq 'ownerfilter') {
17090:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17091:             } elsif ($item eq 'ownerdomfilter') {
17092:                 $filter->{'ownerdomfilter'} =
17093:                     &LONCAPA::clean_domain($filter->{$item});
17094:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17095:                                                        'ownerdomfilter',1);
17096:             } elsif ($item eq 'personfilter') {
17097:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17098:             } elsif ($item eq 'persondomfilter') {
17099:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17100:                                                         'persondomfilter',1);
17101:             } else {
17102:                 $filter->{$item} =~ s/\W//g;
17103:             }
17104:             if (!$filter->{$item}) {
17105:                 $filter->{$item} = '';
17106:             }
17107:         }
17108:         if ($item eq 'domainfilter') {
17109:             my $allow_blank = 1;
17110:             if ($formname eq 'portform') {
17111:                 $allow_blank=0;
17112:             } elsif ($formname eq 'studentform') {
17113:                 $allow_blank=0;
17114:             }
17115:             if ($fixeddom) {
17116:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17117:                                     ' value="'.$codedom.'" />'.
17118:                                     &Apache::lonnet::domain($codedom,'description');
17119:             } else {
17120:                 $domainselectform = &select_dom_form($filter->{$item},
17121:                                                      'domainfilter',
17122:                                                       $allow_blank,'',$onchange);
17123:             }
17124:         } else {
17125:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17126:         }
17127:     }
17128: 
17129:     # last course activity filter and selection
17130:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17131: 
17132:     # course created filter and selection
17133:     if (exists($filter->{'createdfilter'})) {
17134:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17135:     }
17136: 
17137:     my $prefix = $crstype;
17138:     if ($crstype eq 'Placement') {
17139:         $prefix = 'Placement Test'
17140:     }
17141:     my %lt = &Apache::lonlocal::texthash(
17142:                 'cac' => "$prefix Activity",
17143:                 'ccr' => "$prefix Created",
17144:                 'cde' => "$prefix Title",
17145:                 'cdo' => "$prefix Domain",
17146:                 'ins' => 'Institutional Code',
17147:                 'inc' => 'Institutional Categorization',
17148:                 'cow' => "$prefix Owner/Co-owner",
17149:                 'cop' => "$prefix Personnel Includes",
17150:                 'cog' => 'Type',
17151:              );
17152: 
17153:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17154:         my $typeval = 'Course';
17155:         if ($crstype eq 'Community') {
17156:             $typeval = 'Community';
17157:         } elsif ($crstype eq 'Placement') {
17158:             $typeval = 'Placement';
17159:         }
17160:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17161:     } else {
17162:         $typeselectform =  '<select name="type" size="1"';
17163:         if ($onchange) {
17164:             $typeselectform .= ' onchange="'.$onchange.'"';
17165:         }
17166:         $typeselectform .= '>'."\n";
17167:         foreach my $posstype ('Course','Community','Placement') {
17168:             my $shown;
17169:             if ($posstype eq 'Placement') {
17170:                 $shown = &mt('Placement Test');
17171:             } else {
17172:                 $shown = &mt($posstype);
17173:             }
17174:             $typeselectform.='<option value="'.$posstype.'"'.
17175:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17176:         }
17177:         $typeselectform.="</select>";
17178:     }
17179: 
17180:     my ($cloneableonlyform,$cloneabletitle);
17181:     if (exists($filter->{'cloneableonly'})) {
17182:         my $cloneableon = '';
17183:         my $cloneableoff = ' checked="checked"';
17184:         if ($filter->{'cloneableonly'}) {
17185:             $cloneableon = $cloneableoff;
17186:             $cloneableoff = '';
17187:         }
17188:         $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>';
17189:         if ($formname eq 'ccrs') {
17190:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17191:         } else {
17192:             $cloneabletitle = &mt('Cloneable by you');
17193:         }
17194:     }
17195:     my $officialjs;
17196:     if ($crstype eq 'Course') {
17197:         if (exists($filter->{'instcodefilter'})) {
17198: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17199: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17200:             if ($codedom) { 
17201:                 $officialjs = 1;
17202:                 ($instcodeform,$jscript,$$numtitlesref) =
17203:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17204:                                                                   $officialjs,$codetitlesref);
17205:                 if ($jscript) {
17206:                     $jscript = '<script type="text/javascript">'."\n".
17207:                                '// <![CDATA['."\n".
17208:                                $jscript."\n".
17209:                                '// ]]>'."\n".
17210:                                '</script>'."\n";
17211:                 }
17212:             }
17213:             if ($instcodeform eq '') {
17214:                 $instcodeform =
17215:                     '<input type="text" name="instcodefilter" size="10" value="'.
17216:                     $list->{'instcodefilter'}.'" />';
17217:                 $instcodetitle = $lt{'ins'};
17218:             } else {
17219:                 $instcodetitle = $lt{'inc'};
17220:             }
17221:             if ($fixeddom) {
17222:                 $instcodetitle .= '<br />('.$codedom.')';
17223:             }
17224:         }
17225:     }
17226:     my $output = qq|
17227: <form method="post" name="filterpicker" action="$action">
17228: <input type="hidden" name="form" value="$formname" />
17229: |;
17230:     if ($formname eq 'modifycourse') {
17231:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17232:                    '<input type="hidden" name="prevphase" value="'.
17233:                    $prevphase.'" />'."\n";
17234:     } elsif ($formname eq 'quotacheck') {
17235:         $output .= qq|
17236: <input type="hidden" name="sortby" value="" />
17237: <input type="hidden" name="sortorder" value="" />
17238: |;
17239:     } else {
17240:         my $name_input;
17241:         if ($cnameelement ne '') {
17242:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17243:                           $cnameelement.'" />';
17244:         }
17245:         $output .= qq|
17246: <input type="hidden" name="cnumelement" value="$cnumelement" />
17247: <input type="hidden" name="cdomelement" value="$cdomelement" />
17248: $name_input
17249: $roleelement
17250: $multelement
17251: $typeelement
17252: |;
17253:         if ($formname eq 'portform') {
17254:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17255:         }
17256:     }
17257:     if ($fixeddom) {
17258:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17259:     }
17260:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17261:     if ($sincefilterform) {
17262:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17263:                   .$sincefilterform
17264:                   .&Apache::lonhtmlcommon::row_closure();
17265:     }
17266:     if ($createdfilterform) {
17267:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17268:                   .$createdfilterform
17269:                   .&Apache::lonhtmlcommon::row_closure();
17270:     }
17271:     if ($domainselectform) {
17272:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17273:                   .$domainselectform
17274:                   .&Apache::lonhtmlcommon::row_closure();
17275:     }
17276:     if ($typeselectform) {
17277:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17278:             $output .= $typeselectform;
17279:         } else {
17280:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17281:                       .$typeselectform
17282:                       .&Apache::lonhtmlcommon::row_closure();
17283:         }
17284:     }
17285:     if ($instcodeform) {
17286:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17287:                   .$instcodeform
17288:                   .&Apache::lonhtmlcommon::row_closure();
17289:     }
17290:     if (exists($filter->{'ownerfilter'})) {
17291:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17292:                    '<table><tr><td>'.&mt('Username').'<br />'.
17293:                    '<input type="text" name="ownerfilter" size="20" value="'.
17294:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17295:                    $ownerdomselectform.'</td></tr></table>'.
17296:                    &Apache::lonhtmlcommon::row_closure();
17297:     }
17298:     if (exists($filter->{'personfilter'})) {
17299:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17300:                    '<table><tr><td>'.&mt('Username').'<br />'.
17301:                    '<input type="text" name="personfilter" size="20" value="'.
17302:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17303:                    $persondomselectform.'</td></tr></table>'.
17304:                    &Apache::lonhtmlcommon::row_closure();
17305:     }
17306:     if (exists($filter->{'coursefilter'})) {
17307:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17308:                   .'<input type="text" name="coursefilter" size="25" value="'
17309:                   .$list->{'coursefilter'}.'" />'
17310:                   .&Apache::lonhtmlcommon::row_closure();
17311:     }
17312:     if ($cloneableonlyform) {
17313:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17314:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17315:     }
17316:     if (exists($filter->{'descriptfilter'})) {
17317:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17318:                   .'<input type="text" name="descriptfilter" size="40" value="'
17319:                   .$list->{'descriptfilter'}.'" />'
17320:                   .&Apache::lonhtmlcommon::row_closure(1);
17321:     }
17322:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17323:                '<input type="hidden" name="updater" value="" />'."\n".
17324:                '<input type="submit" name="gosearch" value="'.
17325:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17326:     return $jscript.$clonewarning.$output;
17327: }
17328: 
17329: =pod 
17330: 
17331: =item * &timebased_select_form()
17332: 
17333: Create markup for a dropdown list used to select a time-based
17334: filter e.g., Course Activity, Course Created, when searching for courses
17335: or communities
17336: 
17337: Inputs:
17338: 
17339: item - name of form element (sincefilter or createdfilter)
17340: 
17341: filter - anonymous hash of criteria and their values
17342: 
17343: Returns: HTML for a select box contained a blank, then six time selections,
17344:          with value set in incoming form variables currently selected. 
17345: 
17346: Side Effects: None
17347: 
17348: =cut
17349: 
17350: sub timebased_select_form {
17351:     my ($item,$filter) = @_;
17352:     if (ref($filter) eq 'HASH') {
17353:         $filter->{$item} =~ s/[^\d-]//g;
17354:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17355:         return &select_form(
17356:                             $filter->{$item},
17357:                             $item,
17358:                             {      '-1' => '',
17359:                                 '86400' => &mt('today'),
17360:                                '604800' => &mt('last week'),
17361:                               '2592000' => &mt('last month'),
17362:                               '7776000' => &mt('last three months'),
17363:                              '15552000' => &mt('last six months'),
17364:                              '31104000' => &mt('last year'),
17365:                     'select_form_order' =>
17366:                            ['-1','86400','604800','2592000','7776000',
17367:                             '15552000','31104000']});
17368:     }
17369: }
17370: 
17371: =pod
17372: 
17373: =item * &js_changer()
17374: 
17375: Create script tag containing Javascript used to submit course search form
17376: when course type or domain is changed, and also to hide 'Searching ...' on
17377: page load completion for page showing search result.
17378: 
17379: Inputs: None
17380: 
17381: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
17382: 
17383: Side Effects: None
17384: 
17385: =cut
17386: 
17387: sub js_changer {
17388:     return <<ENDJS;
17389: <script type="text/javascript">
17390: // <![CDATA[
17391: function updateFilters(caller) {
17392:     if (typeof(caller) != "undefined") {
17393:         document.filterpicker.updater.value = caller.name;
17394:     }
17395:     document.filterpicker.submit();
17396: }
17397: 
17398: function hideSearching() {
17399:     if (document.getElementById('searching')) {
17400:         document.getElementById('searching').style.display = 'none';
17401:     }
17402:     return;
17403: }
17404: 
17405: // ]]>
17406: </script>
17407: 
17408: ENDJS
17409: }
17410: 
17411: =pod
17412: 
17413: =item * &search_courses()
17414: 
17415: Process selected filters form course search form and pass to lonnet::courseiddump
17416: to retrieve a hash for which keys are courseIDs which match the selected filters.
17417: 
17418: Inputs:
17419: 
17420: dom - domain being searched 
17421: 
17422: type - course type ('Course' or 'Community' or '.' if any).
17423: 
17424: filter - anonymous hash of criteria and their values
17425: 
17426: numtitles - for institutional codes - number of categories
17427: 
17428: cloneruname - optional username of new course owner
17429: 
17430: clonerudom - optional domain of new course owner
17431: 
17432: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
17433:             (used when DC is using course creation form)
17434: 
17435: codetitles - reference to array of titles of components in institutional codes (official courses).
17436: 
17437: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17438:            (and so can clone automatically)
17439: 
17440: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17441: 
17442: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
17443:               courses to clone 
17444: 
17445: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17446: 
17447: 
17448: Side Effects: None
17449: 
17450: =cut
17451: 
17452: 
17453: sub search_courses {
17454:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17455:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17456:     my (%courses,%showcourses,$cloner);
17457:     if (($filter->{'ownerfilter'} ne '') ||
17458:         ($filter->{'ownerdomfilter'} ne '')) {
17459:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17460:                                        $filter->{'ownerdomfilter'};
17461:     }
17462:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17463:         if (!$filter->{$item}) {
17464:             $filter->{$item}='.';
17465:         }
17466:     }
17467:     my $now = time;
17468:     my $timefilter =
17469:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17470:     my ($createdbefore,$createdafter);
17471:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17472:         $createdbefore = $now;
17473:         $createdafter = $now-$filter->{'createdfilter'};
17474:     }
17475:     my ($instcodefilter,$regexpok);
17476:     if ($numtitles) {
17477:         if ($env{'form.official'} eq 'on') {
17478:             $instcodefilter =
17479:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17480:             $regexpok = 1;
17481:         } elsif ($env{'form.official'} eq 'off') {
17482:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17483:             unless ($instcodefilter eq '') {
17484:                 $regexpok = -1;
17485:             }
17486:         }
17487:     } else {
17488:         $instcodefilter = $filter->{'instcodefilter'};
17489:     }
17490:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17491:     if ($type eq '') { $type = '.'; }
17492: 
17493:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17494:         $cloner = $cloneruname.':'.$clonerudom;
17495:     }
17496:     %courses = &Apache::lonnet::courseiddump($dom,
17497:                                              $filter->{'descriptfilter'},
17498:                                              $timefilter,
17499:                                              $instcodefilter,
17500:                                              $filter->{'combownerfilter'},
17501:                                              $filter->{'coursefilter'},
17502:                                              undef,undef,$type,$regexpok,undef,undef,
17503:                                              undef,undef,$cloner,$cc_clone,
17504:                                              $filter->{'cloneableonly'},
17505:                                              $createdbefore,$createdafter,undef,
17506:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17507:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17508:         my $ccrole;
17509:         if ($type eq 'Community') {
17510:             $ccrole = 'co';
17511:         } else {
17512:             $ccrole = 'cc';
17513:         }
17514:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17515:                                                      $filter->{'persondomfilter'},
17516:                                                      'userroles',undef,
17517:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17518:                                                      $dom);
17519:         foreach my $role (keys(%rolehash)) {
17520:             my ($cnum,$cdom,$courserole) = split(':',$role);
17521:             my $cid = $cdom.'_'.$cnum;
17522:             if (exists($courses{$cid})) {
17523:                 if (ref($courses{$cid}) eq 'HASH') {
17524:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17525:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17526:                             push(@{$courses{$cid}{roles}},$courserole);
17527:                         }
17528:                     } else {
17529:                         $courses{$cid}{roles} = [$courserole];
17530:                     }
17531:                     $showcourses{$cid} = $courses{$cid};
17532:                 }
17533:             }
17534:         }
17535:         %courses = %showcourses;
17536:     }
17537:     return %courses;
17538: }
17539: 
17540: =pod
17541: 
17542: =back
17543: 
17544: =head1 Routines for version requirements for current course.
17545: 
17546: =over 4
17547: 
17548: =item * &check_release_required()
17549: 
17550: Compares required LON-CAPA version with version on server, and
17551: if required version is newer looks for a server with the required version.
17552: 
17553: Looks first at servers in user's owen domain; if none suitable, looks at
17554: servers in course's domain are permitted to host sessions for user's domain.
17555: 
17556: Inputs:
17557: 
17558: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17559: 
17560: $courseid - Course ID of current course
17561: 
17562: $rolecode - User's current role in course (for switchserver query string).
17563: 
17564: $required - LON-CAPA version needed by course (format: Major.Minor).
17565: 
17566: 
17567: Returns:
17568: 
17569: $switchserver - query string tp append to /adm/switchserver call (if 
17570:                 current server's LON-CAPA version is too old. 
17571: 
17572: $warning - Message is displayed if no suitable server could be found.
17573: 
17574: =cut
17575: 
17576: sub check_release_required {
17577:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17578:     my ($switchserver,$warning);
17579:     if ($required ne '') {
17580:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17581:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17582:         if ($reqdmajor ne '' && $reqdminor ne '') {
17583:             my $otherserver;
17584:             if (($major eq '' && $minor eq '') ||
17585:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17586:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17587:                 my $switchlcrev =
17588:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17589:                                                            $userdomserver);
17590:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17591:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17592:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17593:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17594:                     if ($cdom ne $env{'user.domain'}) {
17595:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17596:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17597:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17598:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17599:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17600:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17601:                         my $canhost =
17602:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17603:                                                               $coursedomserver,
17604:                                                               $remoterev,
17605:                                                               $udomdefaults{'remotesessions'},
17606:                                                               $defdomdefaults{'hostedsessions'});
17607: 
17608:                         if ($canhost) {
17609:                             $otherserver = $coursedomserver;
17610:                         } else {
17611:                             $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.");
17612:                         }
17613:                     } else {
17614:                         $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).");
17615:                     }
17616:                 } else {
17617:                     $otherserver = $userdomserver;
17618:                 }
17619:             }
17620:             if ($otherserver ne '') {
17621:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17622:             }
17623:         }
17624:     }
17625:     return ($switchserver,$warning);
17626: }
17627: 
17628: =pod
17629: 
17630: =item * &check_release_result()
17631: 
17632: Inputs:
17633: 
17634: $switchwarning - Warning message if no suitable server found to host session.
17635: 
17636: $switchserver - query string to append to /adm/switchserver containing lonHostID
17637:                 and current role.
17638: 
17639: Returns: HTML to display with information about requirement to switch server.
17640:          Either displaying warning with link to Roles/Courses screen or
17641:          display link to switchserver.
17642: 
17643: =cut
17644: 
17645: sub check_release_result {
17646:     my ($switchwarning,$switchserver) = @_;
17647:     my $output = &start_page('Selected course unavailable on this server').
17648:                  '<p class="LC_warning">';
17649:     if ($switchwarning) {
17650:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17651:         if (&show_course()) {
17652:             $output .= &mt('Display courses');
17653:         } else {
17654:             $output .= &mt('Display roles');
17655:         }
17656:         $output .= '</a>';
17657:     } elsif ($switchserver) {
17658:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17659:                    '<br />'.
17660:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17661:                    &mt('Switch Server').
17662:                    '</a>';
17663:     }
17664:     $output .= '</p>'.&end_page();
17665:     return $output;
17666: }
17667: 
17668: =pod
17669: 
17670: =item * &needs_coursereinit()
17671: 
17672: Determine if course contents stored for user's session needs to be
17673: refreshed, because content has changed since "Big Hash" last tied.
17674: 
17675: Check for change is made if time last checked is more than 10 minutes ago
17676: (by default).
17677: 
17678: Inputs:
17679: 
17680: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17681: 
17682: $interval (optional) - Time which may elapse (in s) between last check for content
17683:                        change in current course. (default: 600 s).  
17684: 
17685: Returns: an array; first element is:
17686: 
17687: =over 4
17688: 
17689: 'switch' - if content updates mean user's session
17690:            needs to be switched to a server running a newer LON-CAPA version
17691:  
17692: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17693:            on current server hosting user's session                
17694: 
17695: ''       - if no action required.
17696: 
17697: =back
17698: 
17699: If first item element is 'switch':
17700: 
17701: second item is $switchwarning - Warning message if no suitable server found to host session. 
17702: 
17703: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17704:                               and current role. 
17705: 
17706: otherwise: no other elements returned.
17707: 
17708: =back
17709: 
17710: =cut
17711: 
17712: sub needs_coursereinit {
17713:     my ($loncaparev,$interval) = @_;
17714:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17715:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17716:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17717:     my $now = time;
17718:     if ($interval eq '') {
17719:         $interval = 600;
17720:     }
17721:     if (($now-$env{'request.course.timechecked'})>$interval) {
17722:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17723:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17724:         if ($blocked) {
17725:             return ();
17726:         }
17727:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17728:         if ($lastchange > $env{'request.course.tied'}) {
17729:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17730:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17731:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17732:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17733:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17734:                                              $curr_reqd_hash{'internal.releaserequired'}});
17735:                     my ($switchserver,$switchwarning) =
17736:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17737:                                                 $curr_reqd_hash{'internal.releaserequired'});
17738:                     if ($switchwarning ne '' || $switchserver ne '') {
17739:                         return ('switch',$switchwarning,$switchserver);
17740:                     }
17741:                 }
17742:             }
17743:             return ('update');
17744:         }
17745:     }
17746:     return ();
17747: }
17748: 
17749: sub update_content_constraints {
17750:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
17751:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17752:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17753:     my (%checkresponsetypes,%checkcrsrestypes);
17754:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17755:         my ($item,$name,$value) = split(/:/,$key);
17756:         if ($item eq 'resourcetag') {
17757:             if ($name eq 'responsetype') {
17758:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17759:             }
17760:         } elsif ($item eq 'course') {
17761:             if ($name eq 'courserestype') {
17762:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
17763:             }
17764:         }
17765:     }
17766:     my $navmap = Apache::lonnavmaps::navmap->new();
17767:     if (defined($navmap)) {
17768:         my (%allresponses,%allcrsrestypes);
17769:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
17770:             if ($res->is_tool()) {
17771:                 if ($allcrsrestypes{'exttool'}) {
17772:                     $allcrsrestypes{'exttool'} ++;
17773:                 } else {
17774:                     $allcrsrestypes{'exttool'} = 1;
17775:                 }
17776:                 next;
17777:             }
17778:             my %responses = $res->responseTypes();
17779:             foreach my $key (keys(%responses)) {
17780:                 next unless(exists($checkresponsetypes{$key}));
17781:                 $allresponses{$key} += $responses{$key};
17782:             }
17783:         }
17784:         foreach my $key (keys(%allresponses)) {
17785:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17786:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17787:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17788:             }
17789:         }
17790:         foreach my $key (keys(%allcrsrestypes)) {
17791:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
17792:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17793:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17794:             }
17795:         }
17796:         undef($navmap);
17797:     }
17798:     my (@resources,@order,@resparms,@zombies);
17799:     if ($keeporder) {
17800:         use LONCAPA::map;
17801:         @resources = @LONCAPA::map::resources;
17802:         @order = @LONCAPA::map::order;
17803:         @resparms = @LONCAPA::map::resparms;
17804:         @zombies = @LONCAPA::map::zombies;
17805:     }
17806:     my $suppmap = 'supplemental.sequence';
17807:     my ($suppcount,$supptools,$errors) = (0,0,0);
17808:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
17809:                                                             $suppcount,$supptools,$errors);
17810:     if ($keeporder) {
17811:         @LONCAPA::map::resources = @resources;
17812:         @LONCAPA::map::order = @order;
17813:         @LONCAPA::map::resparms = @resparms;
17814:         @LONCAPA::map::zombies = @zombies;
17815:     }
17816:     if ($supptools) {
17817:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
17818:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17819:             ($reqdmajor,$reqdminor) = ($major,$minor);
17820:         }
17821:     }
17822:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17823:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17824:     }
17825:     return;
17826: }
17827: 
17828: sub allmaps_incourse {
17829:     my ($cdom,$cnum,$chome,$cid) = @_;
17830:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17831:         $cid = $env{'request.course.id'};
17832:         $cdom = $env{'course.'.$cid.'.domain'};
17833:         $cnum = $env{'course.'.$cid.'.num'};
17834:         $chome = $env{'course.'.$cid.'.home'};
17835:     }
17836:     my %allmaps = ();
17837:     my $lastchange =
17838:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17839:     if ($lastchange > $env{'request.course.tied'}) {
17840:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17841:         unless ($ferr) {
17842:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
17843:         }
17844:     }
17845:     my $navmap = Apache::lonnavmaps::navmap->new();
17846:     if (defined($navmap)) {
17847:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17848:             $allmaps{$res->src()} = 1;
17849:         }
17850:     }
17851:     return \%allmaps;
17852: }
17853: 
17854: sub parse_supplemental_title {
17855:     my ($title) = @_;
17856: 
17857:     my ($foldertitle,$renametitle);
17858:     if ($title =~ /&amp;&amp;&amp;/) {
17859:         $title = &HTML::Entites::decode($title);
17860:     }
17861:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17862:         $renametitle=$4;
17863:         my ($time,$uname,$udom) = ($1,$2,$3);
17864:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17865:         my $name =  &plainname($uname,$udom);
17866:         $name = &HTML::Entities::encode($name,'"<>&\'');
17867:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17868:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17869:             $name.': <br />'.$foldertitle;
17870:     }
17871:     if (wantarray) {
17872:         return ($title,$foldertitle,$renametitle);
17873:     }
17874:     return $title;
17875: }
17876: 
17877: sub recurse_supplemental {
17878:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
17879:     if ($suppmap) {
17880:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17881:         if ($fatal) {
17882:             $errors ++;
17883:         } else {
17884:             if ($#LONCAPA::map::resources > 0) {
17885:                 foreach my $res (@LONCAPA::map::resources) {
17886:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17887:                     if (($src ne '') && ($status eq 'res')) {
17888:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17889:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
17890:                                                                    $numfiles,$numexttools,$errors);
17891:                         } else {
17892:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
17893:                                 $numexttools ++;
17894:                             }
17895:                             $numfiles ++;
17896:                         }
17897:                     }
17898:                 }
17899:             }
17900:         }
17901:     }
17902:     return ($numfiles,$numexttools,$errors);
17903: }
17904: 
17905: sub symb_to_docspath {
17906:     my ($symb,$navmapref) = @_;
17907:     return unless ($symb && ref($navmapref));
17908:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17909:     if ($resurl=~/\.(sequence|page)$/) {
17910:         $mapurl=$resurl;
17911:     } elsif ($resurl eq 'adm/navmaps') {
17912:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17913:     }
17914:     my $mapresobj;
17915:     unless (ref($$navmapref)) {
17916:         $$navmapref = Apache::lonnavmaps::navmap->new();
17917:     }
17918:     if (ref($$navmapref)) {
17919:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17920:     }
17921:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17922:     my $type=$2;
17923:     my $path;
17924:     if (ref($mapresobj)) {
17925:         my $pcslist = $mapresobj->map_hierarchy();
17926:         if ($pcslist ne '') {
17927:             foreach my $pc (split(/,/,$pcslist)) {
17928:                 next if ($pc <= 1);
17929:                 my $res = $$navmapref->getByMapPc($pc);
17930:                 if (ref($res)) {
17931:                     my $thisurl = $res->src();
17932:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17933:                     my $thistitle = $res->title();
17934:                     $path .= '&'.
17935:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17936:                              &escape($thistitle).
17937:                              ':'.$res->randompick().
17938:                              ':'.$res->randomout().
17939:                              ':'.$res->encrypted().
17940:                              ':'.$res->randomorder().
17941:                              ':'.$res->is_page();
17942:                 }
17943:             }
17944:         }
17945:         $path =~ s/^\&//;
17946:         my $maptitle = $mapresobj->title();
17947:         if ($mapurl eq 'default') {
17948:             $maptitle = 'Main Content';
17949:         }
17950:         $path .= (($path ne '')? '&' : '').
17951:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17952:                  &escape($maptitle).
17953:                  ':'.$mapresobj->randompick().
17954:                  ':'.$mapresobj->randomout().
17955:                  ':'.$mapresobj->encrypted().
17956:                  ':'.$mapresobj->randomorder().
17957:                  ':'.$mapresobj->is_page();
17958:     } else {
17959:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17960:         my $ispage = (($type eq 'page')? 1 : '');
17961:         if ($mapurl eq 'default') {
17962:             $maptitle = 'Main Content';
17963:         }
17964:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17965:                 &escape($maptitle).':::::'.$ispage;
17966:     }
17967:     unless ($mapurl eq 'default') {
17968:         $path = 'default&'.
17969:                 &escape('Main Content').
17970:                 ':::::&'.$path;
17971:     }
17972:     return $path;
17973: }
17974: 
17975: sub captcha_display {
17976:     my ($context,$lonhost,$defdom) = @_;
17977:     my ($output,$error);
17978:     my ($captcha,$pubkey,$privkey,$version) = 
17979:         &get_captcha_config($context,$lonhost,$defdom);
17980:     if ($captcha eq 'original') {
17981:         $output = &create_captcha();
17982:         unless ($output) {
17983:             $error = 'captcha';
17984:         }
17985:     } elsif ($captcha eq 'recaptcha') {
17986:         $output = &create_recaptcha($pubkey,$version);
17987:         unless ($output) {
17988:             $error = 'recaptcha';
17989:         }
17990:     }
17991:     return ($output,$error,$captcha,$version);
17992: }
17993: 
17994: sub captcha_response {
17995:     my ($context,$lonhost,$defdom) = @_;
17996:     my ($captcha_chk,$captcha_error);
17997:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17998:     if ($captcha eq 'original') {
17999:         ($captcha_chk,$captcha_error) = &check_captcha();
18000:     } elsif ($captcha eq 'recaptcha') {
18001:         $captcha_chk = &check_recaptcha($privkey,$version);
18002:     } else {
18003:         $captcha_chk = 1;
18004:     }
18005:     return ($captcha_chk,$captcha_error);
18006: }
18007: 
18008: sub get_captcha_config {
18009:     my ($context,$lonhost,$dom_in_effect) = @_;
18010:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18011:     my $hostname = &Apache::lonnet::hostname($lonhost);
18012:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18013:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18014:     if ($context eq 'usercreation') {
18015:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18016:         if (ref($domconfig{$context}) eq 'HASH') {
18017:             $hashtocheck = $domconfig{$context}{'cancreate'};
18018:             if (ref($hashtocheck) eq 'HASH') {
18019:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18020:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18021:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18022:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18023:                     }
18024:                     if ($privkey && $pubkey) {
18025:                         $captcha = 'recaptcha';
18026:                         $version = $hashtocheck->{'recaptchaversion'};
18027:                         if ($version ne '2') {
18028:                             $version = 1;
18029:                         }
18030:                     } else {
18031:                         $captcha = 'original';
18032:                     }
18033:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18034:                     $captcha = 'original';
18035:                 }
18036:             }
18037:         } else {
18038:             $captcha = 'captcha';
18039:         }
18040:     } elsif ($context eq 'login') {
18041:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18042:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18043:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18044:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18045:             if ($privkey && $pubkey) {
18046:                 $captcha = 'recaptcha';
18047:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18048:                 if ($version ne '2') {
18049:                     $version = 1; 
18050:                 }
18051:             } else {
18052:                 $captcha = 'original';
18053:             }
18054:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18055:             $captcha = 'original';
18056:         }
18057:     } elsif ($context eq 'passwords') {
18058:         if ($dom_in_effect) {
18059:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18060:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18061:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18062:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18063:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18064:                 }
18065:                 if ($privkey && $pubkey) {
18066:                     $captcha = 'recaptcha';
18067:                     $version = $passwdconf{'recaptchaversion'};
18068:                     if ($version ne '2') {
18069:                         $version = 1;
18070:                     }
18071:                 } else {
18072:                     $captcha = 'original';
18073:                 }
18074:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18075:                 $captcha = 'original';
18076:             }
18077:         }
18078:     } 
18079:     return ($captcha,$pubkey,$privkey,$version);
18080: }
18081: 
18082: sub create_captcha {
18083:     my %captcha_params = &captcha_settings();
18084:     my ($output,$maxtries,$tries) = ('',10,0);
18085:     while ($tries < $maxtries) {
18086:         $tries ++;
18087:         my $captcha = Authen::Captcha->new (
18088:                                            output_folder => $captcha_params{'output_dir'},
18089:                                            data_folder   => $captcha_params{'db_dir'},
18090:                                           );
18091:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18092: 
18093:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18094:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18095:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18096:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
18097:                       '<br />'.
18098:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18099:             last;
18100:         }
18101:     }
18102:     if ($output eq '') {
18103:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18104:     }
18105:     return $output;
18106: }
18107: 
18108: sub captcha_settings {
18109:     my %captcha_params = (
18110:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18111:                            www_output_dir => "/captchaspool",
18112:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18113:                            numchars       => '5',
18114:                          );
18115:     return %captcha_params;
18116: }
18117: 
18118: sub check_captcha {
18119:     my ($captcha_chk,$captcha_error);
18120:     my $code = $env{'form.code'};
18121:     my $md5sum = $env{'form.crypt'};
18122:     my %captcha_params = &captcha_settings();
18123:     my $captcha = Authen::Captcha->new(
18124:                       output_folder => $captcha_params{'output_dir'},
18125:                       data_folder   => $captcha_params{'db_dir'},
18126:                   );
18127:     $captcha_chk = $captcha->check_code($code,$md5sum);
18128:     my %captcha_hash = (
18129:                         0       => 'Code not checked (file error)',
18130:                        -1      => 'Failed: code expired',
18131:                        -2      => 'Failed: invalid code (not in database)',
18132:                        -3      => 'Failed: invalid code (code does not match crypt)',
18133:     );
18134:     if ($captcha_chk != 1) {
18135:         $captcha_error = $captcha_hash{$captcha_chk}
18136:     }
18137:     return ($captcha_chk,$captcha_error);
18138: }
18139: 
18140: sub create_recaptcha {
18141:     my ($pubkey,$version) = @_;
18142:     if ($version >= 2) {
18143:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
18144:     } else {
18145:         my $use_ssl;
18146:         if ($ENV{'SERVER_PORT'} == 443) {
18147:             $use_ssl = 1;
18148:         }
18149:         my $captcha = Captcha::reCAPTCHA->new;
18150:         return $captcha->get_options_setter({theme => 'white'})."\n".
18151:                $captcha->get_html($pubkey,undef,$use_ssl).
18152:                &mt('If the text is hard to read, [_1] will replace them.',
18153:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18154:                '<br /><br />';
18155:     }
18156: }
18157: 
18158: sub check_recaptcha {
18159:     my ($privkey,$version) = @_;
18160:     my $captcha_chk;
18161:     if ($version >= 2) {
18162:         my %info = (
18163:                      secret   => $privkey, 
18164:                      response => $env{'form.g-recaptcha-response'},
18165:                      remoteip => $ENV{'REMOTE_ADDR'},
18166:                    );
18167:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
18168:         $request->content(join('&',map {
18169:                          my $name = escape($_);
18170:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
18171:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
18172:                          : &escape($info{$_}) );
18173:         } keys(%info)));
18174:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18175:         if ($response->is_success)  {
18176:             my $data = JSON::DWIW->from_json($response->decoded_content);
18177:             if (ref($data) eq 'HASH') {
18178:                 if ($data->{'success'}) {
18179:                     $captcha_chk = 1;
18180:                 }
18181:             }
18182:         }
18183:     } else {
18184:         my $captcha = Captcha::reCAPTCHA->new;
18185:         my $captcha_result =
18186:             $captcha->check_answer(
18187:                                     $privkey,
18188:                                     $ENV{'REMOTE_ADDR'},
18189:                                     $env{'form.recaptcha_challenge_field'},
18190:                                     $env{'form.recaptcha_response_field'},
18191:                                   );
18192:         if ($captcha_result->{is_valid}) {
18193:             $captcha_chk = 1;
18194:         }
18195:     }
18196:     return $captcha_chk;
18197: }
18198: 
18199: sub emailusername_info {
18200:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18201:     my %titles = &Apache::lonlocal::texthash (
18202:                      lastname      => 'Last Name',
18203:                      firstname     => 'First Name',
18204:                      institution   => 'School/college/university',
18205:                      location      => "School's city, state/province, country",
18206:                      web           => "School's web address",
18207:                      officialemail => 'E-mail address at institution (if different)',
18208:                      id            => 'Student/Employee ID',
18209:                  );
18210:     return (\@fields,\%titles);
18211: }
18212: 
18213: sub cleanup_html {
18214:     my ($incoming) = @_;
18215:     my $outgoing;
18216:     if ($incoming ne '') {
18217:         $outgoing = $incoming;
18218:         $outgoing =~ s/;/&#059;/g;
18219:         $outgoing =~ s/\#/&#035;/g;
18220:         $outgoing =~ s/\&/&#038;/g;
18221:         $outgoing =~ s/</&#060;/g;
18222:         $outgoing =~ s/>/&#062;/g;
18223:         $outgoing =~ s/\(/&#040/g;
18224:         $outgoing =~ s/\)/&#041;/g;
18225:         $outgoing =~ s/"/&#034;/g;
18226:         $outgoing =~ s/'/&#039;/g;
18227:         $outgoing =~ s/\$/&#036;/g;
18228:         $outgoing =~ s{/}{&#047;}g;
18229:         $outgoing =~ s/=/&#061;/g;
18230:         $outgoing =~ s/\\/&#092;/g
18231:     }
18232:     return $outgoing;
18233: }
18234: 
18235: # Checks for critical messages and returns a redirect url if one exists.
18236: # $interval indicates how often to check for messages.
18237: # $context is the calling context -- roles, grades, contents, menu or flip. 
18238: sub critical_redirect {
18239:     my ($interval,$context) = @_;
18240:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18241:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18242:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18243:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18244:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
18245:             if ($blocked) {
18246:                 my $checkrole = "cm./$cdom/$cnum";
18247:                 if ($env{'request.course.sec'} ne '') {
18248:                     $checkrole .= "/$env{'request.course.sec'}";
18249:                 }
18250:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18251:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18252:                     return;
18253:                 }
18254:             }
18255:         }
18256:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
18257:                                         $env{'user.name'});
18258:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18259:         my $redirecturl;
18260:         if ($what[0]) {
18261: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
18262: 	        $redirecturl='/adm/email?critical=display';
18263: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
18264:                 return (1, $url);
18265:             }
18266:         }
18267:     } 
18268:     return ();
18269: }
18270: 
18271: # Use:
18272: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18273: #
18274: ##################################################
18275: #          password associated functions         #
18276: ##################################################
18277: sub des_keys {
18278:     # Make a new key for DES encryption.
18279:     # Each key has two parts which are returned separately.
18280:     # Please note:  Each key must be passed through the &hex function
18281:     # before it is output to the web browser.  The hex versions cannot
18282:     # be used to decrypt.
18283:     my @hexstr=('0','1','2','3','4','5','6','7',
18284:                 '8','9','a','b','c','d','e','f');
18285:     my $lkey='';
18286:     for (0..7) {
18287:         $lkey.=$hexstr[rand(15)];
18288:     }
18289:     my $ukey='';
18290:     for (0..7) {
18291:         $ukey.=$hexstr[rand(15)];
18292:     }
18293:     return ($lkey,$ukey);
18294: }
18295: 
18296: sub des_decrypt {
18297:     my ($key,$cyphertext) = @_;
18298:     my $keybin=pack("H16",$key);
18299:     my $cypher;
18300:     if ($Crypt::DES::VERSION>=2.03) {
18301:         $cypher=new Crypt::DES $keybin;
18302:     } else {
18303:         $cypher=new DES $keybin;
18304:     }
18305:     my $plaintext='';
18306:     my $cypherlength = length($cyphertext);
18307:     my $numchunks = int($cypherlength/32);
18308:     for (my $j=0; $j<$numchunks; $j++) {
18309:         my $start = $j*32;
18310:         my $cypherblock = substr($cyphertext,$start,32);
18311:         my $chunk =
18312:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18313:         $chunk .=
18314:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18315:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18316:         $plaintext .= $chunk;
18317:     }
18318:     return $plaintext;
18319: }
18320: 
18321: sub get_requested_shorturls {
18322:     my ($cdom,$cnum,$navmap) = @_;
18323:     return unless (ref($navmap));
18324:     my ($numnew,$errors);
18325:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18326:     if (@toshorten) {
18327:         my (%maps,%resources,%titles);
18328:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18329:                                                                'shorturls',$cdom,$cnum);
18330:         if (keys(%resources)) {
18331:             my %tocreate;
18332:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18333:                 my $symb = $resources{$item};
18334:                 if ($symb) {
18335:                     $tocreate{$cnum.'&'.$symb} = 1;
18336:                 }
18337:             }
18338:             if (keys(%tocreate)) {
18339:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18340:                                                       \%tocreate);
18341:             }
18342:         }
18343:     }
18344:     return ($numnew,$errors);
18345: }
18346: 
18347: sub make_short_symbs {
18348:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18349:     my ($numnew,@errors);
18350:     if (ref($tocreateref) eq 'HASH') {
18351:         my %tocreate = %{$tocreateref};
18352:         if (keys(%tocreate)) {
18353:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18354:             my $su = Short::URL->new(no_vowels => 1);
18355:             my $init = '';
18356:             my (%newunique,%addcourse,%courseonly,%failed);
18357:             # get lock on tiny db
18358:             my $now = time;
18359:             if ($lockuser eq '') {
18360:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18361:             }
18362:             my $lockhash = {
18363:                                 "lock\0$now" => $lockuser,
18364:                             };
18365:             my $tries = 0;
18366:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18367:             my ($code,$error);
18368:             while (($gotlock ne 'ok') && ($tries<3)) {
18369:                 $tries ++;
18370:                 sleep 1;
18371:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18372:             }
18373:             if ($gotlock eq 'ok') {
18374:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18375:                                        \%addcourse,\%courseonly,\%failed);
18376:                 if (keys(%failed)) {
18377:                     my $numfailed = scalar(keys(%failed));
18378:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18379:                 }
18380:                 if (keys(%newunique)) {
18381:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18382:                     if ($putres eq 'ok') {
18383:                         $numnew = scalar(keys(%newunique));
18384:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18385:                         unless ($newputres eq 'ok') {
18386:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18387:                         }
18388:                     } else {
18389:                         push(@errors,&mt('error: could not store unique six character URLs'));
18390:                     }
18391:                 }
18392:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18393:                 unless ($dellockres eq 'ok') {
18394:                     push(@errors,&mt('error: could not release lockfile'));
18395:                 }
18396:             } else {
18397:                 push(@errors,&mt('error: could not obtain lockfile'));
18398:             }
18399:             if (keys(%courseonly)) {
18400:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18401:                 if ($result ne 'ok') {
18402:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18403:                 }
18404:             }
18405:         }
18406:     }
18407:     return ($numnew,\@errors);
18408: }
18409: 
18410: sub shorten_symbs {
18411:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18412:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18413:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18414:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18415:     my (%possibles,%collisions);
18416:     foreach my $key (keys(%{$tocreate})) {
18417:         my $num = String::CRC32::crc32($key);
18418:         my $tiny = $su->encode($num,$init);
18419:         if ($tiny) {
18420:             $possibles{$tiny} = $key;
18421:         }
18422:     }
18423:     if (!$init) {
18424:         $init = 1;
18425:     } else {
18426:         $init ++;
18427:     }
18428:     if (keys(%possibles)) {
18429:         my @posstiny = keys(%possibles);
18430:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18431:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18432:         if (keys(%currtiny)) {
18433:             foreach my $key (keys(%currtiny)) {
18434:                 next if ($currtiny{$key} eq '');
18435:                 if ($currtiny{$key} eq $possibles{$key}) {
18436:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18437:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18438:                         $courseonly->{$tsymb} = $key;
18439:                     }
18440:                 } else {
18441:                     $collisions{$possibles{$key}} = 1;
18442:                 }
18443:                 delete($possibles{$key});
18444:             }
18445:         }
18446:         foreach my $key (keys(%possibles)) {
18447:             $newunique->{$key} = $possibles{$key};
18448:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18449:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18450:                 $addcourse->{$tsymb} = $key;
18451:             }
18452:         }
18453:     }
18454:     if (keys(%collisions)) {
18455:         if ($init <5) {
18456:             if (!$init) {
18457:                 $init = 1;
18458:             } else {
18459:                 $init ++;
18460:             }
18461:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18462:                                    $newunique,$addcourse,$courseonly,$failed);
18463:         } else {
18464:             foreach my $key (keys(%collisions)) {
18465:                 $failed->{$key} = 1;
18466:             }
18467:         }
18468:     }
18469:     return $init;
18470: }
18471: 
18472: sub is_nonframeable {
18473:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18474:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18475:     return if (($remprotocol eq '') || ($remhost eq ''));
18476: 
18477:     $remprotocol = lc($remprotocol);
18478:     $remhost = lc($remhost);
18479:     my $remport = 80;
18480:     if ($remprotocol eq 'https') {
18481:         $remport = 443;
18482:     }
18483:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18484:     if ($cached) {
18485:         unless ($nocache) {
18486:             if ($result) {
18487:                 return 1;
18488:             } else {
18489:                 return 0;
18490:             }
18491:         }
18492:     }
18493:     my $uselink;
18494:     my $request = new HTTP::Request('HEAD',$url);
18495:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
18496:     if ($response->is_success()) {
18497:         my $secpolicy = lc($response->header('content-security-policy'));
18498:         my $xframeop = lc($response->header('x-frame-options'));
18499:         $secpolicy =~ s/^\s+|\s+$//g;
18500:         $xframeop =~ s/^\s+|\s+$//g;
18501:         if (($secpolicy ne '') || ($xframeop ne '')) {
18502:             my $remotehost = $remprotocol.'://'.$remhost;
18503:             my ($origin,$protocol,$port);
18504:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18505:                 $port = $ENV{'SERVER_PORT'};
18506:             } else {
18507:                 $port = 80;
18508:             }
18509:             if ($absolute eq '') {
18510:                 $protocol = 'http:';
18511:                 if ($port == 443) {
18512:                     $protocol = 'https:';
18513:                 }
18514:                 $origin = $protocol.'//'.lc($hostname);
18515:             } else {
18516:                 $origin = lc($absolute);
18517:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18518:             }
18519:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18520:                 my $framepolicy = $1;
18521:                 $framepolicy =~ s/^\s+|\s+$//g;
18522:                 my @policies = split(/\s+/,$framepolicy);
18523:                 if (@policies) {
18524:                     if (grep(/^\Q'none'\E$/,@policies)) {
18525:                         $uselink = 1;
18526:                     } else {
18527:                         $uselink = 1;
18528:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18529:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18530:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18531:                             undef($uselink);
18532:                         }
18533:                         if ($uselink) {
18534:                             if (grep(/^\Q'self'\E$/,@policies)) {
18535:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18536:                                     undef($uselink);
18537:                                 }
18538:                             }
18539:                         }
18540:                         if ($uselink) {
18541:                             my @possok;
18542:                             if ($ip ne '') {
18543:                                 push(@possok,$ip);
18544:                             }
18545:                             my $hoststr = '';
18546:                             foreach my $part (reverse(split(/\./,$hostname))) {
18547:                                 if ($hoststr eq '') {
18548:                                     $hoststr = $part;
18549:                                 } else {
18550:                                     $hoststr = "$part.$hoststr";
18551:                                 }
18552:                                 if ($hoststr eq $hostname) {
18553:                                     push(@possok,$hostname);
18554:                                 } else {
18555:                                     push(@possok,"*.$hoststr");
18556:                                 }
18557:                             }
18558:                             if (@possok) {
18559:                                 foreach my $poss (@possok) {
18560:                                     last if (!$uselink);
18561:                                     foreach my $policy (@policies) {
18562:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18563:                                             undef($uselink);
18564:                                             last;
18565:                                         }
18566:                                     }
18567:                                 }
18568:                             }
18569:                         }
18570:                     }
18571:                 }
18572:             } elsif ($xframeop ne '') {
18573:                 $uselink = 1;
18574:                 my @policies = split(/\s*,\s*/,$xframeop);
18575:                 if (@policies) {
18576:                     unless (grep(/^deny$/,@policies)) {
18577:                         if ($origin ne '') {
18578:                             if (grep(/^sameorigin$/,@policies)) {
18579:                                 if ($remotehost eq $origin) {
18580:                                     undef($uselink);
18581:                                 }
18582:                             }
18583:                             if ($uselink) {
18584:                                 foreach my $policy (@policies) {
18585:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18586:                                         my $allowfrom = $1;
18587:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18588:                                             undef($uselink);
18589:                                             last;
18590:                                         }
18591:                                     }
18592:                                 }
18593:                             }
18594:                         }
18595:                     }
18596:                 }
18597:             }
18598:         }
18599:     }
18600:     if ($nocache) {
18601:         if ($cached) {
18602:             my $devalidate;
18603:             if ($uselink && !$result) {
18604:                 $devalidate = 1;
18605:             } elsif (!$uselink && $result) {
18606:                 $devalidate = 1;
18607:             }
18608:             if ($devalidate) {
18609:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18610:             }
18611:         }
18612:     } else {
18613:         if ($uselink) {
18614:             $result = 1;
18615:         } else {
18616:             $result = 0;
18617:         }
18618:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18619:     }
18620:     return $uselink;
18621: }
18622: 
18623: 1;
18624: __END__;
18625: 

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