File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1399: download - view: text, annotated - select for diffs
Thu Dec 1 01:24:53 2022 UTC (17 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- When commit_customrole() or commit_standardrole() are called in list
  context, both the result of assignrole() calls (e.g., ok) and a more verbose
  logging-type message will be returned.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1399 2022/12/01 01:24:53 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::lonnavmaps();
   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 LONCAPA::map();
   76: use HTTP::Request;
   77: use DateTime::TimeZone;
   78: use DateTime::Locale;
   79: use Encode();
   80: use Text::Aspell;
   81: use Authen::Captcha;
   82: use Captcha::reCAPTCHA;
   83: use JSON::DWIW;
   84: use Crypt::DES;
   85: use DynaLoader; # for Crypt::DES version
   86: use MIME::Lite;
   87: use MIME::Types;
   88: use File::Copy();
   89: use File::Path();
   90: use String::CRC32();
   91: use Short::URL();
   92: 
   93: # ---------------------------------------------- Designs
   94: use vars qw(%defaultdesign);
   95: 
   96: my $readit;
   97: 
   98: 
   99: ##
  100: ## Global Variables
  101: ##
  102: 
  103: 
  104: # ----------------------------------------------- SSI with retries:
  105: #
  106: 
  107: =pod
  108: 
  109: =head1 Server Side include with retries:
  110: 
  111: =over 4
  112: 
  113: =item * &ssi_with_retries(resource,retries form)
  114: 
  115: Performs an ssi with some number of retries.  Retries continue either
  116: until the result is ok or until the retry count supplied by the
  117: caller is exhausted.  
  118: 
  119: Inputs:
  120: 
  121: =over 4
  122: 
  123: resource   - Identifies the resource to insert.
  124: 
  125: retries    - Count of the number of retries allowed.
  126: 
  127: form       - Hash that identifies the rendering options.
  128: 
  129: =back
  130: 
  131: Returns:
  132: 
  133: =over 4
  134: 
  135: content    - The content of the response.  If retries were exhausted this is empty.
  136: 
  137: response   - The response from the last attempt (which may or may not have been successful.
  138: 
  139: =back
  140: 
  141: =back
  142: 
  143: =cut
  144: 
  145: sub ssi_with_retries {
  146:     my ($resource, $retries, %form) = @_;
  147: 
  148: 
  149:     my $ok = 0;			# True if we got a good response.
  150:     my $content;
  151:     my $response;
  152: 
  153:     # Try to get the ssi done. within the retries count:
  154: 
  155:     do {
  156: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  157: 	$ok      = $response->is_success;
  158:         if (!$ok) {
  159:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  160:         }
  161: 	$retries--;
  162:     } while (!$ok && ($retries > 0));
  163: 
  164:     if (!$ok) {
  165: 	$content = '';		# On error return an empty content.
  166:     }
  167:     return ($content, $response);
  168: 
  169: }
  170: 
  171: 
  172: 
  173: # ----------------------------------------------- Filetypes/Languages/Copyright
  174: my %language;
  175: my %supported_language;
  176: my %supported_codes;
  177: my %latex_language;		# For choosing hyphenation in <transl..>
  178: my %latex_language_bykey;	# for choosing hyphenation from metadata
  179: my %cprtag;
  180: my %scprtag;
  181: my %fe; my %fd; my %fm;
  182: my %category_extensions;
  183: 
  184: # ---------------------------------------------- Thesaurus variables
  185: #
  186: # %Keywords:
  187: #      A hash used by &keyword to determine if a word is considered a keyword.
  188: # $thesaurus_db_file 
  189: #      Scalar containing the full path to the thesaurus database.
  190: 
  191: my %Keywords;
  192: my $thesaurus_db_file;
  193: 
  194: #
  195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  196: # thesaurus.tab, and filecategories.tab.
  197: #
  198: BEGIN {
  199:     # Variable initialization
  200:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  201:     #
  202:     unless ($readit) {
  203: # ------------------------------------------------------------------- languages
  204:     {
  205:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  206:                                    '/language.tab';
  207:         if ( open(my $fh,'<',$langtabfile) ) {
  208:             while (my $line = <$fh>) {
  209:                 next if ($line=~/^\#/);
  210:                 chomp($line);
  211:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  212:                 $language{$key}=$val.' - '.$enc;
  213:                 if ($sup) {
  214:                     $supported_language{$key}=$sup;
  215: 		    $supported_codes{$key}   = $code;
  216:                 }
  217: 		if ($latex) {
  218: 		    $latex_language_bykey{$key} = $latex;
  219: 		    $latex_language{$code} = $latex;
  220: 		}
  221:             }
  222:             close($fh);
  223:         }
  224:     }
  225: # ------------------------------------------------------------------ copyrights
  226:     {
  227:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  228:                                   '/copyright.tab';
  229:         if ( open (my $fh,'<',$copyrightfile) ) {
  230:             while (my $line = <$fh>) {
  231:                 next if ($line=~/^\#/);
  232:                 chomp($line);
  233:                 my ($key,$val)=(split(/\s+/,$line,2));
  234:                 $cprtag{$key}=$val;
  235:             }
  236:             close($fh);
  237:         }
  238:     }
  239: # ----------------------------------------------------------- source copyrights
  240:     {
  241:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  242:                                   '/source_copyright.tab';
  243:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  244:             while (my $line = <$fh>) {
  245:                 next if ($line =~ /^\#/);
  246:                 chomp($line);
  247:                 my ($key,$val)=(split(/\s+/,$line,2));
  248:                 $scprtag{$key}=$val;
  249:             }
  250:             close($fh);
  251:         }
  252:     }
  253: 
  254: # -------------------------------------------------------------- default domain designs
  255:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  256:     my $designfile = $designdir.'/default.tab';
  257:     if ( open (my $fh,'<',$designfile) ) {
  258:         while (my $line = <$fh>) {
  259:             next if ($line =~ /^\#/);
  260:             chomp($line);
  261:             my ($key,$val)=(split(/\=/,$line));
  262:             if ($val) { $defaultdesign{$key}=$val; }
  263:         }
  264:         close($fh);
  265:     }
  266: 
  267: # ------------------------------------------------------------- file categories
  268:     {
  269:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  270:                                   '/filecategories.tab';
  271:         if ( open (my $fh,'<',$categoryfile) ) {
  272: 	    while (my $line = <$fh>) {
  273: 		next if ($line =~ /^\#/);
  274: 		chomp($line);
  275:                 my ($extension,$category)=(split(/\s+/,$line,2));
  276:                 push(@{$category_extensions{lc($category)}},$extension);
  277:             }
  278:             close($fh);
  279:         }
  280: 
  281:     }
  282: # ------------------------------------------------------------------ file types
  283:     {
  284:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  285:                '/filetypes.tab';
  286:         if ( open (my $fh,'<',$typesfile) ) {
  287:             while (my $line = <$fh>) {
  288: 		next if ($line =~ /^\#/);
  289: 		chomp($line);
  290:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  291:                 if ($descr ne '') {
  292:                     $fe{$ending}=lc($emb);
  293:                     $fd{$ending}=$descr;
  294:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  295:                 }
  296:             }
  297:             close($fh);
  298:         }
  299:     }
  300:     &Apache::lonnet::logthis(
  301:              "<span style='color:yellow;'>INFO: Read file types</span>");
  302:     $readit=1;
  303:     }  # end of unless($readit) 
  304:     
  305: }
  306: 
  307: ###############################################################
  308: ##           HTML and Javascript Helper Functions            ##
  309: ###############################################################
  310: 
  311: =pod 
  312: 
  313: =head1 HTML and Javascript Functions
  314: 
  315: =over 4
  316: 
  317: =item * &browser_and_searcher_javascript()
  318: 
  319: X<browsing, javascript>X<searching, javascript>Returns a string
  320: containing javascript with two functions, C<openbrowser> and
  321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  322: tags.
  323: 
  324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  325: 
  326: inputs: formname, elementname, only, omit
  327: 
  328: formname and elementname indicate the name of the html form and name of
  329: the element that the results of the browsing selection are to be placed in. 
  330: 
  331: Specifying 'only' will restrict the browser to displaying only files
  332: with the given extension.  Can be a comma separated list.
  333: 
  334: Specifying 'omit' will restrict the browser to NOT displaying files
  335: with the given extension.  Can be a comma separated list.
  336: 
  337: =item * &opensearcher(formname,elementname) [javascript]
  338: 
  339: Inputs: formname, elementname
  340: 
  341: formname and elementname specify the name of the html form and the name
  342: of the element the selection from the search results will be placed in.
  343: 
  344: =cut
  345: 
  346: sub browser_and_searcher_javascript {
  347:     my ($mode)=@_;
  348:     if (!defined($mode)) { $mode='edit'; }
  349:     my $resurl=&escape_single(&lastresurl());
  350:     return <<END;
  351: // <!-- BEGIN LON-CAPA Internal
  352:     var editbrowser = null;
  353:     function openbrowser(formname,elementname,only,omit,titleelement) {
  354:         var url = '$resurl/?';
  355:         if (editbrowser == null) {
  356:             url += 'launch=1&';
  357:         }
  358:         url += 'catalogmode=interactive&';
  359:         url += 'mode=$mode&';
  360:         url += 'inhibitmenu=yes&';
  361:         url += 'form=' + formname + '&';
  362:         if (only != null) {
  363:             url += 'only=' + only + '&';
  364:         } else {
  365:             url += 'only=&';
  366: 	}
  367:         if (omit != null) {
  368:             url += 'omit=' + omit + '&';
  369:         } else {
  370:             url += 'omit=&';
  371: 	}
  372:         if (titleelement != null) {
  373:             url += 'titleelement=' + titleelement + '&';
  374:         } else {
  375: 	    url += 'titleelement=&';
  376: 	}
  377:         url += 'element=' + elementname + '';
  378:         var title = 'Browser';
  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  380:         options += ',width=700,height=600';
  381:         editbrowser = open(url,title,options,'1');
  382:         editbrowser.focus();
  383:     }
  384:     var editsearcher;
  385:     function opensearcher(formname,elementname,titleelement) {
  386:         var url = '/adm/searchcat?';
  387:         if (editsearcher == null) {
  388:             url += 'launch=1&';
  389:         }
  390:         url += 'catalogmode=interactive&';
  391:         url += 'mode=$mode&';
  392:         url += 'form=' + formname + '&';
  393:         if (titleelement != null) {
  394:             url += 'titleelement=' + titleelement + '&';
  395:         } else {
  396: 	    url += 'titleelement=&';
  397: 	}
  398:         url += 'element=' + elementname + '';
  399:         var title = 'Search';
  400:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  401:         options += ',width=700,height=600';
  402:         editsearcher = open(url,title,options,'1');
  403:         editsearcher.focus();
  404:     }
  405: // END LON-CAPA Internal -->
  406: END
  407: }
  408: 
  409: sub lastresurl {
  410:     if ($env{'environment.lastresurl'}) {
  411: 	return $env{'environment.lastresurl'}
  412:     } else {
  413: 	return '/res';
  414:     }
  415: }
  416: 
  417: sub storeresurl {
  418:     my $resurl=&Apache::lonnet::clutter(shift);
  419:     unless ($resurl=~/^\/res/) { return 0; }
  420:     $resurl=~s/\/$//;
  421:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  422:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  423:     return 1;
  424: }
  425: 
  426: sub studentbrowser_javascript {
  427:    unless (
  428:             (($env{'request.course.id'}) && 
  429:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  430: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  431: 					  '/'.$env{'request.course.sec'})
  432: 	      ))
  433:          || ($env{'request.role'}=~/^(au|dc|su)/)
  434:           ) { return ''; }  
  435:    return (<<'ENDSTDBRW');
  436: <script type="text/javascript" language="Javascript">
  437: // <![CDATA[
  438:     var stdeditbrowser;
  439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
  440:         var url = '/adm/pickstudent?';
  441:         var filter;
  442: 	if (!ignorefilter) {
  443: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  444: 	}
  445:         if (filter != null) {
  446:            if (filter != '') {
  447:                url += 'filter='+filter+'&';
  448: 	   }
  449:         }
  450:         url += 'form=' + formname + '&unameelement='+uname+
  451:                                     '&udomelement='+udom+
  452:                                     '&clicker='+clicker;
  453: 	if (roleflag) { url+="&roles=1"; }
  454:         if (courseadv == 'condition') {
  455:             if (document.getElementById('courseadv')) {
  456:                 courseadv = document.getElementById('courseadv').value;
  457:             }
  458:         }
  459:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  460:         var title = 'Student_Browser';
  461:         var options = 'scrollbars=1,resizable=1,menubar=0';
  462:         options += ',width=700,height=600';
  463:         stdeditbrowser = open(url,title,options,'1');
  464:         stdeditbrowser.focus();
  465:     }
  466: // ]]>
  467: </script>
  468: ENDSTDBRW
  469: }
  470: 
  471: sub resourcebrowser_javascript {
  472:    unless ($env{'request.course.id'}) { return ''; }
  473:    return (<<'ENDRESBRW');
  474: <script type="text/javascript" language="Javascript">
  475: // <![CDATA[
  476:     var reseditbrowser;
  477:     function openresbrowser(formname,reslink) {
  478:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  479:         var title = 'Resource_Browser';
  480:         var options = 'scrollbars=1,resizable=1,menubar=0';
  481:         options += ',width=700,height=500';
  482:         reseditbrowser = open(url,title,options,'1');
  483:         reseditbrowser.focus();
  484:     }
  485: // ]]>
  486: </script>
  487: ENDRESBRW
  488: }
  489: 
  490: sub selectstudent_link {
  491:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
  492:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  493:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  494:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  495:    if ($env{'request.course.id'}) {  
  496:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  497: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  498: 					'/'.$env{'request.course.sec'})) {
  499: 	   return '';
  500:        }
  501:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  502:        if ($courseadv eq 'only') {
  503:            $callargs .= ",'',1,'$courseadv'";
  504:        } elsif ($courseadv eq 'none') {
  505:            $callargs .= ",'','','$courseadv'";
  506:        } elsif ($courseadv eq 'condition') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        }
  509:        return '<span class="LC_nobreak">'.
  510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  511:               &mt('Select User').'</a></span>';
  512:    }
  513:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  514:        $callargs .= ",'',1"; 
  515:        return '<span class="LC_nobreak">'.
  516:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  517:               &mt('Select User').'</a></span>';
  518:    }
  519:    return '';
  520: }
  521: 
  522: sub selectresource_link {
  523:    my ($form,$reslink,$arg)=@_;
  524:    
  525:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  526:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  527:    unless ($env{'request.course.id'}) { return $arg; }
  528:    return '<span class="LC_nobreak">'.
  529:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  530:               $arg.'</a></span>';
  531: }
  532: 
  533: 
  534: 
  535: sub authorbrowser_javascript {
  536:     return <<"ENDAUTHORBRW";
  537: <script type="text/javascript" language="JavaScript">
  538: // <![CDATA[
  539: var stdeditbrowser;
  540: 
  541: function openauthorbrowser(formname,udom) {
  542:     var url = '/adm/pickauthor?';
  543:     url += 'form='+formname+'&roledom='+udom;
  544:     var title = 'Author_Browser';
  545:     var options = 'scrollbars=1,resizable=1,menubar=0';
  546:     options += ',width=700,height=600';
  547:     stdeditbrowser = open(url,title,options,'1');
  548:     stdeditbrowser.focus();
  549: }
  550: 
  551: // ]]>
  552: </script>
  553: ENDAUTHORBRW
  554: }
  555: 
  556: sub coursebrowser_javascript {
  557:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  558:         $credits_element,$instcode) = @_;
  559:     my $wintitle = 'Course_Browser';
  560:     if ($crstype eq 'Community') {
  561:         $wintitle = 'Community_Browser';
  562:     }
  563:     my $id_functions = &javascript_index_functions();
  564:     my $output = '
  565: <script type="text/javascript" language="JavaScript">
  566: // <![CDATA[
  567:     var stdeditbrowser;'."\n";
  568: 
  569:     $output .= <<"ENDSTDBRW";
  570:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  571:         var url = '/adm/pickcourse?';
  572:         var formid = getFormIdByName(formname);
  573:         var domainfilter = getDomainFromSelectbox(formname,udom);
  574:         if (domainfilter != null) {
  575:            if (domainfilter != '') {
  576:                url += 'domainfilter='+domainfilter+'&';
  577: 	   }
  578:         }
  579:         url += 'form=' + formname + '&cnumelement='+uname+
  580: 	                            '&cdomelement='+udom+
  581:                                     '&cnameelement='+desc;
  582:         if (extra_element !=null && extra_element != '') {
  583:             if (formname == 'rolechoice' || formname == 'studentform') {
  584:                 url += '&roleelement='+extra_element;
  585:                 if (domainfilter == null || domainfilter == '') {
  586:                     url += '&domainfilter='+extra_element;
  587:                 }
  588:             }
  589:             else {
  590:                 if (formname == 'portform') {
  591:                     url += '&setroles='+extra_element;
  592:                 } else {
  593:                     if (formname == 'rules') {
  594:                         url += '&fixeddom='+extra_element; 
  595:                     }
  596:                 }
  597:             }     
  598:         }
  599:         if (type != null && type != '') {
  600:             url += '&type='+type;
  601:         }
  602:         if (type_elem != null && type_elem != '') {
  603:             url += '&typeelement='+type_elem;
  604:         }
  605:         if (formname == 'ccrs') {
  606:             var ownername = document.forms[formid].ccuname.value;
  607:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  608:             url += '&cloner='+ownername+':'+ownerdom;
  609:             if (type == 'Course') {
  610:                 url += '&crscode='+document.forms[formid].crscode.value;
  611:             }
  612:         }
  613:         if (formname == 'requestcrs') {
  614:             url += '&crsdom=$domainfilter&crscode=$instcode';
  615:         }
  616:         if (multflag !=null && multflag != '') {
  617:             url += '&multiple='+multflag;
  618:         }
  619:         var title = '$wintitle';
  620:         var options = 'scrollbars=1,resizable=1,menubar=0';
  621:         options += ',width=700,height=600';
  622:         stdeditbrowser = open(url,title,options,'1');
  623:         stdeditbrowser.focus();
  624:     }
  625: $id_functions
  626: ENDSTDBRW
  627:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  628:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  629:                                       $credits_element);
  630:     }
  631:     $output .= '
  632: // ]]>
  633: </script>';
  634:     return $output;
  635: }
  636: 
  637: sub javascript_index_functions {
  638:     return <<"ENDJS";
  639: 
  640: function getFormIdByName(formname) {
  641:     for (var i=0;i<document.forms.length;i++) {
  642:         if (document.forms[i].name == formname) {
  643:             return i;
  644:         }
  645:     }
  646:     return -1;
  647: }
  648: 
  649: function getIndexByName(formid,item) {
  650:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  651:         if (document.forms[formid].elements[i].name == item) {
  652:             return i;
  653:         }
  654:     }
  655:     return -1;
  656: }
  657: 
  658: function getDomainFromSelectbox(formname,udom) {
  659:     var userdom;
  660:     var formid = getFormIdByName(formname);
  661:     if (formid > -1) {
  662:         var domid = getIndexByName(formid,udom);
  663:         if (domid > -1) {
  664:             if (document.forms[formid].elements[domid].type == 'select-one') {
  665:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  666:             }
  667:             if (document.forms[formid].elements[domid].type == 'hidden') {
  668:                 userdom=document.forms[formid].elements[domid].value;
  669:             }
  670:         }
  671:     }
  672:     return userdom;
  673: }
  674: 
  675: ENDJS
  676: 
  677: }
  678: 
  679: sub javascript_array_indexof {
  680:     return <<ENDJS;
  681: <script type="text/javascript" language="JavaScript">
  682: // <![CDATA[
  683: 
  684: if (!Array.prototype.indexOf) {
  685:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  686:         "use strict";
  687:         if (this === void 0 || this === null) {
  688:             throw new TypeError();
  689:         }
  690:         var t = Object(this);
  691:         var len = t.length >>> 0;
  692:         if (len === 0) {
  693:             return -1;
  694:         }
  695:         var n = 0;
  696:         if (arguments.length > 0) {
  697:             n = Number(arguments[1]);
  698:             if (n !== n) { // shortcut for verifying if it is NaN
  699:                 n = 0;
  700:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  701:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  702:             }
  703:         }
  704:         if (n >= len) {
  705:             return -1;
  706:         }
  707:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  708:         for (; k < len; k++) {
  709:             if (k in t && t[k] === searchElement) {
  710:                 return k;
  711:             }
  712:         }
  713:         return -1;
  714:     }
  715: }
  716: 
  717: // ]]>
  718: </script>
  719: 
  720: ENDJS
  721: 
  722: }
  723: 
  724: sub userbrowser_javascript {
  725:     my $id_functions = &javascript_index_functions();
  726:     return <<"ENDUSERBRW";
  727: 
  728: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  729:     var url = '/adm/pickuser?';
  730:     var userdom = getDomainFromSelectbox(formname,udom);
  731:     if (userdom != null) {
  732:        if (userdom != '') {
  733:            url += 'srchdom='+userdom+'&';
  734:        }
  735:     }
  736:     url += 'form=' + formname + '&unameelement='+uname+
  737:                                 '&udomelement='+udom+
  738:                                 '&ulastelement='+ulast+
  739:                                 '&ufirstelement='+ufirst+
  740:                                 '&uemailelement='+uemail+
  741:                                 '&hideudomelement='+hideudom+
  742:                                 '&coursedom='+crsdom;
  743:     if ((caller != null) && (caller != undefined)) {
  744:         url += '&caller='+caller;
  745:     }
  746:     var title = 'User_Browser';
  747:     var options = 'scrollbars=1,resizable=1,menubar=0';
  748:     options += ',width=700,height=600';
  749:     var stdeditbrowser = open(url,title,options,'1');
  750:     stdeditbrowser.focus();
  751: }
  752: 
  753: function fix_domain (formname,udom,origdom,uname) {
  754:     var formid = getFormIdByName(formname);
  755:     if (formid > -1) {
  756:         var unameid = getIndexByName(formid,uname);
  757:         var domid = getIndexByName(formid,udom);
  758:         var hidedomid = getIndexByName(formid,origdom);
  759:         if (hidedomid > -1) {
  760:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  761:             var unameval = document.forms[formid].elements[unameid].value;
  762:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  763:                 if (domid > -1) {
  764:                     var slct = document.forms[formid].elements[domid];
  765:                     if (slct.type == 'select-one') {
  766:                         var i;
  767:                         for (i=0;i<slct.length;i++) {
  768:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  769:                         }
  770:                     }
  771:                     if (slct.type == 'hidden') {
  772:                         slct.value = fixeddom;
  773:                     }
  774:                 }
  775:             }
  776:         }
  777:     }
  778:     return;
  779: }
  780: 
  781: $id_functions
  782: ENDUSERBRW
  783: }
  784: 
  785: sub setsec_javascript {
  786:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  787:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  788:         $communityrolestr);
  789:     if ($role_element ne '') {
  790:         my @allroles = ('st','ta','ep','in','ad');
  791:         foreach my $crstype ('Course','Community') {
  792:             if ($crstype eq 'Community') {
  793:                 foreach my $role (@allroles) {
  794:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  795:                 }
  796:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  797:             } else {
  798:                 foreach my $role (@allroles) {
  799:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  800:                 }
  801:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  802:             }
  803:         }
  804:         $rolestr = '"'.join('","',@allroles).'"';
  805:         $courserolestr = '"'.join('","',@courserolenames).'"';
  806:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  807:     }
  808:     my $setsections = qq|
  809: function setSect(sectionlist) {
  810:     var sectionsArray = new Array();
  811:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  812:         sectionsArray = sectionlist.split(",");
  813:     }
  814:     var numSections = sectionsArray.length;
  815:     document.$formname.$sec_element.length = 0;
  816:     if (numSections == 0) {
  817:         document.$formname.$sec_element.multiple=false;
  818:         document.$formname.$sec_element.size=1;
  819:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  820:     } else {
  821:         if (numSections == 1) {
  822:             document.$formname.$sec_element.multiple=false;
  823:             document.$formname.$sec_element.size=1;
  824:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  825:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  826:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  827:         } else {
  828:             for (var i=0; i<numSections; i++) {
  829:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  830:             }
  831:             document.$formname.$sec_element.multiple=true
  832:             if (numSections < 3) {
  833:                 document.$formname.$sec_element.size=numSections;
  834:             } else {
  835:                 document.$formname.$sec_element.size=3;
  836:             }
  837:             document.$formname.$sec_element.options[0].selected = false
  838:         }
  839:     }
  840: }
  841: 
  842: function setRole(crstype) {
  843: |;
  844:     if ($role_element eq '') {
  845:         $setsections .= '    return;
  846: }
  847: ';
  848:     } else {
  849:         $setsections .= qq|
  850:     var elementLength = document.$formname.$role_element.length;
  851:     var allroles = Array($rolestr);
  852:     var courserolenames = Array($courserolestr);
  853:     var communityrolenames = Array($communityrolestr);
  854:     if (elementLength != undefined) {
  855:         if (document.$formname.$role_element.options[5].value == 'cc') {
  856:             if (crstype == 'Course') {
  857:                 return;
  858:             } else {
  859:                 allroles[5] = 'co';
  860:                 for (var i=0; i<6; i++) {
  861:                     document.$formname.$role_element.options[i].value = allroles[i];
  862:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  863:                 }
  864:             }
  865:         } else {
  866:             if (crstype == 'Community') {
  867:                 return;
  868:             } else {
  869:                 allroles[5] = 'cc';
  870:                 for (var i=0; i<6; i++) {
  871:                     document.$formname.$role_element.options[i].value = allroles[i];
  872:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  873:                 }
  874:             }
  875:         }
  876:     }
  877:     return;
  878: }
  879: |;
  880:     }
  881:     if ($credits_element) {
  882:         $setsections .= qq|
  883: function setCredits(defaultcredits) {
  884:     document.$formname.$credits_element.value = defaultcredits;
  885:     return;
  886: }
  887: |;
  888:     }
  889:     return $setsections;
  890: }
  891: 
  892: sub selectcourse_link {
  893:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  894:        $typeelement) = @_;
  895:    my $type = $selecttype;
  896:    my $linktext = &mt('Select Course');
  897:    if ($selecttype eq 'Community') {
  898:        $linktext = &mt('Select Community');
  899:    } elsif ($selecttype eq 'Placement') {
  900:        $linktext = &mt('Select Placement Test'); 
  901:    } elsif ($selecttype eq 'Course/Community') {
  902:        $linktext = &mt('Select Course/Community');
  903:        $type = '';
  904:    } elsif ($selecttype eq 'Select') {
  905:        $linktext = &mt('Select');
  906:        $type = '';
  907:    }
  908:    return '<span class="LC_nobreak">'
  909:          ."<a href='"
  910:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  911:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  912:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  913:          ."'>".$linktext.'</a>'
  914:          .'</span>';
  915: }
  916: 
  917: sub selectauthor_link {
  918:    my ($form,$udom)=@_;
  919:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  920:           &mt('Select Author').'</a>';
  921: }
  922: 
  923: sub selectuser_link {
  924:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  925:         $coursedom,$linktext,$caller) = @_;
  926:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  927:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  928:            ');">'.$linktext.'</a>';
  929: }
  930: 
  931: sub check_uncheck_jscript {
  932:     my $jscript = <<"ENDSCRT";
  933: function checkAll(field) {
  934:     if (field.length > 0) {
  935:         for (i = 0; i < field.length; i++) {
  936:             if (!field[i].disabled) { 
  937:                 field[i].checked = true;
  938:             }
  939:         }
  940:     } else {
  941:         if (!field.disabled) { 
  942:             field.checked = true;
  943:         }
  944:     }
  945: }
  946:  
  947: function uncheckAll(field) {
  948:     if (field.length > 0) {
  949:         for (i = 0; i < field.length; i++) {
  950:             field[i].checked = false ;
  951:         }
  952:     } else {
  953:         field.checked = false ;
  954:     }
  955: }
  956: ENDSCRT
  957:     return $jscript;
  958: }
  959: 
  960: sub select_timezone {
  961:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  962:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  963:    if ($includeempty) {
  964:        $output .= '<option value=""';
  965:        if (($selected eq '') || ($selected eq 'local')) {
  966:            $output .= ' selected="selected" ';
  967:        }
  968:        $output .= '> </option>';
  969:    }
  970:    my @timezones = DateTime::TimeZone->all_names;
  971:    foreach my $tzone (@timezones) {
  972:        $output.= '<option value="'.$tzone.'"';
  973:        if ($tzone eq $selected) {
  974:            $output.=' selected="selected"';
  975:        }
  976:        $output.=">$tzone</option>\n";
  977:    }
  978:    $output.="</select>";
  979:    return $output;
  980: }
  981: 
  982: sub select_datelocale {
  983:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  984:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  985:     if ($includeempty) {
  986:         $output .= '<option value=""';
  987:         if ($selected eq '') {
  988:             $output .= ' selected="selected" ';
  989:         }
  990:         $output .= '> </option>';
  991:     }
  992:     my @languages = &Apache::lonlocal::preferred_languages();
  993:     my (@possibles,%locale_names);
  994:     my @locales = DateTime::Locale->ids();
  995:     foreach my $id (@locales) {
  996:         if ($id ne '') {
  997:             my ($en_terr,$native_terr);
  998:             my $loc = DateTime::Locale->load($id);
  999:             if (ref($loc)) {
 1000:                 $en_terr = $loc->name();
 1001:                 $native_terr = $loc->native_name();
 1002:                 if (grep(/^en$/,@languages) || !@languages) {
 1003:                     if ($en_terr ne '') {
 1004:                         $locale_names{$id} = '('.$en_terr.')';
 1005:                     } elsif ($native_terr ne '') {
 1006:                         $locale_names{$id} = $native_terr;
 1007:                     }
 1008:                 } else {
 1009:                     if ($native_terr ne '') {
 1010:                         $locale_names{$id} = $native_terr.' ';
 1011:                     } elsif ($en_terr ne '') {
 1012:                         $locale_names{$id} = '('.$en_terr.')';
 1013:                     }
 1014:                 }
 1015:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1016:                 push(@possibles,$id);
 1017:             } 
 1018:         }
 1019:     }
 1020:     foreach my $item (sort(@possibles)) {
 1021:         $output.= '<option value="'.$item.'"';
 1022:         if ($item eq $selected) {
 1023:             $output.=' selected="selected"';
 1024:         }
 1025:         $output.=">$item";
 1026:         if ($locale_names{$item} ne '') {
 1027:             $output.='  '.$locale_names{$item};
 1028:         }
 1029:         $output.="</option>\n";
 1030:     }
 1031:     $output.="</select>";
 1032:     return $output;
 1033: }
 1034: 
 1035: sub select_language {
 1036:     my ($name,$selected,$includeempty,$noedit) = @_;
 1037:     my %langchoices;
 1038:     if ($includeempty) {
 1039:         %langchoices = ('' => 'No language preference');
 1040:     }
 1041:     foreach my $id (&languageids()) {
 1042:         my $code = &supportedlanguagecode($id);
 1043:         if ($code) {
 1044:             $langchoices{$code} = &plainlanguagedescription($id);
 1045:         }
 1046:     }
 1047:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1048:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1049: }
 1050: 
 1051: =pod
 1052: 
 1053: 
 1054: =item * &list_languages()
 1055: 
 1056: Returns an array reference that is suitable for use in language prompters.
 1057: Each array element is itself a two element array.  The first element
 1058: is the language code.  The second element a descsriptiuon of the 
 1059: language itself.  This is suitable for use in e.g.
 1060: &Apache::edit::select_arg (once dereferenced that is).
 1061: 
 1062: =cut 
 1063: 
 1064: sub list_languages {
 1065:     my @lang_choices;
 1066: 
 1067:     foreach my $id (&languageids()) {
 1068: 	my $code = &supportedlanguagecode($id);
 1069: 	if ($code) {
 1070: 	    my $selector    = $supported_codes{$id};
 1071: 	    my $description = &plainlanguagedescription($id);
 1072: 	    push(@lang_choices, [$selector, $description]);
 1073: 	}
 1074:     }
 1075:     return \@lang_choices;
 1076: }
 1077: 
 1078: =pod
 1079: 
 1080: =item * &linked_select_forms(...)
 1081: 
 1082: linked_select_forms returns a string containing a <script></script> block
 1083: and html for two <select> menus.  The select menus will be linked in that
 1084: changing the value of the first menu will result in new values being placed
 1085: in the second menu.  The values in the select menu will appear in alphabetical
 1086: order unless a defined order is provided.
 1087: 
 1088: linked_select_forms takes the following ordered inputs:
 1089: 
 1090: =over 4
 1091: 
 1092: =item * $formname, the name of the <form> tag
 1093: 
 1094: =item * $middletext, the text which appears between the <select> tags
 1095: 
 1096: =item * $firstdefault, the default value for the first menu
 1097: 
 1098: =item * $firstselectname, the name of the first <select> tag
 1099: 
 1100: =item * $secondselectname, the name of the second <select> tag
 1101: 
 1102: =item * $hashref, a reference to a hash containing the data for the menus.
 1103: 
 1104: =item * $menuorder, the order of values in the first menu
 1105: 
 1106: =item * $onchangefirst, additional javascript call to execute for an onchange
 1107:         event for the first <select> tag
 1108: 
 1109: =item * $onchangesecond, additional javascript call to execute for an onchange
 1110:         event for the second <select> tag
 1111: 
 1112: =item * $suffix, to differentiate separate uses of select2data javascript
 1113:         objects in a page.
 1114: 
 1115: =back 
 1116: 
 1117: Below is an example of such a hash.  Only the 'text', 'default', and 
 1118: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1119: values for the first select menu.  The text that coincides with the 
 1120: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1121: and text for the second menu are given in the hash pointed to by 
 1122: $menu{$choice1}->{'select2'}.  
 1123: 
 1124:  my %menu = ( A1 => { text =>"Choice A1" ,
 1125:                        default => "B3",
 1126:                        select2 => { 
 1127:                            B1 => "Choice B1",
 1128:                            B2 => "Choice B2",
 1129:                            B3 => "Choice B3",
 1130:                            B4 => "Choice B4"
 1131:                            },
 1132:                        order => ['B4','B3','B1','B2'],
 1133:                    },
 1134:                A2 => { text =>"Choice A2" ,
 1135:                        default => "C2",
 1136:                        select2 => { 
 1137:                            C1 => "Choice C1",
 1138:                            C2 => "Choice C2",
 1139:                            C3 => "Choice C3"
 1140:                            },
 1141:                        order => ['C2','C1','C3'],
 1142:                    },
 1143:                A3 => { text =>"Choice A3" ,
 1144:                        default => "D6",
 1145:                        select2 => { 
 1146:                            D1 => "Choice D1",
 1147:                            D2 => "Choice D2",
 1148:                            D3 => "Choice D3",
 1149:                            D4 => "Choice D4",
 1150:                            D5 => "Choice D5",
 1151:                            D6 => "Choice D6",
 1152:                            D7 => "Choice D7"
 1153:                            },
 1154:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1155:                    }
 1156:                );
 1157: 
 1158: =cut
 1159: 
 1160: sub linked_select_forms {
 1161:     my ($formname,
 1162:         $middletext,
 1163:         $firstdefault,
 1164:         $firstselectname,
 1165:         $secondselectname, 
 1166:         $hashref,
 1167:         $menuorder,
 1168:         $onchangefirst,
 1169:         $onchangesecond,
 1170:         $suffix
 1171:         ) = @_;
 1172:     my $second = "document.$formname.$secondselectname";
 1173:     my $first = "document.$formname.$firstselectname";
 1174:     # output the javascript to do the changing
 1175:     my $result = '';
 1176:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1177:     $result.="// <![CDATA[\n";
 1178:     $result.="var select2data${suffix} = new Object();\n";
 1179:     $" = '","';
 1180:     my $debug = '';
 1181:     foreach my $s1 (sort(keys(%$hashref))) {
 1182:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1183:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1184:             $hashref->{$s1}->{'default'}."');\n";
 1185:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1186:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1187:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1188:             @s2values = @{$hashref->{$s1}->{'order'}};
 1189:         }
 1190:         $result.="\"@s2values\");\n";
 1191:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1192:         my @s2texts;
 1193:         foreach my $value (@s2values) {
 1194:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1195:         }
 1196:         $result.="\"@s2texts\");\n";
 1197:     }
 1198:     $"=' ';
 1199:     $result.= <<"END";
 1200: 
 1201: function select1${suffix}_changed() {
 1202:     // Determine new choice
 1203:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1204:     // update select2
 1205:     var values     = select2data${suffix}[newvalue].values;
 1206:     var texts      = select2data${suffix}[newvalue].texts;
 1207:     var select2def = select2data${suffix}[newvalue].def;
 1208:     var i;
 1209:     // out with the old
 1210:     $second.options.length = 0;
 1211:     // in with the new
 1212:     for (i=0;i<values.length; i++) {
 1213:         $second.options[i] = new Option(values[i]);
 1214:         $second.options[i].value = values[i];
 1215:         $second.options[i].text = texts[i];
 1216:         if (values[i] == select2def) {
 1217:             $second.options[i].selected = true;
 1218:         }
 1219:     }
 1220: }
 1221: // ]]>
 1222: </script>
 1223: END
 1224:     # output the initial values for the selection lists
 1225:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1226:     my @order = sort(keys(%{$hashref}));
 1227:     if (ref($menuorder) eq 'ARRAY') {
 1228:         @order = @{$menuorder};
 1229:     }
 1230:     foreach my $value (@order) {
 1231:         $result.="    <option value=\"$value\" ";
 1232:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1233:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1234:     }
 1235:     $result .= "</select>\n";
 1236:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1237:     $result .= $middletext;
 1238:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1239:     if ($onchangesecond) {
 1240:         $result .= ' onchange="'.$onchangesecond.'"';
 1241:     }
 1242:     $result .= ">\n";
 1243:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1244:     
 1245:     my @secondorder = sort(keys(%select2));
 1246:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1247:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1248:     }
 1249:     foreach my $value (@secondorder) {
 1250:         $result.="    <option value=\"$value\" ";        
 1251:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1252:         $result.=">".&mt($select2{$value})."</option>\n";
 1253:     }
 1254:     $result .= "</select>\n";
 1255:     #    return $debug;
 1256:     return $result;
 1257: }   #  end of sub linked_select_forms {
 1258: 
 1259: =pod
 1260: 
 1261: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1262: 
 1263: Returns a string corresponding to an HTML link to the given help
 1264: $topic, where $topic corresponds to the name of a .tex file in
 1265: /home/httpd/html/adm/help/tex, with underscores replaced by
 1266: spaces. 
 1267: 
 1268: $text will optionally be linked to the same topic, allowing you to
 1269: link text in addition to the graphic. If you do not want to link
 1270: text, but wish to specify one of the later parameters, pass an
 1271: empty string. 
 1272: 
 1273: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1274: the link will not open a new window. If false, the link will open
 1275: a new window using Javascript. (Default is false.) 
 1276: 
 1277: $width and $height are optional numerical parameters that will
 1278: override the width and height of the popped up window, which may
 1279: be useful for certain help topics with big pictures included.
 1280: 
 1281: $imgid is the id of the img tag used for the help icon. This may be
 1282: used in a javascript call to switch the image src.  See 
 1283: lonhtmlcommon::htmlareaselectactive() for an example.
 1284: 
 1285: $links_target will optionally be set to a target (_top, _parent or _self).
 1286: 
 1287: =cut
 1288: 
 1289: sub help_open_topic {
 1290:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1291:     $text = "" if (not defined $text);
 1292:     $stayOnPage = 0 if (not defined $stayOnPage);
 1293:     $width = 500 if (not defined $width);
 1294:     $height = 400 if (not defined $height);
 1295:     my $filename = $topic;
 1296:     $filename =~ s/ /_/g;
 1297: 
 1298:     my $template = "";
 1299:     my $link;
 1300:     
 1301:     $topic=~s/\W/\_/g;
 1302: 
 1303:     if (!$stayOnPage) {
 1304: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1305:     } elsif ($stayOnPage eq 'popup') {
 1306:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1307:     } else {
 1308: 	$link = "/adm/help/${filename}.hlp";
 1309:     }
 1310: 
 1311:     # Add the text
 1312:     my $target = ' target="_top"';
 1313:     if ($links_target) {
 1314:         $target = ' target="'.$links_target.'"';
 1315:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1316:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1317:         $target = '';
 1318:     }
 1319:     if ($text ne "") {
 1320: 	$template.='<span class="LC_help_open_topic">'
 1321:                   .'<a'.$target.' href="'.$link.'">'
 1322:                   .$text.'</a>';
 1323:     }
 1324: 
 1325:     # (Always) Add the graphic
 1326:     my $title = &mt('Online Help');
 1327:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1328:     if ($imgid ne '') {
 1329:         $imgid = ' id="'.$imgid.'"';
 1330:     }
 1331:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1332:               .'<img src="'.$helpicon.'" border="0"'
 1333:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1334:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1335:               .' /></a>';
 1336:     if ($text ne "") {	
 1337:         $template.='</span>';
 1338:     }
 1339:     return $template;
 1340: 
 1341: }
 1342: 
 1343: # This is a quicky function for Latex cheatsheet editing, since it 
 1344: # appears in at least four places
 1345: sub helpLatexCheatsheet {
 1346:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1347:     my $out;
 1348:     my $addOther = '';
 1349:     if ($topic) {
 1350: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1351:     }
 1352:     $out = '<span>' # Start cheatsheet
 1353: 	  .$addOther
 1354:           .'<span>'
 1355: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1356: 	  .'</span> <span>'
 1357: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1358: 	  .'</span>';
 1359:     unless ($not_author) {
 1360:         $out .= '<span>'
 1361:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1362:                .'</span> <span>'
 1363:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1364: 	       .'</span>';
 1365:     }
 1366:     $out .= '</span>'; # End cheatsheet
 1367:     return $out;
 1368: }
 1369: 
 1370: sub general_help {
 1371:     my $helptopic='Student_Intro';
 1372:     if ($env{'request.role'}=~/^(ca|au)/) {
 1373: 	$helptopic='Authoring_Intro';
 1374:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1375: 	$helptopic='Course_Coordination_Intro';
 1376:     } elsif ($env{'request.role'}=~/^dc/) {
 1377:         $helptopic='Domain_Coordination_Intro';
 1378:     }
 1379:     return $helptopic;
 1380: }
 1381: 
 1382: sub update_help_link {
 1383:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1384:     my $origurl = $ENV{'REQUEST_URI'};
 1385:     $origurl=~s|^/~|/priv/|;
 1386:     my $timestamp = time;
 1387:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1388:         $$datum = &escape($$datum);
 1389:     }
 1390: 
 1391:     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";
 1392:     my $output .= <<"ENDOUTPUT";
 1393: <script type="text/javascript">
 1394: // <![CDATA[
 1395: banner_link = '$banner_link';
 1396: // ]]>
 1397: </script>
 1398: ENDOUTPUT
 1399:     return $output;
 1400: }
 1401: 
 1402: # now just updates the help link and generates a blue icon
 1403: sub help_open_menu {
 1404:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1405: 	= @_;    
 1406:     $stayOnPage = 1;
 1407:     my $output;
 1408:     if ($component_help) {
 1409: 	if (!$text) {
 1410: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1411: 				       $width,$height,'',$links_target);
 1412: 	} else {
 1413: 	    my $help_text;
 1414: 	    $help_text=&unescape($topic);
 1415: 	    $output='<table><tr><td>'.
 1416: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1417: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1418: 	}
 1419:     }
 1420:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1421:     return $output.$banner_link;
 1422: }
 1423: 
 1424: sub top_nav_help {
 1425:     my ($text,$linkattr) = @_;
 1426:     $text = &mt($text);
 1427:     my $stay_on_page = 1;
 1428: 
 1429:     my ($link,$banner_link);
 1430:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1431:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1432: 	                         : "javascript:helpMenu('open')";
 1433:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1434:     }
 1435:     my $title = &mt('Get help');
 1436:     if ($link) {
 1437:         return <<"END";
 1438: $banner_link
 1439: <a href="$link" title="$title" $linkattr>$text</a>
 1440: END
 1441:     } else {
 1442:         return '&nbsp;'.$text.'&nbsp;';
 1443:     }
 1444: }
 1445: 
 1446: sub help_menu_js {
 1447:     my ($httphost) = @_;
 1448:     my $stayOnPage = 1;
 1449:     my $width = 620;
 1450:     my $height = 600;
 1451:     my $helptopic=&general_help();
 1452:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1453:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1454:     my $start_page =
 1455:         &Apache::loncommon::start_page('Help Menu', undef,
 1456: 				       {'frameset'    => 1,
 1457: 					'js_ready'    => 1,
 1458:                                         'use_absolute' => $httphost,
 1459: 					'add_entries' => {
 1460: 					    'border' => '0', 
 1461: 					    'rows'   => "110,*",},});
 1462:     my $end_page =
 1463:         &Apache::loncommon::end_page({'frameset' => 1,
 1464: 				      'js_ready' => 1,});
 1465: 
 1466:     my $template .= <<"ENDTEMPLATE";
 1467: <script type="text/javascript">
 1468: // <![CDATA[
 1469: // <!-- BEGIN LON-CAPA Internal
 1470: var banner_link = '';
 1471: function helpMenu(target) {
 1472:     var caller = this;
 1473:     if (target == 'open') {
 1474:         var newWindow = null;
 1475:         try {
 1476:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1477:         }
 1478:         catch(error) {
 1479:             writeHelp(caller);
 1480:             return;
 1481:         }
 1482:         if (newWindow) {
 1483:             caller = newWindow;
 1484:         }
 1485:     }
 1486:     writeHelp(caller);
 1487:     return;
 1488: }
 1489: function writeHelp(caller) {
 1490:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1491:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1492:     caller.document.close();
 1493:     caller.focus();
 1494: }
 1495: // END LON-CAPA Internal -->
 1496: // ]]>
 1497: </script>
 1498: ENDTEMPLATE
 1499:     return $template;
 1500: }
 1501: 
 1502: sub help_open_bug {
 1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1504:     unless ($env{'user.adv'}) { return ''; }
 1505:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1506:     $text = "" if (not defined $text);
 1507: 	$stayOnPage=1;
 1508:     $width = 600 if (not defined $width);
 1509:     $height = 600 if (not defined $height);
 1510: 
 1511:     $topic=~s/\W+/\+/g;
 1512:     my $link='';
 1513:     my $template='';
 1514:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1515: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1516:     if (!$stayOnPage)
 1517:     {
 1518: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1519:     }
 1520:     else
 1521:     {
 1522: 	$link = $url;
 1523:     }
 1524: 
 1525:     my $target = '_top';
 1526:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1527:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1528:         $target = '_blank';
 1529:     }
 1530: 
 1531:     # Add the text
 1532:     if ($text ne "")
 1533:     {
 1534: 	$template .= 
 1535:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1536:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1537:     }
 1538: 
 1539:     # Add the graphic
 1540:     my $title = &mt('Report a Bug');
 1541:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1542:     $template .= <<"ENDTEMPLATE";
 1543:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1544: ENDTEMPLATE
 1545:     if ($text ne '') { $template.='</td></tr></table>' };
 1546:     return $template;
 1547: 
 1548: }
 1549: 
 1550: sub help_open_faq {
 1551:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1552:     unless ($env{'user.adv'}) { return ''; }
 1553:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1554:     $text = "" if (not defined $text);
 1555: 	$stayOnPage=1;
 1556:     $width = 350 if (not defined $width);
 1557:     $height = 400 if (not defined $height);
 1558: 
 1559:     $topic=~s/\W+/\+/g;
 1560:     my $link='';
 1561:     my $template='';
 1562:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1563:     if (!$stayOnPage)
 1564:     {
 1565: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1566:     }
 1567:     else
 1568:     {
 1569: 	$link = $url;
 1570:     }
 1571: 
 1572:     # Add the text
 1573:     if ($text ne "")
 1574:     {
 1575: 	$template .= 
 1576:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1577:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1578:     }
 1579: 
 1580:     # Add the graphic
 1581:     my $title = &mt('View the FAQ');
 1582:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1583:     $template .= <<"ENDTEMPLATE";
 1584:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1585: ENDTEMPLATE
 1586:     if ($text ne '') { $template.='</td></tr></table>' };
 1587:     return $template;
 1588: 
 1589: }
 1590: 
 1591: ###############################################################
 1592: ###############################################################
 1593: 
 1594: =pod
 1595: 
 1596: =item * &change_content_javascript():
 1597: 
 1598: This and the next function allow you to create small sections of an
 1599: otherwise static HTML page that you can update on the fly with
 1600: Javascript, even in Netscape 4.
 1601: 
 1602: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1603: must be written to the HTML page once. It will prove the Javascript
 1604: function "change(name, content)". Calling the change function with the
 1605: name of the section 
 1606: you want to update, matching the name passed to C<changable_area>, and
 1607: the new content you want to put in there, will put the content into
 1608: that area.
 1609: 
 1610: B<Note>: Netscape 4 only reserves enough space for the changable area
 1611: to contain room for the original contents. You need to "make space"
 1612: for whatever changes you wish to make, and be B<sure> to check your
 1613: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1614: it's adequate for updating a one-line status display, but little more.
 1615: This script will set the space to 100% width, so you only need to
 1616: worry about height in Netscape 4.
 1617: 
 1618: Modern browsers are much less limiting, and if you can commit to the
 1619: user not using Netscape 4, this feature may be used freely with
 1620: pretty much any HTML.
 1621: 
 1622: =cut
 1623: 
 1624: sub change_content_javascript {
 1625:     # If we're on Netscape 4, we need to use Layer-based code
 1626:     if ($env{'browser.type'} eq 'netscape' &&
 1627: 	$env{'browser.version'} =~ /^4\./) {
 1628: 	return (<<NETSCAPE4);
 1629: 	function change(name, content) {
 1630: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1631: 	    doc.open();
 1632: 	    doc.write(content);
 1633: 	    doc.close();
 1634: 	}
 1635: NETSCAPE4
 1636:     } else {
 1637: 	# Otherwise, we need to use semi-standards-compliant code
 1638: 	# (technically, "innerHTML" isn't standard but the equivalent
 1639: 	# is really scary, and every useful browser supports it
 1640: 	return (<<DOMBASED);
 1641: 	function change(name, content) {
 1642: 	    element = document.getElementById(name);
 1643: 	    element.innerHTML = content;
 1644: 	}
 1645: DOMBASED
 1646:     }
 1647: }
 1648: 
 1649: =pod
 1650: 
 1651: =item * &changable_area($name,$origContent):
 1652: 
 1653: This provides a "changable area" that can be modified on the fly via
 1654: the Javascript code provided in C<change_content_javascript>. $name is
 1655: the name you will use to reference the area later; do not repeat the
 1656: same name on a given HTML page more then once. $origContent is what
 1657: the area will originally contain, which can be left blank.
 1658: 
 1659: =cut
 1660: 
 1661: sub changable_area {
 1662:     my ($name, $origContent) = @_;
 1663: 
 1664:     if ($env{'browser.type'} eq 'netscape' &&
 1665: 	$env{'browser.version'} =~ /^4\./) {
 1666: 	# If this is netscape 4, we need to use the Layer tag
 1667: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1668:     } else {
 1669: 	return "<span id='$name'>$origContent</span>";
 1670:     }
 1671: }
 1672: 
 1673: =pod
 1674: 
 1675: =item * &viewport_geometry_js 
 1676: 
 1677: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1678: 
 1679: =cut
 1680: 
 1681: 
 1682: sub viewport_geometry_js { 
 1683:     return <<"GEOMETRY";
 1684: var Geometry = {};
 1685: function init_geometry() {
 1686:     if (Geometry.init) { return };
 1687:     Geometry.init=1;
 1688:     if (window.innerHeight) {
 1689:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1690:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1691:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1692:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1693:     }
 1694:     else if (document.documentElement && document.documentElement.clientHeight) {
 1695:         Geometry.getViewportHeight =
 1696:             function() { return document.documentElement.clientHeight; };
 1697:         Geometry.getViewportWidth =
 1698:             function() { return document.documentElement.clientWidth; };
 1699: 
 1700:         Geometry.getHorizontalScroll =
 1701:             function() { return document.documentElement.scrollLeft; };
 1702:         Geometry.getVerticalScroll =
 1703:             function() { return document.documentElement.scrollTop; };
 1704:     }
 1705:     else if (document.body.clientHeight) {
 1706:         Geometry.getViewportHeight =
 1707:             function() { return document.body.clientHeight; };
 1708:         Geometry.getViewportWidth =
 1709:             function() { return document.body.clientWidth; };
 1710:         Geometry.getHorizontalScroll =
 1711:             function() { return document.body.scrollLeft; };
 1712:         Geometry.getVerticalScroll =
 1713:             function() { return document.body.scrollTop; };
 1714:     }
 1715: }
 1716: 
 1717: GEOMETRY
 1718: }
 1719: 
 1720: =pod
 1721: 
 1722: =item * &viewport_size_js()
 1723: 
 1724: 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. 
 1725: 
 1726: =cut
 1727: 
 1728: sub viewport_size_js {
 1729:     my $geometry = &viewport_geometry_js();
 1730:     return <<"DIMS";
 1731: 
 1732: $geometry
 1733: 
 1734: function getViewportDims(width,height) {
 1735:     init_geometry();
 1736:     width.value = Geometry.getViewportWidth();
 1737:     height.value = Geometry.getViewportHeight();
 1738:     return;
 1739: }
 1740: 
 1741: DIMS
 1742: }
 1743: 
 1744: =pod
 1745: 
 1746: =item * &resize_textarea_js()
 1747: 
 1748: emits the needed javascript to resize a textarea to be as big as possible
 1749: 
 1750: creates a function resize_textrea that takes two IDs first should be
 1751: the id of the element to resize, second should be the id of a div that
 1752: surrounds everything that comes after the textarea, this routine needs
 1753: to be attached to the <body> for the onload and onresize events.
 1754: 
 1755: =back
 1756: 
 1757: =cut
 1758: 
 1759: sub resize_textarea_js {
 1760:     my $geometry = &viewport_geometry_js();
 1761:     return <<"RESIZE";
 1762:     <script type="text/javascript">
 1763: // <![CDATA[
 1764: $geometry
 1765: 
 1766: function getX(element) {
 1767:     var x = 0;
 1768:     while (element) {
 1769: 	x += element.offsetLeft;
 1770: 	element = element.offsetParent;
 1771:     }
 1772:     return x;
 1773: }
 1774: function getY(element) {
 1775:     var y = 0;
 1776:     while (element) {
 1777: 	y += element.offsetTop;
 1778: 	element = element.offsetParent;
 1779:     }
 1780:     return y;
 1781: }
 1782: 
 1783: 
 1784: function resize_textarea(textarea_id,bottom_id) {
 1785:     init_geometry();
 1786:     var textarea        = document.getElementById(textarea_id);
 1787:     //alert(textarea);
 1788: 
 1789:     var textarea_top    = getY(textarea);
 1790:     var textarea_height = textarea.offsetHeight;
 1791:     var bottom          = document.getElementById(bottom_id);
 1792:     var bottom_top      = getY(bottom);
 1793:     var bottom_height   = bottom.offsetHeight;
 1794:     var window_height   = Geometry.getViewportHeight();
 1795:     var fudge           = 23;
 1796:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1797:     if (new_height < 300) {
 1798: 	new_height = 300;
 1799:     }
 1800:     textarea.style.height=new_height+'px';
 1801: }
 1802: // ]]>
 1803: </script>
 1804: RESIZE
 1805: 
 1806: }
 1807: 
 1808: sub colorfuleditor_js {
 1809:     my $browse_or_search;
 1810:     my $respath;
 1811:     my ($cnum,$cdom) = &crsauthor_url();
 1812:     if ($cnum) {
 1813:         $respath = "/res/$cdom/$cnum/";
 1814:         my %js_lt = &Apache::lonlocal::texthash(
 1815:             sunm => 'Sub-directory name',
 1816:             save => 'Save page to make this permanent',
 1817:         );
 1818:         &js_escape(\%js_lt);
 1819:         $browse_or_search = <<"END";
 1820: 
 1821:     function toggleChooser(form,element,titleid,only,search) {
 1822:         var disp = 'none';
 1823:         if (document.getElementById('chooser_'+element)) {
 1824:             var curr = document.getElementById('chooser_'+element).style.display;
 1825:             if (curr == 'none') {
 1826:                 disp='inline';
 1827:                 if (form.elements['chooser_'+element].length) {
 1828:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1829:                         form.elements['chooser_'+element][i].checked = false;
 1830:                     }
 1831:                 }
 1832:                 toggleResImport(form,element);
 1833:             }
 1834:             document.getElementById('chooser_'+element).style.display = disp;
 1835:         }
 1836:     }
 1837: 
 1838:     function toggleCrsFile(form,element,numdirs) {
 1839:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1840:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1841:             if (curr == 'none') {
 1842:                 if (numdirs) {
 1843:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1844:                     if (numdirs > 1) {
 1845:                         window['select1'+element+'_changed']();
 1846:                     }
 1847:                 }
 1848:             } 
 1849:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1850:             
 1851:         }
 1852:         if (document.getElementById('chooser_'+element+'_upload')) {
 1853:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1854:             if (document.getElementById('uploadcrsres_'+element)) {
 1855:                 document.getElementById('uploadcrsres_'+element).value = '';
 1856:             }
 1857:         }
 1858:         return;
 1859:     }
 1860: 
 1861:     function toggleCrsUpload(form,element,numcrsdirs) {
 1862:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1863:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1864:         }
 1865:         if (document.getElementById('chooser_'+element+'_upload')) {
 1866:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1867:             if (curr == 'none') {
 1868:                 if (numcrsdirs) {
 1869:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1870:                    form.elements['newsubdir_'+element][0].checked = true;
 1871:                    toggleNewsubdir(form,element);
 1872:                 }
 1873:             }
 1874:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1875:         }
 1876:         return;
 1877:     }
 1878: 
 1879:     function toggleResImport(form,element) {
 1880:         var choices = new Array('crsres','upload');
 1881:         for (var i=0; i<choices.length; i++) {
 1882:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1883:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1884:             }
 1885:         }
 1886:     }
 1887: 
 1888:     function toggleNewsubdir(form,element) {
 1889:         var newsub = form.elements['newsubdir_'+element];
 1890:         if (newsub) {
 1891:             if (newsub.length) {
 1892:                 for (var j=0; j<newsub.length; j++) {
 1893:                     if (newsub[j].checked) {
 1894:                         if (document.getElementById('newsubdirname_'+element)) {
 1895:                             if (newsub[j].value == '1') {
 1896:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1897:                                 if (document.getElementById('newsubdir_'+element)) {
 1898:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1899:                                 }
 1900:                             } else {
 1901:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1902:                                 document.getElementById('newsubdirname_'+element).value = "";
 1903:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1904:                             }
 1905:                         }
 1906:                         break; 
 1907:                     }
 1908:                 }
 1909:             }
 1910:         }
 1911:     }
 1912: 
 1913:     function updateCrsFile(form,element) {
 1914:         var directory = form.elements['coursepath_'+element];
 1915:         var filename = form.elements['coursefile_'+element];
 1916:         var path = directory.options[directory.selectedIndex].value;
 1917:         var file = filename.options[filename.selectedIndex].value;
 1918:         form.elements[element].value = '$respath';
 1919:         if (path == '/') {
 1920:             form.elements[element].value += file;
 1921:         } else {
 1922:             form.elements[element].value += path+'/'+file;
 1923:         }
 1924:         unClean();
 1925:         if (document.getElementById('previewimg_'+element)) {
 1926:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1927:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1928:         }
 1929:         if (document.getElementById('showimg_'+element)) {
 1930:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1931:         }
 1932:         toggleChooser(form,element);
 1933:         return;
 1934:     }
 1935: 
 1936:     function uploadDone(suffix,name) {
 1937:         if (name) {
 1938: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1939:             unClean();
 1940:             toggleChooser(document.forms["lonhomework"],suffix);
 1941:         }
 1942:     }
 1943: 
 1944: \$(document).ready(function(){
 1945: 
 1946:     \$(document).delegate('form :submit', 'click', function( event ) {
 1947:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1948:             var buttonId = this.id;
 1949:             var suffix = buttonId.toString();
 1950:             suffix = suffix.replace(/^crsupload_/,'');
 1951:             event.preventDefault();
 1952:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1953:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1954:             \$(this.form).submit();
 1955:             document.lonhomework.target = '';
 1956:             if (document.getElementById('crsuploadto_'+suffix)) {
 1957:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1958:             }
 1959:             return false;
 1960:         }
 1961:     });
 1962: });
 1963: END
 1964:     }
 1965:     return <<"COLORFULEDIT"
 1966: <script type="text/javascript">
 1967: // <![CDATA[>
 1968:     function fold_box(curDepth, lastresource){
 1969: 
 1970:     // we need a list because there can be several blocks you need to fold in one tag
 1971:         var block = document.getElementsByName('foldblock_'+curDepth);
 1972:     // but there is only one folding button per tag
 1973:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1974: 
 1975:         if(block.item(0).style.display == 'none'){
 1976: 
 1977:             foldbutton.value = '@{[&mt("Hide")]}';
 1978:             for (i = 0; i < block.length; i++){
 1979:                 block.item(i).style.display = '';
 1980:             }
 1981:         }else{
 1982: 
 1983:             foldbutton.value = '@{[&mt("Show")]}';
 1984:             for (i = 0; i < block.length; i++){
 1985:                 // block.item(i).style.visibility = 'collapse';
 1986:                 block.item(i).style.display = 'none';
 1987:             }
 1988:         };
 1989:         saveState(lastresource);
 1990:     }
 1991: 
 1992:     function saveState (lastresource) {
 1993: 
 1994:         var tag_list = getTagList();
 1995:         if(tag_list != null){
 1996:             var timestamp = new Date().getTime();
 1997:             var key = lastresource;
 1998: 
 1999:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2000:             // starting with timestamp
 2001:             var value = timestamp+';';
 2002: 
 2003:             // building the list of key-value pairs
 2004:             for(var i = 0; i < tag_list.length; i++){
 2005:                 value += tag_list[i]+',';
 2006:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2007:             }
 2008: 
 2009:             // only iterate whole storage if nothing to override
 2010:             if(localStorage.getItem(key) == null){        
 2011: 
 2012:                 // prevent storage from growing large
 2013:                 if(localStorage.length > 50){
 2014:                     var regex_getTimestamp = /^(?:\d)+;/;
 2015:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2016:                     var oldest_key;
 2017:                     
 2018:                     for(var i = 1; i < localStorage.length; i++){
 2019:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2020:                             oldest_key = localStorage.key(i);
 2021:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2022:                         }
 2023:                     }
 2024:                     localStorage.removeItem(oldest_key);
 2025:                 }
 2026:             }
 2027:             localStorage.setItem(key,value);
 2028:         }
 2029:     }
 2030: 
 2031:     // restore folding status of blocks (on page load)
 2032:     function restoreState (lastresource) {
 2033:         if(localStorage.getItem(lastresource) != null){
 2034:             var key = lastresource;
 2035:             var value = localStorage.getItem(key);
 2036:             var regex_delTimestamp = /^\d+;/;
 2037: 
 2038:             value.replace(regex_delTimestamp, '');
 2039: 
 2040:             var valueArr = value.split(';');
 2041:             var pairs;
 2042:             var elements;
 2043:             for (var i = 0; i < valueArr.length; i++){
 2044:                 pairs = valueArr[i].split(',');
 2045:                 elements = document.getElementsByName(pairs[0]);
 2046: 
 2047:                 for (var j = 0; j < elements.length; j++){  
 2048:                     elements[j].style.display = pairs[1];
 2049:                     if (pairs[1] == "none"){
 2050:                         var regex_id = /([_\\d]+)\$/;
 2051:                         regex_id.exec(pairs[0]);
 2052:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2053:                     }
 2054:                 }
 2055:             }
 2056:         }
 2057:     }
 2058: 
 2059:     function getTagList () {
 2060:         
 2061:         var stringToSearch = document.lonhomework.innerHTML;
 2062: 
 2063:         var ret = new Array();
 2064:         var regex_findBlock = /(foldblock_.*?)"/g;
 2065:         var tag_list = stringToSearch.match(regex_findBlock);
 2066: 
 2067:         if(tag_list != null){
 2068:             for(var i = 0; i < tag_list.length; i++){            
 2069:                 ret.push(tag_list[i].replace(/"/, ''));
 2070:             }
 2071:         }
 2072:         return ret;
 2073:     }
 2074: 
 2075:     function saveScrollPosition (resource) {
 2076:         var tag_list = getTagList();
 2077: 
 2078:         // we dont always want to jump to the first block
 2079:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2080:         if(\$(window).scrollTop() > 170){
 2081:             if(tag_list != null){
 2082:                 var result;
 2083:                 for(var i = 0; i < tag_list.length; i++){
 2084:                     if(isElementInViewport(tag_list[i])){
 2085:                         result += tag_list[i]+';';
 2086:                     }
 2087:                 }
 2088:                 sessionStorage.setItem('anchor_'+resource, result);
 2089:             }
 2090:         } else {
 2091:             // we dont need to save zero, just delete the item to leave everything tidy
 2092:             sessionStorage.removeItem('anchor_'+resource);
 2093:         }
 2094:     }
 2095: 
 2096:     function restoreScrollPosition(resource){
 2097: 
 2098:         var elem = sessionStorage.getItem('anchor_'+resource);
 2099:         if(elem != null){
 2100:             var tag_list = elem.split(';');
 2101:             var elem_list;
 2102: 
 2103:             for(var i = 0; i < tag_list.length; i++){
 2104:                 elem_list = document.getElementsByName(tag_list[i]);
 2105:                 
 2106:                 if(elem_list.length > 0){
 2107:                     elem = elem_list[0];
 2108:                     break;
 2109:                 }
 2110:             }
 2111:             elem.scrollIntoView();
 2112:         }
 2113:     }
 2114: 
 2115:     function isElementInViewport(el) {
 2116: 
 2117:         // change to last element instead of first
 2118:         var elem = document.getElementsByName(el);
 2119:         var rect = elem[0].getBoundingClientRect();
 2120: 
 2121:         return (
 2122:             rect.top >= 0 &&
 2123:             rect.left >= 0 &&
 2124:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2125:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2126:         );
 2127:     }
 2128:     
 2129:     function autosize(depth){
 2130:         var cmInst = window['cm'+depth];
 2131:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2132: 
 2133:         // is fixed size, switching to dynamic
 2134:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2135:             cmInst.setSize("","auto");
 2136:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2137:             sessionStorage.setItem("autosized_"+depth, "yes");
 2138: 
 2139:         // is dynamic size, switching to fixed
 2140:         } else {
 2141:             cmInst.setSize("","300px");
 2142:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2143:             sessionStorage.removeItem("autosized_"+depth);
 2144:         }
 2145:     }
 2146: 
 2147: $browse_or_search
 2148: 
 2149: // ]]>
 2150: </script>
 2151: COLORFULEDIT
 2152: }
 2153: 
 2154: sub xmleditor_js {
 2155:     return <<XMLEDIT
 2156: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2157: <script type="text/javascript">
 2158: // <![CDATA[>
 2159: 
 2160:     function saveScrollPosition (resource) {
 2161: 
 2162:         var scrollPos = \$(window).scrollTop();
 2163:         sessionStorage.setItem(resource,scrollPos);
 2164:     }
 2165: 
 2166:     function restoreScrollPosition(resource){
 2167: 
 2168:         var scrollPos = sessionStorage.getItem(resource);
 2169:         \$(window).scrollTop(scrollPos);
 2170:     }
 2171: 
 2172:     // unless internet explorer
 2173:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2174: 
 2175:         \$(document).ready(function() {
 2176:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2177:         });
 2178:     }
 2179: 
 2180:     // inserts text at cursor position into codemirror (xml editor only)
 2181:     function insertText(text){
 2182:         cm.focus();
 2183:         var curPos = cm.getCursor();
 2184:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2185:     }
 2186: // ]]>
 2187: </script>
 2188: XMLEDIT
 2189: }
 2190: 
 2191: sub insert_folding_button {
 2192:     my $curDepth = $Apache::lonxml::curdepth;
 2193:     my $lastresource = $env{'request.ambiguous'};
 2194: 
 2195:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2196:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2197: }
 2198: 
 2199: sub crsauthor_url {
 2200:     my ($url) = @_;
 2201:     if ($url eq '') {
 2202:         $url = $ENV{'REQUEST_URI'};
 2203:     }
 2204:     my ($cnum,$cdom);
 2205:     if ($env{'request.course.id'}) {
 2206:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2207:         if ($audom ne '' && $auname ne '') {
 2208:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2209:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2210:                 $cnum = $auname;
 2211:                 $cdom = $audom;
 2212:             }
 2213:         }
 2214:     }
 2215:     return ($cnum,$cdom);
 2216: }
 2217: 
 2218: sub import_crsauthor_form {
 2219:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2220:     return (0) unless ($env{'request.course.id'});
 2221:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2222:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2223:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2224:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2225:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2226:     my @ids=&Apache::lonnet::current_machine_ids();
 2227:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2228:     
 2229:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2230:         $is_home = 1;
 2231:     }
 2232:     $relpath = "/priv/$cdom/$cnum";
 2233:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2234:     my %lt = &Apache::lonlocal::texthash (
 2235:         fnam => 'Filename',
 2236:         dire => 'Directory',
 2237:     );
 2238:     my $numdirs = scalar(keys(%files));
 2239:     my (%possexts,$singledir,@singledirfiles);
 2240:     if ($only) {
 2241:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2242:     }
 2243:     my (%nonemptydirs,$possdirs);
 2244:     if ($numdirs > 1) {
 2245:         my @order;
 2246:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2247:             if (ref($files{$key}) eq 'HASH') {
 2248:                 my $shown = $key;
 2249:                 if ($key eq '') {
 2250:                     $shown = '/';
 2251:                 }
 2252:                 my @ordered = ();
 2253:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2254:                     next if ($file =~ /\.rights$/);
 2255:                     if ($only) {
 2256:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2257:                         unless ($possexts{lc($ext)}) {
 2258:                             next;
 2259:                         }
 2260:                     }
 2261:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2262:                     push(@ordered,$file);
 2263:                 }
 2264:                 if (@ordered) {
 2265:                     push(@order,$key);
 2266:                     $nonemptydirs{$key} = 1;
 2267:                     $selimport_menus{$key}->{'text'} = $shown;
 2268:                     $selimport_menus{$key}->{'default'} = '';
 2269:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2270:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2271:                 }
 2272:             }
 2273:         }
 2274:         $possdirs = scalar(keys(%nonemptydirs));
 2275:         if ($possdirs > 1) {
 2276:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2277:             $output = $lt{'dire'}.
 2278:                       &linked_select_forms($form,'<br />'.
 2279:                                            $lt{'fnam'},'',
 2280:                                            $firstselectname,$secondselectname,
 2281:                                            \%selimport_menus,\@order,
 2282:                                            $onchangefirst,'',$suffix).'<br />';
 2283:         } elsif ($possdirs == 1) {
 2284:             $singledir = (keys(%nonemptydirs))[0];
 2285:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2286:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2287:             }
 2288:             delete($selimport_menus{$singledir});
 2289:         }
 2290:     } elsif ($numdirs == 1) {
 2291:         $singledir = (keys(%files))[0];
 2292:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2293:             if ($only) {
 2294:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2295:                 unless ($possexts{lc($ext)}) {
 2296:                     next;
 2297:                 }
 2298:             } else {
 2299:                 next if ($file =~ /\.rights$/);
 2300:             }
 2301:             push(@singledirfiles,$file);
 2302:         }
 2303:         if (@singledirfiles) {
 2304:             $possdirs = 1;
 2305:         }
 2306:     }
 2307:     if (($possdirs == 1) && (@singledirfiles)) {
 2308:         my $showdir = $singledir;
 2309:         if ($singledir eq '') {
 2310:             $showdir = '/';
 2311:         }
 2312:         $output = $lt{'dire'}.
 2313:                   '<select name="'.$firstselectname.'">'.
 2314:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2315:                   '</select><br />'.
 2316:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2317:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2318:         foreach my $file (@singledirfiles) {
 2319:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2320:         }
 2321:         $output .= '</select><br />'."\n";
 2322:     }
 2323:     return ($possdirs,$output);
 2324: }
 2325: 
 2326: =pod
 2327: 
 2328: =head1 Excel and CSV file utility routines
 2329: 
 2330: =cut
 2331: 
 2332: ###############################################################
 2333: ###############################################################
 2334: 
 2335: =pod
 2336: 
 2337: =over 4
 2338: 
 2339: =item * &csv_translate($text) 
 2340: 
 2341: Translate $text to allow it to be output as a 'comma separated values' 
 2342: format.
 2343: 
 2344: =cut
 2345: 
 2346: ###############################################################
 2347: ###############################################################
 2348: sub csv_translate {
 2349:     my $text = shift;
 2350:     $text =~ s/\"/\"\"/g;
 2351:     $text =~ s/\n/ /g;
 2352:     return $text;
 2353: }
 2354: 
 2355: ###############################################################
 2356: ###############################################################
 2357: 
 2358: =pod
 2359: 
 2360: =item * &define_excel_formats()
 2361: 
 2362: Define some commonly used Excel cell formats.
 2363: 
 2364: Currently supported formats:
 2365: 
 2366: =over 4
 2367: 
 2368: =item header
 2369: 
 2370: =item bold
 2371: 
 2372: =item h1
 2373: 
 2374: =item h2
 2375: 
 2376: =item h3
 2377: 
 2378: =item h4
 2379: 
 2380: =item i
 2381: 
 2382: =item date
 2383: 
 2384: =back
 2385: 
 2386: Inputs: $workbook
 2387: 
 2388: Returns: $format, a hash reference.
 2389: 
 2390: 
 2391: =cut
 2392: 
 2393: ###############################################################
 2394: ###############################################################
 2395: sub define_excel_formats {
 2396:     my ($workbook) = @_;
 2397:     my $format;
 2398:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2399:                                                 bottom    => 1,
 2400:                                                 align     => 'center');
 2401:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2402:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2403:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2404:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2405:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2406:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2407:     $format->{'date'} = $workbook->add_format(num_format=>
 2408:                                             'mm/dd/yyyy hh:mm:ss');
 2409:     return $format;
 2410: }
 2411: 
 2412: ###############################################################
 2413: ###############################################################
 2414: 
 2415: =pod
 2416: 
 2417: =item * &create_workbook()
 2418: 
 2419: Create an Excel worksheet.  If it fails, output message on the
 2420: request object and return undefs.
 2421: 
 2422: Inputs: Apache request object
 2423: 
 2424: Returns (undef) on failure, 
 2425:     Excel worksheet object, scalar with filename, and formats 
 2426:     from &Apache::loncommon::define_excel_formats on success
 2427: 
 2428: =cut
 2429: 
 2430: ###############################################################
 2431: ###############################################################
 2432: sub create_workbook {
 2433:     my ($r) = @_;
 2434:         #
 2435:     # Create the excel spreadsheet
 2436:     my $filename = '/prtspool/'.
 2437:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2438:         time.'_'.rand(1000000000).'.xls';
 2439:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2440:     if (! defined($workbook)) {
 2441:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2442:         $r->print(
 2443:             '<p class="LC_error">'
 2444:            .&mt('Problems occurred in creating the new Excel file.')
 2445:            .' '.&mt('This error has been logged.')
 2446:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2447:            .'</p>'
 2448:         );
 2449:         return (undef);
 2450:     }
 2451:     #
 2452:     $workbook->set_tempdir(LONCAPA::tempdir());
 2453:     #
 2454:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2455:     return ($workbook,$filename,$format);
 2456: }
 2457: 
 2458: ###############################################################
 2459: ###############################################################
 2460: 
 2461: =pod
 2462: 
 2463: =item * &create_text_file()
 2464: 
 2465: Create a file to write to and eventually make available to the user.
 2466: If file creation fails, outputs an error message on the request object and 
 2467: return undefs.
 2468: 
 2469: Inputs: Apache request object, and file suffix
 2470: 
 2471: Returns (undef) on failure, 
 2472:     Filehandle and filename on success.
 2473: 
 2474: =cut
 2475: 
 2476: ###############################################################
 2477: ###############################################################
 2478: sub create_text_file {
 2479:     my ($r,$suffix) = @_;
 2480:     if (! defined($suffix)) { $suffix = 'txt'; };
 2481:     my $fh;
 2482:     my $filename = '/prtspool/'.
 2483:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2484:         time.'_'.rand(1000000000).'.'.$suffix;
 2485:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2486:     if (! defined($fh)) {
 2487:         $r->log_error("Couldn't open $filename for output $!");
 2488:         $r->print(
 2489:             '<p class="LC_error">'
 2490:            .&mt('Problems occurred in creating the output file.')
 2491:            .' '.&mt('This error has been logged.')
 2492:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2493:            .'</p>'
 2494:         );
 2495:     }
 2496:     return ($fh,$filename)
 2497: }
 2498: 
 2499: 
 2500: =pod 
 2501: 
 2502: =back
 2503: 
 2504: =cut
 2505: 
 2506: ###############################################################
 2507: ##        Home server <option> list generating code          ##
 2508: ###############################################################
 2509: 
 2510: # ------------------------------------------
 2511: 
 2512: sub domain_select {
 2513:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2514:     my @possdoms;
 2515:     if (ref($incdoms) eq 'ARRAY') {
 2516:         @possdoms = @{$incdoms};
 2517:     } else {
 2518:         @possdoms = &Apache::lonnet::all_domains();
 2519:     }
 2520: 
 2521:     my %domains=map { 
 2522: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2523:     } @possdoms;
 2524: 
 2525:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2526:         foreach my $dom (@{$excdoms}) {
 2527:             delete($domains{$dom});
 2528:         }
 2529:     }
 2530: 
 2531:     if ($multiple) {
 2532: 	$domains{''}=&mt('Any domain');
 2533: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2534: 	return &multiple_select_form($name,$value,4,\%domains);
 2535:     } else {
 2536: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2537: 	return &select_form($name,$value,\%domains);
 2538:     }
 2539: }
 2540: 
 2541: #-------------------------------------------
 2542: 
 2543: =pod
 2544: 
 2545: =head1 Routines for form select boxes
 2546: 
 2547: =over 4
 2548: 
 2549: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2550: 
 2551: Returns a string containing a <select> element int multiple mode
 2552: 
 2553: 
 2554: Args:
 2555:   $name - name of the <select> element
 2556:   $value - scalar or array ref of values that should already be selected
 2557:   $size - number of rows long the select element is
 2558:   $hash - the elements should be 'option' => 'shown text'
 2559:           (shown text should already have been &mt())
 2560:   $order - (optional) array ref of the order to show the elements in
 2561: 
 2562: =cut
 2563: 
 2564: #-------------------------------------------
 2565: sub multiple_select_form {
 2566:     my ($name,$value,$size,$hash,$order)=@_;
 2567:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2568:     my $output='';
 2569:     if (! defined($size)) {
 2570:         $size = 4;
 2571:         if (scalar(keys(%$hash))<4) {
 2572:             $size = scalar(keys(%$hash));
 2573:         }
 2574:     }
 2575:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2576:     my @order;
 2577:     if (ref($order) eq 'ARRAY')  {
 2578:         @order = @{$order};
 2579:     } else {
 2580:         @order = sort(keys(%$hash));
 2581:     }
 2582:     if (exists($$hash{'select_form_order'})) {
 2583:         @order = @{$$hash{'select_form_order'}};
 2584:     }
 2585:         
 2586:     foreach my $key (@order) {
 2587:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2588:         $output.='selected="selected" ' if ($selected{$key});
 2589:         $output.='>'.$hash->{$key}."</option>\n";
 2590:     }
 2591:     $output.="</select>\n";
 2592:     return $output;
 2593: }
 2594: 
 2595: #-------------------------------------------
 2596: 
 2597: =pod
 2598: 
 2599: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2600: 
 2601: Returns a string containing a <select name='$name' size='1'> form to 
 2602: allow a user to select options from a ref to a hash containing:
 2603: option_name => displayed text. An optional $onchange can include
 2604: a javascript onchange item, e.g., onchange="this.form.submit();".
 2605: An optional arg -- $readonly -- if true will cause the select form
 2606: to be disabled, e.g., for the case where an instructor has a section-
 2607: specific role, and is viewing/modifying parameters. 
 2608: 
 2609: See lonrights.pm for an example invocation and use.
 2610: 
 2611: =cut
 2612: 
 2613: #-------------------------------------------
 2614: sub select_form {
 2615:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2616:     return unless (ref($hashref) eq 'HASH');
 2617:     if ($onchange) {
 2618:         $onchange = ' onchange="'.$onchange.'"';
 2619:     }
 2620:     my $disabled;
 2621:     if ($readonly) {
 2622:         $disabled = ' disabled="disabled"';
 2623:     }
 2624:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2625:     my @keys;
 2626:     if (exists($hashref->{'select_form_order'})) {
 2627: 	@keys=@{$hashref->{'select_form_order'}};
 2628:     } else {
 2629: 	@keys=sort(keys(%{$hashref}));
 2630:     }
 2631:     foreach my $key (@keys) {
 2632:         $selectform.=
 2633: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2634:             ($key eq $def ? 'selected="selected" ' : '').
 2635:                 ">".$hashref->{$key}."</option>\n";
 2636:     }
 2637:     $selectform.="</select>";
 2638:     return $selectform;
 2639: }
 2640: 
 2641: # For display filters
 2642: 
 2643: sub display_filter {
 2644:     my ($context) = @_;
 2645:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2646:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2647:     my $phraseinput = 'hidden';
 2648:     my $includeinput = 'hidden';
 2649:     my ($checked,$includetypestext);
 2650:     if ($env{'form.displayfilter'} eq 'containing') {
 2651:         $phraseinput = 'text'; 
 2652:         if ($context eq 'parmslog') {
 2653:             $includeinput = 'checkbox';
 2654:             if ($env{'form.includetypes'}) {
 2655:                 $checked = ' checked="checked"';
 2656:             }
 2657:             $includetypestext = &mt('Include parameter types');
 2658:         }
 2659:     } else {
 2660:         $includetypestext = '&nbsp;';
 2661:     }
 2662:     my ($additional,$secondid,$thirdid);
 2663:     if ($context eq 'parmslog') {
 2664:         $additional = 
 2665:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2666:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2667:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2668:             '</label>';
 2669:         $secondid = 'includetypes';
 2670:         $thirdid = 'includetypestext';
 2671:     }
 2672:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2673:                                                     '$secondid','$thirdid')";
 2674:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2675: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2676: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2677: 	   '</label></span> <span class="LC_nobreak">'.
 2678:            &mt('Filter: [_1]',
 2679: 	   &select_form($env{'form.displayfilter'},
 2680: 			'displayfilter',
 2681: 			{'currentfolder' => 'Current folder/page',
 2682: 			 'containing' => 'Containing phrase',
 2683: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2684: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2685:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2686:                          '" />'.$additional;
 2687: }
 2688: 
 2689: sub display_filter_js {
 2690:     my $includetext = &mt('Include parameter types');
 2691:     return <<"ENDJS";
 2692:   
 2693: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2694:     var firstType = 'hidden';
 2695:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2696:         firstType = 'text';
 2697:     }
 2698:     firstObject = document.getElementById(firstid);
 2699:     if (typeof(firstObject) == 'object') {
 2700:         if (firstObject.type != firstType) {
 2701:             changeInputType(firstObject,firstType);
 2702:         }
 2703:     }
 2704:     if (context == 'parmslog') {
 2705:         var secondType = 'hidden';
 2706:         if (firstType == 'text') {
 2707:             secondType = 'checkbox';
 2708:         }
 2709:         secondObject = document.getElementById(secondid);  
 2710:         if (typeof(secondObject) == 'object') {
 2711:             if (secondObject.type != secondType) {
 2712:                 changeInputType(secondObject,secondType);
 2713:             }
 2714:         }
 2715:         var textItem = document.getElementById(thirdid);
 2716:         var currtext = textItem.innerHTML;
 2717:         var newtext;
 2718:         if (firstType == 'text') {
 2719:             newtext = '$includetext';
 2720:         } else {
 2721:             newtext = '&nbsp;';
 2722:         }
 2723:         if (currtext != newtext) {
 2724:             textItem.innerHTML = newtext;
 2725:         }
 2726:     }
 2727:     return;
 2728: }
 2729: 
 2730: function changeInputType(oldObject,newType) {
 2731:     var newObject = document.createElement('input');
 2732:     newObject.type = newType;
 2733:     if (oldObject.size) {
 2734:         newObject.size = oldObject.size;
 2735:     }
 2736:     if (oldObject.value) {
 2737:         newObject.value = oldObject.value;
 2738:     }
 2739:     if (oldObject.name) {
 2740:         newObject.name = oldObject.name;
 2741:     }
 2742:     if (oldObject.id) {
 2743:         newObject.id = oldObject.id;
 2744:     }
 2745:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2746:     return;
 2747: }
 2748: 
 2749: ENDJS
 2750: }
 2751: 
 2752: sub gradeleveldescription {
 2753:     my $gradelevel=shift;
 2754:     my %gradelevels=(0 => 'Not specified',
 2755: 		     1 => 'Grade 1',
 2756: 		     2 => 'Grade 2',
 2757: 		     3 => 'Grade 3',
 2758: 		     4 => 'Grade 4',
 2759: 		     5 => 'Grade 5',
 2760: 		     6 => 'Grade 6',
 2761: 		     7 => 'Grade 7',
 2762: 		     8 => 'Grade 8',
 2763: 		     9 => 'Grade 9',
 2764: 		     10 => 'Grade 10',
 2765: 		     11 => 'Grade 11',
 2766: 		     12 => 'Grade 12',
 2767: 		     13 => 'Grade 13',
 2768: 		     14 => '100 Level',
 2769: 		     15 => '200 Level',
 2770: 		     16 => '300 Level',
 2771: 		     17 => '400 Level',
 2772: 		     18 => 'Graduate Level');
 2773:     return &mt($gradelevels{$gradelevel});
 2774: }
 2775: 
 2776: sub select_level_form {
 2777:     my ($deflevel,$name)=@_;
 2778:     unless ($deflevel) { $deflevel=0; }
 2779:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2780:     for (my $i=0; $i<=18; $i++) {
 2781:         $selectform.="<option value=\"$i\" ".
 2782:             ($i==$deflevel ? 'selected="selected" ' : '').
 2783:                 ">".&gradeleveldescription($i)."</option>\n";
 2784:     }
 2785:     $selectform.="</select>";
 2786:     return $selectform;
 2787: }
 2788: 
 2789: #-------------------------------------------
 2790: 
 2791: =pod
 2792: 
 2793: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2794: 
 2795: Returns a string containing a <select name='$name' size='1'> form to 
 2796: allow a user to select the domain to preform an operation in.  
 2797: See loncreateuser.pm for an example invocation and use.
 2798: 
 2799: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2800: selected");
 2801: 
 2802: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2803: 
 2804: 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.
 2805: 
 2806: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2807: 
 2808: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2809: 
 2810: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2811: 
 2812: =cut
 2813: 
 2814: #-------------------------------------------
 2815: sub select_dom_form {
 2816:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2817:     if ($onchange) {
 2818:         $onchange = ' onchange="'.$onchange.'"';
 2819:     }
 2820:     if ($disabled) {
 2821:         $disabled = ' disabled="disabled"';
 2822:     }
 2823:     my (@domains,%exclude);
 2824:     if (ref($incdoms) eq 'ARRAY') {
 2825:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2826:     } else {
 2827:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2828:     }
 2829:     if ($includeempty) { @domains=('',@domains); }
 2830:     if (ref($excdoms) eq 'ARRAY') {
 2831:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2832:     }
 2833:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2834:     foreach my $dom (@domains) {
 2835:         next if ($exclude{$dom});
 2836:         $selectdomain.="<option value=\"$dom\" ".
 2837:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2838:         if ($showdomdesc) {
 2839:             if ($dom ne '') {
 2840:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2841:                 if ($domdesc ne '') {
 2842:                     $selectdomain .= ' ('.$domdesc.')';
 2843:                 }
 2844:             } 
 2845:         }
 2846:         $selectdomain .= "</option>\n";
 2847:     }
 2848:     $selectdomain.="</select>";
 2849:     return $selectdomain;
 2850: }
 2851: 
 2852: #-------------------------------------------
 2853: 
 2854: =pod
 2855: 
 2856: =item * &home_server_form_item($domain,$name,$defaultflag)
 2857: 
 2858: input: 4 arguments (two required, two optional) - 
 2859:     $domain - domain of new user
 2860:     $name - name of form element
 2861:     $default - Value of 'default' causes a default item to be first 
 2862:                             option, and selected by default. 
 2863:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2864:                             if 1 server found, or default, if 0 found.
 2865: output: returns 2 items: 
 2866: (a) form element which contains either:
 2867:    (i) <select name="$name">
 2868:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2869:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2870:        </select>
 2871:        form item if there are multiple library servers in $domain, or
 2872:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2873:        if there is only one library server in $domain.
 2874: 
 2875: (b) number of library servers found.
 2876: 
 2877: See loncreateuser.pm for example of use.
 2878: 
 2879: =cut
 2880: 
 2881: #-------------------------------------------
 2882: sub home_server_form_item {
 2883:     my ($domain,$name,$default,$hide) = @_;
 2884:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2885:     my $result;
 2886:     my $numlib = keys(%servers);
 2887:     if ($numlib > 1) {
 2888:         $result .= '<select name="'.$name.'" />'."\n";
 2889:         if ($default) {
 2890:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2891:                        '</option>'."\n";
 2892:         }
 2893:         foreach my $hostid (sort(keys(%servers))) {
 2894:             $result.= '<option value="'.$hostid.'">'.
 2895: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2896:         }
 2897:         $result .= '</select>'."\n";
 2898:     } elsif ($numlib == 1) {
 2899:         my $hostid;
 2900:         foreach my $item (keys(%servers)) {
 2901:             $hostid = $item;
 2902:         }
 2903:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2904:                    $hostid.'" />';
 2905:                    if (!$hide) {
 2906:                        $result .= $hostid.' '.$servers{$hostid};
 2907:                    }
 2908:                    $result .= "\n";
 2909:     } elsif ($default) {
 2910:         $result .= '<input type="hidden" name="'.$name.
 2911:                    '" value="default" />';
 2912:                    if (!$hide) {
 2913:                        $result .= &mt('default');
 2914:                    }
 2915:                    $result .= "\n";
 2916:     }
 2917:     return ($result,$numlib);
 2918: }
 2919: 
 2920: =pod
 2921: 
 2922: =back 
 2923: 
 2924: =cut
 2925: 
 2926: ###############################################################
 2927: ##                  Decoding User Agent                      ##
 2928: ###############################################################
 2929: 
 2930: =pod
 2931: 
 2932: =head1 Decoding the User Agent
 2933: 
 2934: =over 4
 2935: 
 2936: =item * &decode_user_agent()
 2937: 
 2938: Inputs: $r
 2939: 
 2940: Outputs:
 2941: 
 2942: =over 4
 2943: 
 2944: =item * $httpbrowser
 2945: 
 2946: =item * $clientbrowser
 2947: 
 2948: =item * $clientversion
 2949: 
 2950: =item * $clientmathml
 2951: 
 2952: =item * $clientunicode
 2953: 
 2954: =item * $clientos
 2955: 
 2956: =item * $clientmobile
 2957: 
 2958: =item * $clientinfo
 2959: 
 2960: =item * $clientosversion
 2961: 
 2962: =back
 2963: 
 2964: =back 
 2965: 
 2966: =cut
 2967: 
 2968: ###############################################################
 2969: ###############################################################
 2970: sub decode_user_agent {
 2971:     my ($r)=@_;
 2972:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2973:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2974:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2975:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2976:     my $clientbrowser='unknown';
 2977:     my $clientversion='0';
 2978:     my $clientmathml='';
 2979:     my $clientunicode='0';
 2980:     my $clientmobile=0;
 2981:     my $clientosversion='';
 2982:     for (my $i=0;$i<=$#browsertype;$i++) {
 2983:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2984: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2985: 	    $clientbrowser=$bname;
 2986:             $httpbrowser=~/$vreg/i;
 2987: 	    $clientversion=$1;
 2988:             $clientmathml=($clientversion>=$minv);
 2989:             $clientunicode=($clientversion>=$univ);
 2990: 	}
 2991:     }
 2992:     my $clientos='unknown';
 2993:     my $clientinfo;
 2994:     if (($httpbrowser=~/linux/i) ||
 2995:         ($httpbrowser=~/unix/i) ||
 2996:         ($httpbrowser=~/ux/i) ||
 2997:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2998:     if (($httpbrowser=~/vax/i) ||
 2999:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3000:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3001:     if (($httpbrowser=~/mac/i) ||
 3002:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3003:     if ($httpbrowser=~/win/i) {
 3004:         $clientos='win';
 3005:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3006:             $clientosversion = $1;
 3007:         }
 3008:     }
 3009:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3010:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3011:         $clientmobile=lc($1);
 3012:     }
 3013:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3014:         $clientinfo = 'firefox-'.$1;
 3015:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3016:         $clientinfo = 'chromeframe-'.$1;
 3017:     }
 3018:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3019:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3020:             $clientosversion);
 3021: }
 3022: 
 3023: ###############################################################
 3024: ##    Authentication changing form generation subroutines    ##
 3025: ###############################################################
 3026: ##
 3027: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3028: ## hash, and have reasonable default values.
 3029: ##
 3030: ##    formname = the name given in the <form> tag.
 3031: #-------------------------------------------
 3032: 
 3033: =pod
 3034: 
 3035: =head1 Authentication Routines
 3036: 
 3037: =over 4
 3038: 
 3039: =item * &authform_xxxxxx()
 3040: 
 3041: The authform_xxxxxx subroutines provide javascript and html forms which 
 3042: handle some of the conveniences required for authentication forms.  
 3043: This is not an optimal method, but it works.  
 3044: 
 3045: =over 4
 3046: 
 3047: =item * authform_header
 3048: 
 3049: =item * authform_authorwarning
 3050: 
 3051: =item * authform_nochange
 3052: 
 3053: =item * authform_kerberos
 3054: 
 3055: =item * authform_internal
 3056: 
 3057: =item * authform_filesystem
 3058: 
 3059: =item * authform_lti
 3060: 
 3061: =back
 3062: 
 3063: See loncreateuser.pm for invocation and use examples.
 3064: 
 3065: =cut
 3066: 
 3067: #-------------------------------------------
 3068: sub authform_header{  
 3069:     my %in = (
 3070:         formname => 'cu',
 3071:         kerb_def_dom => '',
 3072:         @_,
 3073:     );
 3074:     $in{'formname'} = 'document.' . $in{'formname'};
 3075:     my $result='';
 3076: 
 3077: #---------------------------------------------- Code for upper case translation
 3078:     my $Javascript_toUpperCase;
 3079:     unless ($in{kerb_def_dom}) {
 3080:         $Javascript_toUpperCase =<<"END";
 3081:         switch (choice) {
 3082:            case 'krb': currentform.elements[choicearg].value =
 3083:                currentform.elements[choicearg].value.toUpperCase();
 3084:                break;
 3085:            default:
 3086:         }
 3087: END
 3088:     } else {
 3089:         $Javascript_toUpperCase = "";
 3090:     }
 3091: 
 3092:     my $radioval = "'nochange'";
 3093:     if (defined($in{'curr_authtype'})) {
 3094:         if ($in{'curr_authtype'} ne '') {
 3095:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3096:         }
 3097:     }
 3098:     my $argfield = 'null';
 3099:     if (defined($in{'mode'})) {
 3100:         if ($in{'mode'} eq 'modifycourse')  {
 3101:             if (defined($in{'curr_autharg'})) {
 3102:                 if ($in{'curr_autharg'} ne '') {
 3103:                     $argfield = "'$in{'curr_autharg'}'";
 3104:                 }
 3105:             }
 3106:         }
 3107:     }
 3108: 
 3109:     $result.=<<"END";
 3110: var current = new Object();
 3111: current.radiovalue = $radioval;
 3112: current.argfield = $argfield;
 3113: 
 3114: function changed_radio(choice,currentform) {
 3115:     var choicearg = choice + 'arg';
 3116:     // If a radio button in changed, we need to change the argfield
 3117:     if (current.radiovalue != choice) {
 3118:         current.radiovalue = choice;
 3119:         if (current.argfield != null) {
 3120:             currentform.elements[current.argfield].value = '';
 3121:         }
 3122:         if (choice == 'nochange') {
 3123:             current.argfield = null;
 3124:         } else {
 3125:             current.argfield = choicearg;
 3126:             switch(choice) {
 3127:                 case 'krb': 
 3128:                     currentform.elements[current.argfield].value = 
 3129:                         "$in{'kerb_def_dom'}";
 3130:                 break;
 3131:               default:
 3132:                 break;
 3133:             }
 3134:         }
 3135:     }
 3136:     return;
 3137: }
 3138: 
 3139: function changed_text(choice,currentform) {
 3140:     var choicearg = choice + 'arg';
 3141:     if (currentform.elements[choicearg].value !='') {
 3142:         $Javascript_toUpperCase
 3143:         // clear old field
 3144:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3145:             currentform.elements[current.argfield].value = '';
 3146:         }
 3147:         current.argfield = choicearg;
 3148:     }
 3149:     set_auth_radio_buttons(choice,currentform);
 3150:     return;
 3151: }
 3152: 
 3153: function set_auth_radio_buttons(newvalue,currentform) {
 3154:     var numauthchoices = currentform.login.length;
 3155:     if (typeof numauthchoices  == "undefined") {
 3156:         return;
 3157:     } 
 3158:     var i=0;
 3159:     while (i < numauthchoices) {
 3160:         if (currentform.login[i].value == newvalue) { break; }
 3161:         i++;
 3162:     }
 3163:     if (i == numauthchoices) {
 3164:         return;
 3165:     }
 3166:     current.radiovalue = newvalue;
 3167:     currentform.login[i].checked = true;
 3168:     return;
 3169: }
 3170: END
 3171:     return $result;
 3172: }
 3173: 
 3174: sub authform_authorwarning {
 3175:     my $result='';
 3176:     $result='<i>'.
 3177:         &mt('As a general rule, only authors or co-authors should be '.
 3178:             'filesystem authenticated '.
 3179:             '(which allows access to the server filesystem).')."</i>\n";
 3180:     return $result;
 3181: }
 3182: 
 3183: sub authform_nochange {
 3184:     my %in = (
 3185:               formname => 'document.cu',
 3186:               kerb_def_dom => 'MSU.EDU',
 3187:               @_,
 3188:           );
 3189:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3190:     my $result;
 3191:     if (!$authnum) {
 3192:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3193:     } else {
 3194:         $result = '<label>'.&mt('[_1] Do not change login data',
 3195:                   '<input type="radio" name="login" value="nochange" '.
 3196:                   'checked="checked" onclick="'.
 3197:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3198: 	    '</label>';
 3199:     }
 3200:     return $result;
 3201: }
 3202: 
 3203: sub authform_kerberos {
 3204:     my %in = (
 3205:               formname => 'document.cu',
 3206:               kerb_def_dom => 'MSU.EDU',
 3207:               kerb_def_auth => 'krb4',
 3208:               @_,
 3209:               );
 3210:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3211:         $autharg,$jscall,$disabled);
 3212:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3213:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3214:        $check5 = ' checked="checked"';
 3215:     } else {
 3216:        $check4 = ' checked="checked"';
 3217:     }
 3218:     if ($in{'readonly'}) {
 3219:         $disabled = ' disabled="disabled"';
 3220:     }
 3221:     $krbarg = $in{'kerb_def_dom'};
 3222:     if (defined($in{'curr_authtype'})) {
 3223:         if ($in{'curr_authtype'} eq 'krb') {
 3224:             $krbcheck = ' checked="checked"';
 3225:             if (defined($in{'mode'})) {
 3226:                 if ($in{'mode'} eq 'modifyuser') {
 3227:                     $krbcheck = '';
 3228:                 }
 3229:             }
 3230:             if (defined($in{'curr_kerb_ver'})) {
 3231:                 if ($in{'curr_krb_ver'} eq '5') {
 3232:                     $check5 = ' checked="checked"';
 3233:                     $check4 = '';
 3234:                 } else {
 3235:                     $check4 = ' checked="checked"';
 3236:                     $check5 = '';
 3237:                 }
 3238:             }
 3239:             if (defined($in{'curr_autharg'})) {
 3240:                 $krbarg = $in{'curr_autharg'};
 3241:             }
 3242:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3243:                 if (defined($in{'curr_autharg'})) {
 3244:                     $result = 
 3245:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3246:         $in{'curr_autharg'},$krbver);
 3247:                 } else {
 3248:                     $result =
 3249:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3250:                 }
 3251:                 return $result; 
 3252:             }
 3253:         }
 3254:     } else {
 3255:         if ($authnum == 1) {
 3256:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3257:         }
 3258:     }
 3259:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3260:         return;
 3261:     } elsif ($authtype eq '') {
 3262:         if (defined($in{'mode'})) {
 3263:             if ($in{'mode'} eq 'modifycourse') {
 3264:                 if ($authnum == 1) {
 3265:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3266:                 }
 3267:             }
 3268:         }
 3269:     }
 3270:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3271:     if ($authtype eq '') {
 3272:         $authtype = '<input type="radio" name="login" value="krb" '.
 3273:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3274:                     $krbcheck.$disabled.' />';
 3275:     }
 3276:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3277:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3278:          $in{'curr_authtype'} eq 'krb5') ||
 3279:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3280:          $in{'curr_authtype'} eq 'krb4')) {
 3281:         $result .= &mt
 3282:         ('[_1] Kerberos authenticated with domain [_2] '.
 3283:          '[_3] Version 4 [_4] Version 5 [_5]',
 3284:          '<label>'.$authtype,
 3285:          '</label><input type="text" size="10" name="krbarg" '.
 3286:              'value="'.$krbarg.'" '.
 3287:              'onchange="'.$jscall.'"'.$disabled.' />',
 3288:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3289:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3290: 	 '</label>');
 3291:     } elsif ($can_assign{'krb4'}) {
 3292:         $result .= &mt
 3293:         ('[_1] Kerberos authenticated with domain [_2] '.
 3294:          '[_3] Version 4 [_4]',
 3295:          '<label>'.$authtype,
 3296:          '</label><input type="text" size="10" name="krbarg" '.
 3297:              'value="'.$krbarg.'" '.
 3298:              'onchange="'.$jscall.'"'.$disabled.' />',
 3299:          '<label><input type="hidden" name="krbver" value="4" />',
 3300:          '</label>');
 3301:     } elsif ($can_assign{'krb5'}) {
 3302:         $result .= &mt
 3303:         ('[_1] Kerberos authenticated with domain [_2] '.
 3304:          '[_3] Version 5 [_4]',
 3305:          '<label>'.$authtype,
 3306:          '</label><input type="text" size="10" name="krbarg" '.
 3307:              'value="'.$krbarg.'" '.
 3308:              'onchange="'.$jscall.'"'.$disabled.' />',
 3309:          '<label><input type="hidden" name="krbver" value="5" />',
 3310:          '</label>');
 3311:     }
 3312:     return $result;
 3313: }
 3314: 
 3315: sub authform_internal {
 3316:     my %in = (
 3317:                 formname => 'document.cu',
 3318:                 kerb_def_dom => 'MSU.EDU',
 3319:                 @_,
 3320:                 );
 3321:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3322:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3323:     if ($in{'readonly'}) {
 3324:         $disabled = ' disabled="disabled"';
 3325:     }
 3326:     if (defined($in{'curr_authtype'})) {
 3327:         if ($in{'curr_authtype'} eq 'int') {
 3328:             if ($can_assign{'int'}) {
 3329:                 $intcheck = 'checked="checked" ';
 3330:                 if (defined($in{'mode'})) {
 3331:                     if ($in{'mode'} eq 'modifyuser') {
 3332:                         $intcheck = '';
 3333:                     }
 3334:                 }
 3335:                 if (defined($in{'curr_autharg'})) {
 3336:                     $intarg = $in{'curr_autharg'};
 3337:                 }
 3338:             } else {
 3339:                 $result = &mt('Currently internally authenticated.');
 3340:                 return $result;
 3341:             }
 3342:         }
 3343:     } else {
 3344:         if ($authnum == 1) {
 3345:             $authtype = '<input type="hidden" name="login" value="int" />';
 3346:         }
 3347:     }
 3348:     if (!$can_assign{'int'}) {
 3349:         return;
 3350:     } elsif ($authtype eq '') {
 3351:         if (defined($in{'mode'})) {
 3352:             if ($in{'mode'} eq 'modifycourse') {
 3353:                 if ($authnum == 1) {
 3354:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3355:                 }
 3356:             }
 3357:         }
 3358:     }
 3359:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3360:     if ($authtype eq '') {
 3361:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3362:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3363:     }
 3364:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3365:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3366:     $result = &mt
 3367:         ('[_1] Internally authenticated (with initial password [_2])',
 3368:          '<label>'.$authtype,'</label>'.$autharg);
 3369:     $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>';
 3370:     return $result;
 3371: }
 3372: 
 3373: sub authform_local {
 3374:     my %in = (
 3375:               formname => 'document.cu',
 3376:               kerb_def_dom => 'MSU.EDU',
 3377:               @_,
 3378:               );
 3379:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3380:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3381:     if ($in{'readonly'}) {
 3382:         $disabled = ' disabled="disabled"';
 3383:     } 
 3384:     if (defined($in{'curr_authtype'})) {
 3385:         if ($in{'curr_authtype'} eq 'loc') {
 3386:             if ($can_assign{'loc'}) {
 3387:                 $loccheck = 'checked="checked" ';
 3388:                 if (defined($in{'mode'})) {
 3389:                     if ($in{'mode'} eq 'modifyuser') {
 3390:                         $loccheck = '';
 3391:                     }
 3392:                 }
 3393:                 if (defined($in{'curr_autharg'})) {
 3394:                     $locarg = $in{'curr_autharg'};
 3395:                 }
 3396:             } else {
 3397:                 $result = &mt('Currently using local (institutional) authentication.');
 3398:                 return $result;
 3399:             }
 3400:         }
 3401:     } else {
 3402:         if ($authnum == 1) {
 3403:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3404:         }
 3405:     }
 3406:     if (!$can_assign{'loc'}) {
 3407:         return;
 3408:     } elsif ($authtype eq '') {
 3409:         if (defined($in{'mode'})) {
 3410:             if ($in{'mode'} eq 'modifycourse') {
 3411:                 if ($authnum == 1) {
 3412:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3413:                 }
 3414:             }
 3415:         }
 3416:     }
 3417:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3418:     if ($authtype eq '') {
 3419:         $authtype = '<input type="radio" name="login" value="loc" '.
 3420:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3421:                     $jscall.'"'.$disabled.' />';
 3422:     }
 3423:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3424:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3425:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3426:                   '<label>'.$authtype,'</label>'.$autharg);
 3427:     return $result;
 3428: }
 3429: 
 3430: sub authform_filesystem {
 3431:     my %in = (
 3432:               formname => 'document.cu',
 3433:               kerb_def_dom => 'MSU.EDU',
 3434:               @_,
 3435:               );
 3436:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3437:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3438:     if ($in{'readonly'}) {
 3439:         $disabled = ' disabled="disabled"';
 3440:     }
 3441:     if (defined($in{'curr_authtype'})) {
 3442:         if ($in{'curr_authtype'} eq 'fsys') {
 3443:             if ($can_assign{'fsys'}) {
 3444:                 $fsyscheck = 'checked="checked" ';
 3445:                 if (defined($in{'mode'})) {
 3446:                     if ($in{'mode'} eq 'modifyuser') {
 3447:                         $fsyscheck = '';
 3448:                     }
 3449:                 }
 3450:             } else {
 3451:                 $result = &mt('Currently Filesystem Authenticated.');
 3452:                 return $result;
 3453:             }
 3454:         }
 3455:     } else {
 3456:         if ($authnum == 1) {
 3457:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3458:         }
 3459:     }
 3460:     if (!$can_assign{'fsys'}) {
 3461:         return;
 3462:     } elsif ($authtype eq '') {
 3463:         if (defined($in{'mode'})) {
 3464:             if ($in{'mode'} eq 'modifycourse') {
 3465:                 if ($authnum == 1) {
 3466:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3467:                 }
 3468:             }
 3469:         }
 3470:     }
 3471:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3472:     if ($authtype eq '') {
 3473:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3474:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3475:                     $jscall.'"'.$disabled.' />';
 3476:     }
 3477:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3478:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3479:     $result = &mt
 3480:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3481:          '<label>'.$authtype,'</label>'.$autharg);
 3482:     return $result;
 3483: }
 3484: 
 3485: sub authform_lti {
 3486:     my %in = (
 3487:               formname => 'document.cu',
 3488:               kerb_def_dom => 'MSU.EDU',
 3489:               @_,
 3490:               );
 3491:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3492:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3493:     if ($in{'readonly'}) {
 3494:         $disabled = ' disabled="disabled"';
 3495:     }
 3496:     if (defined($in{'curr_authtype'})) {
 3497:         if ($in{'curr_authtype'} eq 'lti') {
 3498:             if ($can_assign{'lti'}) {
 3499:                 $lticheck = 'checked="checked" ';
 3500:                 if (defined($in{'mode'})) {
 3501:                     if ($in{'mode'} eq 'modifyuser') {
 3502:                         $lticheck = '';
 3503:                     }
 3504:                 }
 3505:             } else {
 3506:                 $result = &mt('Currently LTI Authenticated.');
 3507:                 return $result;
 3508:             }
 3509:         }
 3510:     } else {
 3511:         if ($authnum == 1) {
 3512:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3513:         }
 3514:     }
 3515:     if (!$can_assign{'lti'}) {
 3516:         return;
 3517:     } elsif ($authtype eq '') {
 3518:         if (defined($in{'mode'})) {
 3519:             if ($in{'mode'} eq 'modifycourse') {
 3520:                 if ($authnum == 1) {
 3521:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3522:                 }
 3523:             }
 3524:         }
 3525:     }
 3526:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3527:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3528:         $authtype = '<input type="radio" name="login" value="lti" '.
 3529:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3530:                     $jscall.'"'.$disabled.' />';
 3531:     }
 3532:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3533:     if ($authtype) {
 3534:         $result = &mt('[_1] LTI Authenticated',
 3535:                       '<label>'.$authtype.'</label>'.$autharg);
 3536:     } else {
 3537:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3538:                   $autharg;
 3539:     }
 3540:     return $result;
 3541: }
 3542: 
 3543: sub get_assignable_auth {
 3544:     my ($dom) = @_;
 3545:     if ($dom eq '') {
 3546:         $dom = $env{'request.role.domain'};
 3547:     }
 3548:     my %can_assign = (
 3549:                           krb4 => 1,
 3550:                           krb5 => 1,
 3551:                           int  => 1,
 3552:                           loc  => 1,
 3553:                           lti  => 1,
 3554:                      );
 3555:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3556:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3557:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3558:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3559:             my $context;
 3560:             if ($env{'request.role'} =~ /^au/) {
 3561:                 $context = 'author';
 3562:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3563:                 $context = 'domain';
 3564:             } elsif ($env{'request.course.id'}) {
 3565:                 $context = 'course';
 3566:             }
 3567:             if ($context) {
 3568:                 if (ref($authhash->{$context}) eq 'HASH') {
 3569:                    %can_assign = %{$authhash->{$context}}; 
 3570:                 }
 3571:             }
 3572:         }
 3573:     }
 3574:     my $authnum = 0;
 3575:     foreach my $key (keys(%can_assign)) {
 3576:         if ($can_assign{$key}) {
 3577:             $authnum ++;
 3578:         }
 3579:     }
 3580:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3581:         $authnum --;
 3582:     }
 3583:     return ($authnum,%can_assign);
 3584: }
 3585: 
 3586: sub check_passwd_rules {
 3587:     my ($domain,$plainpass) = @_;
 3588:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3589:     my ($min,$max,@chars,@brokerule,$warning);
 3590:     $min = $Apache::lonnet::passwdmin;
 3591:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3592:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3593:             if ($passwdconf{'min'} > $min) {
 3594:                 $min = $passwdconf{'min'};
 3595:             }
 3596:         }
 3597:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3598:             $max = $passwdconf{'max'};
 3599:         }
 3600:         @chars = @{$passwdconf{'chars'}};
 3601:     }
 3602:     if (($min) && (length($plainpass) < $min)) {
 3603:         push(@brokerule,'min');
 3604:     }
 3605:     if (($max) && (length($plainpass) > $max)) {
 3606:         push(@brokerule,'max');
 3607:     }
 3608:     if (@chars) {
 3609:         my %rules;
 3610:         map { $rules{$_} = 1; } @chars;
 3611:         if ($rules{'uc'}) {
 3612:             unless ($plainpass =~ /[A-Z]/) {
 3613:                 push(@brokerule,'uc');
 3614:             }
 3615:         }
 3616:         if ($rules{'lc'}) {
 3617:             unless ($plainpass =~ /[a-z]/) {
 3618:                 push(@brokerule,'lc');
 3619:             }
 3620:         }
 3621:         if ($rules{'num'}) {
 3622:             unless ($plainpass =~ /\d/) {
 3623:                 push(@brokerule,'num');
 3624:             }
 3625:         }
 3626:         if ($rules{'spec'}) {
 3627:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3628:                 push(@brokerule,'spec');
 3629:             }
 3630:         }
 3631:     }
 3632:     if (@brokerule) {
 3633:         my %rulenames = &Apache::lonlocal::texthash(
 3634:             uc   => 'At least one upper case letter',
 3635:             lc   => 'At least one lower case letter',
 3636:             num  => 'At least one number',
 3637:             spec => 'At least one non-alphanumeric',
 3638:         );
 3639:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3640:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3641:         $rulenames{'num'} .= ': 0123456789';
 3642:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3643:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3644:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3645:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3646:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3647:             if (grep(/^$rule$/,@brokerule)) {
 3648:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3649:             }
 3650:         }
 3651:         $warning .= '</ul>';
 3652:     }
 3653:     if (wantarray) {
 3654:         return @brokerule;
 3655:     }
 3656:     return $warning;
 3657: }
 3658: 
 3659: sub passwd_validation_js {
 3660:     my ($currpasswdval,$domain,$context,$id) = @_;
 3661:     my (%passwdconf,$alertmsg);
 3662:     if ($context eq 'linkprot') {
 3663:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3664:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3665:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3666:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3667:             }
 3668:         }
 3669:         if ($id eq 'add') {
 3670:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3671:         } elsif ($id =~ /^\d+$/) {
 3672:             my $pos = $id+1;
 3673:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3674:         } else {
 3675:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3676:         }
 3677:     } else {
 3678:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3679:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3680:     }
 3681:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3682:     $numrules = 0;
 3683:     $min = $Apache::lonnet::passwdmin;
 3684:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3685:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3686:             if ($passwdconf{'min'} > $min) {
 3687:                 $min = $passwdconf{'min'};
 3688:             }
 3689:         }
 3690:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3691:             $max = $passwdconf{'max'};
 3692:             $numrules ++;
 3693:         }
 3694:         @chars = @{$passwdconf{'chars'}};
 3695:         if (@chars) {
 3696:             $numrules ++;
 3697:         }
 3698:     }
 3699:     if ($min > 0) {
 3700:         $numrules ++;
 3701:     }
 3702:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3703:         if ($min) {
 3704:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3705:         }
 3706:         if ($max) {
 3707:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3708:         }
 3709:         my (@charalerts,@charrules);
 3710:         if (@chars) {
 3711:             if (grep(/^uc$/,@chars)) {
 3712:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3713:                 push(@charrules,'uc');
 3714:             }
 3715:             if (grep(/^lc$/,@chars)) {
 3716:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3717:                 push(@charrules,'lc');
 3718:             }
 3719:             if (grep(/^num$/,@chars)) {
 3720:                 push(@charalerts,&mt('contain at least one number'));
 3721:                 push(@charrules,'num');
 3722:             }
 3723:             if (grep(/^spec$/,@chars)) {
 3724:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3725:                 push(@charrules,'spec');
 3726:             }
 3727:         }
 3728:         $intargjs = qq|            var rulesmsg = '';\n|.
 3729:                     qq|            var currpwval = $currpasswdval;\n|;
 3730:             if ($min) {
 3731:                 $intargjs .= qq|
 3732:             if (currpwval.length < $min) {
 3733:                 rulesmsg += ' - $alert{min}';
 3734:             }
 3735: |;
 3736:             }
 3737:             if ($max) {
 3738:                 $intargjs .= qq|
 3739:             if (currpwval.length > $max) {
 3740:                 rulesmsg += ' - $alert{max}';
 3741:             }
 3742: |;
 3743:             }
 3744:             if (@chars > 0) {
 3745:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3746:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3747:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3748:                              qq|            var charrules = new Array($charrulestr);\n|.
 3749:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3750:                 my %rules;
 3751:                 map { $rules{$_} = 1; } @chars;
 3752:                 if ($rules{'uc'}) {
 3753:                     $intargjs .= qq|
 3754:             var ucRegExp = /[A-Z]/;
 3755:             if (!ucRegExp.test(currpwval)) {
 3756:                 brokerules.push('uc');
 3757:             }
 3758: |;
 3759:                 }
 3760:                 if ($rules{'lc'}) {
 3761:                     $intargjs .= qq|
 3762:             var lcRegExp = /[a-z]/;
 3763:             if (!lcRegExp.test(currpwval)) {
 3764:                 brokerules.push('lc');
 3765:             }
 3766: |;
 3767:                 }
 3768:                 if ($rules{'num'}) {
 3769:                      $intargjs .= qq|
 3770:             var numRegExp = /[0-9]/;
 3771:             if (!numRegExp.test(currpwval)) {
 3772:                 brokerules.push('num');
 3773:             }
 3774: |;
 3775:                 }
 3776:                 if ($rules{'spec'}) {
 3777:                      $intargjs .= q|
 3778:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3779:             if (!specRegExp.test(currpwval)) {
 3780:                 brokerules.push('spec');
 3781:             }
 3782: |;
 3783:                 }
 3784:                 $intargjs .= qq|
 3785:             if (brokerules.length > 0) {
 3786:                 for (var i=0; i<brokerules.length; i++) {
 3787:                     for (var j=0; j<charrules.length; j++) {
 3788:                         if (brokerules[i] == charrules[j]) {
 3789:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3790:                             break;
 3791:                         }
 3792:                     }
 3793:                 }
 3794:             }
 3795: |;
 3796:             }
 3797:             $intargjs .= qq|
 3798:             if (rulesmsg != '') {
 3799:                 rulesmsg = '$alertmsg'+rulesmsg;
 3800:                 alert(rulesmsg);
 3801:                 return false;
 3802:             }
 3803: |;
 3804:     }
 3805:     return ($numrules,$intargjs);
 3806: }
 3807: 
 3808: ###############################################################
 3809: ##    Get Kerberos Defaults for Domain                 ##
 3810: ###############################################################
 3811: ##
 3812: ## Returns default kerberos version and an associated argument
 3813: ## as listed in file domain.tab. If not listed, provides
 3814: ## appropriate default domain and kerberos version.
 3815: ##
 3816: #-------------------------------------------
 3817: 
 3818: =pod
 3819: 
 3820: =item * &get_kerberos_defaults()
 3821: 
 3822: get_kerberos_defaults($target_domain) returns the default kerberos
 3823: version and domain. If not found, it defaults to version 4 and the 
 3824: domain of the server.
 3825: 
 3826: =over 4
 3827: 
 3828: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3829: 
 3830: =back
 3831: 
 3832: =back
 3833: 
 3834: =cut
 3835: 
 3836: #-------------------------------------------
 3837: sub get_kerberos_defaults {
 3838:     my $domain=shift;
 3839:     my ($krbdef,$krbdefdom);
 3840:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3841:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3842:         $krbdef = $domdefaults{'auth_def'};
 3843:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3844:     } else {
 3845:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3846:         my $krbdefdom=$1;
 3847:         $krbdefdom=~tr/a-z/A-Z/;
 3848:         $krbdef = "krb4";
 3849:     }
 3850:     return ($krbdef,$krbdefdom);
 3851: }
 3852: 
 3853: 
 3854: ###############################################################
 3855: ##                Thesaurus Functions                        ##
 3856: ###############################################################
 3857: 
 3858: =pod
 3859: 
 3860: =head1 Thesaurus Functions
 3861: 
 3862: =over 4
 3863: 
 3864: =item * &initialize_keywords()
 3865: 
 3866: Initializes the package variable %Keywords if it is empty.  Uses the
 3867: package variable $thesaurus_db_file.
 3868: 
 3869: =cut
 3870: 
 3871: ###################################################
 3872: 
 3873: sub initialize_keywords {
 3874:     return 1 if (scalar keys(%Keywords));
 3875:     # If we are here, %Keywords is empty, so fill it up
 3876:     #   Make sure the file we need exists...
 3877:     if (! -e $thesaurus_db_file) {
 3878:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3879:                                  " failed because it does not exist");
 3880:         return 0;
 3881:     }
 3882:     #   Set up the hash as a database
 3883:     my %thesaurus_db;
 3884:     if (! tie(%thesaurus_db,'GDBM_File',
 3885:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3886:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3887:                                  $thesaurus_db_file);
 3888:         return 0;
 3889:     } 
 3890:     #  Get the average number of appearances of a word.
 3891:     my $avecount = $thesaurus_db{'average.count'};
 3892:     #  Put keywords (those that appear > average) into %Keywords
 3893:     while (my ($word,$data)=each (%thesaurus_db)) {
 3894:         my ($count,undef) = split /:/,$data;
 3895:         $Keywords{$word}++ if ($count > $avecount);
 3896:     }
 3897:     untie %thesaurus_db;
 3898:     # Remove special values from %Keywords.
 3899:     foreach my $value ('total.count','average.count') {
 3900:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3901:   }
 3902:     return 1;
 3903: }
 3904: 
 3905: ###################################################
 3906: 
 3907: =pod
 3908: 
 3909: =item * &keyword($word)
 3910: 
 3911: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3912: than the average number of times in the thesaurus database.  Calls 
 3913: &initialize_keywords
 3914: 
 3915: =cut
 3916: 
 3917: ###################################################
 3918: 
 3919: sub keyword {
 3920:     return if (!&initialize_keywords());
 3921:     my $word=lc(shift());
 3922:     $word=~s/\W//g;
 3923:     return exists($Keywords{$word});
 3924: }
 3925: 
 3926: ###############################################################
 3927: 
 3928: =pod 
 3929: 
 3930: =item * &get_related_words()
 3931: 
 3932: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3933: an array of words.  If the keyword is not in the thesaurus, an empty array
 3934: will be returned.  The order of the words returned is determined by the
 3935: database which holds them.
 3936: 
 3937: Uses global $thesaurus_db_file.
 3938: 
 3939: 
 3940: =cut
 3941: 
 3942: ###############################################################
 3943: sub get_related_words {
 3944:     my $keyword = shift;
 3945:     my %thesaurus_db;
 3946:     if (! -e $thesaurus_db_file) {
 3947:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3948:                                  "failed because the file does not exist");
 3949:         return ();
 3950:     }
 3951:     if (! tie(%thesaurus_db,'GDBM_File',
 3952:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3953:         return ();
 3954:     } 
 3955:     my @Words=();
 3956:     my $count=0;
 3957:     if (exists($thesaurus_db{$keyword})) {
 3958: 	# The first element is the number of times
 3959: 	# the word appears.  We do not need it now.
 3960: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3961: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3962: 	my $threshold=$mostfrequentcount/10;
 3963:         foreach my $possibleword (@RelatedWords) {
 3964:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3965:             if ($wordcount>$threshold) {
 3966: 		push(@Words,$word);
 3967:                 $count++;
 3968:                 if ($count>10) { last; }
 3969: 	    }
 3970:         }
 3971:     }
 3972:     untie %thesaurus_db;
 3973:     return @Words;
 3974: }
 3975: ###############################################################
 3976: #
 3977: #  Spell checking
 3978: #
 3979: 
 3980: =pod
 3981: 
 3982: =back
 3983: 
 3984: =head1 Spell checking
 3985: 
 3986: =over 4
 3987: 
 3988: =item * &check_spelling($wordlist $language)
 3989: 
 3990: Takes a string containing words and feeds it to an external
 3991: spellcheck program via a pipeline. Returns a string containing
 3992: them mis-spelled words.
 3993: 
 3994: Parameters:
 3995: 
 3996: =over 4
 3997: 
 3998: =item - $wordlist
 3999: 
 4000: String that will be fed into the spellcheck program.
 4001: 
 4002: =item - $language
 4003: 
 4004: Language string that specifies the language for which the spell
 4005: check will be performed.
 4006: 
 4007: =back
 4008: 
 4009: =back
 4010: 
 4011: Note: This sub assumes that aspell is installed.
 4012: 
 4013: 
 4014: =cut
 4015: 
 4016: 
 4017: sub check_spelling {
 4018:     my ($wordlist, $language) = @_;
 4019:     my @misspellings;
 4020:     
 4021:     # Generate the speller and set the langauge.
 4022:     # if explicitly selected:
 4023: 
 4024:     my $speller = Text::Aspell->new;
 4025:     if ($language) {
 4026: 	$speller->set_option('lang', $language);
 4027:     }
 4028: 
 4029:     # Turn the word list into an array of words by splittingon whitespace
 4030: 
 4031:     my @words = split(/\s+/, $wordlist);
 4032: 
 4033:     foreach my $word (@words) {
 4034: 	if(! $speller->check($word)) {
 4035: 	    push(@misspellings, $word);
 4036: 	}
 4037:     }
 4038:     return join(' ', @misspellings);
 4039:     
 4040: }
 4041: 
 4042: # -------------------------------------------------------------- Plaintext name
 4043: =pod
 4044: 
 4045: =head1 User Name Functions
 4046: 
 4047: =over 4
 4048: 
 4049: =item * &plainname($uname,$udom,$first)
 4050: 
 4051: Takes a users logon name and returns it as a string in
 4052: "first middle last generation" form 
 4053: if $first is set to 'lastname' then it returns it as
 4054: 'lastname generation, firstname middlename' if their is a lastname
 4055: 
 4056: =cut
 4057: 
 4058: 
 4059: ###############################################################
 4060: sub plainname {
 4061:     my ($uname,$udom,$first)=@_;
 4062:     return if (!defined($uname) || !defined($udom));
 4063:     my %names=&getnames($uname,$udom);
 4064:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4065: 					  $names{'middlename'},
 4066: 					  $names{'lastname'},
 4067: 					  $names{'generation'},$first);
 4068:     $name=~s/^\s+//;
 4069:     $name=~s/\s+$//;
 4070:     $name=~s/\s+/ /g;
 4071:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4072:     return $name;
 4073: }
 4074: 
 4075: # -------------------------------------------------------------------- Nickname
 4076: =pod
 4077: 
 4078: =item * &nickname($uname,$udom)
 4079: 
 4080: Gets a users name and returns it as a string as
 4081: 
 4082: "&quot;nickname&quot;"
 4083: 
 4084: if the user has a nickname or
 4085: 
 4086: "first middle last generation"
 4087: 
 4088: if the user does not
 4089: 
 4090: =cut
 4091: 
 4092: sub nickname {
 4093:     my ($uname,$udom)=@_;
 4094:     return if (!defined($uname) || !defined($udom));
 4095:     my %names=&getnames($uname,$udom);
 4096:     my $name=$names{'nickname'};
 4097:     if ($name) {
 4098:        $name='&quot;'.$name.'&quot;'; 
 4099:     } else {
 4100:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4101: 	     $names{'lastname'}.' '.$names{'generation'};
 4102:        $name=~s/\s+$//;
 4103:        $name=~s/\s+/ /g;
 4104:     }
 4105:     return $name;
 4106: }
 4107: 
 4108: sub getnames {
 4109:     my ($uname,$udom)=@_;
 4110:     return if (!defined($uname) || !defined($udom));
 4111:     if ($udom eq 'public' && $uname eq 'public') {
 4112: 	return ('lastname' => &mt('Public'));
 4113:     }
 4114:     my $id=$uname.':'.$udom;
 4115:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4116:     if ($cached) {
 4117: 	return %{$names};
 4118:     } else {
 4119: 	my %loadnames=&Apache::lonnet::get('environment',
 4120:                     ['firstname','middlename','lastname','generation','nickname'],
 4121: 					 $udom,$uname);
 4122: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4123: 	return %loadnames;
 4124:     }
 4125: }
 4126: 
 4127: # -------------------------------------------------------------------- getemails
 4128: 
 4129: =pod
 4130: 
 4131: =item * &getemails($uname,$udom)
 4132: 
 4133: Gets a user's email information and returns it as a hash with keys:
 4134: notification, critnotification, permanentemail
 4135: 
 4136: For notification and critnotification, values are comma-separated lists 
 4137: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4138:  
 4139: 
 4140: =cut
 4141: 
 4142: 
 4143: sub getemails {
 4144:     my ($uname,$udom)=@_;
 4145:     if ($udom eq 'public' && $uname eq 'public') {
 4146: 	return;
 4147:     }
 4148:     if (!$udom) { $udom=$env{'user.domain'}; }
 4149:     if (!$uname) { $uname=$env{'user.name'}; }
 4150:     my $id=$uname.':'.$udom;
 4151:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4152:     if ($cached) {
 4153: 	return %{$names};
 4154:     } else {
 4155: 	my %loadnames=&Apache::lonnet::get('environment',
 4156:                     			   ['notification','critnotification',
 4157: 					    'permanentemail'],
 4158: 					   $udom,$uname);
 4159: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4160: 	return %loadnames;
 4161:     }
 4162: }
 4163: 
 4164: sub flush_email_cache {
 4165:     my ($uname,$udom)=@_;
 4166:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4167:     if (!$uname) { $uname=$env{'user.name'};   }
 4168:     return if ($udom eq 'public' && $uname eq 'public');
 4169:     my $id=$uname.':'.$udom;
 4170:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4171: }
 4172: 
 4173: # -------------------------------------------------------------------- getlangs
 4174: 
 4175: =pod
 4176: 
 4177: =item * &getlangs($uname,$udom)
 4178: 
 4179: Gets a user's language preference and returns it as a hash with key:
 4180: language.
 4181: 
 4182: =cut
 4183: 
 4184: 
 4185: sub getlangs {
 4186:     my ($uname,$udom) = @_;
 4187:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4188:     if (!$uname) { $uname=$env{'user.name'};   }
 4189:     my $id=$uname.':'.$udom;
 4190:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4191:     if ($cached) {
 4192:         return %{$langs};
 4193:     } else {
 4194:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4195:                                            $udom,$uname);
 4196:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4197:         return %loadlangs;
 4198:     }
 4199: }
 4200: 
 4201: sub flush_langs_cache {
 4202:     my ($uname,$udom)=@_;
 4203:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4204:     if (!$uname) { $uname=$env{'user.name'};   }
 4205:     return if ($udom eq 'public' && $uname eq 'public');
 4206:     my $id=$uname.':'.$udom;
 4207:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4208: }
 4209: 
 4210: # ------------------------------------------------------------------ Screenname
 4211: 
 4212: =pod
 4213: 
 4214: =item * &screenname($uname,$udom)
 4215: 
 4216: Gets a users screenname and returns it as a string
 4217: 
 4218: =cut
 4219: 
 4220: sub screenname {
 4221:     my ($uname,$udom)=@_;
 4222:     if ($uname eq $env{'user.name'} &&
 4223: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4224:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4225:     return $names{'screenname'};
 4226: }
 4227: 
 4228: 
 4229: # ------------------------------------------------------------- Confirm Wrapper
 4230: =pod
 4231: 
 4232: =item * &confirmwrapper($message)
 4233: 
 4234: Wrap messages about completion of operation in box
 4235: 
 4236: =cut
 4237: 
 4238: sub confirmwrapper {
 4239:     my ($message)=@_;
 4240:     if ($message) {
 4241:         return "\n".'<div class="LC_confirm_box">'."\n"
 4242:                .$message."\n"
 4243:                .'</div>'."\n";
 4244:     } else {
 4245:         return $message;
 4246:     }
 4247: }
 4248: 
 4249: # ------------------------------------------------------------- Message Wrapper
 4250: 
 4251: sub messagewrapper {
 4252:     my ($link,$username,$domain,$subject,$text)=@_;
 4253:     return 
 4254:         '<a href="/adm/email?compose=individual&amp;'.
 4255:         'recname='.$username.'&amp;recdom='.$domain.
 4256: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4257:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4258: }
 4259: 
 4260: # --------------------------------------------------------------- Notes Wrapper
 4261: 
 4262: sub noteswrapper {
 4263:     my ($link,$un,$do)=@_;
 4264:     return 
 4265: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4266: }
 4267: 
 4268: # ------------------------------------------------------------- Aboutme Wrapper
 4269: 
 4270: sub aboutmewrapper {
 4271:     my ($link,$username,$domain,$target,$class)=@_;
 4272:     if (!defined($username)  && !defined($domain)) {
 4273:         return;
 4274:     }
 4275:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4276: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4277: }
 4278: 
 4279: # ------------------------------------------------------------ Syllabus Wrapper
 4280: 
 4281: sub syllabuswrapper {
 4282:     my ($linktext,$coursedir,$domain)=@_;
 4283:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4284: }
 4285: 
 4286: # -----------------------------------------------------------------------------
 4287: 
 4288: sub aboutme_on {
 4289:     my ($uname,$udom)=@_;
 4290:     unless ($uname) { $uname=$env{'user.name'}; }
 4291:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4292:     return if ($udom eq 'public' && $uname eq 'public');
 4293:     my $hashkey=$uname.':'.$udom;
 4294:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4295:     if ($cached) {
 4296:         return $aboutme;
 4297:     }
 4298:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4299:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4300:     return $aboutme;
 4301: }
 4302: 
 4303: sub devalidate_aboutme_cache {
 4304:     my ($uname,$udom)=@_;
 4305:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4306:     if (!$uname) { $uname=$env{'user.name'};   }
 4307:     return if ($udom eq 'public' && $uname eq 'public');
 4308:     my $id=$uname.':'.$udom;
 4309:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4310: }
 4311: 
 4312: sub track_student_link {
 4313:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4314:     my $link ="/adm/trackstudent?";
 4315:     my $title = 'View recent activity';
 4316:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4317:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4318:         $link .= "selected_student=$sname:$sdom";
 4319:         $title .= ' of this student';
 4320:     } 
 4321:     if (defined($target) && $target !~ /^\s*$/) {
 4322:         $target = qq{target="$target"};
 4323:     } else {
 4324:         $target = '';
 4325:     }
 4326:     if ($start) { $link.='&amp;start='.$start; }
 4327:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4328:     $title = &mt($title);
 4329:     $linktext = &mt($linktext);
 4330:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4331: 	&help_open_topic('View_recent_activity');
 4332: }
 4333: 
 4334: sub slot_reservations_link {
 4335:     my ($linktext,$sname,$sdom,$target) = @_;
 4336:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4337:     my $title = 'View slot reservation history';
 4338:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4339:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4340:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4341:         $title .= ' of this student';
 4342:     }
 4343:     if (defined($target) && $target !~ /^\s*$/) {
 4344:         $target = qq{target="$target"};
 4345:     } else {
 4346:         $target = '';
 4347:     }
 4348:     $title = &mt($title);
 4349:     $linktext = &mt($linktext);
 4350:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4351: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4352: 
 4353: }
 4354: 
 4355: # ===================================================== Display a student photo
 4356: 
 4357: 
 4358: sub student_image_tag {
 4359:     my ($domain,$user)=@_;
 4360:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4361:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4362: 	return '<img src="'.$imgsrc.'" align="right" />';
 4363:     } else {
 4364: 	return '';
 4365:     }
 4366: }
 4367: 
 4368: =pod
 4369: 
 4370: =back
 4371: 
 4372: =head1 Access .tab File Data
 4373: 
 4374: =over 4
 4375: 
 4376: =item * &languageids() 
 4377: 
 4378: returns list of all language ids
 4379: 
 4380: =cut
 4381: 
 4382: sub languageids {
 4383:     return sort(keys(%language));
 4384: }
 4385: 
 4386: =pod
 4387: 
 4388: =item * &languagedescription() 
 4389: 
 4390: returns description of a specified language id
 4391: 
 4392: =cut
 4393: 
 4394: sub languagedescription {
 4395:     my $code=shift;
 4396:     return  ($supported_language{$code}?'* ':'').
 4397:             $language{$code}.
 4398: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4399: }
 4400: 
 4401: =pod
 4402: 
 4403: =item * &plainlanguagedescription
 4404: 
 4405: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4406: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4407: 
 4408: =cut
 4409: 
 4410: sub plainlanguagedescription {
 4411:     my $code=shift;
 4412:     return $language{$code};
 4413: }
 4414: 
 4415: =pod
 4416: 
 4417: =item * &supportedlanguagecode
 4418: 
 4419: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4420: code.
 4421: 
 4422: =cut
 4423: 
 4424: sub supportedlanguagecode {
 4425:     my $code=shift;
 4426:     return $supported_language{$code};
 4427: }
 4428: 
 4429: =pod
 4430: 
 4431: =item * &latexlanguage()
 4432: 
 4433: Given a language key code returns the correspondnig language to use
 4434: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4435: is no supported hyphenation for the language code.
 4436: 
 4437: =cut
 4438: 
 4439: sub latexlanguage {
 4440:     my $code = shift;
 4441:     return $latex_language{$code};
 4442: }
 4443: 
 4444: =pod
 4445: 
 4446: =item * &latexhyphenation()
 4447: 
 4448: Same as above but what's supplied is the language as it might be stored
 4449: in the metadata.
 4450: 
 4451: =cut
 4452: 
 4453: sub latexhyphenation {
 4454:     my $key = shift;
 4455:     return $latex_language_bykey{$key};
 4456: }
 4457: 
 4458: =pod
 4459: 
 4460: =item * &copyrightids() 
 4461: 
 4462: returns list of all copyrights
 4463: 
 4464: =cut
 4465: 
 4466: sub copyrightids {
 4467:     return sort(keys(%cprtag));
 4468: }
 4469: 
 4470: =pod
 4471: 
 4472: =item * &copyrightdescription() 
 4473: 
 4474: returns description of a specified copyright id
 4475: 
 4476: =cut
 4477: 
 4478: sub copyrightdescription {
 4479:     return &mt($cprtag{shift(@_)});
 4480: }
 4481: 
 4482: =pod
 4483: 
 4484: =item * &source_copyrightids() 
 4485: 
 4486: returns list of all source copyrights
 4487: 
 4488: =cut
 4489: 
 4490: sub source_copyrightids {
 4491:     return sort(keys(%scprtag));
 4492: }
 4493: 
 4494: =pod
 4495: 
 4496: =item * &source_copyrightdescription() 
 4497: 
 4498: returns description of a specified source copyright id
 4499: 
 4500: =cut
 4501: 
 4502: sub source_copyrightdescription {
 4503:     return &mt($scprtag{shift(@_)});
 4504: }
 4505: 
 4506: =pod
 4507: 
 4508: =item * &filecategories() 
 4509: 
 4510: returns list of all file categories
 4511: 
 4512: =cut
 4513: 
 4514: sub filecategories {
 4515:     return sort(keys(%category_extensions));
 4516: }
 4517: 
 4518: =pod
 4519: 
 4520: =item * &filecategorytypes() 
 4521: 
 4522: returns list of file types belonging to a given file
 4523: category
 4524: 
 4525: =cut
 4526: 
 4527: sub filecategorytypes {
 4528:     my ($cat) = @_;
 4529:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4530:         return @{$category_extensions{lc($cat)}};
 4531:     } else {
 4532:         return ();
 4533:     }
 4534: }
 4535: 
 4536: =pod
 4537: 
 4538: =item * &fileembstyle() 
 4539: 
 4540: returns embedding style for a specified file type
 4541: 
 4542: =cut
 4543: 
 4544: sub fileembstyle {
 4545:     return $fe{lc(shift(@_))};
 4546: }
 4547: 
 4548: sub filemimetype {
 4549:     return $fm{lc(shift(@_))};
 4550: }
 4551: 
 4552: 
 4553: sub filecategoryselect {
 4554:     my ($name,$value)=@_;
 4555:     return &select_form($value,$name,
 4556:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4557: }
 4558: 
 4559: =pod
 4560: 
 4561: =item * &filedescription() 
 4562: 
 4563: returns description for a specified file type
 4564: 
 4565: =cut
 4566: 
 4567: sub filedescription {
 4568:     my $file_description = $fd{lc(shift())};
 4569:     $file_description =~ s:([\[\]]):~$1:g;
 4570:     return &mt($file_description);
 4571: }
 4572: 
 4573: =pod
 4574: 
 4575: =item * &filedescriptionex() 
 4576: 
 4577: returns description for a specified file type with
 4578: extra formatting
 4579: 
 4580: =cut
 4581: 
 4582: sub filedescriptionex {
 4583:     my $ex=shift;
 4584:     my $file_description = $fd{lc($ex)};
 4585:     $file_description =~ s:([\[\]]):~$1:g;
 4586:     return '.'.$ex.' '.&mt($file_description);
 4587: }
 4588: 
 4589: # End of .tab access
 4590: =pod
 4591: 
 4592: =back
 4593: 
 4594: =cut
 4595: 
 4596: # ------------------------------------------------------------------ File Types
 4597: sub fileextensions {
 4598:     return sort(keys(%fe));
 4599: }
 4600: 
 4601: # ----------------------------------------------------------- Display Languages
 4602: # returns a hash with all desired display languages
 4603: #
 4604: 
 4605: sub display_languages {
 4606:     my %languages=();
 4607:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4608: 	$languages{$lang}=1;
 4609:     }
 4610:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4611:     if ($env{'form.displaylanguage'}) {
 4612: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4613: 	    $languages{$lang}=1;
 4614:         }
 4615:     }
 4616:     return %languages;
 4617: }
 4618: 
 4619: sub languages {
 4620:     my ($possible_langs) = @_;
 4621:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4622:     if (!ref($possible_langs)) {
 4623: 	if( wantarray ) {
 4624: 	    return @preferred_langs;
 4625: 	} else {
 4626: 	    return $preferred_langs[0];
 4627: 	}
 4628:     }
 4629:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4630:     my @preferred_possibilities;
 4631:     foreach my $preferred_lang (@preferred_langs) {
 4632: 	if (exists($possibilities{$preferred_lang})) {
 4633: 	    push(@preferred_possibilities, $preferred_lang);
 4634: 	}
 4635:     }
 4636:     if( wantarray ) {
 4637: 	return @preferred_possibilities;
 4638:     }
 4639:     return $preferred_possibilities[0];
 4640: }
 4641: 
 4642: sub user_lang {
 4643:     my ($touname,$toudom,$fromcid) = @_;
 4644:     my @userlangs;
 4645:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4646:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4647:                     $env{'course.'.$fromcid.'.languages'}));
 4648:     } else {
 4649:         my %langhash = &getlangs($touname,$toudom);
 4650:         if ($langhash{'languages'} ne '') {
 4651:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4652:         } else {
 4653:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4654:             if ($domdefs{'lang_def'} ne '') {
 4655:                 @userlangs = ($domdefs{'lang_def'});
 4656:             }
 4657:         }
 4658:     }
 4659:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4660:     my $user_lh = Apache::localize->get_handle(@languages);
 4661:     return $user_lh;
 4662: }
 4663: 
 4664: 
 4665: ###############################################################
 4666: ##               Student Answer Attempts                     ##
 4667: ###############################################################
 4668: 
 4669: =pod
 4670: 
 4671: =head1 Alternate Problem Views
 4672: 
 4673: =over 4
 4674: 
 4675: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4676:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4677: 
 4678: Return string with previous attempt on problem. Arguments:
 4679: 
 4680: =over 4
 4681: 
 4682: =item * $symb: Problem, including path
 4683: 
 4684: =item * $username: username of the desired student
 4685: 
 4686: =item * $domain: domain of the desired student
 4687: 
 4688: =item * $course: Course ID
 4689: 
 4690: =item * $getattempt: Leave blank for all attempts, otherwise put
 4691:     something
 4692: 
 4693: =item * $regexp: if string matches this regexp, the string will be
 4694:     sent to $gradesub
 4695: 
 4696: =item * $gradesub: routine that processes the string if it matches $regexp
 4697: 
 4698: =item * $usec: section of the desired student
 4699: 
 4700: =item * $identifier: counter for student (multiple students one problem) or 
 4701:     problem (one student; whole sequence).
 4702: 
 4703: =back
 4704: 
 4705: The output string is a table containing all desired attempts, if any.
 4706: 
 4707: =cut
 4708: 
 4709: sub get_previous_attempt {
 4710:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4711:   my $prevattempts='';
 4712:   no strict 'refs';
 4713:   if ($symb) {
 4714:     my (%returnhash)=
 4715:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4716:     if ($returnhash{'version'}) {
 4717:       my %lasthash=();
 4718:       my $version;
 4719:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4720:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4721:             if ($key =~ /\.rawrndseed$/) {
 4722:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4723:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4724:             } else {
 4725:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4726:             }
 4727:         }
 4728:       }
 4729:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4730:       $prevattempts.='<th>'.&mt('History').'</th>';
 4731:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4732:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4733:       foreach my $key (sort(keys(%lasthash))) {
 4734: 	my ($ign,@parts) = split(/\./,$key);
 4735: 	if ($#parts > 0) {
 4736: 	  my $data=$parts[-1];
 4737:           next if ($data eq 'foilorder');
 4738: 	  pop(@parts);
 4739:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4740:           if ($data eq 'type') {
 4741:               unless ($showsurv) {
 4742:                   my $id = join(',',@parts);
 4743:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4744:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4745:                       $lasthidden{$ign.'.'.$id} = 1;
 4746:                   }
 4747:               }
 4748:               if ($identifier ne '') {
 4749:                   my $id = join(',',@parts);
 4750:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4751:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4752:                       $hidestatus{$ign.'.'.$id} = 1;
 4753:                   }
 4754:               }
 4755:           } elsif ($data eq 'regrader') {
 4756:               if (($identifier ne '') && (@parts)) {
 4757:                   my $id = join(',',@parts);
 4758:                   $regraded{$ign.'.'.$id} = 1;
 4759:               }
 4760:           } 
 4761: 	} else {
 4762: 	  if ($#parts == 0) {
 4763: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4764: 	  } else {
 4765: 	    $prevattempts.='<th>'.$ign.'</th>';
 4766: 	  }
 4767: 	}
 4768:       }
 4769:       $prevattempts.=&end_data_table_header_row();
 4770:       if ($getattempt eq '') {
 4771:         my (%solved,%resets,%probstatus);
 4772:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4773:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4774:                 foreach my $id (keys(%regraded)) {
 4775:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4776:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4777:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4778:                         push(@{$resets{$id}},$version);
 4779:                     }
 4780:                 }
 4781:             }
 4782:         }
 4783: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4784:             my (@hidden,@unsolved);
 4785:             if (%typeparts) {
 4786:                 foreach my $id (keys(%typeparts)) {
 4787:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4788:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4789:                         push(@hidden,$id);
 4790:                     } elsif ($identifier ne '') {
 4791:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4792:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4793:                                 ($hidestatus{$id})) {
 4794:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4795:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4796:                                 push(@{$solved{$id}},$version);
 4797:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4798:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4799:                                 my $skip;
 4800:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4801:                                     foreach my $reset (@{$resets{$id}}) {
 4802:                                         if ($reset > $solved{$id}[-1]) {
 4803:                                             $skip=1;
 4804:                                             last;
 4805:                                         }
 4806:                                     }
 4807:                                 }
 4808:                                 unless ($skip) {
 4809:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4810:                                     push(@unsolved,$partslist);
 4811:                                 }
 4812:                             }
 4813:                         }
 4814:                     }
 4815:                 }
 4816:             }
 4817:             $prevattempts.=&start_data_table_row().
 4818:                            '<td>'.&mt('Transaction [_1]',$version);
 4819:             if (@unsolved) {
 4820:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4821:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4822:                                  &mt('Hide').'</label></span>';
 4823:             }
 4824:             $prevattempts .= '</td>';
 4825:             if (@hidden) {
 4826:                 foreach my $key (sort(keys(%lasthash))) {
 4827:                     next if ($key =~ /\.foilorder$/);
 4828:                     my $hide;
 4829:                     foreach my $id (@hidden) {
 4830:                         if ($key =~ /^\Q$id\E/) {
 4831:                             $hide = 1;
 4832:                             last;
 4833:                         }
 4834:                     }
 4835:                     if ($hide) {
 4836:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4837:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4838:                             my $value = &format_previous_attempt_value($key,
 4839:                                              $returnhash{$version.':'.$key});
 4840:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4841:                         } else {
 4842:                             $prevattempts.='<td>&nbsp;</td>';
 4843:                         }
 4844:                     } else {
 4845:                         if ($key =~ /\./) {
 4846:                             my $value = $returnhash{$version.':'.$key};
 4847:                             if ($key =~ /\.rndseed$/) {
 4848:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4849:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4850:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4851:                                 }
 4852:                             }
 4853:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4854:                                            '&nbsp;</td>';
 4855:                         } else {
 4856:                             $prevattempts.='<td>&nbsp;</td>';
 4857:                         }
 4858:                     }
 4859:                 }
 4860:             } else {
 4861: 	        foreach my $key (sort(keys(%lasthash))) {
 4862:                     next if ($key =~ /\.foilorder$/);
 4863:                     my $value = $returnhash{$version.':'.$key};
 4864:                     if ($key =~ /\.rndseed$/) {
 4865:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4866:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4867:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4868:                         }
 4869:                     }
 4870:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4871:                                    '&nbsp;</td>';
 4872: 	        }
 4873:             }
 4874: 	    $prevattempts.=&end_data_table_row();
 4875: 	 }
 4876:       }
 4877:       my @currhidden = keys(%lasthidden);
 4878:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4879:       foreach my $key (sort(keys(%lasthash))) {
 4880:           next if ($key =~ /\.foilorder$/);
 4881:           if (%typeparts) {
 4882:               my $hidden;
 4883:               foreach my $id (@currhidden) {
 4884:                   if ($key =~ /^\Q$id\E/) {
 4885:                       $hidden = 1;
 4886:                       last;
 4887:                   }
 4888:               }
 4889:               if ($hidden) {
 4890:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4891:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4892:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4893:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4894:                           $value = &$gradesub($value);
 4895:                       }
 4896:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4897:                   } else {
 4898:                       $prevattempts.='<td>&nbsp;</td>';
 4899:                   }
 4900:               } else {
 4901:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4902:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4903:                       $value = &$gradesub($value);
 4904:                   }
 4905:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4906:               }
 4907:           } else {
 4908: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4909: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4910:                   $value = &$gradesub($value);
 4911:               }
 4912: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4913:           }
 4914:       }
 4915:       $prevattempts.= &end_data_table_row().&end_data_table();
 4916:     } else {
 4917:       my $msg;
 4918:       if ($symb =~ /ext\.tool$/) {
 4919:           $msg = &mt('No grade passed back.');
 4920:       } else {
 4921:           $msg = &mt('Nothing submitted - no attempts.');
 4922:       }
 4923:       $prevattempts=
 4924: 	  &start_data_table().&start_data_table_row().
 4925: 	  '<td>'.$msg.'</td>'.
 4926: 	  &end_data_table_row().&end_data_table();
 4927:     }
 4928:   } else {
 4929:     $prevattempts=
 4930: 	  &start_data_table().&start_data_table_row().
 4931: 	  '<td>'.&mt('No data.').'</td>'.
 4932: 	  &end_data_table_row().&end_data_table();
 4933:   }
 4934: }
 4935: 
 4936: sub format_previous_attempt_value {
 4937:     my ($key,$value) = @_;
 4938:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4939:         $value = &Apache::lonlocal::locallocaltime($value);
 4940:     } elsif (ref($value) eq 'ARRAY') {
 4941:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4942:     } elsif ($key =~ /answerstring$/) {
 4943:         my %answers = &Apache::lonnet::str2hash($value);
 4944:         my @answer = %answers;
 4945:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4946:         my @anskeys = sort(keys(%answers));
 4947:         if (@anskeys == 1) {
 4948:             my $answer = $answers{$anskeys[0]};
 4949:             if ($answer =~ m{\0}) {
 4950:                 $answer =~ s{\0}{,}g;
 4951:             }
 4952:             my $tag_internal_answer_name = 'INTERNAL';
 4953:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4954:                 $value = $answer; 
 4955:             } else {
 4956:                 $value = $anskeys[0].'='.$answer;
 4957:             }
 4958:         } else {
 4959:             foreach my $ans (@anskeys) {
 4960:                 my $answer = $answers{$ans};
 4961:                 if ($answer =~ m{\0}) {
 4962:                     $answer =~ s{\0}{,}g;
 4963:                 }
 4964:                 $value .=  $ans.'='.$answer.'<br />';;
 4965:             } 
 4966:         }
 4967:     } else {
 4968:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4969:     }
 4970:     return $value;
 4971: }
 4972: 
 4973: 
 4974: sub relative_to_absolute {
 4975:     my ($url,$output)=@_;
 4976:     my $parser=HTML::TokeParser->new(\$output);
 4977:     my $token;
 4978:     my $thisdir=$url;
 4979:     my @rlinks=();
 4980:     while ($token=$parser->get_token) {
 4981: 	if ($token->[0] eq 'S') {
 4982: 	    if ($token->[1] eq 'a') {
 4983: 		if ($token->[2]->{'href'}) {
 4984: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4985: 		}
 4986: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4987: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4988: 	    } elsif ($token->[1] eq 'base') {
 4989: 		$thisdir=$token->[2]->{'href'};
 4990: 	    }
 4991: 	}
 4992:     }
 4993:     $thisdir=~s-/[^/]*$--;
 4994:     foreach my $link (@rlinks) {
 4995: 	unless (($link=~/^https?\:\/\//i) ||
 4996: 		($link=~/^\//) ||
 4997: 		($link=~/^javascript:/i) ||
 4998: 		($link=~/^mailto:/i) ||
 4999: 		($link=~/^\#/)) {
 5000: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5001: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5002: 	}
 5003:     }
 5004: # -------------------------------------------------- Deal with Applet codebases
 5005:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5006:     return $output;
 5007: }
 5008: 
 5009: =pod
 5010: 
 5011: =item * &get_student_view()
 5012: 
 5013: show a snapshot of what student was looking at
 5014: 
 5015: =cut
 5016: 
 5017: sub get_student_view {
 5018:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5019:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5020:   my (%form);
 5021:   my @elements=('symb','courseid','domain','username');
 5022:   foreach my $element (@elements) {
 5023:       $form{'grade_'.$element}=eval '$'.$element #'
 5024:   }
 5025:   if (defined($moreenv)) {
 5026:       %form=(%form,%{$moreenv});
 5027:   }
 5028:   if (defined($target)) { $form{'grade_target'} = $target; }
 5029:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5030:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5031:       $feedurl =~ s{^/adm/wrapper}{};
 5032:   }
 5033:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5034:   $userview=~s/\<body[^\>]*\>//gi;
 5035:   $userview=~s/\<\/body\>//gi;
 5036:   $userview=~s/\<html\>//gi;
 5037:   $userview=~s/\<\/html\>//gi;
 5038:   $userview=~s/\<head\>//gi;
 5039:   $userview=~s/\<\/head\>//gi;
 5040:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5041:   $userview=&relative_to_absolute($feedurl,$userview);
 5042:   if (wantarray) {
 5043:      return ($userview,$response);
 5044:   } else {
 5045:      return $userview;
 5046:   }
 5047: }
 5048: 
 5049: sub get_student_view_with_retries {
 5050:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5051: 
 5052:     my $ok = 0;                 # True if we got a good response.
 5053:     my $content;
 5054:     my $response;
 5055: 
 5056:     # Try to get the student_view done. within the retries count:
 5057:     
 5058:     do {
 5059:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5060:          $ok      = $response->is_success;
 5061:          if (!$ok) {
 5062:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5063:          }
 5064:          $retries--;
 5065:     } while (!$ok && ($retries > 0));
 5066:     
 5067:     if (!$ok) {
 5068:        $content = '';          # On error return an empty content.
 5069:     }
 5070:     if (wantarray) {
 5071:        return ($content, $response);
 5072:     } else {
 5073:        return $content;
 5074:     }
 5075: }
 5076: 
 5077: sub css_links {
 5078:     my ($currsymb,$level) = @_;
 5079:     my ($links,@symbs,%cssrefs,%httpref);
 5080:     if ($level eq 'map') {
 5081:         my $navmap = Apache::lonnavmaps::navmap->new();
 5082:         if (ref($navmap)) {
 5083:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5084:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5085:             foreach my $res (@resources) {
 5086:                 if (ref($res) && $res->symb()) {
 5087:                     push(@symbs,$res->symb());
 5088:                 }
 5089:             }
 5090:         }
 5091:     } else {
 5092:         @symbs = ($currsymb);
 5093:     }
 5094:     foreach my $symb (@symbs) {
 5095:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5096:         if ($css_href =~ /\S/) {
 5097:             unless ($css_href =~ m{https?://}) {
 5098:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5099:                 my $proburl =  &Apache::lonnet::clutter($url);
 5100:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5101:                 unless ($css_href =~ m{^/}) {
 5102:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5103:                 }
 5104:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5105:                     unless (($httpref{'httpref.'.$css_href}) ||
 5106:                             (&Apache::lonnet::is_on_map($css_href))) {
 5107:                         my $thisurl = $proburl;
 5108:                         if ($env{'httpref.'.$proburl}) {
 5109:                             $thisurl = $env{'httpref.'.$proburl};
 5110:                         }
 5111:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5112:                     }
 5113:                 }
 5114:             }
 5115:             $cssrefs{$css_href} = 1;
 5116:         }
 5117:     }
 5118:     if (keys(%httpref)) {
 5119:         &Apache::lonnet::appenv(\%httpref);
 5120:     }
 5121:     if (keys(%cssrefs)) {
 5122:         foreach my $css_href (keys(%cssrefs)) {
 5123:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5124:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5125:         }
 5126:     }
 5127:     return $links;
 5128: }
 5129: 
 5130: =pod
 5131: 
 5132: =item * &get_student_answers() 
 5133: 
 5134: show a snapshot of how student was answering problem
 5135: 
 5136: =cut
 5137: 
 5138: sub get_student_answers {
 5139:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5140:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5141:   my (%moreenv);
 5142:   my @elements=('symb','courseid','domain','username');
 5143:   foreach my $element (@elements) {
 5144:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5145:   }
 5146:   $moreenv{'grade_target'}='answer';
 5147:   %moreenv=(%form,%moreenv);
 5148:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5149:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5150:   return $userview;
 5151: }
 5152: 
 5153: =pod
 5154: 
 5155: =item * &submlink()
 5156: 
 5157: Inputs: $text $uname $udom $symb $target
 5158: 
 5159: Returns: A link to grades.pm such as to see the SUBM view of a student
 5160: 
 5161: =cut
 5162: 
 5163: ###############################################
 5164: sub submlink {
 5165:     my ($text,$uname,$udom,$symb,$target)=@_;
 5166:     if (!($uname && $udom)) {
 5167: 	(my $cursymb, my $courseid,$udom,$uname)=
 5168: 	    &Apache::lonnet::whichuser($symb);
 5169: 	if (!$symb) { $symb=$cursymb; }
 5170:     }
 5171:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5172:     $symb=&escape($symb);
 5173:     if ($target) { $target=" target=\"$target\""; }
 5174:     return
 5175:         '<a href="/adm/grades?command=submission'.
 5176:         '&amp;symb='.$symb.
 5177:         '&amp;student='.$uname.
 5178:         '&amp;userdom='.$udom.'"'.
 5179:         $target.'>'.$text.'</a>';
 5180: }
 5181: ##############################################
 5182: 
 5183: =pod
 5184: 
 5185: =item * &pgrdlink()
 5186: 
 5187: Inputs: $text $uname $udom $symb $target
 5188: 
 5189: Returns: A link to grades.pm such as to see the PGRD view of a student
 5190: 
 5191: =cut
 5192: 
 5193: ###############################################
 5194: sub pgrdlink {
 5195:     my $link=&submlink(@_);
 5196:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5197:     return $link;
 5198: }
 5199: ##############################################
 5200: 
 5201: =pod
 5202: 
 5203: =item * &pprmlink()
 5204: 
 5205: Inputs: $text $uname $udom $symb $target
 5206: 
 5207: Returns: A link to parmset.pm such as to see the PPRM view of a
 5208: student and a specific resource
 5209: 
 5210: =cut
 5211: 
 5212: ###############################################
 5213: sub pprmlink {
 5214:     my ($text,$uname,$udom,$symb,$target)=@_;
 5215:     if (!($uname && $udom)) {
 5216: 	(my $cursymb, my $courseid,$udom,$uname)=
 5217: 	    &Apache::lonnet::whichuser($symb);
 5218: 	if (!$symb) { $symb=$cursymb; }
 5219:     }
 5220:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5221:     $symb=&escape($symb);
 5222:     if ($target) { $target="target=\"$target\""; }
 5223:     return '<a href="/adm/parmset?command=set&amp;'.
 5224: 	'symb='.$symb.'&amp;uname='.$uname.
 5225: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5226: }
 5227: ##############################################
 5228: 
 5229: =pod
 5230: 
 5231: =back
 5232: 
 5233: =cut
 5234: 
 5235: ###############################################
 5236: 
 5237: 
 5238: sub timehash {
 5239:     my ($thistime) = @_;
 5240:     my $timezone = &Apache::lonlocal::gettimezone();
 5241:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5242:                      ->set_time_zone($timezone);
 5243:     my $wday = $dt->day_of_week();
 5244:     if ($wday == 7) { $wday = 0; }
 5245:     return ( 'second' => $dt->second(),
 5246:              'minute' => $dt->minute(),
 5247:              'hour'   => $dt->hour(),
 5248:              'day'     => $dt->day_of_month(),
 5249:              'month'   => $dt->month(),
 5250:              'year'    => $dt->year(),
 5251:              'weekday' => $wday,
 5252:              'dayyear' => $dt->day_of_year(),
 5253:              'dlsav'   => $dt->is_dst() );
 5254: }
 5255: 
 5256: sub utc_string {
 5257:     my ($date)=@_;
 5258:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5259: }
 5260: 
 5261: sub maketime {
 5262:     my %th=@_;
 5263:     my ($epoch_time,$timezone,$dt);
 5264:     $timezone = &Apache::lonlocal::gettimezone();
 5265:     eval {
 5266:         $dt = DateTime->new( year   => $th{'year'},
 5267:                              month  => $th{'month'},
 5268:                              day    => $th{'day'},
 5269:                              hour   => $th{'hour'},
 5270:                              minute => $th{'minute'},
 5271:                              second => $th{'second'},
 5272:                              time_zone => $timezone,
 5273:                          );
 5274:     };
 5275:     if (!$@) {
 5276:         $epoch_time = $dt->epoch;
 5277:         if ($epoch_time) {
 5278:             return $epoch_time;
 5279:         }
 5280:     }
 5281:     return POSIX::mktime(
 5282:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5283:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5284: }
 5285: 
 5286: #########################################
 5287: 
 5288: sub findallcourses {
 5289:     my ($roles,$uname,$udom) = @_;
 5290:     my %roles;
 5291:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5292:     my %courses;
 5293:     my $now=time;
 5294:     if (!defined($uname)) {
 5295:         $uname = $env{'user.name'};
 5296:     }
 5297:     if (!defined($udom)) {
 5298:         $udom = $env{'user.domain'};
 5299:     }
 5300:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5301:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5302:         if (!%roles) {
 5303:             %roles = (
 5304:                        cc => 1,
 5305:                        co => 1,
 5306:                        in => 1,
 5307:                        ep => 1,
 5308:                        ta => 1,
 5309:                        cr => 1,
 5310:                        st => 1,
 5311:              );
 5312:         }
 5313:         foreach my $entry (keys(%roleshash)) {
 5314:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5315:             if ($trole =~ /^cr/) { 
 5316:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5317:             } else {
 5318:                 next if (!exists($roles{$trole}));
 5319:             }
 5320:             if ($tend) {
 5321:                 next if ($tend < $now);
 5322:             }
 5323:             if ($tstart) {
 5324:                 next if ($tstart > $now);
 5325:             }
 5326:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5327:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5328:             my $value = $trole.'/'.$cdom.'/';
 5329:             if ($secpart eq '') {
 5330:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5331:                 $sec = 'none';
 5332:                 $value .= $cnum.'/';
 5333:             } else {
 5334:                 $cnum = $cnumpart;
 5335:                 ($sec,$role) = split(/_/,$secpart);
 5336:                 $value .= $cnum.'/'.$sec;
 5337:             }
 5338:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5339:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5340:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5341:                 }
 5342:             } else {
 5343:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5344:             }
 5345:         }
 5346:     } else {
 5347:         foreach my $key (keys(%env)) {
 5348: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5349:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5350: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5351: 	        next if ($role eq 'ca' || $role eq 'aa');
 5352: 	        next if (%roles && !exists($roles{$role}));
 5353: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5354:                 my $active=1;
 5355:                 if ($starttime) {
 5356: 		    if ($now<$starttime) { $active=0; }
 5357:                 }
 5358:                 if ($endtime) {
 5359:                     if ($now>$endtime) { $active=0; }
 5360:                 }
 5361:                 if ($active) {
 5362:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5363:                     if ($sec eq '') {
 5364:                         $sec = 'none';
 5365:                     } else {
 5366:                         $value .= $sec;
 5367:                     }
 5368:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5369:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5370:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5371:                         }
 5372:                     } else {
 5373:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5374:                     }
 5375:                 }
 5376:             }
 5377:         }
 5378:     }
 5379:     return %courses;
 5380: }
 5381: 
 5382: ###############################################
 5383: 
 5384: sub blockcheck {
 5385:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5386:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5387:         my ($has_evb,$check_ipaccess);
 5388:         my $dom = $env{'user.domain'};
 5389:         if ($env{'request.course.id'}) {
 5390:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5391:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5392:             my $checkrole = "cm./$cdom/$cnum";
 5393:             my $sec = $env{'request.course.sec'};
 5394:             if ($sec ne '') {
 5395:                 $checkrole .= "/$sec";
 5396:             }
 5397:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5398:                 ($env{'request.role'} !~ /^st/)) {
 5399:                 $has_evb = 1;
 5400:             }
 5401:             unless ($has_evb) {
 5402:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5403:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5404:                     if ($udom eq $cdom) {
 5405:                         $check_ipaccess = 1;
 5406:                     }
 5407:                 }
 5408:             }
 5409:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5410:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5411:             my $checkrole;
 5412:             if ($env{'request.role.domain'} eq '') {
 5413:                 $checkrole = "cm./$env{'user.domain'}/";
 5414:             } else {
 5415:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5416:             }
 5417:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5418:                 $has_evb = 1;
 5419:             }
 5420:         }
 5421:         unless ($has_evb || $check_ipaccess) {
 5422:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5423:             if (($dom eq 'public') && ($activity eq 'port')) {
 5424:                 $dom = $udom;
 5425:             }
 5426:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5427:                 $check_ipaccess = 1;
 5428:             } else {
 5429:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5430:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5431:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5432:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5433:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5434:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5435:                         $check_ipaccess = 1;
 5436:                     }
 5437:                 }
 5438:             }
 5439:         }
 5440:         if ($check_ipaccess) {
 5441:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5442:             unless (defined($cached)) {
 5443:                 my %domconfig =
 5444:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5445:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5446:             }
 5447:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5448:                 foreach my $id (keys(%{$ipaccessref})) {
 5449:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5450:                         my $range = $ipaccessref->{$id}->{'ip'};
 5451:                         if ($range) {
 5452:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5453:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5454:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5455:                                         return ('','','',$id,$dom);
 5456:                                         last;
 5457:                                     }
 5458:                                 }
 5459:                             }
 5460:                         }
 5461:                     }
 5462:                 }
 5463:             }
 5464:         }
 5465:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5466:             return ();
 5467:         }
 5468:     }
 5469:     if (defined($udom) && defined($uname)) {
 5470:         # If uname and udom are for a course, check for blocks in the course.
 5471:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5472:             my ($startblock,$endblock,$triggerblock) =
 5473:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5474:             return ($startblock,$endblock,$triggerblock);
 5475:         }
 5476:     } else {
 5477:         $udom = $env{'user.domain'};
 5478:         $uname = $env{'user.name'};
 5479:     }
 5480: 
 5481:     my $startblock = 0;
 5482:     my $endblock = 0;
 5483:     my $triggerblock = '';
 5484:     my %live_courses;
 5485:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5486:         %live_courses = &findallcourses(undef,$uname,$udom);
 5487:     }
 5488: 
 5489:     # If uname is for a user, and activity is course-specific, i.e.,
 5490:     # boards, chat or groups, check for blocking in current course only.
 5491: 
 5492:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5493:          $activity eq 'groups' || $activity eq 'printout' ||
 5494:          $activity eq 'search' || $activity eq 'reinit' ||
 5495:          $activity eq 'alert') &&
 5496:         ($env{'request.course.id'})) {
 5497:         foreach my $key (keys(%live_courses)) {
 5498:             if ($key ne $env{'request.course.id'}) {
 5499:                 delete($live_courses{$key});
 5500:             }
 5501:         }
 5502:     }
 5503: 
 5504:     my $otheruser = 0;
 5505:     my %own_courses;
 5506:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5507:         # Resource belongs to user other than current user.
 5508:         $otheruser = 1;
 5509:         # Gather courses for current user
 5510:         %own_courses = 
 5511:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5512:     }
 5513: 
 5514:     # Gather active course roles - course coordinator, instructor, 
 5515:     # exam proctor, ta, student, or custom role.
 5516: 
 5517:     foreach my $course (keys(%live_courses)) {
 5518:         my ($cdom,$cnum);
 5519:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5520:             $cdom = $env{'course.'.$course.'.domain'};
 5521:             $cnum = $env{'course.'.$course.'.num'};
 5522:         } else {
 5523:             ($cdom,$cnum) = split(/_/,$course); 
 5524:         }
 5525:         my $no_ownblock = 0;
 5526:         my $no_userblock = 0;
 5527:         if ($otheruser && $activity ne 'com') {
 5528:             # Check if current user has 'evb' priv for this
 5529:             if (defined($own_courses{$course})) {
 5530:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5531:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5532:                     if ($sec ne 'none') {
 5533:                         $checkrole .= '/'.$sec;
 5534:                     }
 5535:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5536:                         $no_ownblock = 1;
 5537:                         last;
 5538:                     }
 5539:                 }
 5540:             }
 5541:             # if they have 'evb' priv and are currently not playing student
 5542:             next if (($no_ownblock) &&
 5543:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5544:         }
 5545:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5546:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5547:             if ($sec ne 'none') {
 5548:                 $checkrole .= '/'.$sec;
 5549:             }
 5550:             if ($otheruser) {
 5551:                 # Resource belongs to user other than current user.
 5552:                 # Assemble privs for that user, and check for 'evb' priv.
 5553:                 my (%allroles,%userroles);
 5554:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5555:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5556:                         my ($trole,$tdom,$tnum,$tsec);
 5557:                         if ($entry =~ /^cr/) {
 5558:                             ($trole,$tdom,$tnum,$tsec) = 
 5559:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5560:                         } else {
 5561:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5562:                         }
 5563:                         my ($spec,$area,$trest);
 5564:                         $area = '/'.$tdom.'/'.$tnum;
 5565:                         $trest = $tnum;
 5566:                         if ($tsec ne '') {
 5567:                             $area .= '/'.$tsec;
 5568:                             $trest .= '/'.$tsec;
 5569:                         }
 5570:                         $spec = $trole.'.'.$area;
 5571:                         if ($trole =~ /^cr/) {
 5572:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5573:                                                               $tdom,$spec,$trest,$area);
 5574:                         } else {
 5575:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5576:                                                                 $tdom,$spec,$trest,$area);
 5577:                         }
 5578:                     }
 5579:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5580:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5581:                         if ($1) {
 5582:                             $no_userblock = 1;
 5583:                             last;
 5584:                         }
 5585:                     }
 5586:                 }
 5587:             } else {
 5588:                 # Resource belongs to current user
 5589:                 # Check for 'evb' priv via lonnet::allowed().
 5590:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5591:                     $no_ownblock = 1;
 5592:                     last;
 5593:                 }
 5594:             }
 5595:         }
 5596:         # if they have the evb priv and are currently not playing student
 5597:         next if (($no_ownblock) &&
 5598:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5599:         next if ($no_userblock);
 5600: 
 5601:         # Retrieve blocking times and identity of blocker for course
 5602:         # of specified user, unless user has 'evb' privilege.
 5603: 
 5604:         my ($start,$end,$trigger) = 
 5605:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5606:         if (($start != 0) && 
 5607:             (($startblock == 0) || ($startblock > $start))) {
 5608:             $startblock = $start;
 5609:             if ($trigger ne '') {
 5610:                 $triggerblock = $trigger;
 5611:             }
 5612:         }
 5613:         if (($end != 0)  &&
 5614:             (($endblock == 0) || ($endblock < $end))) {
 5615:             $endblock = $end;
 5616:             if ($trigger ne '') {
 5617:                 $triggerblock = $trigger;
 5618:             }
 5619:         }
 5620:     }
 5621:     return ($startblock,$endblock,$triggerblock);
 5622: }
 5623: 
 5624: sub get_blocks {
 5625:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5626:     my $startblock = 0;
 5627:     my $endblock = 0;
 5628:     my $triggerblock = '';
 5629:     my $course = $cdom.'_'.$cnum;
 5630:     $setters->{$course} = {};
 5631:     $setters->{$course}{'staff'} = [];
 5632:     $setters->{$course}{'times'} = [];
 5633:     $setters->{$course}{'triggers'} = [];
 5634:     my (@blockers,%triggered);
 5635:     my $now = time;
 5636:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5637:     if ($activity eq 'docs') {
 5638:         my ($blocked,$nosymbcache,$noenccheck);
 5639:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5640:             $blocked = 1;
 5641:             $nosymbcache = 1;
 5642:             $noenccheck = 1;
 5643:         }
 5644:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5645:         foreach my $block (@blockers) {
 5646:             if ($block =~ /^firstaccess____(.+)$/) {
 5647:                 my $item = $1;
 5648:                 my $type = 'map';
 5649:                 my $timersymb = $item;
 5650:                 if ($item eq 'course') {
 5651:                     $type = 'course';
 5652:                 } elsif ($item =~ /___\d+___/) {
 5653:                     $type = 'resource';
 5654:                 } else {
 5655:                     $timersymb = &Apache::lonnet::symbread($item);
 5656:                 }
 5657:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5658:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5659:                 $triggered{$block} = {
 5660:                                        start => $start,
 5661:                                        end   => $end,
 5662:                                        type  => $type,
 5663:                                      };
 5664:             }
 5665:         }
 5666:     } else {
 5667:         foreach my $block (keys(%commblocks)) {
 5668:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5669:                 my ($start,$end) = ($1,$2);
 5670:                 if ($start <= time && $end >= time) {
 5671:                     if (ref($commblocks{$block}) eq 'HASH') {
 5672:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5673:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5674:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5675:                                     push(@blockers,$block);
 5676:                                 }
 5677:                             }
 5678:                         }
 5679:                     }
 5680:                 }
 5681:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5682:                 my $item = $1;
 5683:                 my $timersymb = $item; 
 5684:                 my $type = 'map';
 5685:                 if ($item eq 'course') {
 5686:                     $type = 'course';
 5687:                 } elsif ($item =~ /___\d+___/) {
 5688:                     $type = 'resource';
 5689:                 } else {
 5690:                     $timersymb = &Apache::lonnet::symbread($item);
 5691:                 }
 5692:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5693:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5694:                 if ($start && $end) {
 5695:                     if (($start <= time) && ($end >= time)) {
 5696:                         if (ref($commblocks{$block}) eq 'HASH') {
 5697:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5698:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5699:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5700:                                         push(@blockers,$block);
 5701:                                         $triggered{$block} = {
 5702:                                                                start => $start,
 5703:                                                                end   => $end,
 5704:                                                                type  => $type,
 5705:                                                              };
 5706:                                     }
 5707:                                 }
 5708:                             }
 5709:                         }
 5710:                     }
 5711:                 }
 5712:             }
 5713:         }
 5714:     }
 5715:     foreach my $blocker (@blockers) {
 5716:         my ($staff_name,$staff_dom,$title,$blocks) =
 5717:             &parse_block_record($commblocks{$blocker});
 5718:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5719:         my ($start,$end,$triggertype);
 5720:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5721:             ($start,$end) = ($1,$2);
 5722:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5723:             $start = $triggered{$blocker}{'start'};
 5724:             $end = $triggered{$blocker}{'end'};
 5725:             $triggertype = $triggered{$blocker}{'type'};
 5726:         }
 5727:         if ($start) {
 5728:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5729:             if ($triggertype) {
 5730:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5731:             } else {
 5732:                 push(@{$$setters{$course}{'triggers'}},0);
 5733:             }
 5734:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5735:                 $startblock = $start;
 5736:                 if ($triggertype) {
 5737:                     $triggerblock = $blocker;
 5738:                 }
 5739:             }
 5740:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5741:                $endblock = $end;
 5742:                if ($triggertype) {
 5743:                    $triggerblock = $blocker;
 5744:                }
 5745:             }
 5746:         }
 5747:     }
 5748:     return ($startblock,$endblock,$triggerblock);
 5749: }
 5750: 
 5751: sub parse_block_record {
 5752:     my ($record) = @_;
 5753:     my ($setuname,$setudom,$title,$blocks);
 5754:     if (ref($record) eq 'HASH') {
 5755:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5756:         $title = &unescape($record->{'event'});
 5757:         $blocks = $record->{'blocks'};
 5758:     } else {
 5759:         my @data = split(/:/,$record,3);
 5760:         if (scalar(@data) eq 2) {
 5761:             $title = $data[1];
 5762:             ($setuname,$setudom) = split(/@/,$data[0]);
 5763:         } else {
 5764:             ($setuname,$setudom,$title) = @data;
 5765:         }
 5766:         $blocks = { 'com' => 'on' };
 5767:     }
 5768:     return ($setuname,$setudom,$title,$blocks);
 5769: }
 5770: 
 5771: sub blocking_status {
 5772:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5773:     my %setters;
 5774: 
 5775: # check for active blocking
 5776:     if ($clientip eq '') {
 5777:         $clientip = &Apache::lonnet::get_requestor_ip();
 5778:     }
 5779:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5780:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5781:     my $blocked = 0;
 5782:     if (($startblock && $endblock) || ($by_ip)) {
 5783:         $blocked = 1;
 5784:     }
 5785: 
 5786: # caller just wants to know whether a block is active
 5787:     if (!wantarray) { return $blocked; }
 5788: 
 5789: # build a link to a popup window containing the details
 5790:     my $querystring  = "?activity=$activity";
 5791: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5792:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5793:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5794:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5795:     } elsif ($activity eq 'docs') {
 5796:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5797:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5798:         if ($symb) {
 5799:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5800:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5801:         }
 5802:     }
 5803: 
 5804:     my $output .= <<'END_MYBLOCK';
 5805: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5806:     var options = "width=" + w + ",height=" + h + ",";
 5807:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5808:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5809:     var newWin = window.open(url, wdwName, options);
 5810:     newWin.focus();
 5811: }
 5812: END_MYBLOCK
 5813: 
 5814:     $output = Apache::lonhtmlcommon::scripttag($output);
 5815:   
 5816:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5817:     my $text = &mt('Communication Blocked');
 5818:     my $class = 'LC_comblock';
 5819:     if ($activity eq 'docs') {
 5820:         $text = &mt('Content Access Blocked');
 5821:         $class = '';
 5822:     } elsif ($activity eq 'printout') {
 5823:         $text = &mt('Printing Blocked');
 5824:     } elsif ($activity eq 'passwd') {
 5825:         $text = &mt('Password Changing Blocked');
 5826:     } elsif ($activity eq 'grades') {
 5827:         $text = &mt('Gradebook Blocked');
 5828:     } elsif ($activity eq 'search') {
 5829:         $text = &mt('Search Blocked');
 5830:     } elsif ($activity eq 'alert') {
 5831:         $text = &mt('Checking Critical Messages Blocked');
 5832:     } elsif ($activity eq 'reinit') {
 5833:         $text = &mt('Checking Course Update Blocked');
 5834:     } elsif ($activity eq 'about') {
 5835:         $text = &mt('Access to User Information Pages Blocked');
 5836:     } elsif ($activity eq 'wishlist') {
 5837:         $text = &mt('Access to Stored Links Blocked');
 5838:     } elsif ($activity eq 'annotate') {
 5839:         $text = &mt('Access to Annotations Blocked');
 5840:     }
 5841:     $output .= <<"END_BLOCK";
 5842: <div class='$class'>
 5843:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5844:   title='$text'>
 5845:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5846:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5847:   title='$text'>$text</a>
 5848: </div>
 5849: 
 5850: END_BLOCK
 5851: 
 5852:     return ($blocked, $output);
 5853: }
 5854: 
 5855: ###############################################
 5856: 
 5857: sub check_ip_acc {
 5858:     my ($acc,$clientip)=@_;
 5859:     &Apache::lonxml::debug("acc is $acc");
 5860:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5861:         return 1;
 5862:     }
 5863:     my ($ip,$allowed);
 5864:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5865:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5866:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5867:     } else {
 5868:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5869:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5870:     }
 5871: 
 5872:     my $name;
 5873:     my %access = (
 5874:                      allowfrom => 1,
 5875:                      denyfrom  => 0,
 5876:                  );
 5877:     my @allows;
 5878:     my @denies;
 5879:     foreach my $item (split(',',$acc)) {
 5880:         $item =~ s/^\s*//;
 5881:         $item =~ s/\s*$//;
 5882:         my $pattern;
 5883:         if ($item =~ /^\!(.+)$/) {
 5884:             push(@denies,$1);
 5885:         } else {
 5886:             push(@allows,$item);
 5887:         }
 5888:    }
 5889:    my $numdenies = scalar(@denies);
 5890:    my $numallows = scalar(@allows);
 5891:    my $count = 0;
 5892:    foreach my $pattern (@denies,@allows) {
 5893:         $count ++; 
 5894:         my $acctype = 'allowfrom';
 5895:         if ($count <= $numdenies) {
 5896:             $acctype = 'denyfrom';
 5897:         }
 5898:         if ($pattern =~ /\*$/) {
 5899:             #35.8.*
 5900:             $pattern=~s/\*//;
 5901:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5902:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5903:             #35.8.3.[34-56]
 5904:             my $low=$2;
 5905:             my $high=$3;
 5906:             $pattern=$1;
 5907:             if ($ip =~ /^\Q$pattern\E/) {
 5908:                 my $last=(split(/\./,$ip))[3];
 5909:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5910:             }
 5911:         } elsif ($pattern =~ /^\*/) {
 5912:             #*.msu.edu
 5913:             $pattern=~s/\*//;
 5914:             if (!defined($name)) {
 5915:                 use Socket;
 5916:                 my $netaddr=inet_aton($ip);
 5917:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5918:             }
 5919:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5920:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5921:             #127.0.0.1
 5922:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5923:         } else {
 5924:             #some.name.com
 5925:             if (!defined($name)) {
 5926:                 use Socket;
 5927:                 my $netaddr=inet_aton($ip);
 5928:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5929:             }
 5930:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5931:         }
 5932:         if ($allowed =~ /^(0|1)$/) { last; }
 5933:     }
 5934:     if ($allowed eq '') {
 5935:         if ($numdenies && !$numallows) {
 5936:             $allowed = 1;
 5937:         } else {
 5938:             $allowed = 0;
 5939:         }
 5940:     }
 5941:     return $allowed;
 5942: }
 5943: 
 5944: ###############################################
 5945: 
 5946: =pod
 5947: 
 5948: =head1 Domain Template Functions
 5949: 
 5950: =over 4
 5951: 
 5952: =item * &determinedomain()
 5953: 
 5954: Inputs: $domain (usually will be undef)
 5955: 
 5956: Returns: Determines which domain should be used for designs
 5957: 
 5958: =cut
 5959: 
 5960: ###############################################
 5961: sub determinedomain {
 5962:     my $domain=shift;
 5963:     if (! $domain) {
 5964:         # Determine domain if we have not been given one
 5965:         $domain = &Apache::lonnet::default_login_domain();
 5966:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5967:         if ($env{'request.role.domain'}) { 
 5968:             $domain=$env{'request.role.domain'}; 
 5969:         }
 5970:     }
 5971:     return $domain;
 5972: }
 5973: ###############################################
 5974: 
 5975: sub devalidate_domconfig_cache {
 5976:     my ($udom)=@_;
 5977:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5978: }
 5979: 
 5980: # ---------------------- Get domain configuration for a domain
 5981: sub get_domainconf {
 5982:     my ($udom) = @_;
 5983:     my $cachetime=1800;
 5984:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5985:     if (defined($cached)) { return %{$result}; }
 5986: 
 5987:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5988: 					     ['login','rolecolors','autoenroll'],$udom);
 5989:     my (%designhash,%legacy);
 5990:     if (keys(%domconfig) > 0) {
 5991:         if (ref($domconfig{'login'}) eq 'HASH') {
 5992:             if (keys(%{$domconfig{'login'}})) {
 5993:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5994:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5995:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5996:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5997:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5998:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5999:                                         if ($key eq 'loginvia') {
 6000:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6001:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6002:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6003:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6004: 
 6005:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6006:                                                 } else {
 6007:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6008:                                                 }
 6009:                                             }
 6010:                                         } elsif ($key eq 'headtag') {
 6011:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6012:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6013:                                             }
 6014:                                         }
 6015:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6016:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6017:                                         }
 6018:                                     }
 6019:                                 }
 6020:                             }
 6021:                         } elsif ($key eq 'saml') {
 6022:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6023:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6024:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6025:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6026:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6027:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6028:                                         }
 6029:                                     }
 6030:                                 }
 6031:                             }
 6032:                         } else {
 6033:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6034:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6035:                                     $domconfig{'login'}{$key}{$img};
 6036:                             }
 6037:                         }
 6038:                     } else {
 6039:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6040:                     }
 6041:                 }
 6042:             } else {
 6043:                 $legacy{'login'} = 1;
 6044:             }
 6045:         } else {
 6046:             $legacy{'login'} = 1;
 6047:         }
 6048:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6049:             if (keys(%{$domconfig{'rolecolors'}})) {
 6050:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6051:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6052:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6053:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6054:                         }
 6055:                     }
 6056:                 }
 6057:             } else {
 6058:                 $legacy{'rolecolors'} = 1;
 6059:             }
 6060:         } else {
 6061:             $legacy{'rolecolors'} = 1;
 6062:         }
 6063:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6064:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6065:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6066:             }
 6067:         }
 6068:         if (keys(%legacy) > 0) {
 6069:             my %legacyhash = &get_legacy_domconf($udom);
 6070:             foreach my $item (keys(%legacyhash)) {
 6071:                 if ($item =~ /^\Q$udom\E\.login/) {
 6072:                     if ($legacy{'login'}) { 
 6073:                         $designhash{$item} = $legacyhash{$item};
 6074:                     }
 6075:                 } else {
 6076:                     if ($legacy{'rolecolors'}) {
 6077:                         $designhash{$item} = $legacyhash{$item};
 6078:                     }
 6079:                 }
 6080:             }
 6081:         }
 6082:     } else {
 6083:         %designhash = &get_legacy_domconf($udom); 
 6084:     }
 6085:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6086: 				  $cachetime);
 6087:     return %designhash;
 6088: }
 6089: 
 6090: sub get_legacy_domconf {
 6091:     my ($udom) = @_;
 6092:     my %legacyhash;
 6093:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6094:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6095:     if (-e $designfile) {
 6096:         if ( open (my $fh,'<',$designfile) ) {
 6097:             while (my $line = <$fh>) {
 6098:                 next if ($line =~ /^\#/);
 6099:                 chomp($line);
 6100:                 my ($key,$val)=(split(/\=/,$line));
 6101:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6102:             }
 6103:             close($fh);
 6104:         }
 6105:     }
 6106:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6107:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6108:     }
 6109:     return %legacyhash;
 6110: }
 6111: 
 6112: =pod
 6113: 
 6114: =item * &domainlogo()
 6115: 
 6116: Inputs: $domain (usually will be undef)
 6117: 
 6118: Returns: A link to a domain logo, if the domain logo exists.
 6119: If the domain logo does not exist, a description of the domain.
 6120: 
 6121: =cut
 6122: 
 6123: ###############################################
 6124: sub domainlogo {
 6125:     my $domain = &determinedomain(shift);
 6126:     my %designhash = &get_domainconf($domain);    
 6127:     # See if there is a logo
 6128:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6129:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6130:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6131: 	    if ($imgsrc =~ m{^/res/}) {
 6132: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6133: 		&Apache::lonnet::repcopy($local_name);
 6134: 	    }
 6135: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6136:         }
 6137:         my $alttext = $domain;
 6138:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6139:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6140:         }
 6141:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6142:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6143:         return &Apache::lonnet::domain($domain,'description');
 6144:     } else {
 6145:         return '';
 6146:     }
 6147: }
 6148: ##############################################
 6149: 
 6150: =pod
 6151: 
 6152: =item * &designparm()
 6153: 
 6154: Inputs: $which parameter; $domain (usually will be undef)
 6155: 
 6156: Returns: value of designparamter $which
 6157: 
 6158: =cut
 6159: 
 6160: 
 6161: ##############################################
 6162: sub designparm {
 6163:     my ($which,$domain)=@_;
 6164:     if (exists($env{'environment.color.'.$which})) {
 6165:         return $env{'environment.color.'.$which};
 6166:     }
 6167:     $domain=&determinedomain($domain);
 6168:     my %domdesign;
 6169:     unless ($domain eq 'public') {
 6170:         %domdesign = &get_domainconf($domain);
 6171:     }
 6172:     my $output;
 6173:     if ($domdesign{$domain.'.'.$which} ne '') {
 6174:         $output = $domdesign{$domain.'.'.$which};
 6175:     } else {
 6176:         $output = $defaultdesign{$which};
 6177:     }
 6178:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6179:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6180:         if ($output =~ m{^/(adm|res)/}) {
 6181:             if ($output =~ m{^/res/}) {
 6182:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6183:                 &Apache::lonnet::repcopy($local_name);
 6184:             }
 6185:             $output = &lonhttpdurl($output);
 6186:         }
 6187:     }
 6188:     return $output;
 6189: }
 6190: 
 6191: ##############################################
 6192: =pod
 6193: 
 6194: =item * &authorspace()
 6195: 
 6196: Inputs: $url (usually will be undef).
 6197: 
 6198: Returns: Path to Authoring Space containing the resource or 
 6199:          directory being viewed (or for which action is being taken). 
 6200:          If $url is provided, and begins /priv/<domain>/<uname>
 6201:          the path will be that portion of the $context argument.
 6202:          Otherwise the path will be for the author space of the current
 6203:          user when the current role is author, or for that of the 
 6204:          co-author/assistant co-author space when the current role 
 6205:          is co-author or assistant co-author.
 6206: 
 6207: =cut
 6208: 
 6209: sub authorspace {
 6210:     my ($url) = @_;
 6211:     if ($url ne '') {
 6212:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6213:            return $1;
 6214:         }
 6215:     }
 6216:     my $caname = '';
 6217:     my $cadom = '';
 6218:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6219:         ($cadom,$caname) =
 6220:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6221:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6222:         $caname = $env{'user.name'};
 6223:         $cadom = $env{'user.domain'};
 6224:     }
 6225:     if (($caname ne '') && ($cadom ne '')) {
 6226:         return "/priv/$cadom/$caname/";
 6227:     }
 6228:     return;
 6229: }
 6230: 
 6231: ##############################################
 6232: =pod
 6233: 
 6234: =item * &head_subbox()
 6235: 
 6236: Inputs: $content (contains HTML code with page functions, etc.)
 6237: 
 6238: Returns: HTML div with $content
 6239:          To be included in page header
 6240: 
 6241: =cut
 6242: 
 6243: sub head_subbox {
 6244:     my ($content)=@_;
 6245:     my $output =
 6246:         '<div class="LC_head_subbox">'
 6247:        .$content
 6248:        .'</div>'
 6249: }
 6250: 
 6251: ##############################################
 6252: =pod
 6253: 
 6254: =item * &CSTR_pageheader()
 6255: 
 6256: Input: (optional) filename from which breadcrumb trail is built.
 6257:        In most cases no input as needed, as $env{'request.filename'}
 6258:        is appropriate for use in building the breadcrumb trail.
 6259:        frameset flag
 6260:        If page header is being requested for use in a frameset, then
 6261:        the second (option) argument -- frameset will be true, and
 6262:        the target attribute set for links should be target="_parent".
 6263: 
 6264: Returns: HTML div with CSTR path and recent box
 6265:          To be included on Authoring Space pages
 6266: 
 6267: =cut
 6268: 
 6269: sub CSTR_pageheader {
 6270:     my ($trailfile,$frameset) = @_;
 6271:     if ($trailfile eq '') {
 6272:         $trailfile = $env{'request.filename'};
 6273:     }
 6274: 
 6275: # this is for resources; directories have customtitle, and crumbs
 6276: # and select recent are created in lonpubdir.pm
 6277: 
 6278:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6279:     my ($udom,$uname,$thisdisfn)=
 6280:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6281:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6282:     $formaction =~ s{/+}{/}g;
 6283: 
 6284:     my $parentpath = '';
 6285:     my $lastitem = '';
 6286:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6287:         $parentpath = $1;
 6288:         $lastitem = $2;
 6289:     } else {
 6290:         $lastitem = $thisdisfn;
 6291:     }
 6292: 
 6293:     my ($crsauthor,$title);
 6294:     if (($env{'request.course.id'}) &&
 6295:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6296:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6297:         $crsauthor = 1;
 6298:         $title = &mt('Course Authoring Space');
 6299:     } else {
 6300:         $title = &mt('Authoring Space');
 6301:     }
 6302: 
 6303:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6304:     if ($frameset) {
 6305:         $target = ' target="_parent"';
 6306:         $crumbtarget = '_parent';
 6307:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6308:         $target = '';
 6309:         $crumbtarget = '';
 6310:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6311:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6312:         $crumbtarget = $env{'request.deeplink.target'};
 6313:     }
 6314: 
 6315:     my $output =
 6316:          '<div>'
 6317:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6318:         .'<b>'.$title.'</b> '
 6319:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6320:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6321: 
 6322:     if ($lastitem) {
 6323:         $output .=
 6324:              '<span class="LC_filename">'
 6325:             .$lastitem
 6326:             .'</span>';
 6327:     }
 6328: 
 6329:     if ($crsauthor) {
 6330:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6331:     } else {
 6332:         $output .=
 6333:              '<br />'
 6334:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6335:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6336:             .'</form>'
 6337:             .&Apache::lonmenu::constspaceform($frameset);
 6338:     }
 6339:     $output .= '</div>';
 6340: 
 6341:     return $output;
 6342: }
 6343: 
 6344: ###############################################
 6345: ###############################################
 6346: 
 6347: =pod
 6348: 
 6349: =back
 6350: 
 6351: =head1 HTML Helpers
 6352: 
 6353: =over 4
 6354: 
 6355: =item * &bodytag()
 6356: 
 6357: Returns a uniform header for LON-CAPA web pages.
 6358: 
 6359: Inputs: 
 6360: 
 6361: =over 4
 6362: 
 6363: =item * $title, A title to be displayed on the page.
 6364: 
 6365: =item * $function, the current role (can be undef).
 6366: 
 6367: =item * $addentries, extra parameters for the <body> tag.
 6368: 
 6369: =item * $bodyonly, if defined, only return the <body> tag.
 6370: 
 6371: =item * $domain, if defined, force a given domain.
 6372: 
 6373: =item * $forcereg, if page should register as content page (relevant for 
 6374:             text interface only)
 6375: 
 6376: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6377:                      navigational links
 6378: 
 6379: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6380: 
 6381: =item * $args, optional argument valid values are
 6382:             no_auto_mt_title -> prevents &mt()ing the title arg
 6383:             use_absolute     -> for external resource or syllabus, this will
 6384:                                 contain https://<hostname> if server uses
 6385:                                 https (as per hosts.tab), but request is for http
 6386:             hostname         -> hostname, from $r->hostname().
 6387: 
 6388: =item * $advtoolsref, optional argument, ref to an array containing
 6389:             inlineremote items to be added in "Functions" menu below
 6390:             breadcrumbs.
 6391: 
 6392: =item * $ltiscope, optional argument, will be one of: resource, map or
 6393:             course, if LON-CAPA is in LTI Provider context. Value is
 6394:             the scope of use, i.e., launch was for access to a single, a map
 6395:             or the entire course.
 6396: 
 6397: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6398:             context, this will contain the URL for the landing item in
 6399:             the course, after launch from an LTI Consumer
 6400: 
 6401: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6402:             context, this will contain a reference to hash of items
 6403:             to be included in the page header and/or inline menu.
 6404: 
 6405: =item * $menucoll, optional argument, if specific menu collection is in
 6406:             effect, either set as the default for the course, or set for
 6407:             the deeplink paramater for $env{'request.deeplink.login'}
 6408:             then $menucoll will be the number of that collection. 
 6409: 
 6410: =item * $menuref, optional argument, reference to a hash, containing the
 6411:             menu options included for the menu in effect, based on the
 6412:             configuration for the numbered menu collection in use.  
 6413: 
 6414: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6415:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6416:             if so, $showncrumbsref is set there to 1, and will propagate back
 6417:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6418:             being called a second time.
 6419: 
 6420: =back
 6421: 
 6422: Returns: A uniform header for LON-CAPA web pages.  
 6423: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6424: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6425: other decorations will be returned.
 6426: 
 6427: =cut
 6428: 
 6429: sub bodytag {
 6430:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6431:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6432:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6433: 
 6434:     my $public;
 6435:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6436:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6437:         $public = 1;
 6438:     }
 6439:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6440:     my $httphost = $args->{'use_absolute'};
 6441:     my $hostname = $args->{'hostname'};
 6442: 
 6443:     $function = &get_users_function() if (!$function);
 6444:     my $img =    &designparm($function.'.img',$domain);
 6445:     my $font =   &designparm($function.'.font',$domain);
 6446:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6447: 
 6448:     my %design = ( 'style'   => 'margin-top: 0',
 6449: 		   'bgcolor' => $pgbg,
 6450: 		   'text'    => $font,
 6451:                    'alink'   => &designparm($function.'.alink',$domain),
 6452: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6453: 		   'link'    => &designparm($function.'.link',$domain),);
 6454:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6455: 
 6456:  # role and realm
 6457:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6458:     if ($realm) {
 6459:         $realm = '/'.$realm;
 6460:     }
 6461:     if ($role eq 'ca') {
 6462:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6463:         $realm = &plainname($rname,$rdom);
 6464:     } 
 6465: # realm
 6466:     my ($cid,$sec);
 6467:     if ($env{'request.course.id'}) {
 6468:         $cid = $env{'request.course.id'};
 6469:         if ($env{'request.course.sec'}) {
 6470:             $sec = $env{'request.course.sec'};
 6471:         }
 6472:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6473:         if (&Apache::lonnet::is_course($1,$2)) {
 6474:             $cid = $1.'_'.$2;
 6475:             $sec = $3;
 6476:         }
 6477:     }
 6478:     if ($cid) {
 6479:         if ($env{'request.role'} !~ /^cr/) {
 6480:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6481:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6482:             if ($env{'request.role.desc'}) {
 6483:                 $role = $env{'request.role.desc'};
 6484:             } else {
 6485:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6486:             }
 6487:         } else {
 6488:             $role = (split(/\//,$role,4))[-1]; 
 6489:         }
 6490:         if ($sec) {
 6491:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6492:         }   
 6493: 	$realm = $env{'course.'.$cid.'.description'};
 6494:     } else {
 6495:         $role = &Apache::lonnet::plaintext($role);
 6496:     }
 6497: 
 6498:     if (!$realm) { $realm='&nbsp;'; }
 6499: 
 6500:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6501: 
 6502: # construct main body tag
 6503:     my $bodytag = "<body $extra_body_attr>".
 6504: 	&Apache::lontexconvert::init_math_support();
 6505: 
 6506:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6507: 
 6508:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6509:         return $bodytag;
 6510:     }
 6511: 
 6512:     if ($public) {
 6513: 	undef($role);
 6514:     }
 6515: 
 6516:     my $showcrstitle = 1;
 6517:     if (($cid) && ($env{'request.lti.login'})) {
 6518:         if (ref($ltimenu) eq 'HASH') {
 6519:             unless ($ltimenu->{'role'}) {
 6520:                 undef($role);
 6521:             }
 6522:             unless ($ltimenu->{'coursetitle'}) {
 6523:                 $realm='&nbsp;';
 6524:                 $showcrstitle = 0;
 6525:             }
 6526:         }
 6527:     } elsif (($cid) && ($menucoll)) {
 6528:         if (ref($menuref) eq 'HASH') {
 6529:             unless ($menuref->{'role'}) {
 6530:                 undef($role);
 6531:             }
 6532:             unless ($menuref->{'crs'}) {
 6533:                 $realm='&nbsp;';
 6534:                 $showcrstitle = 0;
 6535:             }
 6536:         }
 6537:     }
 6538: 
 6539:     my $titleinfo = '<h1>'.$title.'</h1>';
 6540:     #
 6541:     # Extra info if you are the DC
 6542:     my $dc_info = '';
 6543:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6544:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6545:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6546:         $dc_info =~ s/\s+$//;
 6547:     }
 6548: 
 6549:     my $crstype;
 6550:     if ($cid) {
 6551:         $crstype = $env{'course.'.$cid.'.type'};
 6552:     } elsif ($args->{'crstype'}) {
 6553:         $crstype = $args->{'crstype'};
 6554:     }
 6555:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6556:         undef($role);
 6557:     } else {
 6558:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6559:     }
 6560: 
 6561:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6562: 
 6563:         #    if ($env{'request.state'} eq 'construct') {
 6564:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6565:         #    }
 6566: 
 6567:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6568:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6569: 
 6570:         unless ($args->{'no_primary_menu'}) {
 6571:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6572:                                                               $args->{'links_disabled'},
 6573:                                                               $args->{'links_target'});
 6574: 
 6575:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6576:                 if ($dc_info) {
 6577:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6578:                 }
 6579:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6580:                                <em>$realm</em> $dc_info</div>|;
 6581:                 return $bodytag;
 6582:             }
 6583: 
 6584:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6585:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6586:             }
 6587: 
 6588:             $bodytag .= $right;
 6589: 
 6590:             if ($dc_info) {
 6591:                 $dc_info = &dc_courseid_toggle($dc_info);
 6592:             }
 6593:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6594:         }
 6595: 
 6596:         #if directed to not display the secondary menu, don't.  
 6597:         if ($args->{'no_secondary_menu'}) {
 6598:             return $bodytag;
 6599:         }
 6600:         #don't show menus for public users
 6601:         if (!$public){
 6602:             unless ($args->{'no_inline_menu'}) {
 6603:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6604:                                                             $args->{'no_primary_menu'},
 6605:                                                             $menucoll,$menuref,
 6606:                                                             $args->{'links_disabled'},
 6607:                                                             $args->{'links_target'});
 6608:             }
 6609:             $bodytag .= Apache::lonmenu::serverform();
 6610:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6611:             if ($env{'request.state'} eq 'construct') {
 6612:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6613:                                 $args->{'bread_crumbs'},'','',$hostname,
 6614:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6615:             } elsif ($forcereg) {
 6616:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6617:                                 $args->{'group'},$args->{'hide_buttons'},
 6618:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6619:             } else {
 6620:                 $bodytag .= 
 6621:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6622:                                                         $forcereg,$args->{'group'},
 6623:                                                         $args->{'bread_crumbs'},
 6624:                                                         $advtoolsref,'',$hostname);
 6625:             }
 6626:         }else{
 6627:             # this is to seperate menu from content when there's no secondary
 6628:             # menu. Especially needed for public accessible ressources.
 6629:             $bodytag .= '<hr style="clear:both" />';
 6630:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6631:         }
 6632: 
 6633:         return $bodytag;
 6634: }
 6635: 
 6636: sub dc_courseid_toggle {
 6637:     my ($dc_info) = @_;
 6638:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6639:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6640:            &mt('(More ...)').'</a></span>'.
 6641:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6642: }
 6643: 
 6644: sub make_attr_string {
 6645:     my ($register,$attr_ref) = @_;
 6646: 
 6647:     if ($attr_ref && !ref($attr_ref)) {
 6648: 	die("addentries Must be a hash ref ".
 6649: 	    join(':',caller(1))." ".
 6650: 	    join(':',caller(0))." ");
 6651:     }
 6652: 
 6653:     if ($register) {
 6654: 	my ($on_load,$on_unload);
 6655: 	foreach my $key (keys(%{$attr_ref})) {
 6656: 	    if      (lc($key) eq 'onload') {
 6657: 		$on_load.=$attr_ref->{$key}.';';
 6658: 		delete($attr_ref->{$key});
 6659: 
 6660: 	    } elsif (lc($key) eq 'onunload') {
 6661: 		$on_unload.=$attr_ref->{$key}.';';
 6662: 		delete($attr_ref->{$key});
 6663: 	    }
 6664: 	}
 6665: 	$attr_ref->{'onload'}  = $on_load;
 6666: 	$attr_ref->{'onunload'}= $on_unload;
 6667:     }
 6668: 
 6669:     my $attr_string;
 6670:     foreach my $attr (sort(keys(%$attr_ref))) {
 6671: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6672:     }
 6673:     return $attr_string;
 6674: }
 6675: 
 6676: 
 6677: ###############################################
 6678: ###############################################
 6679: 
 6680: =pod
 6681: 
 6682: =item * &endbodytag()
 6683: 
 6684: Returns a uniform footer for LON-CAPA web pages.
 6685: 
 6686: Inputs: 1 - optional reference to an args hash
 6687: If in the hash, key for noredirectlink has a value which evaluates to true,
 6688: a 'Continue' link is not displayed if the page contains an
 6689: internal redirect in the <head></head> section,
 6690: i.e., $env{'internal.head.redirect'} exists   
 6691: 
 6692: =cut
 6693: 
 6694: sub endbodytag {
 6695:     my ($args) = @_;
 6696:     my $endbodytag;
 6697:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6698:         $endbodytag='</body>';
 6699:     }
 6700:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6701:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6702:             my ($endbodyjs,$idattr);
 6703:             if ($env{'internal.head.to_opener'}) {
 6704:                 my $linkid = 'LC_continue_link';
 6705:                 $idattr = ' id="'.$linkid.'"';
 6706:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6707:                 $endbodyjs=<<ENDJS;
 6708: <script type="text/javascript">
 6709: // <![CDATA[
 6710: function ebFunction(evt) {
 6711:     evt.preventDefault();
 6712:     var dest = '$redirect_for_js';
 6713:     if (window.opener != null && !window.opener.closed) {
 6714:         window.opener.location.href=dest;
 6715:         window.close();
 6716:     } else {
 6717:         window.location.href=dest;
 6718:     }
 6719:     return false;
 6720: }
 6721: 
 6722: \$(document).ready(function () {
 6723:   if (document.getElementById('$linkid')) {
 6724:     var clickelem = document.getElementById('$linkid');
 6725:     clickelem.addEventListener('click',ebFunction,false);
 6726:   }
 6727: });
 6728: // ]]>
 6729: </script>
 6730: ENDJS
 6731:             }
 6732: 	    $endbodytag=
 6733: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6734: 	        &mt('Continue').'</a>'.
 6735: 	        $endbodytag;
 6736:         }
 6737:     }
 6738:     return $endbodytag;
 6739: }
 6740: 
 6741: =pod
 6742: 
 6743: =item * &standard_css()
 6744: 
 6745: Returns a style sheet
 6746: 
 6747: Inputs: (all optional)
 6748:             domain         -> force to color decorate a page for a specific
 6749:                                domain
 6750:             function       -> force usage of a specific rolish color scheme
 6751:             bgcolor        -> override the default page bgcolor
 6752: 
 6753: =cut
 6754: 
 6755: sub standard_css {
 6756:     my ($function,$domain,$bgcolor) = @_;
 6757:     $function  = &get_users_function() if (!$function);
 6758:     my $img    = &designparm($function.'.img',   $domain);
 6759:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6760:     my $font   = &designparm($function.'.font',  $domain);
 6761:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6762: #second colour for later usage
 6763:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6764:     my $pgbg_or_bgcolor =
 6765: 	         $bgcolor ||
 6766: 	         &designparm($function.'.pgbg',  $domain);
 6767:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6768:     my $alink  = &designparm($function.'.alink', $domain);
 6769:     my $vlink  = &designparm($function.'.vlink', $domain);
 6770:     my $link   = &designparm($function.'.link',  $domain);
 6771: 
 6772:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6773:     my $mono                 = 'monospace';
 6774:     my $data_table_head      = $sidebg;
 6775:     my $data_table_light     = '#FAFAFA';
 6776:     my $data_table_dark      = '#E0E0E0';
 6777:     my $data_table_darker    = '#CCCCCC';
 6778:     my $data_table_highlight = '#FFFF00';
 6779:     my $mail_new             = '#FFBB77';
 6780:     my $mail_new_hover       = '#DD9955';
 6781:     my $mail_read            = '#BBBB77';
 6782:     my $mail_read_hover      = '#999944';
 6783:     my $mail_replied         = '#AAAA88';
 6784:     my $mail_replied_hover   = '#888855';
 6785:     my $mail_other           = '#99BBBB';
 6786:     my $mail_other_hover     = '#669999';
 6787:     my $table_header         = '#DDDDDD';
 6788:     my $feedback_link_bg     = '#BBBBBB';
 6789:     my $lg_border_color      = '#C8C8C8';
 6790:     my $button_hover         = '#BF2317';
 6791: 
 6792:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6793:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6794:                                              : '0 3px 0 4px';
 6795: 
 6796: 
 6797:     return <<END;
 6798: 
 6799: /* needed for iframe to allow 100% height in FF */
 6800: body, html { 
 6801:     margin: 0;
 6802:     padding: 0 0.5%;
 6803:     height: 99%; /* to avoid scrollbars */
 6804: }
 6805: 
 6806: body {
 6807:   font-family: $sans;
 6808:   line-height:130%;
 6809:   font-size:0.83em;
 6810:   color:$font;
 6811: }
 6812: 
 6813: a:focus,
 6814: a:focus img {
 6815:   color: red;
 6816: }
 6817: 
 6818: form, .inline {
 6819:   display: inline;
 6820: }
 6821: 
 6822: .LC_right {
 6823:   text-align:right;
 6824: }
 6825: 
 6826: .LC_middle {
 6827:   vertical-align:middle;
 6828: }
 6829: 
 6830: .LC_floatleft {
 6831:   float: left;
 6832: }
 6833: 
 6834: .LC_floatright {
 6835:   float: right;
 6836: }
 6837: 
 6838: .LC_400Box {
 6839:   width:400px;
 6840: }
 6841: 
 6842: .LC_iframecontainer {
 6843:     width: 98%;
 6844:     margin: 0;
 6845:     position: fixed;
 6846:     top: 8.5em;
 6847:     bottom: 0;
 6848: }
 6849: 
 6850: .LC_iframecontainer iframe{
 6851:     border: none;
 6852:     width: 100%;
 6853:     height: 100%;
 6854: }
 6855: 
 6856: .LC_filename {
 6857:   font-family: $mono;
 6858:   white-space:pre;
 6859:   font-size: 120%;
 6860: }
 6861: 
 6862: .LC_fileicon {
 6863:   border: none;
 6864:   height: 1.3em;
 6865:   vertical-align: text-bottom;
 6866:   margin-right: 0.3em;
 6867:   text-decoration:none;
 6868: }
 6869: 
 6870: .LC_setting {
 6871:   text-decoration:underline;
 6872: }
 6873: 
 6874: .LC_error {
 6875:   color: red;
 6876: }
 6877: 
 6878: .LC_warning {
 6879:   color: darkorange;
 6880: }
 6881: 
 6882: .LC_diff_removed {
 6883:   color: red;
 6884: }
 6885: 
 6886: .LC_info,
 6887: .LC_success,
 6888: .LC_diff_added {
 6889:   color: green;
 6890: }
 6891: 
 6892: div.LC_confirm_box {
 6893:   background-color: #FAFAFA;
 6894:   border: 1px solid $lg_border_color;
 6895:   margin-right: 0;
 6896:   padding: 5px;
 6897: }
 6898: 
 6899: div.LC_confirm_box .LC_error img,
 6900: div.LC_confirm_box .LC_success img {
 6901:   vertical-align: middle;
 6902: }
 6903: 
 6904: .LC_maxwidth {
 6905:   max-width: 100%;
 6906:   height: auto;
 6907: }
 6908: 
 6909: .LC_textsize_mobile {
 6910:   \@media only screen and (max-device-width: 480px) {
 6911:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6912:   }
 6913: }
 6914: 
 6915: .LC_icon {
 6916:   border: none;
 6917:   vertical-align: middle;
 6918: }
 6919: 
 6920: .LC_docs_spacer {
 6921:   width: 25px;
 6922:   height: 1px;
 6923:   border: none;
 6924: }
 6925: 
 6926: .LC_internal_info {
 6927:   color: #999999;
 6928: }
 6929: 
 6930: .LC_discussion {
 6931:   background: $data_table_dark;
 6932:   border: 1px solid black;
 6933:   margin: 2px;
 6934: }
 6935: 
 6936: .LC_disc_action_left {
 6937:   background: $sidebg;
 6938:   text-align: left;
 6939:   padding: 4px;
 6940:   margin: 2px;
 6941: }
 6942: 
 6943: .LC_disc_action_right {
 6944:   background: $sidebg;
 6945:   text-align: right;
 6946:   padding: 4px;
 6947:   margin: 2px;
 6948: }
 6949: 
 6950: .LC_disc_new_item {
 6951:   background: white;
 6952:   border: 2px solid red;
 6953:   margin: 4px;
 6954:   padding: 4px;
 6955: }
 6956: 
 6957: .LC_disc_old_item {
 6958:   background: white;
 6959:   margin: 4px;
 6960:   padding: 4px;
 6961: }
 6962: 
 6963: table.LC_pastsubmission {
 6964:   border: 1px solid black;
 6965:   margin: 2px;
 6966: }
 6967: 
 6968: table#LC_menubuttons {
 6969:   width: 100%;
 6970:   background: $pgbg;
 6971:   border: 2px;
 6972:   border-collapse: separate;
 6973:   padding: 0;
 6974: }
 6975: 
 6976: table#LC_title_bar a {
 6977:   color: $fontmenu;
 6978: }
 6979: 
 6980: table#LC_title_bar {
 6981:   clear: both;
 6982:   display: none;
 6983: }
 6984: 
 6985: table#LC_title_bar,
 6986: table.LC_breadcrumbs, /* obsolete? */
 6987: table#LC_title_bar.LC_with_remote {
 6988:   width: 100%;
 6989:   border-color: $pgbg;
 6990:   border-style: solid;
 6991:   border-width: $border;
 6992:   background: $pgbg;
 6993:   color: $fontmenu;
 6994:   border-collapse: collapse;
 6995:   padding: 0;
 6996:   margin: 0;
 6997: }
 6998: 
 6999: ul.LC_breadcrumb_tools_outerlist {
 7000:     margin: 0;
 7001:     padding: 0;
 7002:     position: relative;
 7003:     list-style: none;
 7004: }
 7005: ul.LC_breadcrumb_tools_outerlist li {
 7006:     display: inline;
 7007: }
 7008: 
 7009: .LC_breadcrumb_tools_navigation {
 7010:     padding: 0;
 7011:     margin: 0;
 7012:     float: left;
 7013: }
 7014: .LC_breadcrumb_tools_tools {
 7015:     padding: 0;
 7016:     margin: 0;
 7017:     float: right;
 7018: }
 7019: 
 7020: .LC_placement_prog {
 7021:     padding-right: 20px;
 7022:     font-weight: bold;
 7023:     font-size: 90%;
 7024: }
 7025: 
 7026: table#LC_title_bar td {
 7027:   background: $tabbg;
 7028: }
 7029: 
 7030: table#LC_menubuttons img {
 7031:   border: none;
 7032: }
 7033: 
 7034: .LC_breadcrumbs_component {
 7035:   float: right;
 7036:   margin: 0 1em;
 7037: }
 7038: .LC_breadcrumbs_component img {
 7039:   vertical-align: middle;
 7040: }
 7041: 
 7042: .LC_breadcrumbs_hoverable {
 7043:   background: $sidebg;
 7044: }
 7045: 
 7046: td.LC_table_cell_checkbox {
 7047:   text-align: center;
 7048: }
 7049: 
 7050: .LC_fontsize_small {
 7051:   font-size: 70%;
 7052: }
 7053: 
 7054: #LC_breadcrumbs {
 7055:   clear:both;
 7056:   background: $sidebg;
 7057:   border-bottom: 1px solid $lg_border_color;
 7058:   line-height: 2.5em;
 7059:   overflow: hidden;
 7060:   margin: 0;
 7061:   padding: 0;
 7062:   text-align: left;
 7063: }
 7064: 
 7065: .LC_head_subbox, .LC_actionbox {
 7066:   clear:both;
 7067:   background: #F8F8F8; /* $sidebg; */
 7068:   border: 1px solid $sidebg;
 7069:   margin: 0 0 10px 0;
 7070:   padding: 3px;
 7071:   text-align: left;
 7072: }
 7073: 
 7074: .LC_fontsize_medium {
 7075:   font-size: 85%;
 7076: }
 7077: 
 7078: .LC_fontsize_large {
 7079:   font-size: 120%;
 7080: }
 7081: 
 7082: .LC_menubuttons_inline_text {
 7083:   color: $font;
 7084:   font-size: 90%;
 7085:   padding-left:3px;
 7086: }
 7087: 
 7088: .LC_menubuttons_inline_text img{
 7089:   vertical-align: middle;
 7090: }
 7091: 
 7092: li.LC_menubuttons_inline_text img {
 7093:   cursor:pointer;
 7094:   text-decoration: none;
 7095: }
 7096: 
 7097: .LC_menubuttons_link {
 7098:   text-decoration: none;
 7099: }
 7100: 
 7101: .LC_menubuttons_category {
 7102:   color: $font;
 7103:   background: $pgbg;
 7104:   font-size: larger;
 7105:   font-weight: bold;
 7106: }
 7107: 
 7108: td.LC_menubuttons_text {
 7109:   color: $font;
 7110: }
 7111: 
 7112: .LC_current_location {
 7113:   background: $tabbg;
 7114: }
 7115: 
 7116: td.LC_zero_height {
 7117:   line-height: 0; 
 7118:   cellpadding: 0;
 7119: }
 7120: 
 7121: table.LC_data_table {
 7122:   border: 1px solid #000000;
 7123:   border-collapse: separate;
 7124:   border-spacing: 1px;
 7125:   background: $pgbg;
 7126: }
 7127: 
 7128: .LC_data_table_dense {
 7129:   font-size: small;
 7130: }
 7131: 
 7132: table.LC_nested_outer {
 7133:   border: 1px solid #000000;
 7134:   border-collapse: collapse;
 7135:   border-spacing: 0;
 7136:   width: 100%;
 7137: }
 7138: 
 7139: table.LC_innerpickbox,
 7140: table.LC_nested {
 7141:   border: none;
 7142:   border-collapse: collapse;
 7143:   border-spacing: 0;
 7144:   width: 100%;
 7145: }
 7146: 
 7147: table.LC_data_table tr th,
 7148: table.LC_calendar tr th,
 7149: table.LC_prior_tries tr th,
 7150: table.LC_innerpickbox tr th {
 7151:   font-weight: bold;
 7152:   background-color: $data_table_head;
 7153:   color:$fontmenu;
 7154:   font-size:90%;
 7155: }
 7156: 
 7157: table.LC_innerpickbox tr th,
 7158: table.LC_innerpickbox tr td {
 7159:   vertical-align: top;
 7160: }
 7161: 
 7162: table.LC_data_table tr.LC_info_row > td {
 7163:   background-color: #CCCCCC;
 7164:   font-weight: bold;
 7165:   text-align: left;
 7166: }
 7167: 
 7168: table.LC_data_table tr.LC_odd_row > td {
 7169:   background-color: $data_table_light;
 7170:   padding: 2px;
 7171:   vertical-align: top;
 7172: }
 7173: 
 7174: table.LC_pick_box tr > td.LC_odd_row {
 7175:   background-color: $data_table_light;
 7176:   vertical-align: top;
 7177: }
 7178: 
 7179: table.LC_data_table tr.LC_even_row > td {
 7180:   background-color: $data_table_dark;
 7181:   padding: 2px;
 7182:   vertical-align: top;
 7183: }
 7184: 
 7185: table.LC_pick_box tr > td.LC_even_row {
 7186:   background-color: $data_table_dark;
 7187:   vertical-align: top;
 7188: }
 7189: 
 7190: table.LC_data_table tr.LC_data_table_highlight td {
 7191:   background-color: $data_table_darker;
 7192: }
 7193: 
 7194: table.LC_data_table tr td.LC_leftcol_header {
 7195:   background-color: $data_table_head;
 7196:   font-weight: bold;
 7197: }
 7198: 
 7199: table.LC_data_table tr.LC_empty_row td,
 7200: table.LC_nested tr.LC_empty_row td {
 7201:   font-weight: bold;
 7202:   font-style: italic;
 7203:   text-align: center;
 7204:   padding: 8px;
 7205: }
 7206: 
 7207: table.LC_data_table tr.LC_empty_row td,
 7208: table.LC_data_table tr.LC_footer_row td {
 7209:   background-color: $sidebg;
 7210: }
 7211: 
 7212: table.LC_nested tr.LC_empty_row td {
 7213:   background-color: #FFFFFF;
 7214: }
 7215: 
 7216: table.LC_caption {
 7217: }
 7218: 
 7219: table.LC_nested tr.LC_empty_row td {
 7220:   padding: 4ex
 7221: }
 7222: 
 7223: table.LC_nested_outer tr th {
 7224:   font-weight: bold;
 7225:   color:$fontmenu;
 7226:   background-color: $data_table_head;
 7227:   font-size: small;
 7228:   border-bottom: 1px solid #000000;
 7229: }
 7230: 
 7231: table.LC_nested_outer tr td.LC_subheader {
 7232:   background-color: $data_table_head;
 7233:   font-weight: bold;
 7234:   font-size: small;
 7235:   border-bottom: 1px solid #000000;
 7236:   text-align: right;
 7237: }
 7238: 
 7239: table.LC_nested tr.LC_info_row td {
 7240:   background-color: #CCCCCC;
 7241:   font-weight: bold;
 7242:   font-size: small;
 7243:   text-align: center;
 7244: }
 7245: 
 7246: table.LC_nested tr.LC_info_row td.LC_left_item,
 7247: table.LC_nested_outer tr th.LC_left_item {
 7248:   text-align: left;
 7249: }
 7250: 
 7251: table.LC_nested td {
 7252:   background-color: #FFFFFF;
 7253:   font-size: small;
 7254: }
 7255: 
 7256: table.LC_nested_outer tr th.LC_right_item,
 7257: table.LC_nested tr.LC_info_row td.LC_right_item,
 7258: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7259: table.LC_nested tr td.LC_right_item {
 7260:   text-align: right;
 7261: }
 7262: 
 7263: table.LC_nested tr.LC_odd_row td {
 7264:   background-color: #EEEEEE;
 7265: }
 7266: 
 7267: table.LC_createuser {
 7268: }
 7269: 
 7270: table.LC_createuser tr.LC_section_row td {
 7271:   font-size: small;
 7272: }
 7273: 
 7274: table.LC_createuser tr.LC_info_row td  {
 7275:   background-color: #CCCCCC;
 7276:   font-weight: bold;
 7277:   text-align: center;
 7278: }
 7279: 
 7280: table.LC_calendar {
 7281:   border: 1px solid #000000;
 7282:   border-collapse: collapse;
 7283:   width: 98%;
 7284: }
 7285: 
 7286: table.LC_calendar_pickdate {
 7287:   font-size: xx-small;
 7288: }
 7289: 
 7290: table.LC_calendar tr td {
 7291:   border: 1px solid #000000;
 7292:   vertical-align: top;
 7293:   width: 14%;
 7294: }
 7295: 
 7296: table.LC_calendar tr td.LC_calendar_day_empty {
 7297:   background-color: $data_table_dark;
 7298: }
 7299: 
 7300: table.LC_calendar tr td.LC_calendar_day_current {
 7301:   background-color: $data_table_highlight;
 7302: }
 7303: 
 7304: table.LC_data_table tr td.LC_mail_new {
 7305:   background-color: $mail_new;
 7306: }
 7307: 
 7308: table.LC_data_table tr.LC_mail_new:hover {
 7309:   background-color: $mail_new_hover;
 7310: }
 7311: 
 7312: table.LC_data_table tr td.LC_mail_read {
 7313:   background-color: $mail_read;
 7314: }
 7315: 
 7316: /*
 7317: table.LC_data_table tr.LC_mail_read:hover {
 7318:   background-color: $mail_read_hover;
 7319: }
 7320: */
 7321: 
 7322: table.LC_data_table tr td.LC_mail_replied {
 7323:   background-color: $mail_replied;
 7324: }
 7325: 
 7326: /*
 7327: table.LC_data_table tr.LC_mail_replied:hover {
 7328:   background-color: $mail_replied_hover;
 7329: }
 7330: */
 7331: 
 7332: table.LC_data_table tr td.LC_mail_other {
 7333:   background-color: $mail_other;
 7334: }
 7335: 
 7336: /*
 7337: table.LC_data_table tr.LC_mail_other:hover {
 7338:   background-color: $mail_other_hover;
 7339: }
 7340: */
 7341: 
 7342: table.LC_data_table tr > td.LC_browser_file,
 7343: table.LC_data_table tr > td.LC_browser_file_published {
 7344:   background: #AAEE77;
 7345: }
 7346: 
 7347: table.LC_data_table tr > td.LC_browser_file_locked,
 7348: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7349:   background: #FFAA99;
 7350: }
 7351: 
 7352: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7353:   background: #888888;
 7354: }
 7355: 
 7356: table.LC_data_table tr > td.LC_browser_file_modified,
 7357: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7358:   background: #F8F866;
 7359: }
 7360: 
 7361: table.LC_data_table tr.LC_browser_folder > td {
 7362:   background: #E0E8FF;
 7363: }
 7364: 
 7365: table.LC_data_table tr > td.LC_roles_is {
 7366:   /* background: #77FF77; */
 7367: }
 7368: 
 7369: table.LC_data_table tr > td.LC_roles_future {
 7370:   border-right: 8px solid #FFFF77;
 7371: }
 7372: 
 7373: table.LC_data_table tr > td.LC_roles_will {
 7374:   border-right: 8px solid #FFAA77;
 7375: }
 7376: 
 7377: table.LC_data_table tr > td.LC_roles_expired {
 7378:   border-right: 8px solid #FF7777;
 7379: }
 7380: 
 7381: table.LC_data_table tr > td.LC_roles_will_not {
 7382:   border-right: 8px solid #AAFF77;
 7383: }
 7384: 
 7385: table.LC_data_table tr > td.LC_roles_selected {
 7386:   border-right: 8px solid #11CC55;
 7387: }
 7388: 
 7389: span.LC_current_location {
 7390:   font-size:larger;
 7391:   background: $pgbg;
 7392: }
 7393: 
 7394: span.LC_current_nav_location {
 7395:   font-weight:bold;
 7396:   background: $sidebg;
 7397: }
 7398: 
 7399: span.LC_parm_menu_item {
 7400:   font-size: larger;
 7401: }
 7402: 
 7403: span.LC_parm_scope_all {
 7404:   color: red;
 7405: }
 7406: 
 7407: span.LC_parm_scope_folder {
 7408:   color: green;
 7409: }
 7410: 
 7411: span.LC_parm_scope_resource {
 7412:   color: orange;
 7413: }
 7414: 
 7415: span.LC_parm_part {
 7416:   color: blue;
 7417: }
 7418: 
 7419: span.LC_parm_folder,
 7420: span.LC_parm_symb {
 7421:   font-size: x-small;
 7422:   font-family: $mono;
 7423:   color: #AAAAAA;
 7424: }
 7425: 
 7426: ul.LC_parm_parmlist li {
 7427:   display: inline-block;
 7428:   padding: 0.3em 0.8em;
 7429:   vertical-align: top;
 7430:   width: 150px;
 7431:   border-top:1px solid $lg_border_color;
 7432: }
 7433: 
 7434: td.LC_parm_overview_level_menu,
 7435: td.LC_parm_overview_map_menu,
 7436: td.LC_parm_overview_parm_selectors,
 7437: td.LC_parm_overview_restrictions  {
 7438:   border: 1px solid black;
 7439:   border-collapse: collapse;
 7440: }
 7441: 
 7442: span.LC_parm_recursive,
 7443: td.LC_parm_recursive {
 7444:   font-weight: bold;
 7445:   font-size: smaller;
 7446: }
 7447: 
 7448: table.LC_parm_overview_restrictions td {
 7449:   border-width: 1px 4px 1px 4px;
 7450:   border-style: solid;
 7451:   border-color: $pgbg;
 7452:   text-align: center;
 7453: }
 7454: 
 7455: table.LC_parm_overview_restrictions th {
 7456:   background: $tabbg;
 7457:   border-width: 1px 4px 1px 4px;
 7458:   border-style: solid;
 7459:   border-color: $pgbg;
 7460: }
 7461: 
 7462: table#LC_helpmenu {
 7463:   border: none;
 7464:   height: 55px;
 7465:   border-spacing: 0;
 7466: }
 7467: 
 7468: table#LC_helpmenu fieldset legend {
 7469:   font-size: larger;
 7470: }
 7471: 
 7472: table#LC_helpmenu_links {
 7473:   width: 100%;
 7474:   border: 1px solid black;
 7475:   background: $pgbg;
 7476:   padding: 0;
 7477:   border-spacing: 1px;
 7478: }
 7479: 
 7480: table#LC_helpmenu_links tr td {
 7481:   padding: 1px;
 7482:   background: $tabbg;
 7483:   text-align: center;
 7484:   font-weight: bold;
 7485: }
 7486: 
 7487: table#LC_helpmenu_links a:link,
 7488: table#LC_helpmenu_links a:visited,
 7489: table#LC_helpmenu_links a:active {
 7490:   text-decoration: none;
 7491:   color: $font;
 7492: }
 7493: 
 7494: table#LC_helpmenu_links a:hover {
 7495:   text-decoration: underline;
 7496:   color: $vlink;
 7497: }
 7498: 
 7499: .LC_chrt_popup_exists {
 7500:   border: 1px solid #339933;
 7501:   margin: -1px;
 7502: }
 7503: 
 7504: .LC_chrt_popup_up {
 7505:   border: 1px solid yellow;
 7506:   margin: -1px;
 7507: }
 7508: 
 7509: .LC_chrt_popup {
 7510:   border: 1px solid #8888FF;
 7511:   background: #CCCCFF;
 7512: }
 7513: 
 7514: table.LC_pick_box {
 7515:   border-collapse: separate;
 7516:   background: white;
 7517:   border: 1px solid black;
 7518:   border-spacing: 1px;
 7519: }
 7520: 
 7521: table.LC_pick_box td.LC_pick_box_title {
 7522:   background: $sidebg;
 7523:   font-weight: bold;
 7524:   text-align: left;
 7525:   vertical-align: top;
 7526:   width: 184px;
 7527:   padding: 8px;
 7528: }
 7529: 
 7530: table.LC_pick_box td.LC_pick_box_value {
 7531:   text-align: left;
 7532:   padding: 8px;
 7533: }
 7534: 
 7535: table.LC_pick_box td.LC_pick_box_select {
 7536:   text-align: left;
 7537:   padding: 8px;
 7538: }
 7539: 
 7540: table.LC_pick_box td.LC_pick_box_separator {
 7541:   padding: 0;
 7542:   height: 1px;
 7543:   background: black;
 7544: }
 7545: 
 7546: table.LC_pick_box td.LC_pick_box_submit {
 7547:   text-align: right;
 7548: }
 7549: 
 7550: table.LC_pick_box td.LC_evenrow_value {
 7551:   text-align: left;
 7552:   padding: 8px;
 7553:   background-color: $data_table_light;
 7554: }
 7555: 
 7556: table.LC_pick_box td.LC_oddrow_value {
 7557:   text-align: left;
 7558:   padding: 8px;
 7559:   background-color: $data_table_light;
 7560: }
 7561: 
 7562: span.LC_helpform_receipt_cat {
 7563:   font-weight: bold;
 7564: }
 7565: 
 7566: table.LC_group_priv_box {
 7567:   background: white;
 7568:   border: 1px solid black;
 7569:   border-spacing: 1px;
 7570: }
 7571: 
 7572: table.LC_group_priv_box td.LC_pick_box_title {
 7573:   background: $tabbg;
 7574:   font-weight: bold;
 7575:   text-align: right;
 7576:   width: 184px;
 7577: }
 7578: 
 7579: table.LC_group_priv_box td.LC_groups_fixed {
 7580:   background: $data_table_light;
 7581:   text-align: center;
 7582: }
 7583: 
 7584: table.LC_group_priv_box td.LC_groups_optional {
 7585:   background: $data_table_dark;
 7586:   text-align: center;
 7587: }
 7588: 
 7589: table.LC_group_priv_box td.LC_groups_functionality {
 7590:   background: $data_table_darker;
 7591:   text-align: center;
 7592:   font-weight: bold;
 7593: }
 7594: 
 7595: table.LC_group_priv td {
 7596:   text-align: left;
 7597:   padding: 0;
 7598: }
 7599: 
 7600: .LC_navbuttons {
 7601:   margin: 2ex 0ex 2ex 0ex;
 7602: }
 7603: 
 7604: .LC_topic_bar {
 7605:   font-weight: bold;
 7606:   background: $tabbg;
 7607:   margin: 1em 0em 1em 2em;
 7608:   padding: 3px;
 7609:   font-size: 1.2em;
 7610: }
 7611: 
 7612: .LC_topic_bar span {
 7613:   left: 0.5em;
 7614:   position: absolute;
 7615:   vertical-align: middle;
 7616:   font-size: 1.2em;
 7617: }
 7618: 
 7619: table.LC_course_group_status {
 7620:   margin: 20px;
 7621: }
 7622: 
 7623: table.LC_status_selector td {
 7624:   vertical-align: top;
 7625:   text-align: center;
 7626:   padding: 4px;
 7627: }
 7628: 
 7629: div.LC_feedback_link {
 7630:   clear: both;
 7631:   background: $sidebg;
 7632:   width: 100%;
 7633:   padding-bottom: 10px;
 7634:   border: 1px $tabbg solid;
 7635:   height: 22px;
 7636:   line-height: 22px;
 7637:   padding-top: 5px;
 7638: }
 7639: 
 7640: div.LC_feedback_link img {
 7641:   height: 22px;
 7642:   vertical-align:middle;
 7643: }
 7644: 
 7645: div.LC_feedback_link a {
 7646:   text-decoration: none;
 7647: }
 7648: 
 7649: div.LC_comblock {
 7650:   display:inline;
 7651:   color:$font;
 7652:   font-size:90%;
 7653: }
 7654: 
 7655: div.LC_feedback_link div.LC_comblock {
 7656:   padding-left:5px;
 7657: }
 7658: 
 7659: div.LC_feedback_link div.LC_comblock a {
 7660:   color:$font;
 7661: }
 7662: 
 7663: span.LC_feedback_link {
 7664:   /* background: $feedback_link_bg; */
 7665:   font-size: larger;
 7666: }
 7667: 
 7668: span.LC_message_link {
 7669:   /* background: $feedback_link_bg; */
 7670:   font-size: larger;
 7671:   position: absolute;
 7672:   right: 1em;
 7673: }
 7674: 
 7675: table.LC_prior_tries {
 7676:   border: 1px solid #000000;
 7677:   border-collapse: separate;
 7678:   border-spacing: 1px;
 7679: }
 7680: 
 7681: table.LC_prior_tries td {
 7682:   padding: 2px;
 7683: }
 7684: 
 7685: .LC_answer_correct {
 7686:   background: lightgreen;
 7687:   color: darkgreen;
 7688:   padding: 6px;
 7689: }
 7690: 
 7691: .LC_answer_charged_try {
 7692:   background: #FFAAAA;
 7693:   color: darkred;
 7694:   padding: 6px;
 7695: }
 7696: 
 7697: .LC_answer_not_charged_try,
 7698: .LC_answer_no_grade,
 7699: .LC_answer_late {
 7700:   background: lightyellow;
 7701:   color: black;
 7702:   padding: 6px;
 7703: }
 7704: 
 7705: .LC_answer_previous {
 7706:   background: lightblue;
 7707:   color: darkblue;
 7708:   padding: 6px;
 7709: }
 7710: 
 7711: .LC_answer_no_message {
 7712:   background: #FFFFFF;
 7713:   color: black;
 7714:   padding: 6px;
 7715: }
 7716: 
 7717: .LC_answer_unknown,
 7718: .LC_answer_warning {
 7719:   background: orange;
 7720:   color: black;
 7721:   padding: 6px;
 7722: }
 7723: 
 7724: span.LC_prior_numerical,
 7725: span.LC_prior_string,
 7726: span.LC_prior_custom,
 7727: span.LC_prior_reaction,
 7728: span.LC_prior_math {
 7729:   font-family: $mono;
 7730:   white-space: pre;
 7731: }
 7732: 
 7733: span.LC_prior_string {
 7734:   font-family: $mono;
 7735:   white-space: pre;
 7736: }
 7737: 
 7738: table.LC_prior_option {
 7739:   width: 100%;
 7740:   border-collapse: collapse;
 7741: }
 7742: 
 7743: table.LC_prior_rank,
 7744: table.LC_prior_match {
 7745:   border-collapse: collapse;
 7746: }
 7747: 
 7748: table.LC_prior_option tr td,
 7749: table.LC_prior_rank tr td,
 7750: table.LC_prior_match tr td {
 7751:   border: 1px solid #000000;
 7752: }
 7753: 
 7754: .LC_nobreak {
 7755:   white-space: nowrap;
 7756: }
 7757: 
 7758: span.LC_cusr_emph {
 7759:   font-style: italic;
 7760: }
 7761: 
 7762: span.LC_cusr_subheading {
 7763:   font-weight: normal;
 7764:   font-size: 85%;
 7765: }
 7766: 
 7767: div.LC_docs_entry_move {
 7768:   border: 1px solid #BBBBBB;
 7769:   background: #DDDDDD;
 7770:   width: 22px;
 7771:   padding: 1px;
 7772:   margin: 0;
 7773: }
 7774: 
 7775: table.LC_data_table tr > td.LC_docs_entry_commands,
 7776: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7777:   font-size: x-small;
 7778: }
 7779: 
 7780: .LC_docs_entry_parameter {
 7781:   white-space: nowrap;
 7782: }
 7783: 
 7784: .LC_docs_copy {
 7785:   color: #000099;
 7786: }
 7787: 
 7788: .LC_docs_cut {
 7789:   color: #550044;
 7790: }
 7791: 
 7792: .LC_docs_rename {
 7793:   color: #009900;
 7794: }
 7795: 
 7796: .LC_docs_remove {
 7797:   color: #990000;
 7798: }
 7799: 
 7800: .LC_docs_alias {
 7801:   color: #440055;  
 7802: }
 7803: 
 7804: .LC_domprefs_email,
 7805: .LC_docs_alias_name,
 7806: .LC_docs_reinit_warn,
 7807: .LC_docs_ext_edit {
 7808:   font-size: x-small;
 7809: }
 7810: 
 7811: table.LC_docs_adddocs td,
 7812: table.LC_docs_adddocs th {
 7813:   border: 1px solid #BBBBBB;
 7814:   padding: 4px;
 7815:   background: #DDDDDD;
 7816: }
 7817: 
 7818: table.LC_sty_begin {
 7819:   background: #BBFFBB;
 7820: }
 7821: 
 7822: table.LC_sty_end {
 7823:   background: #FFBBBB;
 7824: }
 7825: 
 7826: table.LC_double_column {
 7827:   border-width: 0;
 7828:   border-collapse: collapse;
 7829:   width: 100%;
 7830:   padding: 2px;
 7831: }
 7832: 
 7833: table.LC_double_column tr td.LC_left_col {
 7834:   top: 2px;
 7835:   left: 2px;
 7836:   width: 47%;
 7837:   vertical-align: top;
 7838: }
 7839: 
 7840: table.LC_double_column tr td.LC_right_col {
 7841:   top: 2px;
 7842:   right: 2px;
 7843:   width: 47%;
 7844:   vertical-align: top;
 7845: }
 7846: 
 7847: div.LC_left_float {
 7848:   float: left;
 7849:   padding-right: 5%;
 7850:   padding-bottom: 4px;
 7851: }
 7852: 
 7853: div.LC_clear_float_header {
 7854:   padding-bottom: 2px;
 7855: }
 7856: 
 7857: div.LC_clear_float_footer {
 7858:   padding-top: 10px;
 7859:   clear: both;
 7860: }
 7861: 
 7862: div.LC_grade_show_user {
 7863: /*  border-left: 5px solid $sidebg; */
 7864:   border-top: 5px solid #000000;
 7865:   margin: 50px 0 0 0;
 7866:   padding: 15px 0 5px 10px;
 7867: }
 7868: 
 7869: div.LC_grade_show_user_odd_row {
 7870: /*  border-left: 5px solid #000000; */
 7871: }
 7872: 
 7873: div.LC_grade_show_user div.LC_Box {
 7874:   margin-right: 50px;
 7875: }
 7876: 
 7877: div.LC_grade_submissions,
 7878: div.LC_grade_message_center,
 7879: div.LC_grade_info_links {
 7880:   margin: 5px;
 7881:   width: 99%;
 7882:   background: #FFFFFF;
 7883: }
 7884: 
 7885: div.LC_grade_submissions_header,
 7886: div.LC_grade_message_center_header {
 7887:   font-weight: bold;
 7888:   font-size: large;
 7889: }
 7890: 
 7891: div.LC_grade_submissions_body,
 7892: div.LC_grade_message_center_body {
 7893:   border: 1px solid black;
 7894:   width: 99%;
 7895:   background: #FFFFFF;
 7896: }
 7897: 
 7898: table.LC_scantron_action {
 7899:   width: 100%;
 7900: }
 7901: 
 7902: table.LC_scantron_action tr th {
 7903:   font-weight:bold;
 7904:   font-style:normal;
 7905: }
 7906: 
 7907: .LC_edit_problem_header,
 7908: div.LC_edit_problem_footer {
 7909:   font-weight: normal;
 7910:   font-size:  medium;
 7911:   margin: 2px;
 7912:   background-color: $sidebg;
 7913: }
 7914: 
 7915: div.LC_edit_problem_header,
 7916: div.LC_edit_problem_header div,
 7917: div.LC_edit_problem_footer,
 7918: div.LC_edit_problem_footer div,
 7919: div.LC_edit_problem_editxml_header,
 7920: div.LC_edit_problem_editxml_header div {
 7921:   z-index: 100;
 7922: }
 7923: 
 7924: div.LC_edit_problem_header_title {
 7925:   font-weight: bold;
 7926:   font-size: larger;
 7927:   background: $tabbg;
 7928:   padding: 3px;
 7929:   margin: 0 0 5px 0;
 7930: }
 7931: 
 7932: table.LC_edit_problem_header_title {
 7933:   width: 100%;
 7934:   background: $tabbg;
 7935: }
 7936: 
 7937: div.LC_edit_actionbar {
 7938:     background-color: $sidebg;
 7939:     margin: 0;
 7940:     padding: 0;
 7941:     line-height: 200%;
 7942: }
 7943: 
 7944: div.LC_edit_actionbar div{
 7945:     padding: 0;
 7946:     margin: 0;
 7947:     display: inline-block;
 7948: }
 7949: 
 7950: .LC_edit_opt {
 7951:   padding-left: 1em;
 7952:   white-space: nowrap;
 7953: }
 7954: 
 7955: .LC_edit_problem_latexhelper{
 7956:     text-align: right;
 7957: }
 7958: 
 7959: #LC_edit_problem_colorful div{
 7960:     margin-left: 40px;
 7961: }
 7962: 
 7963: #LC_edit_problem_codemirror div{
 7964:     margin-left: 0px;
 7965: }
 7966: 
 7967: img.stift {
 7968:   border-width: 0;
 7969:   vertical-align: middle;
 7970: }
 7971: 
 7972: table td.LC_mainmenu_col_fieldset {
 7973:   vertical-align: top;
 7974: }
 7975: 
 7976: div.LC_createcourse {
 7977:   margin: 10px 10px 10px 10px;
 7978: }
 7979: 
 7980: .LC_dccid {
 7981:   float: right;
 7982:   margin: 0.2em 0 0 0;
 7983:   padding: 0;
 7984:   font-size: 90%;
 7985:   display:none;
 7986: }
 7987: 
 7988: ol.LC_primary_menu a:hover,
 7989: ol#LC_MenuBreadcrumbs a:hover,
 7990: ol#LC_PathBreadcrumbs a:hover,
 7991: ul#LC_secondary_menu a:hover,
 7992: .LC_FormSectionClearButton input:hover
 7993: ul.LC_TabContent   li:hover a {
 7994:   color:$button_hover;
 7995:   text-decoration:none;
 7996: }
 7997: 
 7998: h1 {
 7999:   padding: 0;
 8000:   line-height:130%;
 8001: }
 8002: 
 8003: h2,
 8004: h3,
 8005: h4,
 8006: h5,
 8007: h6 {
 8008:   margin: 5px 0 5px 0;
 8009:   padding: 0;
 8010:   line-height:130%;
 8011: }
 8012: 
 8013: .LC_hcell {
 8014:   padding:3px 15px 3px 15px;
 8015:   margin: 0;
 8016:   background-color:$tabbg;
 8017:   color:$fontmenu;
 8018:   border-bottom:solid 1px $lg_border_color;
 8019: }
 8020: 
 8021: .LC_Box > .LC_hcell {
 8022:   margin: 0 -10px 10px -10px;
 8023: }
 8024: 
 8025: .LC_noBorder {
 8026:   border: 0;
 8027: }
 8028: 
 8029: .LC_FormSectionClearButton input {
 8030:   background-color:transparent;
 8031:   border: none;
 8032:   cursor:pointer;
 8033:   text-decoration:underline;
 8034: }
 8035: 
 8036: .LC_help_open_topic {
 8037:   color: #FFFFFF;
 8038:   background-color: #EEEEFF;
 8039:   margin: 1px;
 8040:   padding: 4px;
 8041:   border: 1px solid #000033;
 8042:   white-space: nowrap;
 8043:   /* vertical-align: middle; */
 8044: }
 8045: 
 8046: dl,
 8047: ul,
 8048: div,
 8049: fieldset {
 8050:   margin: 10px 10px 10px 0;
 8051:   /* overflow: hidden; */
 8052: }
 8053: 
 8054: article.geogebraweb div {
 8055:     margin: 0;
 8056: }
 8057: 
 8058: fieldset > legend {
 8059:   font-weight: bold;
 8060:   padding: 0 5px 0 5px;
 8061: }
 8062: 
 8063: #LC_nav_bar {
 8064:   float: left;
 8065:   background-color: $pgbg_or_bgcolor;
 8066:   margin: 0 0 2px 0;
 8067: }
 8068: 
 8069: #LC_realm {
 8070:   margin: 0.2em 0 0 0;
 8071:   padding: 0;
 8072:   font-weight: bold;
 8073:   text-align: center;
 8074:   background-color: $pgbg_or_bgcolor;
 8075: }
 8076: 
 8077: #LC_nav_bar em {
 8078:   font-weight: bold;
 8079:   font-style: normal;
 8080: }
 8081: 
 8082: ol.LC_primary_menu {
 8083:   margin: 0;
 8084:   padding: 0;
 8085: }
 8086: 
 8087: ol#LC_PathBreadcrumbs {
 8088:   margin: 0;
 8089: }
 8090: 
 8091: ol.LC_primary_menu li {
 8092:   color: RGB(80, 80, 80);
 8093:   vertical-align: middle;
 8094:   text-align: left;
 8095:   list-style: none;
 8096:   position: relative;
 8097:   float: left;
 8098:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8099:   line-height: 1.5em;
 8100: }
 8101: 
 8102: ol.LC_primary_menu li a,
 8103: ol.LC_primary_menu li p {
 8104:   display: block;
 8105:   margin: 0;
 8106:   padding: 0 5px 0 10px;
 8107:   text-decoration: none;
 8108: }
 8109: 
 8110: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8111:   display: inline-block;
 8112:   width: 95%;
 8113:   text-align: left;
 8114: }
 8115: 
 8116: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8117:   display: inline-block;	
 8118:   width: 5%;
 8119:   float: right;
 8120:   text-align: right;
 8121:   font-size: 70%;
 8122: }
 8123: 
 8124: ol.LC_primary_menu ul {
 8125:   display: none;
 8126:   width: 15em;
 8127:   background-color: $data_table_light;
 8128:   position: absolute;
 8129:   top: 100%;
 8130: }
 8131: 
 8132: ol.LC_primary_menu ul ul {
 8133:   left: 100%;
 8134:   top: 0;
 8135: }
 8136: 
 8137: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8138:   display: block;
 8139:   position: absolute;
 8140:   margin: 0;
 8141:   padding: 0;
 8142:   z-index: 2;
 8143: }
 8144: 
 8145: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8146: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8147:   font-size: 90%;
 8148:   vertical-align: top;
 8149:   float: none;
 8150:   border-left: 1px solid black;
 8151:   border-right: 1px solid black;
 8152: /* A dark bottom border to visualize different menu options; 
 8153: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8154:   border-bottom: 1px solid $data_table_dark; 
 8155: }
 8156: 
 8157: ol.LC_primary_menu li li p:hover {
 8158:   color:$button_hover;
 8159:   text-decoration:none;
 8160:   background-color:$data_table_dark;
 8161: }
 8162: 
 8163: ol.LC_primary_menu li li a:hover {
 8164:    color:$button_hover;
 8165:    background-color:$data_table_dark;
 8166: }
 8167: 
 8168: /* Font-size equal to the size of the predecessors*/
 8169: ol.LC_primary_menu li:hover li li {
 8170:   font-size: 100%;
 8171: }
 8172: 
 8173: ol.LC_primary_menu li img {
 8174:   vertical-align: bottom;
 8175:   height: 1.1em;
 8176:   margin: 0.2em 0 0 0;
 8177: }
 8178: 
 8179: ol.LC_primary_menu a {
 8180:   color: RGB(80, 80, 80);
 8181:   text-decoration: none;
 8182: }
 8183: 
 8184: ol.LC_primary_menu a.LC_new_message {
 8185:   font-weight:bold;
 8186:   color: darkred;
 8187: }
 8188: 
 8189: ol.LC_docs_parameters {
 8190:   margin-left: 0;
 8191:   padding: 0;
 8192:   list-style: none;
 8193: }
 8194: 
 8195: ol.LC_docs_parameters li {
 8196:   margin: 0;
 8197:   padding-right: 20px;
 8198:   display: inline;
 8199: }
 8200: 
 8201: ol.LC_docs_parameters li:before {
 8202:   content: "\\002022 \\0020";
 8203: }
 8204: 
 8205: li.LC_docs_parameters_title {
 8206:   font-weight: bold;
 8207: }
 8208: 
 8209: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8210:   content: "";
 8211: }
 8212: 
 8213: ul#LC_secondary_menu {
 8214:   clear: right;
 8215:   color: $fontmenu;
 8216:   background: $tabbg;
 8217:   list-style: none;
 8218:   padding: 0;
 8219:   margin: 0;
 8220:   width: 100%;
 8221:   text-align: left;
 8222:   float: left;
 8223: }
 8224: 
 8225: ul#LC_secondary_menu li {
 8226:   font-weight: bold;
 8227:   line-height: 1.8em;
 8228:   border-right: 1px solid black;
 8229:   float: left;
 8230: }
 8231: 
 8232: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8233:   background-color: $data_table_light;
 8234: }
 8235: 
 8236: ul#LC_secondary_menu li a {
 8237:   padding: 0 0.8em;
 8238: }
 8239: 
 8240: ul#LC_secondary_menu li ul {
 8241:   display: none;
 8242: }
 8243: 
 8244: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8245:   display: block;
 8246:   position: absolute;
 8247:   margin: 0;
 8248:   padding: 0;
 8249:   list-style:none;
 8250:   float: none;
 8251:   background-color: $data_table_light;
 8252:   z-index: 2;
 8253:   margin-left: -1px;
 8254: }
 8255: 
 8256: ul#LC_secondary_menu li ul li {
 8257:   font-size: 90%;
 8258:   vertical-align: top;
 8259:   border-left: 1px solid black;
 8260:   border-right: 1px solid black;
 8261:   background-color: $data_table_light;
 8262:   list-style:none;
 8263:   float: none;
 8264: }
 8265: 
 8266: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8267:   background-color: $data_table_dark;
 8268: }
 8269: 
 8270: ul.LC_TabContent {
 8271:   display:block;
 8272:   background: $sidebg;
 8273:   border-bottom: solid 1px $lg_border_color;
 8274:   list-style:none;
 8275:   margin: -1px -10px 0 -10px;
 8276:   padding: 0;
 8277: }
 8278: 
 8279: ul.LC_TabContent li,
 8280: ul.LC_TabContentBigger li {
 8281:   float:left;
 8282: }
 8283: 
 8284: ul#LC_secondary_menu li a {
 8285:   color: $fontmenu;
 8286:   text-decoration: none;
 8287: }
 8288: 
 8289: ul.LC_TabContent {
 8290:   min-height:20px;
 8291: }
 8292: 
 8293: ul.LC_TabContent li {
 8294:   vertical-align:middle;
 8295:   padding: 0 16px 0 10px;
 8296:   background-color:$tabbg;
 8297:   border-bottom:solid 1px $lg_border_color;
 8298:   border-left: solid 1px $font;
 8299: }
 8300: 
 8301: ul.LC_TabContent .right {
 8302:   float:right;
 8303: }
 8304: 
 8305: ul.LC_TabContent li a,
 8306: ul.LC_TabContent li {
 8307:   color:rgb(47,47,47);
 8308:   text-decoration:none;
 8309:   font-size:95%;
 8310:   font-weight:bold;
 8311:   min-height:20px;
 8312: }
 8313: 
 8314: ul.LC_TabContent li a:hover,
 8315: ul.LC_TabContent li a:focus {
 8316:   color: $button_hover;
 8317:   background:none;
 8318:   outline:none;
 8319: }
 8320: 
 8321: ul.LC_TabContent li:hover {
 8322:   color: $button_hover;
 8323:   cursor:pointer;
 8324: }
 8325: 
 8326: ul.LC_TabContent li.active {
 8327:   color: $font;
 8328:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8329:   border-bottom:solid 1px #FFFFFF;
 8330:   cursor: default;
 8331: }
 8332: 
 8333: ul.LC_TabContent li.active a {
 8334:   color:$font;
 8335:   background:#FFFFFF;
 8336:   outline: none;
 8337: }
 8338: 
 8339: ul.LC_TabContent li.goback {
 8340:   float: left;
 8341:   border-left: none;
 8342: }
 8343: 
 8344: #maincoursedoc {
 8345:   clear:both;
 8346: }
 8347: 
 8348: ul.LC_TabContentBigger {
 8349:   display:block;
 8350:   list-style:none;
 8351:   padding: 0;
 8352: }
 8353: 
 8354: ul.LC_TabContentBigger li {
 8355:   vertical-align:bottom;
 8356:   height: 30px;
 8357:   font-size:110%;
 8358:   font-weight:bold;
 8359:   color: #737373;
 8360: }
 8361: 
 8362: ul.LC_TabContentBigger li.active {
 8363:   position: relative;
 8364:   top: 1px;
 8365: }
 8366: 
 8367: ul.LC_TabContentBigger li a {
 8368:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8369:   height: 30px;
 8370:   line-height: 30px;
 8371:   text-align: center;
 8372:   display: block;
 8373:   text-decoration: none;
 8374:   outline: none;  
 8375: }
 8376: 
 8377: ul.LC_TabContentBigger li.active a {
 8378:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8379:   color:$font;
 8380: }
 8381: 
 8382: ul.LC_TabContentBigger li b {
 8383:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8384:   display: block;
 8385:   float: left;
 8386:   padding: 0 30px;
 8387:   border-bottom: 1px solid $lg_border_color;
 8388: }
 8389: 
 8390: ul.LC_TabContentBigger li:hover b {
 8391:   color:$button_hover;
 8392: }
 8393: 
 8394: ul.LC_TabContentBigger li.active b {
 8395:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8396:   color:$font;
 8397:   border: 0;
 8398: }
 8399: 
 8400: 
 8401: ul.LC_CourseBreadcrumbs {
 8402:   background: $sidebg;
 8403:   height: 2em;
 8404:   padding-left: 10px;
 8405:   margin: 0;
 8406:   list-style-position: inside;
 8407: }
 8408: 
 8409: ol#LC_MenuBreadcrumbs,
 8410: ol#LC_PathBreadcrumbs {
 8411:   padding-left: 10px;
 8412:   margin: 0;
 8413:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8414: }
 8415: 
 8416: ol#LC_MenuBreadcrumbs li,
 8417: ol#LC_PathBreadcrumbs li,
 8418: ul.LC_CourseBreadcrumbs li {
 8419:   display: inline;
 8420:   white-space: normal;  
 8421: }
 8422: 
 8423: ol#LC_MenuBreadcrumbs li a,
 8424: ul.LC_CourseBreadcrumbs li a {
 8425:   text-decoration: none;
 8426:   font-size:90%;
 8427: }
 8428: 
 8429: ol#LC_MenuBreadcrumbs h1 {
 8430:   display: inline;
 8431:   font-size: 90%;
 8432:   line-height: 2.5em;
 8433:   margin: 0;
 8434:   padding: 0;
 8435: }
 8436: 
 8437: ol#LC_PathBreadcrumbs li a {
 8438:   text-decoration:none;
 8439:   font-size:100%;
 8440:   font-weight:bold;
 8441: }
 8442: 
 8443: .LC_Box {
 8444:   border: solid 1px $lg_border_color;
 8445:   padding: 0 10px 10px 10px;
 8446: }
 8447: 
 8448: .LC_DocsBox {
 8449:   border: solid 1px $lg_border_color;
 8450:   padding: 0 0 10px 10px;
 8451: }
 8452: 
 8453: .LC_AboutMe_Image {
 8454:   float:left;
 8455:   margin-right:10px;
 8456: }
 8457: 
 8458: .LC_Clear_AboutMe_Image {
 8459:   clear:left;
 8460: }
 8461: 
 8462: dl.LC_ListStyleClean dt {
 8463:   padding-right: 5px;
 8464:   display: table-header-group;
 8465: }
 8466: 
 8467: dl.LC_ListStyleClean dd {
 8468:   display: table-row;
 8469: }
 8470: 
 8471: .LC_ListStyleClean,
 8472: .LC_ListStyleSimple,
 8473: .LC_ListStyleNormal,
 8474: .LC_ListStyleSpecial {
 8475:   /* display:block; */
 8476:   list-style-position: inside;
 8477:   list-style-type: none;
 8478:   overflow: hidden;
 8479:   padding: 0;
 8480: }
 8481: 
 8482: .LC_ListStyleSimple li,
 8483: .LC_ListStyleSimple dd,
 8484: .LC_ListStyleNormal li,
 8485: .LC_ListStyleNormal dd,
 8486: .LC_ListStyleSpecial li,
 8487: .LC_ListStyleSpecial dd {
 8488:   margin: 0;
 8489:   padding: 5px 5px 5px 10px;
 8490:   clear: both;
 8491: }
 8492: 
 8493: .LC_ListStyleClean li,
 8494: .LC_ListStyleClean dd {
 8495:   padding-top: 0;
 8496:   padding-bottom: 0;
 8497: }
 8498: 
 8499: .LC_ListStyleSimple dd,
 8500: .LC_ListStyleSimple li {
 8501:   border-bottom: solid 1px $lg_border_color;
 8502: }
 8503: 
 8504: .LC_ListStyleSpecial li,
 8505: .LC_ListStyleSpecial dd {
 8506:   list-style-type: none;
 8507:   background-color: RGB(220, 220, 220);
 8508:   margin-bottom: 4px;
 8509: }
 8510: 
 8511: table.LC_SimpleTable {
 8512:   margin:5px;
 8513:   border:solid 1px $lg_border_color;
 8514: }
 8515: 
 8516: table.LC_SimpleTable tr {
 8517:   padding: 0;
 8518:   border:solid 1px $lg_border_color;
 8519: }
 8520: 
 8521: table.LC_SimpleTable thead {
 8522:   background:rgb(220,220,220);
 8523: }
 8524: 
 8525: div.LC_columnSection {
 8526:   display: block;
 8527:   clear: both;
 8528:   overflow: hidden;
 8529:   margin: 0;
 8530: }
 8531: 
 8532: div.LC_columnSection>* {
 8533:   float: left;
 8534:   margin: 10px 20px 10px 0;
 8535:   overflow:hidden;
 8536: }
 8537: 
 8538: table em {
 8539:   font-weight: bold;
 8540:   font-style: normal;
 8541: }
 8542: 
 8543: table.LC_tableBrowseRes,
 8544: table.LC_tableOfContent {
 8545:   border:none;
 8546:   border-spacing: 1px;
 8547:   padding: 3px;
 8548:   background-color: #FFFFFF;
 8549:   font-size: 90%;
 8550: }
 8551: 
 8552: table.LC_tableOfContent {
 8553:   border-collapse: collapse;
 8554: }
 8555: 
 8556: table.LC_tableBrowseRes a,
 8557: table.LC_tableOfContent a {
 8558:   background-color: transparent;
 8559:   text-decoration: none;
 8560: }
 8561: 
 8562: table.LC_tableOfContent img {
 8563:   border: none;
 8564:   height: 1.3em;
 8565:   vertical-align: text-bottom;
 8566:   margin-right: 0.3em;
 8567: }
 8568: 
 8569: a#LC_content_toolbar_firsthomework {
 8570:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8571: }
 8572: 
 8573: a#LC_content_toolbar_everything {
 8574:   background-image:url(/res/adm/pages/show-all.gif);
 8575: }
 8576: 
 8577: a#LC_content_toolbar_uncompleted {
 8578:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8579: }
 8580: 
 8581: #LC_content_toolbar_clearbubbles {
 8582:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8583: }
 8584: 
 8585: a#LC_content_toolbar_changefolder {
 8586:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8587: }
 8588: 
 8589: a#LC_content_toolbar_changefolder_toggled {
 8590:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8591: }
 8592: 
 8593: a#LC_content_toolbar_edittoplevel {
 8594:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8595: }
 8596: 
 8597: a#LC_content_toolbar_printout {
 8598:   background-image:url(/res/adm/pages/printout.gif);
 8599: }
 8600: 
 8601: ul#LC_toolbar li a:hover {
 8602:   background-position: bottom center;
 8603: }
 8604: 
 8605: ul#LC_toolbar {
 8606:   padding: 0;
 8607:   margin: 2px;
 8608:   list-style:none;
 8609:   position:relative;
 8610:   background-color:white;
 8611:   overflow: auto;
 8612: }
 8613: 
 8614: ul#LC_toolbar li {
 8615:   border:1px solid white;
 8616:   padding: 0;
 8617:   margin: 0;
 8618:   float: left;
 8619:   display:inline;
 8620:   vertical-align:middle;
 8621:   white-space: nowrap;
 8622: }
 8623: 
 8624: 
 8625: a.LC_toolbarItem {
 8626:   display:block;
 8627:   padding: 0;
 8628:   margin: 0;
 8629:   height: 32px;
 8630:   width: 32px;
 8631:   color:white;
 8632:   border: none;
 8633:   background-repeat:no-repeat;
 8634:   background-color:transparent;
 8635: }
 8636: 
 8637: ul.LC_funclist {
 8638:     margin: 0;
 8639:     padding: 0.5em 1em 0.5em 0;
 8640: }
 8641: 
 8642: ul.LC_funclist > li:first-child {
 8643:     font-weight:bold; 
 8644:     margin-left:0.8em;
 8645: }
 8646: 
 8647: ul.LC_funclist + ul.LC_funclist {
 8648:     /* 
 8649:        left border as a seperator if we have more than
 8650:        one list 
 8651:     */
 8652:     border-left: 1px solid $sidebg;
 8653:     /* 
 8654:        this hides the left border behind the border of the 
 8655:        outer box if element is wrapped to the next 'line' 
 8656:     */
 8657:     margin-left: -1px;
 8658: }
 8659: 
 8660: ul.LC_funclist li {
 8661:   display: inline;
 8662:   white-space: nowrap;
 8663:   margin: 0 0 0 25px;
 8664:   line-height: 150%;
 8665: }
 8666: 
 8667: .LC_hidden {
 8668:   display: none;
 8669: }
 8670: 
 8671: .LCmodal-overlay {
 8672: 		position:fixed;
 8673: 		top:0;
 8674: 		right:0;
 8675: 		bottom:0;
 8676: 		left:0;
 8677: 		height:100%;
 8678: 		width:100%;
 8679: 		margin:0;
 8680: 		padding:0;
 8681: 		background:#999;
 8682: 		opacity:.75;
 8683: 		filter: alpha(opacity=75);
 8684: 		-moz-opacity: 0.75;
 8685: 		z-index:101;
 8686: }
 8687: 
 8688: * html .LCmodal-overlay {   
 8689: 		position: absolute;
 8690: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8691: }
 8692: 
 8693: .LCmodal-window {
 8694: 		position:fixed;
 8695: 		top:50%;
 8696: 		left:50%;
 8697: 		margin:0;
 8698: 		padding:0;
 8699: 		z-index:102;
 8700: 	}
 8701: 
 8702: * html .LCmodal-window {
 8703: 		position:absolute;
 8704: }
 8705: 
 8706: .LCclose-window {
 8707: 		position:absolute;
 8708: 		width:32px;
 8709: 		height:32px;
 8710: 		right:8px;
 8711: 		top:8px;
 8712: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8713: 		text-indent:-99999px;
 8714: 		overflow:hidden;
 8715: 		cursor:pointer;
 8716: }
 8717: 
 8718: .LCisDisabled {
 8719:   cursor: not-allowed;
 8720:   opacity: 0.5;
 8721: }
 8722: 
 8723: a[aria-disabled="true"] {
 8724:   color: currentColor;
 8725:   display: inline-block;  /* For IE11/ MS Edge bug */
 8726:   pointer-events: none;
 8727:   text-decoration: none;
 8728: }
 8729: 
 8730: pre.LC_wordwrap {
 8731:   white-space: pre-wrap;
 8732:   white-space: -moz-pre-wrap;
 8733:   white-space: -pre-wrap;
 8734:   white-space: -o-pre-wrap;
 8735:   word-wrap: break-word;
 8736: }
 8737: 
 8738: /*
 8739:   styles used for response display
 8740: */
 8741: div.LC_radiofoil, div.LC_rankfoil {
 8742:   margin: .5em 0em .5em 0em;
 8743: }
 8744: table.LC_itemgroup {
 8745:   margin-top: 1em;
 8746: }
 8747: 
 8748: /*
 8749:   styles used by TTH when "Default set of options to pass to tth/m
 8750:   when converting TeX" in course settings has been set
 8751: 
 8752:   option passed: -t
 8753: 
 8754: */
 8755: 
 8756: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8757: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8758: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8759: td div.norm {line-height:normal;}
 8760: 
 8761: /*
 8762:   option passed -y3
 8763: */
 8764: 
 8765: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8766: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8767: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8768: 
 8769: /*
 8770:   sections with roles, for content only
 8771: */
 8772: section[class^="role-"] {
 8773:   padding-left: 10px;
 8774:   padding-right: 5px;
 8775:   margin-top: 8px;
 8776:   margin-bottom: 8px;
 8777:   border: 1px solid #2A4;
 8778:   border-radius: 5px;
 8779:   box-shadow: 0px 1px 1px #BBB;
 8780: }
 8781: section[class^="role-"]>h1 {
 8782:   position: relative;
 8783:   margin: 0px;
 8784:   padding-top: 10px;
 8785:   padding-left: 40px;
 8786: }
 8787: section[class^="role-"]>h1:before {
 8788:   position: absolute;
 8789:   left: -5px;
 8790:   top: 5px;
 8791: }
 8792: section.role-activity>h1:before {
 8793:   content:url('/adm/daxe/images/section_icons/activity.png');
 8794: }
 8795: section.role-advice>h1:before {
 8796:   content:url('/adm/daxe/images/section_icons/advice.png');
 8797: }
 8798: section.role-bibliography>h1:before {
 8799:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8800: }
 8801: section.role-citation>h1:before {
 8802:   content:url('/adm/daxe/images/section_icons/citation.png');
 8803: }
 8804: section.role-conclusion>h1:before {
 8805:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8806: }
 8807: section.role-definition>h1:before {
 8808:   content:url('/adm/daxe/images/section_icons/definition.png');
 8809: }
 8810: section.role-demonstration>h1:before {
 8811:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8812: }
 8813: section.role-example>h1:before {
 8814:   content:url('/adm/daxe/images/section_icons/example.png');
 8815: }
 8816: section.role-explanation>h1:before {
 8817:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8818: }
 8819: section.role-introduction>h1:before {
 8820:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8821: }
 8822: section.role-method>h1:before {
 8823:   content:url('/adm/daxe/images/section_icons/method.png');
 8824: }
 8825: section.role-more_information>h1:before {
 8826:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8827: }
 8828: section.role-objectives>h1:before {
 8829:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8830: }
 8831: section.role-prerequisites>h1:before {
 8832:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8833: }
 8834: section.role-remark>h1:before {
 8835:   content:url('/adm/daxe/images/section_icons/remark.png');
 8836: }
 8837: section.role-reminder>h1:before {
 8838:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8839: }
 8840: section.role-summary>h1:before {
 8841:   content:url('/adm/daxe/images/section_icons/summary.png');
 8842: }
 8843: section.role-syntax>h1:before {
 8844:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8845: }
 8846: section.role-warning>h1:before {
 8847:   content:url('/adm/daxe/images/section_icons/warning.png');
 8848: }
 8849: 
 8850: #LC_minitab_header {
 8851:   float:left;
 8852:   width:100%;
 8853:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8854:   font-size:93%;
 8855:   line-height:normal;
 8856:   margin: 0.5em 0 0.5em 0;
 8857: }
 8858: #LC_minitab_header ul {
 8859:   margin:0;
 8860:   padding:10px 10px 0;
 8861:   list-style:none;
 8862: }
 8863: #LC_minitab_header li {
 8864:   float:left;
 8865:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8866:   margin:0;
 8867:   padding:0 0 0 9px;
 8868: }
 8869: #LC_minitab_header a {
 8870:   display:block;
 8871:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8872:   padding:5px 15px 4px 6px;
 8873: }
 8874: #LC_minitab_header #LC_current_minitab {
 8875:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8876: }
 8877: #LC_minitab_header #LC_current_minitab a {
 8878:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8879:   padding-bottom:5px;
 8880: }
 8881: 
 8882: 
 8883: END
 8884: }
 8885: 
 8886: =pod
 8887: 
 8888: =item * &headtag()
 8889: 
 8890: Returns a uniform footer for LON-CAPA web pages.
 8891: 
 8892: Inputs: $title - optional title for the head
 8893:         $head_extra - optional extra HTML to put inside the <head>
 8894:         $args - optional arguments
 8895:             force_register - if is true call registerurl so the remote is 
 8896:                              informed
 8897:             redirect       -> array ref of
 8898:                                    1- seconds before redirect occurs
 8899:                                    2- url to redirect to
 8900:                                    3- whether the side effect should occur
 8901:                            (side effect of setting 
 8902:                                $env{'internal.head.redirect'} to the url 
 8903:                                redirected to)
 8904:                                    4- whether the redirect target should be
 8905:                                       the opener of the current (pop-up)
 8906:                                       window (side effect of setting
 8907:                                       $env{'internal.head.to_opener'} to
 8908:                                       1, if true.
 8909:                                    5- whether encrypt check should be skipped
 8910:             domain         -> force to color decorate a page for a specific
 8911:                                domain
 8912:             function       -> force usage of a specific rolish color scheme
 8913:             bgcolor        -> override the default page bgcolor
 8914:             no_auto_mt_title
 8915:                            -> prevent &mt()ing the title arg
 8916: 
 8917: =cut
 8918: 
 8919: sub headtag {
 8920:     my ($title,$head_extra,$args) = @_;
 8921:     
 8922:     my $function = $args->{'function'} || &get_users_function();
 8923:     my $domain   = $args->{'domain'}   || &determinedomain();
 8924:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8925:     my $httphost = $args->{'use_absolute'};
 8926:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8927: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8928: 		   #time(),
 8929: 		   $env{'environment.color.timestamp'},
 8930: 		   $function,$domain,$bgcolor);
 8931: 
 8932:     $url = '/adm/css/'.&escape($url).'.css';
 8933: 
 8934:     my $result =
 8935: 	'<head>'.
 8936: 	&font_settings($args);
 8937: 
 8938:     my $inhibitprint;
 8939:     if ($args->{'print_suppress'}) {
 8940:         $inhibitprint = &print_suppression();
 8941:     }
 8942: 
 8943:     if (!$args->{'frameset'}) {
 8944: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8945:     }
 8946:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8947:         $result .= Apache::lonxml::display_title();
 8948:     }
 8949:     if (!$args->{'no_nav_bar'} 
 8950: 	&& !$args->{'only_body'}
 8951: 	&& !$args->{'frameset'}) {
 8952: 	$result .= &help_menu_js($httphost);
 8953:         $result.=&modal_window();
 8954:         $result.=&togglebox_script();
 8955:         $result.=&wishlist_window();
 8956:         $result.=&LCprogressbarUpdate_script();
 8957:     } else {
 8958:         if ($args->{'add_modal'}) {
 8959:            $result.=&modal_window();
 8960:         }
 8961:         if ($args->{'add_wishlist'}) {
 8962:            $result.=&wishlist_window();
 8963:         }
 8964:         if ($args->{'add_togglebox'}) {
 8965:            $result.=&togglebox_script();
 8966:         }
 8967:         if ($args->{'add_progressbar'}) {
 8968:            $result.=&LCprogressbarUpdate_script();
 8969:         }
 8970:     }
 8971:     if (ref($args->{'redirect'})) {
 8972: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8973:         if (!$skip_enc_check) {
 8974:             $url = &Apache::lonenc::check_encrypt($url);
 8975:         }
 8976: 	if (!$inhibit_continue) {
 8977: 	    $env{'internal.head.redirect'} = $url;
 8978: 	}
 8979: 	$result.=<<"ADDMETA";
 8980: <meta http-equiv="pragma" content="no-cache" />
 8981: ADDMETA
 8982:         if ($to_opener) {
 8983:             $env{'internal.head.to_opener'} = 1;
 8984:             my $dest = &js_escape($url);
 8985:             my $timeout = int($time * 1000);
 8986:             $result .=<<"ENDJS";
 8987: <script type="text/javascript">
 8988: // <![CDATA[
 8989: function LC_To_Opener() {
 8990:     var dest = '$dest';
 8991:     if (dest != '') {
 8992:         if (window.opener != null && !window.opener.closed) {
 8993:             window.opener.location.href=dest;
 8994:             window.close();
 8995:         } else {
 8996:             window.location.href=dest;
 8997:         }
 8998:     }
 8999: }
 9000: \$(document).ready(function () {
 9001:     setTimeout('LC_To_Opener()',$timeout);
 9002: });
 9003: // ]]>
 9004: </script>
 9005: ENDJS
 9006:         } else {
 9007:             $result.=<<"ADDMETA";
 9008: <meta http-equiv="Refresh" content="$time; url=$url" />
 9009: ADDMETA
 9010:         }
 9011:     } else {
 9012:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9013:             my $requrl = $env{'request.uri'};
 9014:             if ($requrl eq '') {
 9015:                 $requrl = $ENV{'REQUEST_URI'};
 9016:                 $requrl =~ s/\?.+$//;
 9017:             }
 9018:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9019:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9020:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9021:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9022:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9023:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9024:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9025:                     my ($offload,$offloadoth);
 9026:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9027:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9028:                             $offload = 1;
 9029:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9030:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9031:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9032:                                     $offloadoth = 1;
 9033:                                     $dom_in_use = $env{'user.domain'};
 9034:                                 }
 9035:                             }
 9036:                         }
 9037:                     }
 9038:                     unless ($offload) {
 9039:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9040:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9041:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9042:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9043:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9044:                                         $offload = 1;
 9045:                                         $offloadoth = 1;
 9046:                                         $dom_in_use = $env{'user.domain'};
 9047:                                     }
 9048:                                 }
 9049:                             }
 9050:                         }
 9051:                     }
 9052:                     if ($offload) {
 9053:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9054:                         if (($newserver eq '') && ($offloadoth)) {
 9055:                             my @domains = &Apache::lonnet::current_machine_domains();
 9056:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9057:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9058:                             }
 9059:                         }
 9060:                         if (($newserver) && ($newserver ne $lonhost)) {
 9061:                             my $numsec = 5;
 9062:                             my $timeout = $numsec * 1000;
 9063:                             my ($newurl,$locknum,%locks,$msg);
 9064:                             if ($env{'request.role.adv'}) {
 9065:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9066:                             }
 9067:                             my $disable_submit = 0;
 9068:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9069:                                 $disable_submit = 1;
 9070:                             }
 9071:                             if ($locknum) {
 9072:                                 my @lockinfo = sort(values(%locks));
 9073:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9074:                                        join(", ",sort(values(%locks)))."\n";
 9075:                                 if (&show_course()) {
 9076:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9077:                                 } else {
 9078:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9079:                                 }
 9080:                             } else {
 9081:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9082:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9083:                                 }
 9084:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9085:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9086:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9087:                                     $newurl .= '&role='.$env{'request.role'};
 9088:                                 }
 9089:                                 if ($env{'request.symb'}) {
 9090:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9091:                                     if ($shownsymb =~ m{^/enc/}) {
 9092:                                         my $reqdmajor = 2;
 9093:                                         my $reqdminor = 11;
 9094:                                         my $reqdsubminor = 3;
 9095:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9096:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9097:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9098:                                         if (($major eq '' && $minor eq '') ||
 9099:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9100:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9101:                                              ($reqdsubminor > $subminor))))) {
 9102:                                             undef($shownsymb);
 9103:                                         }
 9104:                                     }
 9105:                                     if ($shownsymb) {
 9106:                                         &js_escape(\$shownsymb);
 9107:                                         $newurl .= '&symb='.$shownsymb;
 9108:                                     }
 9109:                                 } else {
 9110:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9111:                                     &js_escape(\$shownurl);
 9112:                                     $newurl .= '&origurl='.$shownurl;
 9113:                                 }
 9114:                             }
 9115:                             &js_escape(\$msg);
 9116:                             $result.=<<OFFLOAD
 9117: <meta http-equiv="pragma" content="no-cache" />
 9118: <script type="text/javascript">
 9119: // <![CDATA[
 9120: function LC_Offload_Now() {
 9121:     var dest = "$newurl";
 9122:     if (dest != '') {
 9123:         window.location.href="$newurl";
 9124:     }
 9125: }
 9126: \$(document).ready(function () {
 9127:     window.alert('$msg');
 9128:     if ($disable_submit) {
 9129:         \$(".LC_hwk_submit").prop("disabled", true);
 9130:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9131:     }
 9132:     setTimeout('LC_Offload_Now()', $timeout);
 9133: });
 9134: // ]]>
 9135: </script>
 9136: OFFLOAD
 9137:                         }
 9138:                     }
 9139:                 }
 9140:             }
 9141:         }
 9142:     }
 9143:     if (!defined($title)) {
 9144: 	$title = 'The LearningOnline Network with CAPA';
 9145:     }
 9146:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9147:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9148: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9149:     if (!$args->{'frameset'}) {
 9150:         $result .= ' /';
 9151:     }
 9152:     $result .= '>' 
 9153:         .$inhibitprint
 9154: 	.$head_extra;
 9155:     my $clientmobile;
 9156:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9157:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9158:     } else {
 9159:         $clientmobile = $env{'browser.mobile'};
 9160:     }
 9161:     if ($clientmobile) {
 9162:         $result .= '
 9163: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9164: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9165:     }
 9166:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9167:     return $result.'</head>';
 9168: }
 9169: 
 9170: =pod
 9171: 
 9172: =item * &font_settings()
 9173: 
 9174: Returns neccessary <meta> to set the proper encoding
 9175: 
 9176: Inputs: optional reference to HASH -- $args passed to &headtag()
 9177: 
 9178: =cut
 9179: 
 9180: sub font_settings {
 9181:     my ($args) = @_;
 9182:     my $headerstring='';
 9183:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9184:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9185:         $headerstring.=
 9186:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9187:         if (!$args->{'frameset'}) {
 9188: 	    $headerstring.= ' /';
 9189:         }
 9190: 	$headerstring .= '>'."\n";
 9191:     }
 9192:     return $headerstring;
 9193: }
 9194: 
 9195: =pod
 9196: 
 9197: =item * &print_suppression()
 9198: 
 9199: In course context returns css which causes the body to be blank when media="print",
 9200: if printout generation is unavailable for the current resource.
 9201: 
 9202: This could be because:
 9203: 
 9204: (a) printstartdate is in the future
 9205: 
 9206: (b) printenddate is in the past
 9207: 
 9208: (c) there is an active exam block with "printout"
 9209: functionality blocked
 9210: 
 9211: Users with pav, pfo or evb privileges are exempt.
 9212: 
 9213: Inputs: none
 9214: 
 9215: =cut
 9216: 
 9217: 
 9218: sub print_suppression {
 9219:     my $noprint;
 9220:     if ($env{'request.course.id'}) {
 9221:         my $scope = $env{'request.course.id'};
 9222:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9223:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9224:             return;
 9225:         }
 9226:         if ($env{'request.course.sec'} ne '') {
 9227:             $scope .= "/$env{'request.course.sec'}";
 9228:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9229:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9230:                 return;
 9231:             }
 9232:         }
 9233:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9234:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9235:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9236:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9237:         if ($blocked) {
 9238:             my $checkrole = "cm./$cdom/$cnum";
 9239:             if ($env{'request.course.sec'} ne '') {
 9240:                 $checkrole .= "/$env{'request.course.sec'}";
 9241:             }
 9242:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9243:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9244:                 $noprint = 1;
 9245:             }
 9246:         }
 9247:         unless ($noprint) {
 9248:             my $symb = &Apache::lonnet::symbread();
 9249:             if ($symb ne '') {
 9250:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9251:                 if (ref($navmap)) {
 9252:                     my $res = $navmap->getBySymb($symb);
 9253:                     if (ref($res)) {
 9254:                         if (!$res->resprintable()) {
 9255:                             $noprint = 1;
 9256:                         }
 9257:                     }
 9258:                 }
 9259:             }
 9260:         }
 9261:         if ($noprint) {
 9262:             return <<"ENDSTYLE";
 9263: <style type="text/css" media="print">
 9264:     body { display:none }
 9265: </style>
 9266: ENDSTYLE
 9267:         }
 9268:     }
 9269:     return;
 9270: }
 9271: 
 9272: =pod
 9273: 
 9274: =item * &xml_begin()
 9275: 
 9276: Returns the needed doctype and <html>
 9277: 
 9278: Inputs: none
 9279: 
 9280: =cut
 9281: 
 9282: sub xml_begin {
 9283:     my ($is_frameset) = @_;
 9284:     my $output='';
 9285: 
 9286:     if ($env{'browser.mathml'}) {
 9287: 	$output='<?xml version="1.0"?>'
 9288:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9289: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9290:             
 9291: #	    .'<!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">] >'
 9292: 	    .'<!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">'
 9293:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9294: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9295:     } elsif ($is_frameset) {
 9296:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9297:                 '<html>'."\n";
 9298:     } else {
 9299: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9300:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9301:     }
 9302:     return $output;
 9303: }
 9304: 
 9305: =pod
 9306: 
 9307: =item * &start_page()
 9308: 
 9309: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9310: 
 9311: Inputs:
 9312: 
 9313: =over 4
 9314: 
 9315: $title - optional title for the page
 9316: 
 9317: $head_extra - optional extra HTML to incude inside the <head>
 9318: 
 9319: $args - additional optional args supported are:
 9320: 
 9321: =over 8
 9322: 
 9323:              only_body      -> is true will set &bodytag() onlybodytag
 9324:                                     arg on
 9325:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9326:              add_entries    -> additional attributes to add to the  <body>
 9327:              domain         -> force to color decorate a page for a 
 9328:                                     specific domain
 9329:              function       -> force usage of a specific rolish color
 9330:                                     scheme
 9331:              redirect       -> see &headtag()
 9332:              bgcolor        -> override the default page bg color
 9333:              js_ready       -> return a string ready for being used in 
 9334:                                     a javascript writeln
 9335:              html_encode    -> return a string ready for being used in 
 9336:                                     a html attribute
 9337:              force_register -> if is true will turn on the &bodytag()
 9338:                                     $forcereg arg
 9339:              frameset       -> if true will start with a <frameset>
 9340:                                     rather than <body>
 9341:              skip_phases    -> hash ref of 
 9342:                                     head -> skip the <html><head> generation
 9343:                                     body -> skip all <body> generation
 9344:              no_auto_mt_title -> prevent &mt()ing the title arg
 9345:              bread_crumbs ->             Array containing breadcrumbs
 9346:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9347:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9348:                                     to lonhtmlcommon::breadcrumbs
 9349:              group          -> includes the current group, if page is for a 
 9350:                                specific group
 9351:              use_absolute   -> for request for external resource or syllabus, this
 9352:                                will contain https://<hostname> if server uses
 9353:                                https (as per hosts.tab), but request is for http
 9354:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9355:              links_disabled -> Links in primary and secondary menus are disabled
 9356:                                (Can enable them once page has loaded - see lonroles.pm
 9357:                                for an example).
 9358:              links_target   -> Target for links, e.g., _parent (optional).
 9359: 
 9360: =back
 9361: 
 9362: =back
 9363: 
 9364: =cut
 9365: 
 9366: sub start_page {
 9367:     my ($title,$head_extra,$args) = @_;
 9368:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9369: 
 9370:     $env{'internal.start_page'}++;
 9371:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9372: 
 9373:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9374:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9375:     }
 9376: 
 9377:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9378:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9379:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9380:                 $args->{'no_primary_menu'} = 1;
 9381:             }
 9382:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9383:                 $args->{'no_inline_menu'} = 1;
 9384:             }
 9385:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9386:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9387:             }
 9388:         } else {
 9389:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9390:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9391:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9392:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9393:                     $args->{'no_primary_menu'} = 1;
 9394:                 }
 9395:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9396:                     $args->{'no_inline_menu'} = 1;
 9397:                 }
 9398:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9399:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9400:                 }
 9401:             }
 9402:         }
 9403:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9404:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9405:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9406:     } elsif ($env{'request.course.id'}) {
 9407:         my $expiretime=600;
 9408:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9409:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9410:         }
 9411:         my ($deeplinkmenu,$menuref);
 9412:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9413:         if ($menucoll) {
 9414:             if (ref($menuref) eq 'HASH') {
 9415:                 %menu = %{$menuref};
 9416:             }
 9417:             if ($menu{'top'} eq 'n') {
 9418:                 $args->{'no_primary_menu'} = 1;
 9419:             }
 9420:             if ($menu{'inline'} eq 'n') {
 9421:                 unless (&Apache::lonnet::allowed('opa')) {
 9422:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9423:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9424:                     my $crstype = &course_type();
 9425:                     my $now = time;
 9426:                     my $ccrole;
 9427:                     if ($crstype eq 'Community') {
 9428:                         $ccrole = 'co';
 9429:                     } else {
 9430:                         $ccrole = 'cc';
 9431:                     }
 9432:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9433:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9434:                         if ((($start) && ($start<0)) ||
 9435:                             (($end) && ($end<$now))  ||
 9436:                             (($start) && ($now<$start))) {
 9437:                             $args->{'no_inline_menu'} = 1;
 9438:                         }
 9439:                     } else {
 9440:                         $args->{'no_inline_menu'} = 1;
 9441:                     }
 9442:                 }
 9443:             }
 9444:         }
 9445:     }
 9446: 
 9447:     my $showncrumbs;
 9448:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9449: 	if ($args->{'frameset'}) {
 9450: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9451: 						$args->{'add_entries'});
 9452: 	    $result .= "\n<frameset $attr_string>\n";
 9453:         } else {
 9454:             $result .=
 9455:                 &bodytag($title, 
 9456:                          $args->{'function'},       $args->{'add_entries'},
 9457:                          $args->{'only_body'},      $args->{'domain'},
 9458:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9459:                          $args->{'bgcolor'},        $args,
 9460:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9461:                          \%menu,\$showncrumbs);
 9462:         }
 9463:     }
 9464: 
 9465:     if ($args->{'js_ready'}) {
 9466: 		$result = &js_ready($result);
 9467:     }
 9468:     if ($args->{'html_encode'}) {
 9469: 		$result = &html_encode($result);
 9470:     }
 9471: 
 9472:     # Preparation for new and consistent functionlist at top of screen
 9473:     # if ($args->{'functionlist'}) {
 9474:     #            $result .= &build_functionlist();
 9475:     #}
 9476: 
 9477:     # Don't add anything more if only_body wanted or in const space
 9478:     return $result if    $args->{'only_body'} 
 9479:                       || $env{'request.state'} eq 'construct';
 9480: 
 9481:     #Breadcrumbs
 9482:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9483:         unless ($showncrumbs) {
 9484: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9485: 		#if any br links exists, add them to the breadcrumbs
 9486: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9487: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9488: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9489: 			}
 9490: 		}
 9491:                 # if @advtools array contains items add then to the breadcrumbs
 9492:                 if (@advtools > 0) {
 9493:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9494:                 }
 9495:                 my $menulink;
 9496:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9497:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9498:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9499:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9500:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9501:                      (!$env{'request.role.adv'}))) {
 9502:                     $menulink = 0;
 9503:                 } else {
 9504:                     undef($menulink);
 9505:                 }
 9506:                 my $linkprotout;
 9507:                 if ($env{'request.deeplink.login'}) {
 9508:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9509:                     if ($linkprotout) {
 9510:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9511:                     }
 9512:                 }
 9513: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9514: 		if(exists($args->{'bread_crumbs_component'})){
 9515: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9516:                 } else {
 9517: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9518: 		}
 9519:         }
 9520:     }
 9521:     return $result;
 9522: }
 9523: 
 9524: sub end_page {
 9525:     my ($args) = @_;
 9526:     $env{'internal.end_page'}++;
 9527:     my $result;
 9528:     if ($args->{'discussion'}) {
 9529: 	my ($target,$parser);
 9530: 	if (ref($args->{'discussion'})) {
 9531: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9532: 				$args->{'discussion'}{'parser'});
 9533: 	}
 9534: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9535:     }
 9536:     if ($args->{'frameset'}) {
 9537: 	$result .= '</frameset>';
 9538:     } else {
 9539: 	$result .= &endbodytag($args);
 9540:     }
 9541:     unless ($args->{'notbody'}) {
 9542:         $result .= "\n</html>";
 9543:     }
 9544: 
 9545:     if ($args->{'js_ready'}) {
 9546: 	$result = &js_ready($result);
 9547:     }
 9548: 
 9549:     if ($args->{'html_encode'}) {
 9550: 	$result = &html_encode($result);
 9551:     }
 9552: 
 9553:     return $result;
 9554: }
 9555: 
 9556: sub menucoll_in_effect {
 9557:     my ($menucoll,$deeplinkmenu,%menu);
 9558:     if ($env{'request.course.id'}) {
 9559:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9560:         if ($env{'request.deeplink.login'}) {
 9561:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9562:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9563:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9564:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9565:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9566:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9567:                     if (ref($navmap)) {
 9568:                         $deeplink = $navmap->get_mapparam(undef,
 9569:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9570:                                                           '0.deeplink');
 9571:                     } else {
 9572:                         $check_login_symb = 1;
 9573:                     }
 9574:                 } else {
 9575:                     my $symb = &Apache::lonnet::symbread();
 9576:                     if ($symb) {
 9577:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9578:                     } else {
 9579:                         $check_login_symb = 1;
 9580:                     }
 9581:                 }
 9582:             } else {
 9583:                 $check_login_symb = 1;
 9584:             }
 9585:             if ($check_login_symb) {
 9586:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9587:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9588:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9589:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9590:                     if (ref($navmap)) {
 9591:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9592:                     }
 9593:                 } else {
 9594:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9595:                 }
 9596:             }
 9597:             if ($deeplink ne '') {
 9598:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9599:                 if ($display =~ /^\d+$/) {
 9600:                     $deeplinkmenu = 1;
 9601:                     $menucoll = $display;
 9602:                 }
 9603:             }
 9604:         }
 9605:         if ($menucoll) {
 9606:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9607:         }
 9608:     }
 9609:     return ($menucoll,$deeplinkmenu,\%menu);
 9610: }
 9611: 
 9612: sub deeplink_login_symb {
 9613:     my ($cnum,$cdom) = @_;
 9614:     my $login_symb;
 9615:     if ($env{'request.deeplink.login'}) {
 9616:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9617:     }
 9618:     return $login_symb;
 9619: }
 9620: 
 9621: sub symb_from_tinyurl {
 9622:     my ($url,$cnum,$cdom) = @_;
 9623:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9624:         my $key = $1;
 9625:         my ($tinyurl,$login);
 9626:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9627:         if (defined($cached)) {
 9628:             $tinyurl = $result;
 9629:         } else {
 9630:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9631:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9632:             if ($currtiny{$key} ne '') {
 9633:                 $tinyurl = $currtiny{$key};
 9634:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9635:             }
 9636:         }
 9637:         if ($tinyurl ne '') {
 9638:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9639:             if (wantarray) {
 9640:                 return ($cnumreq,$symb);
 9641:             } elsif ($cnumreq eq $cnum) {
 9642:                 return $symb;
 9643:             }
 9644:         }
 9645:     }
 9646:     if (wantarray) {
 9647:         return ();
 9648:     } else {
 9649:         return;
 9650:     }
 9651: }
 9652: 
 9653: sub wishlist_window {
 9654:     return(<<'ENDWISHLIST');
 9655: <script type="text/javascript">
 9656: // <![CDATA[
 9657: // <!-- BEGIN LON-CAPA Internal
 9658: function set_wishlistlink(title, path) {
 9659:     if (!title) {
 9660:         title = document.title;
 9661:         title = title.replace(/^LON-CAPA /,'');
 9662:     }
 9663:     title = encodeURIComponent(title);
 9664:     title = title.replace("'","\\\'");
 9665:     if (!path) {
 9666:         path = location.pathname;
 9667:     }
 9668:     path = encodeURIComponent(path);
 9669:     path = path.replace("'","\\\'");
 9670:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9671:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9672: }
 9673: // END LON-CAPA Internal -->
 9674: // ]]>
 9675: </script>
 9676: ENDWISHLIST
 9677: }
 9678: 
 9679: sub modal_window {
 9680:     return(<<'ENDMODAL');
 9681: <script type="text/javascript">
 9682: // <![CDATA[
 9683: // <!-- BEGIN LON-CAPA Internal
 9684: var modalWindow = {
 9685: 	parent:"body",
 9686: 	windowId:null,
 9687: 	content:null,
 9688: 	width:null,
 9689: 	height:null,
 9690: 	close:function()
 9691: 	{
 9692: 	        $(".LCmodal-window").remove();
 9693: 	        $(".LCmodal-overlay").remove();
 9694: 	},
 9695: 	open:function()
 9696: 	{
 9697: 		var modal = "";
 9698: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9699: 		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;\">";
 9700: 		modal += this.content;
 9701: 		modal += "</div>";	
 9702: 
 9703: 		$(this.parent).append(modal);
 9704: 
 9705: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9706: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9707: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9708: 	}
 9709: };
 9710: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9711: 	{
 9712:                 source = source.replace(/'/g,"&#39;");
 9713: 		modalWindow.windowId = "myModal";
 9714: 		modalWindow.width = width;
 9715: 		modalWindow.height = height;
 9716: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9717: 		modalWindow.open();
 9718: 	};
 9719: // END LON-CAPA Internal -->
 9720: // ]]>
 9721: </script>
 9722: ENDMODAL
 9723: }
 9724: 
 9725: sub modal_link {
 9726:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9727:     unless ($width) { $width=480; }
 9728:     unless ($height) { $height=400; }
 9729:     unless ($scrolling) { $scrolling='yes'; }
 9730:     unless ($transparency) { $transparency='true'; }
 9731: 
 9732:     my $target_attr;
 9733:     if (defined($target)) {
 9734:         $target_attr = 'target="'.$target.'"';
 9735:     }
 9736:     return <<"ENDLINK";
 9737: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9738: ENDLINK
 9739: }
 9740: 
 9741: sub modal_adhoc_script {
 9742:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9743:     my $mathjax;
 9744:     if ($possmathjax) {
 9745:         $mathjax = <<'ENDJAX';
 9746:                if (typeof MathJax == 'object') {
 9747:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9748:                }
 9749: ENDJAX
 9750:     }
 9751:     return (<<ENDADHOC);
 9752: <script type="text/javascript">
 9753: // <![CDATA[
 9754:         var $funcname = function()
 9755:         {
 9756:                 modalWindow.windowId = "myModal";
 9757:                 modalWindow.width = $width;
 9758:                 modalWindow.height = $height;
 9759:                 modalWindow.content = '$content';
 9760:                 modalWindow.open();
 9761:                 $mathjax
 9762:         };  
 9763: // ]]>
 9764: </script>
 9765: ENDADHOC
 9766: }
 9767: 
 9768: sub modal_adhoc_inner {
 9769:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9770:     my $innerwidth=$width-20;
 9771:     $content=&js_ready(
 9772:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9773:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9774:                  $content.
 9775:                  &end_scrollbox().
 9776:                  &end_page()
 9777:              );
 9778:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9779: }
 9780: 
 9781: sub modal_adhoc_window {
 9782:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9783:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9784:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9785: }
 9786: 
 9787: sub modal_adhoc_launch {
 9788:     my ($funcname,$width,$height,$content)=@_;
 9789:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9790: <script type="text/javascript">
 9791: // <![CDATA[
 9792: $funcname();
 9793: // ]]>
 9794: </script>
 9795: ENDLAUNCH
 9796: }
 9797: 
 9798: sub modal_adhoc_close {
 9799:     return (<<ENDCLOSE);
 9800: <script type="text/javascript">
 9801: // <![CDATA[
 9802: modalWindow.close();
 9803: // ]]>
 9804: </script>
 9805: ENDCLOSE
 9806: }
 9807: 
 9808: sub togglebox_script {
 9809:    return(<<ENDTOGGLE);
 9810: <script type="text/javascript"> 
 9811: // <![CDATA[
 9812: function LCtoggleDisplay(id,hidetext,showtext) {
 9813:    link = document.getElementById(id + "link").childNodes[0];
 9814:    with (document.getElementById(id).style) {
 9815:       if (display == "none" ) {
 9816:           display = "inline";
 9817:           link.nodeValue = hidetext;
 9818:         } else {
 9819:           display = "none";
 9820:           link.nodeValue = showtext;
 9821:        }
 9822:    }
 9823: }
 9824: // ]]>
 9825: </script>
 9826: ENDTOGGLE
 9827: }
 9828: 
 9829: sub start_togglebox {
 9830:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9831:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9832:     unless ($showtext) { $showtext=&mt('show'); }
 9833:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9834:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9835:     return &start_data_table().
 9836:            &start_data_table_header_row().
 9837:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9838:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9839:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9840:            &end_data_table_header_row().
 9841:            '<tr id="'.$id.'" style="display:none""><td>';
 9842: }
 9843: 
 9844: sub end_togglebox {
 9845:     return '</td></tr>'.&end_data_table();
 9846: }
 9847: 
 9848: sub LCprogressbar_script {
 9849:    my ($id,$number_to_do)=@_;
 9850:    if ($number_to_do) {
 9851:        return(<<ENDPROGRESS);
 9852: <script type="text/javascript">
 9853: // <![CDATA[
 9854: \$('#progressbar$id').progressbar({
 9855:   value: 0,
 9856:   change: function(event, ui) {
 9857:     var newVal = \$(this).progressbar('option', 'value');
 9858:     \$('.pblabel', this).text(LCprogressTxt);
 9859:   }
 9860: });
 9861: // ]]>
 9862: </script>
 9863: ENDPROGRESS
 9864:    } else {
 9865:        return(<<ENDPROGRESS);
 9866: <script type="text/javascript">
 9867: // <![CDATA[
 9868: \$('#progressbar$id').progressbar({
 9869:   value: false,
 9870:   create: function(event, ui) {
 9871:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9872:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9873:   }
 9874: });
 9875: // ]]>
 9876: </script>
 9877: ENDPROGRESS
 9878:    }
 9879: }
 9880: 
 9881: sub LCprogressbarUpdate_script {
 9882:    return(<<ENDPROGRESSUPDATE);
 9883: <style type="text/css">
 9884: .ui-progressbar { position:relative; }
 9885: .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%; }
 9886: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9887: </style>
 9888: <script type="text/javascript">
 9889: // <![CDATA[
 9890: var LCprogressTxt='---';
 9891: 
 9892: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9893:    LCprogressTxt=progresstext;
 9894:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9895:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9896:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9897:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9898:    } else {
 9899:        \$('#progressbar'+id).progressbar('value',percent);
 9900:    }
 9901: }
 9902: // ]]>
 9903: </script>
 9904: ENDPROGRESSUPDATE
 9905: }
 9906: 
 9907: my $LClastpercent;
 9908: my $LCidcnt;
 9909: my $LCcurrentid;
 9910: 
 9911: sub LCprogressbar {
 9912:     my ($r,$number_to_do,$preamble)=@_;
 9913:     $LClastpercent=0;
 9914:     $LCidcnt++;
 9915:     $LCcurrentid=$$.'_'.$LCidcnt;
 9916:     my ($starting,$content);
 9917:     if ($number_to_do) {
 9918:         $starting=&mt('Starting');
 9919:         $content=(<<ENDPROGBAR);
 9920: $preamble
 9921:   <div id="progressbar$LCcurrentid">
 9922:     <span class="pblabel">$starting</span>
 9923:   </div>
 9924: ENDPROGBAR
 9925:     } else {
 9926:         $starting=&mt('Loading...');
 9927:         $LClastpercent='false';
 9928:         $content=(<<ENDPROGBAR);
 9929: $preamble
 9930:   <div id="progressbar$LCcurrentid">
 9931:       <div class="progress-label">$starting</div>
 9932:   </div>
 9933: ENDPROGBAR
 9934:     }
 9935:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9936: }
 9937: 
 9938: sub LCprogressbarUpdate {
 9939:     my ($r,$val,$text,$number_to_do)=@_;
 9940:     if ($number_to_do) {
 9941:         unless ($val) { 
 9942:             if ($LClastpercent) {
 9943:                 $val=$LClastpercent;
 9944:             } else {
 9945:                 $val=0;
 9946:             }
 9947:         }
 9948:         if ($val<0) { $val=0; }
 9949:         if ($val>100) { $val=0; }
 9950:         $LClastpercent=$val;
 9951:         unless ($text) { $text=$val.'%'; }
 9952:     } else {
 9953:         $val = 'false';
 9954:     }
 9955:     $text=&js_ready($text);
 9956:     &r_print($r,<<ENDUPDATE);
 9957: <script type="text/javascript">
 9958: // <![CDATA[
 9959: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9960: // ]]>
 9961: </script>
 9962: ENDUPDATE
 9963: }
 9964: 
 9965: sub LCprogressbarClose {
 9966:     my ($r)=@_;
 9967:     $LClastpercent=0;
 9968:     &r_print($r,<<ENDCLOSE);
 9969: <script type="text/javascript">
 9970: // <![CDATA[
 9971: \$("#progressbar$LCcurrentid").hide('slow'); 
 9972: // ]]>
 9973: </script>
 9974: ENDCLOSE
 9975: }
 9976: 
 9977: sub r_print {
 9978:     my ($r,$to_print)=@_;
 9979:     if ($r) {
 9980:       $r->print($to_print);
 9981:       $r->rflush();
 9982:     } else {
 9983:       print($to_print);
 9984:     }
 9985: }
 9986: 
 9987: sub html_encode {
 9988:     my ($result) = @_;
 9989: 
 9990:     $result = &HTML::Entities::encode($result,'<>&"');
 9991:     
 9992:     return $result;
 9993: }
 9994: 
 9995: sub js_ready {
 9996:     my ($result) = @_;
 9997: 
 9998:     $result =~ s/[\n\r]/ /xmsg;
 9999:     $result =~ s/\\/\\\\/xmsg;
10000:     $result =~ s/'/\\'/xmsg;
10001:     $result =~ s{</}{<\\/}xmsg;
10002:     
10003:     return $result;
10004: }
10005: 
10006: sub validate_page {
10007:     if (  exists($env{'internal.start_page'})
10008: 	  &&     $env{'internal.start_page'} > 1) {
10009: 	&Apache::lonnet::logthis('start_page called multiple times '.
10010: 				 $env{'internal.start_page'}.' '.
10011: 				 $ENV{'request.filename'});
10012:     }
10013:     if (  exists($env{'internal.end_page'})
10014: 	  &&     $env{'internal.end_page'} > 1) {
10015: 	&Apache::lonnet::logthis('end_page called multiple times '.
10016: 				 $env{'internal.end_page'}.' '.
10017: 				 $env{'request.filename'});
10018:     }
10019:     if (     exists($env{'internal.start_page'})
10020: 	&& ! exists($env{'internal.end_page'})) {
10021: 	&Apache::lonnet::logthis('start_page called without end_page '.
10022: 				 $env{'request.filename'});
10023:     }
10024:     if (   ! exists($env{'internal.start_page'})
10025: 	&&   exists($env{'internal.end_page'})) {
10026: 	&Apache::lonnet::logthis('end_page called without start_page'.
10027: 				 $env{'request.filename'});
10028:     }
10029: }
10030: 
10031: 
10032: sub start_scrollbox {
10033:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10034:     unless ($outerwidth) { $outerwidth='520px'; }
10035:     unless ($width) { $width='500px'; }
10036:     unless ($height) { $height='200px'; }
10037:     my ($table_id,$div_id,$tdcol);
10038:     if ($id ne '') {
10039:         $table_id = ' id="table_'.$id.'"';
10040:         $div_id = ' id="div_'.$id.'"';
10041:     }
10042:     if ($bgcolor ne '') {
10043:         $tdcol = "background-color: $bgcolor;";
10044:     }
10045:     my $nicescroll_js;
10046:     if ($env{'browser.mobile'}) {
10047:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10048:     }
10049:     return <<"END";
10050: $nicescroll_js
10051: 
10052: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10053: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10054: END
10055: }
10056: 
10057: sub end_scrollbox {
10058:     return '</div></td></tr></table>';
10059: }
10060: 
10061: sub nicescroll_javascript {
10062:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10063:     my %options;
10064:     if (ref($cursor) eq 'HASH') {
10065:         %options = %{$cursor};
10066:     }
10067:     unless ($options{'railalign'} =~ /^left|right$/) {
10068:         $options{'railalign'} = 'left';
10069:     }
10070:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10071:         my $function  = &get_users_function();
10072:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10073:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10074:             $options{'cursorcolor'} = '#00F';
10075:         }
10076:     }
10077:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10078:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10079:             $options{'cursoropacity'}='1.0';
10080:         }
10081:     } else {
10082:         $options{'cursoropacity'}='1.0';
10083:     }
10084:     if ($options{'cursorfixedheight'} eq 'none') {
10085:         delete($options{'cursorfixedheight'});
10086:     } else {
10087:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10088:     }
10089:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10090:         delete($options{'railoffset'});
10091:     }
10092:     my @niceoptions;
10093:     while (my($key,$value) = each(%options)) {
10094:         if ($value =~ /^\{.+\}$/) {
10095:             push(@niceoptions,$key.':'.$value);
10096:         } else {
10097:             push(@niceoptions,$key.':"'.$value.'"');
10098:         }
10099:     }
10100:     my $nicescroll_js = '
10101: $(document).ready(
10102:       function() {
10103:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10104:       }
10105: );
10106: ';
10107:     if ($framecheck) {
10108:         $nicescroll_js .= '
10109: function expand_div(caller) {
10110:     if (top === self) {
10111:         document.getElementById("'.$id.'").style.width = "auto";
10112:         document.getElementById("'.$id.'").style.height = "auto";
10113:     } else {
10114:         try {
10115:             if (parent.frames) {
10116:                 if (parent.frames.length > 1) {
10117:                     var framesrc = parent.frames[1].location.href;
10118:                     var currsrc = framesrc.replace(/\#.*$/,"");
10119:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10120:                         document.getElementById("'.$id.'").style.width = "auto";
10121:                         document.getElementById("'.$id.'").style.height = "auto";
10122:                     }
10123:                 }
10124:             }
10125:         } catch (e) {
10126:             return;
10127:         }
10128:     }
10129:     return;
10130: }
10131: ';
10132:     }
10133:     if ($needjsready) {
10134:         $nicescroll_js = '
10135: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10136:     } else {
10137:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10138:     }
10139:     return $nicescroll_js;
10140: }
10141: 
10142: sub simple_error_page {
10143:     my ($r,$title,$msg,$args) = @_;
10144:     my %displayargs;
10145:     if (ref($args) eq 'HASH') {
10146:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10147:         if ($args->{'only_body'}) {
10148:             $displayargs{'only_body'} = 1;
10149:         }
10150:         if ($args->{'no_nav_bar'}) {
10151:             $displayargs{'no_nav_bar'} = 1;
10152:         }
10153:     } else {
10154:         $msg = &mt($msg);
10155:     }
10156: 
10157:     my $page =
10158: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10159: 	'<p class="LC_error">'.$msg.'</p>'.
10160: 	&Apache::loncommon::end_page();
10161:     if (ref($r)) {
10162: 	$r->print($page);
10163: 	return;
10164:     }
10165:     return $page;
10166: }
10167: 
10168: {
10169:     my @row_count;
10170: 
10171:     sub start_data_table_count {
10172:         unshift(@row_count, 0);
10173:         return;
10174:     }
10175: 
10176:     sub end_data_table_count {
10177:         shift(@row_count);
10178:         return;
10179:     }
10180: 
10181:     sub start_data_table {
10182: 	my ($add_class,$id) = @_;
10183: 	my $css_class = (join(' ','LC_data_table',$add_class));
10184:         my $table_id;
10185:         if (defined($id)) {
10186:             $table_id = ' id="'.$id.'"';
10187:         }
10188: 	&start_data_table_count();
10189: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10190:     }
10191: 
10192:     sub end_data_table {
10193: 	&end_data_table_count();
10194: 	return '</table>'."\n";;
10195:     }
10196: 
10197:     sub start_data_table_row {
10198: 	my ($add_class, $id) = @_;
10199: 	$row_count[0]++;
10200: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10201: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10202:         $id = (' id="'.$id.'"') unless ($id eq '');
10203:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10204:     }
10205:     
10206:     sub continue_data_table_row {
10207: 	my ($add_class, $id) = @_;
10208: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10209: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10210:         $id = (' id="'.$id.'"') unless ($id eq '');
10211:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10212:     }
10213: 
10214:     sub end_data_table_row {
10215: 	return '</tr>'."\n";;
10216:     }
10217: 
10218:     sub start_data_table_empty_row {
10219: #	$row_count[0]++;
10220: 	return  '<tr class="LC_empty_row" >'."\n";;
10221:     }
10222: 
10223:     sub end_data_table_empty_row {
10224: 	return '</tr>'."\n";;
10225:     }
10226: 
10227:     sub start_data_table_header_row {
10228: 	return  '<tr class="LC_header_row">'."\n";;
10229:     }
10230: 
10231:     sub end_data_table_header_row {
10232: 	return '</tr>'."\n";;
10233:     }
10234: 
10235:     sub data_table_caption {
10236:         my $caption = shift;
10237:         return "<caption class=\"LC_caption\">$caption</caption>";
10238:     }
10239: }
10240: 
10241: =pod
10242: 
10243: =item * &inhibit_menu_check($arg)
10244: 
10245: Checks for a inhibitmenu state and generates output to preserve it
10246: 
10247: Inputs:         $arg - can be any of
10248:                      - undef - in which case the return value is a string 
10249:                                to add  into arguments list of a uri
10250:                      - 'input' - in which case the return value is a HTML
10251:                                  <form> <input> field of type hidden to
10252:                                  preserve the value
10253:                      - a url - in which case the return value is the url with
10254:                                the neccesary cgi args added to preserve the
10255:                                inhibitmenu state
10256:                      - a ref to a url - no return value, but the string is
10257:                                         updated to include the neccessary cgi
10258:                                         args to preserve the inhibitmenu state
10259: 
10260: =cut
10261: 
10262: sub inhibit_menu_check {
10263:     my ($arg) = @_;
10264:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10265:     if ($arg eq 'input') {
10266: 	if ($env{'form.inhibitmenu'}) {
10267: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10268: 	} else {
10269: 	    return
10270: 	}
10271:     }
10272:     if ($env{'form.inhibitmenu'}) {
10273: 	if (ref($arg)) {
10274: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10275: 	} elsif ($arg eq '') {
10276: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10277: 	} else {
10278: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10279: 	}
10280:     }
10281:     if (!ref($arg)) {
10282: 	return $arg;
10283:     }
10284: }
10285: 
10286: ###############################################
10287: 
10288: =pod
10289: 
10290: =back
10291: 
10292: =head1 User Information Routines
10293: 
10294: =over 4
10295: 
10296: =item * &get_users_function()
10297: 
10298: Used by &bodytag to determine the current users primary role.
10299: Returns either 'student','coordinator','admin', or 'author'.
10300: 
10301: =cut
10302: 
10303: ###############################################
10304: sub get_users_function {
10305:     my $function = 'norole';
10306:     if ($env{'request.role'}=~/^(st)/) {
10307:         $function='student';
10308:     }
10309:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10310:         $function='coordinator';
10311:     }
10312:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10313:         $function='admin';
10314:     }
10315:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10316:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10317:         $function='author';
10318:     }
10319:     return $function;
10320: }
10321: 
10322: ###############################################
10323: 
10324: =pod
10325: 
10326: =item * &show_course()
10327: 
10328: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10329: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10330: 
10331: Inputs:
10332: None
10333: 
10334: Outputs:
10335: Scalar: 1 if 'Course' to be used, 0 otherwise.
10336: 
10337: =cut
10338: 
10339: ###############################################
10340: sub show_course {
10341:     my $course = !$env{'user.adv'};
10342:     if (!$env{'user.adv'}) {
10343:         foreach my $env (keys(%env)) {
10344:             next if ($env !~ m/^user\.priv\./);
10345:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10346:                 $course = 0;
10347:                 last;
10348:             }
10349:         }
10350:     }
10351:     return $course;
10352: }
10353: 
10354: ###############################################
10355: 
10356: =pod
10357: 
10358: =item * &check_user_status()
10359: 
10360: Determines current status of supplied role for a
10361: specific user. Roles can be active, previous or future.
10362: 
10363: Inputs: 
10364: user's domain, user's username, course's domain,
10365: course's number, optional section ID.
10366: 
10367: Outputs:
10368: role status: active, previous or future. 
10369: 
10370: =cut
10371: 
10372: sub check_user_status {
10373:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10374:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10375:     my @uroles = keys(%userinfo);
10376:     my $srchstr;
10377:     my $active_chk = 'none';
10378:     my $now = time;
10379:     if (@uroles > 0) {
10380:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10381:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10382:         } else {
10383:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10384:         }
10385:         if (grep/^\Q$srchstr\E$/,@uroles) {
10386:             my $role_end = 0;
10387:             my $role_start = 0;
10388:             $active_chk = 'active';
10389:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10390:                 $role_end = $1;
10391:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10392:                     $role_start = $1;
10393:                 }
10394:             }
10395:             if ($role_start > 0) {
10396:                 if ($now < $role_start) {
10397:                     $active_chk = 'future';
10398:                 }
10399:             }
10400:             if ($role_end > 0) {
10401:                 if ($now > $role_end) {
10402:                     $active_chk = 'previous';
10403:                 }
10404:             }
10405:         }
10406:     }
10407:     return $active_chk;
10408: }
10409: 
10410: ###############################################
10411: 
10412: =pod
10413: 
10414: =item * &get_sections()
10415: 
10416: Determines all the sections for a course including
10417: sections with students and sections containing other roles.
10418: Incoming parameters: 
10419: 
10420: 1. domain
10421: 2. course number 
10422: 3. reference to array containing roles for which sections should 
10423: be gathered (optional).
10424: 4. reference to array containing status types for which sections 
10425: should be gathered (optional).
10426: 
10427: If the third argument is undefined, sections are gathered for any role. 
10428: If the fourth argument is undefined, sections are gathered for any status.
10429: Permissible values are 'active' or 'future' or 'previous'.
10430:  
10431: Returns section hash (keys are section IDs, values are
10432: number of users in each section), subject to the
10433: optional roles filter, optional status filter 
10434: 
10435: =cut
10436: 
10437: ###############################################
10438: sub get_sections {
10439:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10440:     if (!defined($cdom) || !defined($cnum)) {
10441:         my $cid =  $env{'request.course.id'};
10442: 
10443: 	return if (!defined($cid));
10444: 
10445:         $cdom = $env{'course.'.$cid.'.domain'};
10446:         $cnum = $env{'course.'.$cid.'.num'};
10447:     }
10448: 
10449:     my %sectioncount;
10450:     my $now = time;
10451: 
10452:     my $check_students = 1;
10453:     my $only_students = 0;
10454:     if (ref($possible_roles) eq 'ARRAY') {
10455:         if (grep(/^st$/,@{$possible_roles})) {
10456:             if (@{$possible_roles} == 1) {
10457:                 $only_students = 1;
10458:             }
10459:         } else {
10460:             $check_students = 0;
10461:         }
10462:     }
10463: 
10464:     if ($check_students) { 
10465: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10466: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10467: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10468:         my $start_index = &Apache::loncoursedata::CL_START();
10469:         my $end_index = &Apache::loncoursedata::CL_END();
10470:         my $status;
10471: 	while (my ($student,$data) = each(%$classlist)) {
10472: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10473: 				                     $data->[$status_index],
10474:                                                      $data->[$start_index],
10475:                                                      $data->[$end_index]);
10476:             if ($stu_status eq 'Active') {
10477:                 $status = 'active';
10478:             } elsif ($end < $now) {
10479:                 $status = 'previous';
10480:             } elsif ($start > $now) {
10481:                 $status = 'future';
10482:             } 
10483: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10484:                 if ((!defined($possible_status)) || (($status ne '') && 
10485:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10486: 		    $sectioncount{$section}++;
10487:                 }
10488: 	    }
10489: 	}
10490:     }
10491:     if ($only_students) {
10492:         return %sectioncount;
10493:     }
10494:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10495:     foreach my $user (sort(keys(%courseroles))) {
10496: 	if ($user !~ /^(\w{2})/) { next; }
10497: 	my ($role) = ($user =~ /^(\w{2})/);
10498: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10499: 	my ($section,$status);
10500: 	if ($role eq 'cr' &&
10501: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10502: 	    $section=$1;
10503: 	}
10504: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10505: 	if (!defined($section) || $section eq '-1') { next; }
10506:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10507:         if ($end == -1 && $start == -1) {
10508:             next; #deleted role
10509:         }
10510:         if (!defined($possible_status)) { 
10511:             $sectioncount{$section}++;
10512:         } else {
10513:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10514:                 $status = 'active';
10515:             } elsif ($end < $now) {
10516:                 $status = 'future';
10517:             } elsif ($start > $now) {
10518:                 $status = 'previous';
10519:             }
10520:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10521:                 $sectioncount{$section}++;
10522:             }
10523:         }
10524:     }
10525:     return %sectioncount;
10526: }
10527: 
10528: ###############################################
10529: 
10530: =pod
10531: 
10532: =item * &get_course_users()
10533: 
10534: Retrieves usernames:domains for users in the specified course
10535: with specific role(s), and access status. 
10536: 
10537: Incoming parameters:
10538: 1. course domain
10539: 2. course number
10540: 3. access status: users must have - either active, 
10541: previous, future, or all.
10542: 4. reference to array of permissible roles
10543: 5. reference to array of section restrictions (optional)
10544: 6. reference to results object (hash of hashes).
10545: 7. reference to optional userdata hash
10546: 8. reference to optional statushash
10547: 9. flag if privileged users (except those set to unhide in
10548:    course settings) should be excluded    
10549: Keys of top level results hash are roles.
10550: Keys of inner hashes are username:domain, with 
10551: values set to access type.
10552: Optional userdata hash returns an array with arguments in the 
10553: same order as loncoursedata::get_classlist() for student data.
10554: 
10555: Optional statushash returns
10556: 
10557: Entries for end, start, section and status are blank because
10558: of the possibility of multiple values for non-student roles.
10559: 
10560: =cut
10561: 
10562: ###############################################
10563: 
10564: sub get_course_users {
10565:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10566:     my %idx = ();
10567:     my %seclists;
10568: 
10569:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10570:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10571:     $idx{end} = &Apache::loncoursedata::CL_END();
10572:     $idx{start} = &Apache::loncoursedata::CL_START();
10573:     $idx{id} = &Apache::loncoursedata::CL_ID();
10574:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10575:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10576:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10577: 
10578:     if (grep(/^st$/,@{$roles})) {
10579:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10580:         my $now = time;
10581:         foreach my $student (keys(%{$classlist})) {
10582:             my $match = 0;
10583:             my $secmatch = 0;
10584:             my $section = $$classlist{$student}[$idx{section}];
10585:             my $status = $$classlist{$student}[$idx{status}];
10586:             if ($section eq '') {
10587:                 $section = 'none';
10588:             }
10589:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10590:                 if (grep(/^all$/,@{$sections})) {
10591:                     $secmatch = 1;
10592:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10593:                     if (grep(/^none$/,@{$sections})) {
10594:                         $secmatch = 1;
10595:                     }
10596:                 } else {  
10597: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10598: 		        $secmatch = 1;
10599:                     }
10600: 		}
10601:                 if (!$secmatch) {
10602:                     next;
10603:                 }
10604:             }
10605:             if (defined($$types{'active'})) {
10606:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10607:                     push(@{$$users{st}{$student}},'active');
10608:                     $match = 1;
10609:                 }
10610:             }
10611:             if (defined($$types{'previous'})) {
10612:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10613:                     push(@{$$users{st}{$student}},'previous');
10614:                     $match = 1;
10615:                 }
10616:             }
10617:             if (defined($$types{'future'})) {
10618:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10619:                     push(@{$$users{st}{$student}},'future');
10620:                     $match = 1;
10621:                 }
10622:             }
10623:             if ($match) {
10624:                 push(@{$seclists{$student}},$section);
10625:                 if (ref($userdata) eq 'HASH') {
10626:                     $$userdata{$student} = $$classlist{$student};
10627:                 }
10628:                 if (ref($statushash) eq 'HASH') {
10629:                     $statushash->{$student}{'st'}{$section} = $status;
10630:                 }
10631:             }
10632:         }
10633:     }
10634:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10635:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10636:         my $now = time;
10637:         my %displaystatus = ( previous => 'Expired',
10638:                               active   => 'Active',
10639:                               future   => 'Future',
10640:                             );
10641:         my (%nothide,@possdoms);
10642:         if ($hidepriv) {
10643:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10644:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10645:                 if ($user !~ /:/) {
10646:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10647:                 } else {
10648:                     $nothide{$user} = 1;
10649:                 }
10650:             }
10651:             my @possdoms = ($cdom);
10652:             if ($coursehash{'checkforpriv'}) {
10653:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10654:             }
10655:         }
10656:         foreach my $person (sort(keys(%coursepersonnel))) {
10657:             my $match = 0;
10658:             my $secmatch = 0;
10659:             my $status;
10660:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10661:             $user =~ s/:$//;
10662:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10663:             if ($end == -1 || $start == -1) {
10664:                 next;
10665:             }
10666:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10667:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10668:                 my ($uname,$udom) = split(/:/,$user);
10669:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10670:                     if (grep(/^all$/,@{$sections})) {
10671:                         $secmatch = 1;
10672:                     } elsif ($usec eq '') {
10673:                         if (grep(/^none$/,@{$sections})) {
10674:                             $secmatch = 1;
10675:                         }
10676:                     } else {
10677:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10678:                             $secmatch = 1;
10679:                         }
10680:                     }
10681:                     if (!$secmatch) {
10682:                         next;
10683:                     }
10684:                 }
10685:                 if ($usec eq '') {
10686:                     $usec = 'none';
10687:                 }
10688:                 if ($uname ne '' && $udom ne '') {
10689:                     if ($hidepriv) {
10690:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10691:                             (!$nothide{$uname.':'.$udom})) {
10692:                             next;
10693:                         }
10694:                     }
10695:                     if ($end > 0 && $end < $now) {
10696:                         $status = 'previous';
10697:                     } elsif ($start > $now) {
10698:                         $status = 'future';
10699:                     } else {
10700:                         $status = 'active';
10701:                     }
10702:                     foreach my $type (keys(%{$types})) { 
10703:                         if ($status eq $type) {
10704:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10705:                                 push(@{$$users{$role}{$user}},$type);
10706:                             }
10707:                             $match = 1;
10708:                         }
10709:                     }
10710:                     if (($match) && (ref($userdata) eq 'HASH')) {
10711:                         if (!exists($$userdata{$uname.':'.$udom})) {
10712: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10713:                         }
10714:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10715:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10716:                         }
10717:                         if (ref($statushash) eq 'HASH') {
10718:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10719:                         }
10720:                     }
10721:                 }
10722:             }
10723:         }
10724:         if (grep(/^ow$/,@{$roles})) {
10725:             if ((defined($cdom)) && (defined($cnum))) {
10726:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10727:                 if ( defined($csettings{'internal.courseowner'}) ) {
10728:                     my $owner = $csettings{'internal.courseowner'};
10729:                     next if ($owner eq '');
10730:                     my ($ownername,$ownerdom);
10731:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10732:                         $ownername = $1;
10733:                         $ownerdom = $2;
10734:                     } else {
10735:                         $ownername = $owner;
10736:                         $ownerdom = $cdom;
10737:                         $owner = $ownername.':'.$ownerdom;
10738:                     }
10739:                     @{$$users{'ow'}{$owner}} = 'any';
10740:                     if (defined($userdata) && 
10741: 			!exists($$userdata{$owner})) {
10742: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10743:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10744:                             push(@{$seclists{$owner}},'none');
10745:                         }
10746:                         if (ref($statushash) eq 'HASH') {
10747:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10748:                         }
10749: 		    }
10750:                 }
10751:             }
10752:         }
10753:         foreach my $user (keys(%seclists)) {
10754:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10755:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10756:         }
10757:     }
10758:     return;
10759: }
10760: 
10761: sub get_user_info {
10762:     my ($udom,$uname,$idx,$userdata) = @_;
10763:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10764: 	&plainname($uname,$udom,'lastname');
10765:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10766:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10767:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10768:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10769:     return;
10770: }
10771: 
10772: ###############################################
10773: 
10774: =pod
10775: 
10776: =item * &get_user_quota()
10777: 
10778: Retrieves quota assigned for storage of user files.
10779: Default is to report quota for portfolio files.
10780: 
10781: Incoming parameters:
10782: 1. user's username
10783: 2. user's domain
10784: 3. quota name - portfolio, author, or course
10785:    (if no quota name provided, defaults to portfolio).
10786: 4. crstype - official, unofficial, textbook, placement or community, 
10787:    if quota name is course
10788: 
10789: Returns:
10790: 1. Disk quota (in MB) assigned to student.
10791: 2. (Optional) Type of setting: custom or default
10792:    (individually assigned or default for user's 
10793:    institutional status).
10794: 3. (Optional) - User's institutional status (e.g., faculty, staff
10795:    or student - types as defined in localenroll::inst_usertypes 
10796:    for user's domain, which determines default quota for user.
10797: 4. (Optional) - Default quota which would apply to the user.
10798: 
10799: If a value has been stored in the user's environment, 
10800: it will return that, otherwise it returns the maximal default
10801: defined for the user's institutional status(es) in the domain.
10802: 
10803: =cut
10804: 
10805: ###############################################
10806: 
10807: 
10808: sub get_user_quota {
10809:     my ($uname,$udom,$quotaname,$crstype) = @_;
10810:     my ($quota,$quotatype,$settingstatus,$defquota);
10811:     if (!defined($udom)) {
10812:         $udom = $env{'user.domain'};
10813:     }
10814:     if (!defined($uname)) {
10815:         $uname = $env{'user.name'};
10816:     }
10817:     if (($udom eq '' || $uname eq '') ||
10818:         ($udom eq 'public') && ($uname eq 'public')) {
10819:         $quota = 0;
10820:         $quotatype = 'default';
10821:         $defquota = 0; 
10822:     } else {
10823:         my $inststatus;
10824:         if ($quotaname eq 'course') {
10825:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10826:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10827:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10828:             } else {
10829:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10830:                 $quota = $cenv{'internal.uploadquota'};
10831:             }
10832:         } else {
10833:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10834:                 if ($quotaname eq 'author') {
10835:                     $quota = $env{'environment.authorquota'};
10836:                 } else {
10837:                     $quota = $env{'environment.portfolioquota'};
10838:                 }
10839:                 $inststatus = $env{'environment.inststatus'};
10840:             } else {
10841:                 my %userenv = 
10842:                     &Apache::lonnet::get('environment',['portfolioquota',
10843:                                          'authorquota','inststatus'],$udom,$uname);
10844:                 my ($tmp) = keys(%userenv);
10845:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10846:                     if ($quotaname eq 'author') {
10847:                         $quota = $userenv{'authorquota'};
10848:                     } else {
10849:                         $quota = $userenv{'portfolioquota'};
10850:                     }
10851:                     $inststatus = $userenv{'inststatus'};
10852:                 } else {
10853:                     undef(%userenv);
10854:                 }
10855:             }
10856:         }
10857:         if ($quota eq '' || wantarray) {
10858:             if ($quotaname eq 'course') {
10859:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10860:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
10861:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
10862:                     ($crstype eq 'placement')) { 
10863:                     $defquota = $domdefs{$crstype.'quota'};
10864:                 }
10865:                 if ($defquota eq '') {
10866:                     $defquota = 500;
10867:                 }
10868:             } else {
10869:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10870:             }
10871:             if ($quota eq '') {
10872:                 $quota = $defquota;
10873:                 $quotatype = 'default';
10874:             } else {
10875:                 $quotatype = 'custom';
10876:             }
10877:         }
10878:     }
10879:     if (wantarray) {
10880:         return ($quota,$quotatype,$settingstatus,$defquota);
10881:     } else {
10882:         return $quota;
10883:     }
10884: }
10885: 
10886: ###############################################
10887: 
10888: =pod
10889: 
10890: =item * &default_quota()
10891: 
10892: Retrieves default quota assigned for storage of user portfolio files,
10893: given an (optional) user's institutional status.
10894: 
10895: Incoming parameters:
10896: 
10897: 1. domain
10898: 2. (Optional) institutional status(es).  This is a : separated list of 
10899:    status types (e.g., faculty, staff, student etc.)
10900:    which apply to the user for whom the default is being retrieved.
10901:    If the institutional status string in undefined, the domain
10902:    default quota will be returned.
10903: 3.  quota name - portfolio, author, or course
10904:    (if no quota name provided, defaults to portfolio).
10905: 
10906: Returns:
10907: 
10908: 1. Default disk quota (in MB) for user portfolios in the domain.
10909: 2. (Optional) institutional type which determined the value of the
10910:    default quota.
10911: 
10912: If a value has been stored in the domain's configuration db,
10913: it will return that, otherwise it returns 20 (for backwards 
10914: compatibility with domains which have not set up a configuration
10915: db file; the original statically defined portfolio quota was 20 MB). 
10916: 
10917: If the user's status includes multiple types (e.g., staff and student),
10918: the largest default quota which applies to the user determines the
10919: default quota returned.
10920: 
10921: =cut
10922: 
10923: ###############################################
10924: 
10925: 
10926: sub default_quota {
10927:     my ($udom,$inststatus,$quotaname) = @_;
10928:     my ($defquota,$settingstatus);
10929:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10930:                                             ['quotas'],$udom);
10931:     my $key = 'defaultquota';
10932:     if ($quotaname eq 'author') {
10933:         $key = 'authorquota';
10934:     }
10935:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10936:         if ($inststatus ne '') {
10937:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10938:             foreach my $item (@statuses) {
10939:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10940:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10941:                         if ($defquota eq '') {
10942:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10943:                             $settingstatus = $item;
10944:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10945:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10946:                             $settingstatus = $item;
10947:                         }
10948:                     }
10949:                 } elsif ($key eq 'defaultquota') {
10950:                     if ($quotahash{'quotas'}{$item} ne '') {
10951:                         if ($defquota eq '') {
10952:                             $defquota = $quotahash{'quotas'}{$item};
10953:                             $settingstatus = $item;
10954:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10955:                             $defquota = $quotahash{'quotas'}{$item};
10956:                             $settingstatus = $item;
10957:                         }
10958:                     }
10959:                 }
10960:             }
10961:         }
10962:         if ($defquota eq '') {
10963:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10964:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10965:             } elsif ($key eq 'defaultquota') {
10966:                 $defquota = $quotahash{'quotas'}{'default'};
10967:             }
10968:             $settingstatus = 'default';
10969:             if ($defquota eq '') {
10970:                 if ($quotaname eq 'author') {
10971:                     $defquota = 500;
10972:                 }
10973:             }
10974:         }
10975:     } else {
10976:         $settingstatus = 'default';
10977:         if ($quotaname eq 'author') {
10978:             $defquota = 500;
10979:         } else {
10980:             $defquota = 20;
10981:         }
10982:     }
10983:     if (wantarray) {
10984:         return ($defquota,$settingstatus);
10985:     } else {
10986:         return $defquota;
10987:     }
10988: }
10989: 
10990: ###############################################
10991: 
10992: =pod
10993: 
10994: =item * &excess_filesize_warning()
10995: 
10996: Returns warning message if upload of file to authoring space, or copying
10997: of existing file within authoring space will cause quota for the authoring
10998: space to be exceeded.
10999: 
11000: Same, if upload of a file directly to a course/community via Course Editor
11001: will cause quota for uploaded content for the course to be exceeded.
11002: 
11003: Inputs: 7 
11004: 1. username or coursenum
11005: 2. domain
11006: 3. context ('author' or 'course')
11007: 4. filename of file for which action is being requested
11008: 5. filesize (kB) of file
11009: 6. action being taken: copy or upload.
11010: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11011: 
11012: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11013:          otherwise return null.
11014: 
11015: =back
11016: 
11017: =cut
11018: 
11019: sub excess_filesize_warning {
11020:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11021:     my $current_disk_usage = 0;
11022:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11023:     if ($context eq 'author') {
11024:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11025:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11026:     } else {
11027:         foreach my $subdir ('docs','supplemental') {
11028:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11029:         }
11030:     }
11031:     $disk_quota = int($disk_quota * 1000);
11032:     if (($current_disk_usage + $filesize) > $disk_quota) {
11033:         return '<p class="LC_warning">'.
11034:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11035:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11036:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11037:                             $disk_quota,$current_disk_usage).
11038:                '</p>';
11039:     }
11040:     return;
11041: }
11042: 
11043: ###############################################
11044: 
11045: 
11046: 
11047: 
11048: sub get_secgrprole_info {
11049:     my ($cdom,$cnum,$needroles,$type)  = @_;
11050:     my %sections_count = &get_sections($cdom,$cnum);
11051:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11052:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11053:     my @groups = sort(keys(%curr_groups));
11054:     my $allroles = [];
11055:     my $rolehash;
11056:     my $accesshash = {
11057:                      active => 'Currently has access',
11058:                      future => 'Will have future access',
11059:                      previous => 'Previously had access',
11060:                   };
11061:     if ($needroles) {
11062:         $rolehash = {'all' => 'all'};
11063:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11064: 	if (&Apache::lonnet::error(%user_roles)) {
11065: 	    undef(%user_roles);
11066: 	}
11067:         foreach my $item (keys(%user_roles)) {
11068:             my ($role)=split(/\:/,$item,2);
11069:             if ($role eq 'cr') { next; }
11070:             if ($role =~ /^cr/) {
11071:                 $$rolehash{$role} = (split('/',$role))[3];
11072:             } else {
11073:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11074:             }
11075:         }
11076:         foreach my $key (sort(keys(%{$rolehash}))) {
11077:             push(@{$allroles},$key);
11078:         }
11079:         push (@{$allroles},'st');
11080:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11081:     }
11082:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11083: }
11084: 
11085: sub user_picker {
11086:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11087:     my $currdom = $dom;
11088:     my @alldoms = &Apache::lonnet::all_domains();
11089:     if (@alldoms == 1) {
11090:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11091:                                                ['directorysrch'],$alldoms[0]);
11092:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11093:         my $showdom = $domdesc;
11094:         if ($showdom eq '') {
11095:             $showdom = $dom;
11096:         }
11097:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11098:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11099:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11100:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11101:             }
11102:         }
11103:     }
11104:     my %curr_selected = (
11105:                         srchin => 'dom',
11106:                         srchby => 'lastname',
11107:                       );
11108:     my $srchterm;
11109:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11110:         if ($srch->{'srchby'} ne '') {
11111:             $curr_selected{'srchby'} = $srch->{'srchby'};
11112:         }
11113:         if ($srch->{'srchin'} ne '') {
11114:             $curr_selected{'srchin'} = $srch->{'srchin'};
11115:         }
11116:         if ($srch->{'srchtype'} ne '') {
11117:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11118:         }
11119:         if ($srch->{'srchdomain'} ne '') {
11120:             $currdom = $srch->{'srchdomain'};
11121:         }
11122:         $srchterm = $srch->{'srchterm'};
11123:     }
11124:     my %html_lt=&Apache::lonlocal::texthash(
11125:                     'usr'       => 'Search criteria',
11126:                     'doma'      => 'Domain/institution to search',
11127:                     'uname'     => 'username',
11128:                     'lastname'  => 'last name',
11129:                     'lastfirst' => 'last name, first name',
11130:                     'crs'       => 'in this course',
11131:                     'dom'       => 'in selected LON-CAPA domain', 
11132:                     'alc'       => 'all LON-CAPA',
11133:                     'instd'     => 'in institutional directory for selected domain',
11134:                     'exact'     => 'is',
11135:                     'contains'  => 'contains',
11136:                     'begins'    => 'begins with',
11137:                                        );
11138:     my %js_lt=&Apache::lonlocal::texthash(
11139:                     'youm'      => "You must include some text to search for.",
11140:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11141:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11142:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11143:                     'ymcd'      => "You must choose a domain when using a domain search.",
11144:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11145:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11146:                      'thfo'     => "The following need to be corrected before the search can be run:",
11147:                                        );
11148:     &html_escape(\%html_lt);
11149:     &js_escape(\%js_lt);
11150:     my $domform;
11151:     my $allow_blank = 1;
11152:     if ($fixeddom) {
11153:         $allow_blank = 0;
11154:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11155:     } else {
11156:         my $defdom = $env{'request.role.domain'};
11157:         my ($trusted,$untrusted);
11158:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11159:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11160:         } elsif ($context eq 'author') {
11161:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11162:         } elsif ($context eq 'domain') {
11163:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11164:         }
11165:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11166:     }
11167:     my $srchinsel = ' <select name="srchin">';
11168: 
11169:     my @srchins = ('crs','dom','alc','instd');
11170: 
11171:     foreach my $option (@srchins) {
11172:         # FIXME 'alc' option unavailable until 
11173:         #       loncreateuser::print_user_query_page()
11174:         #       has been completed.
11175:         next if ($option eq 'alc');
11176:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11177:         next if ($option eq 'crs' && !$env{'request.course.id'});
11178:         next if (($option eq 'instd') && ($noinstd));
11179:         if ($curr_selected{'srchin'} eq $option) {
11180:             $srchinsel .= ' 
11181:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11182:         } else {
11183:             $srchinsel .= '
11184:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11185:         }
11186:     }
11187:     $srchinsel .= "\n  </select>\n";
11188: 
11189:     my $srchbysel =  ' <select name="srchby">';
11190:     foreach my $option ('lastname','lastfirst','uname') {
11191:         if ($curr_selected{'srchby'} eq $option) {
11192:             $srchbysel .= '
11193:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11194:         } else {
11195:             $srchbysel .= '
11196:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11197:          }
11198:     }
11199:     $srchbysel .= "\n  </select>\n";
11200: 
11201:     my $srchtypesel = ' <select name="srchtype">';
11202:     foreach my $option ('begins','contains','exact') {
11203:         if ($curr_selected{'srchtype'} eq $option) {
11204:             $srchtypesel .= '
11205:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11206:         } else {
11207:             $srchtypesel .= '
11208:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11209:         }
11210:     }
11211:     $srchtypesel .= "\n  </select>\n";
11212: 
11213:     my ($newuserscript,$new_user_create);
11214:     my $context_dom = $env{'request.role.domain'};
11215:     if ($context eq 'requestcrs') {
11216:         if ($env{'form.coursedom'} ne '') { 
11217:             $context_dom = $env{'form.coursedom'};
11218:         }
11219:     }
11220:     if ($forcenewuser) {
11221:         if (ref($srch) eq 'HASH') {
11222:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11223:                 if ($cancreate) {
11224:                     $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>';
11225:                 } else {
11226:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11227:                     my %usertypetext = (
11228:                         official   => 'institutional',
11229:                         unofficial => 'non-institutional',
11230:                     );
11231:                     $new_user_create = '<p class="LC_warning">'
11232:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11233:                                       .' '
11234:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11235:                                           ,'<a href="'.$helplink.'">','</a>')
11236:                                       .'</p><br />';
11237:                 }
11238:             }
11239:         }
11240: 
11241:         $newuserscript = <<"ENDSCRIPT";
11242: 
11243: function setSearch(createnew,callingForm) {
11244:     if (createnew == 1) {
11245:         for (var i=0; i<callingForm.srchby.length; i++) {
11246:             if (callingForm.srchby.options[i].value == 'uname') {
11247:                 callingForm.srchby.selectedIndex = i;
11248:             }
11249:         }
11250:         for (var i=0; i<callingForm.srchin.length; i++) {
11251:             if ( callingForm.srchin.options[i].value == 'dom') {
11252: 		callingForm.srchin.selectedIndex = i;
11253:             }
11254:         }
11255:         for (var i=0; i<callingForm.srchtype.length; i++) {
11256:             if (callingForm.srchtype.options[i].value == 'exact') {
11257:                 callingForm.srchtype.selectedIndex = i;
11258:             }
11259:         }
11260:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11261:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11262:                 callingForm.srchdomain.selectedIndex = i;
11263:             }
11264:         }
11265:     }
11266: }
11267: ENDSCRIPT
11268: 
11269:     }
11270: 
11271:     my $output = <<"END_BLOCK";
11272: <script type="text/javascript">
11273: // <![CDATA[
11274: function validateEntry(callingForm) {
11275: 
11276:     var checkok = 1;
11277:     var srchin;
11278:     for (var i=0; i<callingForm.srchin.length; i++) {
11279: 	if ( callingForm.srchin[i].checked ) {
11280: 	    srchin = callingForm.srchin[i].value;
11281: 	}
11282:     }
11283: 
11284:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11285:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11286:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11287:     var srchterm =  callingForm.srchterm.value;
11288:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11289:     var msg = "";
11290: 
11291:     if (srchterm == "") {
11292:         checkok = 0;
11293:         msg += "$js_lt{'youm'}\\n";
11294:     }
11295: 
11296:     if (srchtype== 'begins') {
11297:         if (srchterm.length < 2) {
11298:             checkok = 0;
11299:             msg += "$js_lt{'thte'}\\n";
11300:         }
11301:     }
11302: 
11303:     if (srchtype== 'contains') {
11304:         if (srchterm.length < 3) {
11305:             checkok = 0;
11306:             msg += "$js_lt{'thet'}\\n";
11307:         }
11308:     }
11309:     if (srchin == 'instd') {
11310:         if (srchdomain == '') {
11311:             checkok = 0;
11312:             msg += "$js_lt{'yomc'}\\n";
11313:         }
11314:     }
11315:     if (srchin == 'dom') {
11316:         if (srchdomain == '') {
11317:             checkok = 0;
11318:             msg += "$js_lt{'ymcd'}\\n";
11319:         }
11320:     }
11321:     if (srchby == 'lastfirst') {
11322:         if (srchterm.indexOf(",") == -1) {
11323:             checkok = 0;
11324:             msg += "$js_lt{'whus'}\\n";
11325:         }
11326:         if (srchterm.indexOf(",") == srchterm.length -1) {
11327:             checkok = 0;
11328:             msg += "$js_lt{'whse'}\\n";
11329:         }
11330:     }
11331:     if (checkok == 0) {
11332:         alert("$js_lt{'thfo'}\\n"+msg);
11333:         return;
11334:     }
11335:     if (checkok == 1) {
11336:         callingForm.submit();
11337:     }
11338: }
11339: 
11340: $newuserscript
11341: 
11342: // ]]>
11343: </script>
11344: 
11345: $new_user_create
11346: 
11347: END_BLOCK
11348: 
11349:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11350:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11351:                $domform.
11352:                &Apache::lonhtmlcommon::row_closure().
11353:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11354:                $srchbysel.
11355:                $srchtypesel. 
11356:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11357:                $srchinsel.
11358:                &Apache::lonhtmlcommon::row_closure(1). 
11359:                &Apache::lonhtmlcommon::end_pick_box().
11360:                '<br />';
11361:     return ($output,1);
11362: }
11363: 
11364: sub user_rule_check {
11365:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11366:     my ($response,%inst_response);
11367:     if (ref($usershash) eq 'HASH') {
11368:         if (keys(%{$usershash}) > 1) {
11369:             my (%by_username,%by_id,%userdoms);
11370:             my $checkid; 
11371:             if (ref($checks) eq 'HASH') {
11372:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11373:                     $checkid = 1;
11374:                 }
11375:             }
11376:             foreach my $user (keys(%{$usershash})) {
11377:                 my ($uname,$udom) = split(/:/,$user);
11378:                 if ($checkid) {
11379:                     if (ref($usershash->{$user}) eq 'HASH') {
11380:                         if ($usershash->{$user}->{'id'} ne '') {
11381:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11382:                             $userdoms{$udom} = 1;
11383:                             if (ref($inst_results) eq 'HASH') {
11384:                                 $inst_results->{$uname.':'.$udom} = {};
11385:                             }
11386:                         }
11387:                     }
11388:                 } else {
11389:                     $by_username{$udom}{$uname} = 1;
11390:                     $userdoms{$udom} = 1;
11391:                     if (ref($inst_results) eq 'HASH') {
11392:                         $inst_results->{$uname.':'.$udom} = {};
11393:                     }
11394:                 }
11395:             }
11396:             foreach my $udom (keys(%userdoms)) {
11397:                 if (!$got_rules->{$udom}) {
11398:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11399:                                                              ['usercreation'],$udom);
11400:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11401:                         foreach my $item ('username','id') {
11402:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11403:                                 $$curr_rules{$udom}{$item} =
11404:                                     $domconfig{'usercreation'}{$item.'_rule'};
11405:                             }
11406:                         }
11407:                     }
11408:                     $got_rules->{$udom} = 1;
11409:                 }
11410:             }
11411:             if ($checkid) {
11412:                 foreach my $udom (keys(%by_id)) {
11413:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11414:                     if ($outcome eq 'ok') {
11415:                         foreach my $id (keys(%{$by_id{$udom}})) {
11416:                             my $uname = $by_id{$udom}{$id};
11417:                             $inst_response{$uname.':'.$udom} = $outcome;
11418:                         }
11419:                         if (ref($results) eq 'HASH') {
11420:                             foreach my $uname (keys(%{$results})) {
11421:                                 if (exists($inst_response{$uname.':'.$udom})) {
11422:                                     $inst_response{$uname.':'.$udom} = $outcome;
11423:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11424:                                 }
11425:                             }
11426:                         }
11427:                     }
11428:                 }
11429:             } else {
11430:                 foreach my $udom (keys(%by_username)) {
11431:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11432:                     if ($outcome eq 'ok') {
11433:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11434:                             $inst_response{$uname.':'.$udom} = $outcome;
11435:                         }
11436:                         if (ref($results) eq 'HASH') {
11437:                             foreach my $uname (keys(%{$results})) {
11438:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11439:                             }
11440:                         }
11441:                     }
11442:                 }
11443:             }
11444:         } elsif (keys(%{$usershash}) == 1) {
11445:             my $user = (keys(%{$usershash}))[0];
11446:             my ($uname,$udom) = split(/:/,$user);
11447:             if (($udom ne '') && ($uname ne '')) {
11448:                 if (ref($usershash->{$user}) eq 'HASH') {
11449:                     if (ref($checks) eq 'HASH') {
11450:                         if (defined($checks->{'username'})) {
11451:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11452:                                 &Apache::lonnet::get_instuser($udom,$uname);
11453:                         } elsif (defined($checks->{'id'})) {
11454:                             if ($usershash->{$user}->{'id'} ne '') {
11455:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11456:                                     &Apache::lonnet::get_instuser($udom,undef,
11457:                                                                   $usershash->{$user}->{'id'});
11458:                             } else {
11459:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11460:                                     &Apache::lonnet::get_instuser($udom,$uname);
11461:                             }
11462:                         }
11463:                     } else {
11464:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11465:                             &Apache::lonnet::get_instuser($udom,$uname);
11466:                        return;
11467:                     }
11468:                     if (!$got_rules->{$udom}) {
11469:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11470:                                                                  ['usercreation'],$udom);
11471:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11472:                             foreach my $item ('username','id') {
11473:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11474:                                    $$curr_rules{$udom}{$item} = 
11475:                                        $domconfig{'usercreation'}{$item.'_rule'};
11476:                                 }
11477:                             }
11478:                         }
11479:                         $got_rules->{$udom} = 1;
11480:                     }
11481:                 }
11482:             } else {
11483:                 return;
11484:             }
11485:         } else {
11486:             return;
11487:         }
11488:         foreach my $user (keys(%{$usershash})) {
11489:             my ($uname,$udom) = split(/:/,$user);
11490:             next if (($udom eq '') || ($uname eq ''));
11491:             my $id;
11492:             if (ref($inst_results) eq 'HASH') {
11493:                 if (ref($inst_results->{$user}) eq 'HASH') {
11494:                     $id = $inst_results->{$user}->{'id'};
11495:                 }
11496:             }
11497:             if ($id eq '') { 
11498:                 if (ref($usershash->{$user})) {
11499:                     $id = $usershash->{$user}->{'id'};
11500:                 }
11501:             }
11502:             foreach my $item (keys(%{$checks})) {
11503:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11504:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11505:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11506:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11507:                                                                              $$curr_rules{$udom}{$item});
11508:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11509:                                 if ($rule_check{$rule}) {
11510:                                     $$rulematch{$user}{$item} = $rule;
11511:                                     if ($inst_response{$user} eq 'ok') {
11512:                                         if (ref($inst_results) eq 'HASH') {
11513:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11514:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11515:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11516:                                                 } elsif ($item eq 'id') {
11517:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11518:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11519:                                                     }
11520:                                                 }
11521:                                             }
11522:                                         }
11523:                                     }
11524:                                     last;
11525:                                 }
11526:                             }
11527:                         }
11528:                     }
11529:                 }
11530:             }
11531:         }
11532:     }
11533:     return;
11534: }
11535: 
11536: sub user_rule_formats {
11537:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11538:     my %text = ( 
11539:                  'username' => 'Usernames',
11540:                  'id'       => 'IDs',
11541:                );
11542:     my $output;
11543:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11544:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11545:         if (@{$ruleorder} > 0) {
11546:             $output = '<br />'.
11547:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11548:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11549:                       ' <ul>';
11550:             foreach my $rule (@{$ruleorder}) {
11551:                 if (ref($curr_rules) eq 'ARRAY') {
11552:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11553:                         if (ref($rules->{$rule}) eq 'HASH') {
11554:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11555:                                         $rules->{$rule}{'desc'}.'</li>';
11556:                         }
11557:                     }
11558:                 }
11559:             }
11560:             $output .= '</ul>';
11561:         }
11562:     }
11563:     return $output;
11564: }
11565: 
11566: sub instrule_disallow_msg {
11567:     my ($checkitem,$domdesc,$count,$mode) = @_;
11568:     my $response;
11569:     my %text = (
11570:                   item   => 'username',
11571:                   items  => 'usernames',
11572:                   match  => 'matches',
11573:                   do     => 'does',
11574:                   action => 'a username',
11575:                   one    => 'one',
11576:                );
11577:     if ($count > 1) {
11578:         $text{'item'} = 'usernames';
11579:         $text{'match'} ='match';
11580:         $text{'do'} = 'do';
11581:         $text{'action'} = 'usernames',
11582:         $text{'one'} = 'ones';
11583:     }
11584:     if ($checkitem eq 'id') {
11585:         $text{'items'} = 'IDs';
11586:         $text{'item'} = 'ID';
11587:         $text{'action'} = 'an ID';
11588:         if ($count > 1) {
11589:             $text{'item'} = 'IDs';
11590:             $text{'action'} = 'IDs';
11591:         }
11592:     }
11593:     $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 />';
11594:     if ($mode eq 'upload') {
11595:         if ($checkitem eq 'username') {
11596:             $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'}.");
11597:         } elsif ($checkitem eq 'id') {
11598:             $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.");
11599:         }
11600:     } elsif ($mode eq 'selfcreate') {
11601:         if ($checkitem eq 'id') {
11602:             $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.");
11603:         }
11604:     } else {
11605:         if ($checkitem eq 'username') {
11606:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11607:         } elsif ($checkitem eq 'id') {
11608:             $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.");
11609:         }
11610:     }
11611:     return $response;
11612: }
11613: 
11614: sub personal_data_fieldtitles {
11615:     my %fieldtitles = &Apache::lonlocal::texthash (
11616:                         id => 'Student/Employee ID',
11617:                         permanentemail => 'E-mail address',
11618:                         lastname => 'Last Name',
11619:                         firstname => 'First Name',
11620:                         middlename => 'Middle Name',
11621:                         generation => 'Generation',
11622:                         gen => 'Generation',
11623:                         inststatus => 'Affiliation',
11624:                    );
11625:     return %fieldtitles;
11626: }
11627: 
11628: sub sorted_inst_types {
11629:     my ($dom) = @_;
11630:     my ($usertypes,$order);
11631:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11632:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11633:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11634:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11635:     } else {
11636:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11637:     }
11638:     my $othertitle = &mt('All users');
11639:     if ($env{'request.course.id'}) {
11640:         $othertitle  = &mt('Any users');
11641:     }
11642:     my @types;
11643:     if (ref($order) eq 'ARRAY') {
11644:         @types = @{$order};
11645:     }
11646:     if (@types == 0) {
11647:         if (ref($usertypes) eq 'HASH') {
11648:             @types = sort(keys(%{$usertypes}));
11649:         }
11650:     }
11651:     if (keys(%{$usertypes}) > 0) {
11652:         $othertitle = &mt('Other users');
11653:     }
11654:     return ($othertitle,$usertypes,\@types);
11655: }
11656: 
11657: sub get_institutional_codes {
11658:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11659: # Get complete list of course sections to update
11660:     my @currsections = ();
11661:     my @currxlists = ();
11662:     my (%unclutteredsec,%unclutteredlcsec);
11663:     my $coursecode = $$settings{'internal.coursecode'};
11664:     my $crskey = $crs.':'.$coursecode;
11665:     @{$unclutteredsec{$crskey}} = ();
11666:     @{$unclutteredlcsec{$crskey}} = ();
11667: 
11668:     if ($$settings{'internal.sectionnums'} ne '') {
11669:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11670:     }
11671: 
11672:     if ($$settings{'internal.crosslistings'} ne '') {
11673:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11674:     }
11675: 
11676:     if (@currxlists > 0) {
11677:         foreach my $xl (@currxlists) {
11678:             if ($xl =~ /^([^:]+):(\w*)$/) {
11679:                 unless (grep/^$1$/,@{$allcourses}) {
11680:                     push(@{$allcourses},$1);
11681:                     $$LC_code{$1} = $2;
11682:                 }
11683:             }
11684:         }
11685:     }
11686: 
11687:     if (@currsections > 0) {
11688:         foreach my $sec (@currsections) {
11689:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11690:                 my $instsec = $1;
11691:                 my $lc_sec = $2;
11692:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11693:                     push(@{$unclutteredsec{$crskey}},$instsec);
11694:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11695:                 }
11696:             }
11697:         }
11698:     }
11699: 
11700:     if (@{$unclutteredsec{$crskey}} > 0) {
11701:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11702:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11703:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11704:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11705:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11706:                     push(@{$allcourses},$sec);
11707:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11708:                 }
11709:             }
11710:         }
11711:     }
11712:     return;
11713: }
11714: 
11715: sub get_standard_codeitems {
11716:     return ('Year','Semester','Department','Number','Section');
11717: }
11718: 
11719: =pod
11720: 
11721: =head1 Slot Helpers
11722: 
11723: =over 4
11724: 
11725: =item * sorted_slots()
11726: 
11727: Sorts an array of slot names in order of an optional sort key,
11728: default sort is by slot start time (earliest first). 
11729: 
11730: Inputs:
11731: 
11732: =over 4
11733: 
11734: slotsarr  - Reference to array of unsorted slot names.
11735: 
11736: slots     - Reference to hash of hash, where outer hash keys are slot names.
11737: 
11738: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11739: 
11740: =back
11741: 
11742: Returns:
11743: 
11744: =over 4
11745: 
11746: sorted   - An array of slot names sorted by a specified sort key 
11747:            (default sort key is start time of the slot).
11748: 
11749: =back
11750: 
11751: =cut
11752: 
11753: 
11754: sub sorted_slots {
11755:     my ($slotsarr,$slots,$sortkey) = @_;
11756:     if ($sortkey eq '') {
11757:         $sortkey = 'starttime';
11758:     }
11759:     my @sorted;
11760:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11761:         @sorted =
11762:             sort {
11763:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11764:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11765:                      }
11766:                      if (ref($slots->{$a})) { return -1;}
11767:                      if (ref($slots->{$b})) { return 1;}
11768:                      return 0;
11769:                  } @{$slotsarr};
11770:     }
11771:     return @sorted;
11772: }
11773: 
11774: =pod
11775: 
11776: =item * get_future_slots()
11777: 
11778: Inputs:
11779: 
11780: =over 4
11781: 
11782: cnum - course number
11783: 
11784: cdom - course domain
11785: 
11786: now - current UNIX time
11787: 
11788: symb - optional symb
11789: 
11790: =back
11791: 
11792: Returns:
11793: 
11794: =over 4
11795: 
11796: sorted_reservable - ref to array of student_schedulable slots currently 
11797:                     reservable, ordered by end date of reservation period.
11798: 
11799: reservable_now - ref to hash of student_schedulable slots currently
11800:                  reservable.
11801: 
11802:     Keys in inner hash are:
11803:     (a) symb: either blank or symb to which slot use is restricted.
11804:     (b) endreserve: end date of reservation period.
11805:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11806:         selected.
11807: 
11808: sorted_future - ref to array of student_schedulable slots reservable in
11809:                 the future, ordered by start date of reservation period.
11810: 
11811: future_reservable - ref to hash of student_schedulable slots reservable
11812:                     in the future.
11813: 
11814:     Keys in inner hash are:
11815:     (a) symb: either blank or symb to which slot use is restricted.
11816:     (b) startreserve: start date of reservation period.
11817:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11818:         selected.
11819: 
11820: =back
11821: 
11822: =cut
11823: 
11824: sub get_future_slots {
11825:     my ($cnum,$cdom,$now,$symb) = @_;
11826:     my $map;
11827:     if ($symb) {
11828:         ($map) = &Apache::lonnet::decode_symb($symb);
11829:     }
11830:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11831:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11832:     foreach my $slot (keys(%slots)) {
11833:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11834:         if ($symb) {
11835:             if ($slots{$slot}->{'symb'} ne '') {
11836:                 my $canuse;
11837:                 my %oksymbs;
11838:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11839:                 map { $oksymbs{$_} = 1; } @slotsymbs;
11840:                 if ($oksymbs{$symb}) {
11841:                     $canuse = 1;
11842:                 } else {
11843:                     foreach my $item (@slotsymbs) {
11844:                         if ($item =~ /\.(page|sequence)$/) {
11845:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11846:                             if (($map ne '') && ($map eq $sloturl)) {
11847:                                 $canuse = 1;
11848:                                 last;
11849:                             }
11850:                         }
11851:                     }
11852:                 }
11853:                 next unless ($canuse);
11854:             }
11855:         }
11856:         if (($slots{$slot}->{'starttime'} > $now) &&
11857:             ($slots{$slot}->{'endtime'} > $now)) {
11858:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11859:                 my $userallowed = 0;
11860:                 if ($slots{$slot}->{'allowedsections'}) {
11861:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11862:                     if (!defined($env{'request.role.sec'})
11863:                         && grep(/^No section assigned$/,@allowed_sec)) {
11864:                         $userallowed=1;
11865:                     } else {
11866:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11867:                             $userallowed=1;
11868:                         }
11869:                     }
11870:                     unless ($userallowed) {
11871:                         if (defined($env{'request.course.groups'})) {
11872:                             my @groups = split(/:/,$env{'request.course.groups'});
11873:                             foreach my $group (@groups) {
11874:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11875:                                     $userallowed=1;
11876:                                     last;
11877:                                 }
11878:                             }
11879:                         }
11880:                     }
11881:                 }
11882:                 if ($slots{$slot}->{'allowedusers'}) {
11883:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11884:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11885:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11886:                         $userallowed = 1;
11887:                     }
11888:                 }
11889:                 next unless($userallowed);
11890:             }
11891:             my $startreserve = $slots{$slot}->{'startreserve'};
11892:             my $endreserve = $slots{$slot}->{'endreserve'};
11893:             my $symb = $slots{$slot}->{'symb'};
11894:             my $uniqueperiod;
11895:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11896:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11897:             }
11898:             if (($startreserve < $now) &&
11899:                 (!$endreserve || $endreserve > $now)) {
11900:                 my $lastres = $endreserve;
11901:                 if (!$lastres) {
11902:                     $lastres = $slots{$slot}->{'starttime'};
11903:                 }
11904:                 $reservable_now{$slot} = {
11905:                                            symb       => $symb,
11906:                                            endreserve => $lastres,
11907:                                            uniqueperiod => $uniqueperiod,
11908:                                          };
11909:             } elsif (($startreserve > $now) &&
11910:                      (!$endreserve || $endreserve > $startreserve)) {
11911:                 $future_reservable{$slot} = {
11912:                                               symb         => $symb,
11913:                                               startreserve => $startreserve,
11914:                                               uniqueperiod => $uniqueperiod,
11915:                                             };
11916:             }
11917:         }
11918:     }
11919:     my @unsorted_reservable = keys(%reservable_now);
11920:     if (@unsorted_reservable > 0) {
11921:         @sorted_reservable = 
11922:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11923:     }
11924:     my @unsorted_future = keys(%future_reservable);
11925:     if (@unsorted_future > 0) {
11926:         @sorted_future =
11927:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11928:     }
11929:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11930: }
11931: 
11932: =pod
11933: 
11934: =back
11935: 
11936: =head1 HTTP Helpers
11937: 
11938: =over 4
11939: 
11940: =item * &get_unprocessed_cgi($query,$possible_names)
11941: 
11942: Modify the %env hash to contain unprocessed CGI form parameters held in
11943: $query.  The parameters listed in $possible_names (an array reference),
11944: will be set in $env{'form.name'} if they do not already exist.
11945: 
11946: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11947: $possible_names is an ref to an array of form element names.  As an example:
11948: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11949: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11950: 
11951: =cut
11952: 
11953: sub get_unprocessed_cgi {
11954:   my ($query,$possible_names)= @_;
11955:   # $Apache::lonxml::debug=1;
11956:   foreach my $pair (split(/&/,$query)) {
11957:     my ($name, $value) = split(/=/,$pair);
11958:     $name = &unescape($name);
11959:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11960:       $value =~ tr/+/ /;
11961:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11962:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11963:     }
11964:   }
11965: }
11966: 
11967: =pod
11968: 
11969: =item * &cacheheader() 
11970: 
11971: returns cache-controlling header code
11972: 
11973: =cut
11974: 
11975: sub cacheheader {
11976:     unless ($env{'request.method'} eq 'GET') { return ''; }
11977:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11978:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11979:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11980:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11981:     return $output;
11982: }
11983: 
11984: =pod
11985: 
11986: =item * &no_cache($r) 
11987: 
11988: specifies header code to not have cache
11989: 
11990: =cut
11991: 
11992: sub no_cache {
11993:     my ($r) = @_;
11994:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11995: 	$env{'request.method'} ne 'GET') { return ''; }
11996:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11997:     $r->no_cache(1);
11998:     $r->header_out("Expires" => $date);
11999:     $r->header_out("Pragma" => "no-cache");
12000: }
12001: 
12002: sub content_type {
12003:     my ($r,$type,$charset) = @_;
12004:     if ($r) {
12005: 	#  Note that printout.pl calls this with undef for $r.
12006: 	&no_cache($r);
12007:     }
12008:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12009:     unless ($charset) {
12010: 	$charset=&Apache::lonlocal::current_encoding;
12011:     }
12012:     if ($charset) { $type.='; charset='.$charset; }
12013:     if ($r) {
12014: 	$r->content_type($type);
12015:     } else {
12016: 	print("Content-type: $type\n\n");
12017:     }
12018: }
12019: 
12020: =pod
12021: 
12022: =item * &add_to_env($name,$value) 
12023: 
12024: adds $name to the %env hash with value
12025: $value, if $name already exists, the entry is converted to an array
12026: reference and $value is added to the array.
12027: 
12028: =cut
12029: 
12030: sub add_to_env {
12031:   my ($name,$value)=@_;
12032:   if (defined($env{$name})) {
12033:     if (ref($env{$name})) {
12034:       #already have multiple values
12035:       push(@{ $env{$name} },$value);
12036:     } else {
12037:       #first time seeing multiple values, convert hash entry to an arrayref
12038:       my $first=$env{$name};
12039:       undef($env{$name});
12040:       push(@{ $env{$name} },$first,$value);
12041:     }
12042:   } else {
12043:     $env{$name}=$value;
12044:   }
12045: }
12046: 
12047: =pod
12048: 
12049: =item * &get_env_multiple($name) 
12050: 
12051: gets $name from the %env hash, it seemlessly handles the cases where multiple
12052: values may be defined and end up as an array ref.
12053: 
12054: returns an array of values
12055: 
12056: =cut
12057: 
12058: sub get_env_multiple {
12059:     my ($name) = @_;
12060:     my @values;
12061:     if (defined($env{$name})) {
12062:         # exists is it an array
12063:         if (ref($env{$name})) {
12064:             @values=@{ $env{$name} };
12065:         } else {
12066:             $values[0]=$env{$name};
12067:         }
12068:     }
12069:     return(@values);
12070: }
12071: 
12072: # Looks at given dependencies, and returns something depending on the context.
12073: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12074: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12075: # For all other contexts, returns ($output, $counter, $numpathchg).
12076: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12077: # $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.
12078: # $numpathchg: integer with the number of cleaned up dependency paths.
12079: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12080: # \%mapping: hash reference clean path -> original path for all dependencies.
12081: # @param {string} actionurl - The path to the handler, indicative of the context.
12082: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12083: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12084: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12085: # @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)
12086: # @return {Array} - array depending on the context (not a reference)
12087: sub ask_for_embedded_content {
12088:     # NOTE: documentation was added afterwards, it could be wrong
12089:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12090:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12091:         %currsubfile,%unused,$rem);
12092:     my $counter = 0;
12093:     my $numnew = 0;
12094:     my $numremref = 0;
12095:     my $numinvalid = 0;
12096:     my $numpathchg = 0;
12097:     my $numexisting = 0;
12098:     my $numunused = 0;
12099:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12100:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12101:     my $heading = &mt('Upload embedded files');
12102:     my $buttontext = &mt('Upload');
12103: 
12104:     # fills these variables based on the context:
12105:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12106:     # $path, $fileloc, $title, $rem, $filename
12107:     if ($env{'request.course.id'}) {
12108:         if ($actionurl eq '/adm/dependencies') {
12109:             $navmap = Apache::lonnavmaps::navmap->new();
12110:         }
12111:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12112:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12113:     }
12114:     if (($actionurl eq '/adm/portfolio') || 
12115:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12116:         my $current_path='/';
12117:         if ($env{'form.currentpath'}) {
12118:             $current_path = $env{'form.currentpath'};
12119:         }
12120:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12121:             $udom = $cdom;
12122:             $uname = $cnum;
12123:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12124:         } else {
12125:             $udom = $env{'user.domain'};
12126:             $uname = $env{'user.name'};
12127:             $url = '/userfiles/portfolio';
12128:         }
12129:         $toplevel = $url.'/';
12130:         $url .= $current_path;
12131:         $getpropath = 1;
12132:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12133:              ($actionurl eq '/adm/imsimport')) { 
12134:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12135:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12136:         $toplevel = $url;
12137:         if ($rest ne '') {
12138:             $url .= $rest;
12139:         }
12140:     } elsif ($actionurl eq '/adm/coursedocs') {
12141:         if (ref($args) eq 'HASH') {
12142:             $url = $args->{'docs_url'};
12143:             $toplevel = $url;
12144:             if ($args->{'context'} eq 'paste') {
12145:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12146:                 ($path) = 
12147:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12148:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12149:                 $fileloc =~ s{^/}{};
12150:             }
12151:         }
12152:     } elsif ($actionurl eq '/adm/dependencies')  {
12153:         if ($env{'request.course.id'} ne '') {
12154:             if (ref($args) eq 'HASH') {
12155:                 $url = $args->{'docs_url'};
12156:                 $title = $args->{'docs_title'};
12157:                 $toplevel = $url; 
12158:                 unless ($toplevel =~ m{^/}) {
12159:                     $toplevel = "/$url";
12160:                 }
12161:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12162:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12163:                     $path = $1;
12164:                 } else {
12165:                     ($path) =
12166:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12167:                 }
12168:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12169:                     $fileloc = $toplevel;
12170:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12171:                     my ($udom,$uname,$fname) =
12172:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12173:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12174:                 } else {
12175:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12176:                 }
12177:                 $fileloc =~ s{^/}{};
12178:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12179:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12180:             }
12181:         }
12182:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12183:         $udom = $cdom;
12184:         $uname = $cnum;
12185:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12186:         $toplevel = $url;
12187:         $path = $url;
12188:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12189:         $fileloc =~ s{^/}{};
12190:     }
12191:     
12192:     # parses the dependency paths to get some info
12193:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12194:     # $newfiles: hash URL -> 1 for new files or external URLs
12195:     # (will be completed later)
12196:     # $mapping:
12197:     #   for external URLs: external URL -> external URL
12198:     #   for relative paths: clean path -> original path
12199:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12200:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12201:     foreach my $file (keys(%{$allfiles})) {
12202:         my $embed_file;
12203:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12204:             $embed_file = $1;
12205:         } else {
12206:             $embed_file = $file;
12207:         }
12208:         my ($absolutepath,$cleaned_file);
12209:         if ($embed_file =~ m{^\w+://}) {
12210:             $cleaned_file = $embed_file;
12211:             $newfiles{$cleaned_file} = 1;
12212:             $mapping{$cleaned_file} = $embed_file;
12213:         } else {
12214:             $cleaned_file = &clean_path($embed_file);
12215:             if ($embed_file =~ m{^/}) {
12216:                 $absolutepath = $embed_file;
12217:             }
12218:             if ($cleaned_file =~ m{/}) {
12219:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12220:                 $path = &check_for_traversal($path,$url,$toplevel);
12221:                 my $item = $fname;
12222:                 if ($path ne '') {
12223:                     $item = $path.'/'.$fname;
12224:                     $subdependencies{$path}{$fname} = 1;
12225:                 } else {
12226:                     $dependencies{$item} = 1;
12227:                 }
12228:                 if ($absolutepath) {
12229:                     $mapping{$item} = $absolutepath;
12230:                 } else {
12231:                     $mapping{$item} = $embed_file;
12232:                 }
12233:             } else {
12234:                 $dependencies{$embed_file} = 1;
12235:                 if ($absolutepath) {
12236:                     $mapping{$cleaned_file} = $absolutepath;
12237:                 } else {
12238:                     $mapping{$cleaned_file} = $embed_file;
12239:                 }
12240:             }
12241:         }
12242:     }
12243:     
12244:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12245:     # and lists
12246:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12247:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12248:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12249:     #                                    the path had to be cleaned up
12250:     # $existing: hash clean path -> 1 if the file exists
12251:     # $numexisting: number of keys in $existing
12252:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12253:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12254:     #                                      dependency subdirectories that are
12255:     #                                      not listed as dependencies, with some exceptions using $rem
12256:     my $dirptr = 16384;
12257:     foreach my $path (keys(%subdependencies)) {
12258:         $currsubfile{$path} = {};
12259:         if (($actionurl eq '/adm/portfolio') || 
12260:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12261:             my ($sublistref,$listerror) =
12262:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12263:             if (ref($sublistref) eq 'ARRAY') {
12264:                 foreach my $line (@{$sublistref}) {
12265:                     my ($file_name,$rest) = split(/\&/,$line,2);
12266:                     $currsubfile{$path}{$file_name} = 1;
12267:                 }
12268:             }
12269:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12270:             if (opendir(my $dir,$url.'/'.$path)) {
12271:                 my @subdir_list = grep(!/^\./,readdir($dir));
12272:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12273:             }
12274:         } elsif (($actionurl eq '/adm/dependencies') ||
12275:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12276:                   ($args->{'context'} eq 'paste')) ||
12277:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12278:             if ($env{'request.course.id'} ne '') {
12279:                 my $dir;
12280:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12281:                     $dir = $fileloc;
12282:                 } else {
12283:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12284:                 }
12285:                 if ($dir ne '') {
12286:                     my ($sublistref,$listerror) =
12287:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12288:                     if (ref($sublistref) eq 'ARRAY') {
12289:                         foreach my $line (@{$sublistref}) {
12290:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12291:                                 undef,$mtime)=split(/\&/,$line,12);
12292:                             unless (($testdir&$dirptr) ||
12293:                                     ($file_name =~ /^\.\.?$/)) {
12294:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12295:                             }
12296:                         }
12297:                     }
12298:                 }
12299:             }
12300:         }
12301:         foreach my $file (keys(%{$subdependencies{$path}})) {
12302:             if (exists($currsubfile{$path}{$file})) {
12303:                 my $item = $path.'/'.$file;
12304:                 unless ($mapping{$item} eq $item) {
12305:                     $pathchanges{$item} = 1;
12306:                 }
12307:                 $existing{$item} = 1;
12308:                 $numexisting ++;
12309:             } else {
12310:                 $newfiles{$path.'/'.$file} = 1;
12311:             }
12312:         }
12313:         if ($actionurl eq '/adm/dependencies') {
12314:             foreach my $path (keys(%currsubfile)) {
12315:                 if (ref($currsubfile{$path}) eq 'HASH') {
12316:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12317:                          unless ($subdependencies{$path}{$file}) {
12318:                              next if (($rem ne '') &&
12319:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12320:                                        (ref($navmap) &&
12321:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12322:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12323:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12324:                              $unused{$path.'/'.$file} = 1; 
12325:                          }
12326:                     }
12327:                 }
12328:             }
12329:         }
12330:     }
12331:     
12332:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12333:     # for files in $url or $fileloc (target directory) in some contexts
12334:     my %currfile;
12335:     if (($actionurl eq '/adm/portfolio') ||
12336:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12337:         my ($dirlistref,$listerror) =
12338:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12339:         if (ref($dirlistref) eq 'ARRAY') {
12340:             foreach my $line (@{$dirlistref}) {
12341:                 my ($file_name,$rest) = split(/\&/,$line,2);
12342:                 $currfile{$file_name} = 1;
12343:             }
12344:         }
12345:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12346:         if (opendir(my $dir,$url)) {
12347:             my @dir_list = grep(!/^\./,readdir($dir));
12348:             map {$currfile{$_} = 1;} @dir_list;
12349:         }
12350:     } elsif (($actionurl eq '/adm/dependencies') ||
12351:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12352:               ($args->{'context'} eq 'paste')) ||
12353:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12354:         if ($env{'request.course.id'} ne '') {
12355:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12356:             if ($dir ne '') {
12357:                 my ($dirlistref,$listerror) =
12358:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12359:                 if (ref($dirlistref) eq 'ARRAY') {
12360:                     foreach my $line (@{$dirlistref}) {
12361:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12362:                             $size,undef,$mtime)=split(/\&/,$line,12);
12363:                         unless (($testdir&$dirptr) ||
12364:                                 ($file_name =~ /^\.\.?$/)) {
12365:                             $currfile{$file_name} = [$size,$mtime];
12366:                         }
12367:                     }
12368:                 }
12369:             }
12370:         }
12371:     }
12372:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12373:     # are not in subdirectories, using $currfile
12374:     foreach my $file (keys(%dependencies)) {
12375:         if (exists($currfile{$file})) {
12376:             unless ($mapping{$file} eq $file) {
12377:                 $pathchanges{$file} = 1;
12378:             }
12379:             $existing{$file} = 1;
12380:             $numexisting ++;
12381:         } else {
12382:             $newfiles{$file} = 1;
12383:         }
12384:     }
12385:     foreach my $file (keys(%currfile)) {
12386:         unless (($file eq $filename) ||
12387:                 ($file eq $filename.'.bak') ||
12388:                 ($dependencies{$file})) {
12389:             if ($actionurl eq '/adm/dependencies') {
12390:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12391:                     next if (($rem ne '') &&
12392:                              (($env{"httpref.$rem".$file} ne '') ||
12393:                               (ref($navmap) &&
12394:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12395:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12396:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12397:                 }
12398:             }
12399:             $unused{$file} = 1;
12400:         }
12401:     }
12402:     
12403:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12404:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12405:         ($args->{'context'} eq 'paste')) {
12406:         $counter = scalar(keys(%existing));
12407:         $numpathchg = scalar(keys(%pathchanges));
12408:         return ($output,$counter,$numpathchg,\%existing);
12409:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12410:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12411:         $counter = scalar(keys(%existing));
12412:         $numpathchg = scalar(keys(%pathchanges));
12413:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12414:     }
12415:     
12416:     # returns HTML otherwise, with dependency results and to ask for more uploads
12417:     
12418:     # $upload_output: missing dependencies (with upload form)
12419:     # $modify_output: uploaded dependencies (in use)
12420:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12421:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12422:         if ($actionurl eq '/adm/dependencies') {
12423:             next if ($embed_file =~ m{^\w+://});
12424:         }
12425:         $upload_output .= &start_data_table_row().
12426:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12427:                           '<span class="LC_filename">'.$embed_file.'</span>';
12428:         unless ($mapping{$embed_file} eq $embed_file) {
12429:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12430:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12431:         }
12432:         $upload_output .= '</td>';
12433:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12434:             $upload_output.='<td align="right">'.
12435:                             '<span class="LC_info LC_fontsize_medium">'.
12436:                             &mt("URL points to web address").'</span>';
12437:             $numremref++;
12438:         } elsif ($args->{'error_on_invalid_names'}
12439:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12440:             $upload_output.='<td align="right"><span class="LC_warning">'.
12441:                             &mt('Invalid characters').'</span>';
12442:             $numinvalid++;
12443:         } else {
12444:             $upload_output .= '<td>'.
12445:                               &embedded_file_element('upload_embedded',$counter,
12446:                                                      $embed_file,\%mapping,
12447:                                                      $allfiles,$codebase,'upload');
12448:             $counter ++;
12449:             $numnew ++;
12450:         }
12451:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12452:     }
12453:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12454:         if ($actionurl eq '/adm/dependencies') {
12455:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12456:             $modify_output .= &start_data_table_row().
12457:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12458:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12459:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12460:                               '<td>'.$size.'</td>'.
12461:                               '<td>'.$mtime.'</td>'.
12462:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12463:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12464:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12465:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12466:                               &embedded_file_element('upload_embedded',$counter,
12467:                                                      $embed_file,\%mapping,
12468:                                                      $allfiles,$codebase,'modify').
12469:                               '</div></td>'.
12470:                               &end_data_table_row()."\n";
12471:             $counter ++;
12472:         } else {
12473:             $upload_output .= &start_data_table_row().
12474:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12475:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12476:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12477:                               &Apache::loncommon::end_data_table_row()."\n";
12478:         }
12479:     }
12480:     my $delidx = $counter;
12481:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12482:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12483:         $delete_output .= &start_data_table_row().
12484:                           '<td><img src="'.&icon($oldfile).'" />'.
12485:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12486:                           '<td>'.$size.'</td>'.
12487:                           '<td>'.$mtime.'</td>'.
12488:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12489:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12490:                           &embedded_file_element('upload_embedded',$delidx,
12491:                                                  $oldfile,\%mapping,$allfiles,
12492:                                                  $codebase,'delete').'</td>'.
12493:                           &end_data_table_row()."\n"; 
12494:         $numunused ++;
12495:         $delidx ++;
12496:     }
12497:     if ($upload_output) {
12498:         $upload_output = &start_data_table().
12499:                          $upload_output.
12500:                          &end_data_table()."\n";
12501:     }
12502:     if ($modify_output) {
12503:         $modify_output = &start_data_table().
12504:                          &start_data_table_header_row().
12505:                          '<th>'.&mt('File').'</th>'.
12506:                          '<th>'.&mt('Size (KB)').'</th>'.
12507:                          '<th>'.&mt('Modified').'</th>'.
12508:                          '<th>'.&mt('Upload replacement?').'</th>'.
12509:                          &end_data_table_header_row().
12510:                          $modify_output.
12511:                          &end_data_table()."\n";
12512:     }
12513:     if ($delete_output) {
12514:         $delete_output = &start_data_table().
12515:                          &start_data_table_header_row().
12516:                          '<th>'.&mt('File').'</th>'.
12517:                          '<th>'.&mt('Size (KB)').'</th>'.
12518:                          '<th>'.&mt('Modified').'</th>'.
12519:                          '<th>'.&mt('Delete?').'</th>'.
12520:                          &end_data_table_header_row().
12521:                          $delete_output.
12522:                          &end_data_table()."\n";
12523:     }
12524:     my $applies = 0;
12525:     if ($numremref) {
12526:         $applies ++;
12527:     }
12528:     if ($numinvalid) {
12529:         $applies ++;
12530:     }
12531:     if ($numexisting) {
12532:         $applies ++;
12533:     }
12534:     if ($counter || $numunused) {
12535:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12536:                   ' method="post" enctype="multipart/form-data">'."\n".
12537:                   $state.'<h3>'.$heading.'</h3>'; 
12538:         if ($actionurl eq '/adm/dependencies') {
12539:             if ($numnew) {
12540:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12541:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12542:                            $upload_output.'<br />'."\n";
12543:             }
12544:             if ($numexisting) {
12545:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12546:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12547:                            $modify_output.'<br />'."\n";
12548:                            $buttontext = &mt('Save changes');
12549:             }
12550:             if ($numunused) {
12551:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12552:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12553:                            $delete_output.'<br />'."\n";
12554:                            $buttontext = &mt('Save changes');
12555:             }
12556:         } else {
12557:             $output .= $upload_output.'<br />'."\n";
12558:         }
12559:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12560:                    $counter.'" />'."\n";
12561:         if ($actionurl eq '/adm/dependencies') { 
12562:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12563:                        $numnew.'" />'."\n";
12564:         } elsif ($actionurl eq '') {
12565:             $output .=  '<input type="hidden" name="phase" value="three" />';
12566:         }
12567:     } elsif ($applies) {
12568:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12569:         if ($applies > 1) {
12570:             $output .=  
12571:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12572:             if ($numremref) {
12573:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12574:             }
12575:             if ($numinvalid) {
12576:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12577:             }
12578:             if ($numexisting) {
12579:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12580:             }
12581:             $output .= '</ul><br />';
12582:         } elsif ($numremref) {
12583:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12584:         } elsif ($numinvalid) {
12585:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12586:         } elsif ($numexisting) {
12587:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12588:         }
12589:         $output .= $upload_output.'<br />';
12590:     }
12591:     my ($pathchange_output,$chgcount);
12592:     $chgcount = $counter;
12593:     if (keys(%pathchanges) > 0) {
12594:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12595:             if ($counter) {
12596:                 $output .= &embedded_file_element('pathchange',$chgcount,
12597:                                                   $embed_file,\%mapping,
12598:                                                   $allfiles,$codebase,'change');
12599:             } else {
12600:                 $pathchange_output .= 
12601:                     &start_data_table_row().
12602:                     '<td><input type ="checkbox" name="namechange" value="'.
12603:                     $chgcount.'" checked="checked" /></td>'.
12604:                     '<td>'.$mapping{$embed_file}.'</td>'.
12605:                     '<td>'.$embed_file.
12606:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12607:                                            \%mapping,$allfiles,$codebase,'change').
12608:                     '</td>'.&end_data_table_row();
12609:             }
12610:             $numpathchg ++;
12611:             $chgcount ++;
12612:         }
12613:     }
12614:     if (($counter) || ($numunused)) {
12615:         if ($numpathchg) {
12616:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12617:                        $numpathchg.'" />'."\n";
12618:         }
12619:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12620:             ($actionurl eq '/adm/imsimport')) {
12621:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12622:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12623:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12624:         } elsif ($actionurl eq '/adm/dependencies') {
12625:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12626:         }
12627:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12628:     } elsif ($numpathchg) {
12629:         my %pathchange = ();
12630:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12631:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12632:             $output .= '<p>'.&mt('or').'</p>'; 
12633:         }
12634:     }
12635:     return ($output,$counter,$numpathchg);
12636: }
12637: 
12638: =pod
12639: 
12640: =item * clean_path($name)
12641: 
12642: Performs clean-up of directories, subdirectories and filename in an
12643: embedded object, referenced in an HTML file which is being uploaded
12644: to a course or portfolio, where 
12645: "Upload embedded images/multimedia files if HTML file" checkbox was
12646: checked.
12647: 
12648: Clean-up is similar to replacements in lonnet::clean_filename()
12649: except each / between sub-directory and next level is preserved.
12650: 
12651: =cut
12652: 
12653: sub clean_path {
12654:     my ($embed_file) = @_;
12655:     $embed_file =~s{^/+}{};
12656:     my @contents;
12657:     if ($embed_file =~ m{/}) {
12658:         @contents = split(/\//,$embed_file);
12659:     } else {
12660:         @contents = ($embed_file);
12661:     }
12662:     my $lastidx = scalar(@contents)-1;
12663:     for (my $i=0; $i<=$lastidx; $i++) { 
12664:         $contents[$i]=~s{\\}{/}g;
12665:         $contents[$i]=~s/\s+/\_/g;
12666:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12667:         if ($i == $lastidx) {
12668:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12669:         }
12670:     }
12671:     if ($lastidx > 0) {
12672:         return join('/',@contents);
12673:     } else {
12674:         return $contents[0];
12675:     }
12676: }
12677: 
12678: sub embedded_file_element {
12679:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12680:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12681:                    (ref($codebase) eq 'HASH'));
12682:     my $output;
12683:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12684:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12685:     }
12686:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12687:                &escape($embed_file).'" />';
12688:     unless (($context eq 'upload_embedded') && 
12689:             ($mapping->{$embed_file} eq $embed_file)) {
12690:         $output .='
12691:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12692:     }
12693:     my $attrib;
12694:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12695:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12696:     }
12697:     $output .=
12698:         "\n\t\t".
12699:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12700:         $attrib.'" />';
12701:     if (exists($codebase->{$mapping->{$embed_file}})) {
12702:         $output .=
12703:             "\n\t\t".
12704:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12705:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12706:     }
12707:     return $output;
12708: }
12709: 
12710: sub get_dependency_details {
12711:     my ($currfile,$currsubfile,$embed_file) = @_;
12712:     my ($size,$mtime,$showsize,$showmtime);
12713:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12714:         if ($embed_file =~ m{/}) {
12715:             my ($path,$fname) = split(/\//,$embed_file);
12716:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12717:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12718:             }
12719:         } else {
12720:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12721:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12722:             }
12723:         }
12724:         $showsize = $size/1024.0;
12725:         $showsize = sprintf("%.1f",$showsize);
12726:         if ($mtime > 0) {
12727:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12728:         }
12729:     }
12730:     return ($showsize,$showmtime);
12731: }
12732: 
12733: sub ask_embedded_js {
12734:     return <<"END";
12735: <script type="text/javascript"">
12736: // <![CDATA[
12737: function toggleBrowse(counter) {
12738:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12739:     var fileid = document.getElementById('embedded_item_'+counter);
12740:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12741:     if (chkboxid.checked == true) {
12742:         uploaddivid.style.display='block';
12743:     } else {
12744:         uploaddivid.style.display='none';
12745:         fileid.value = '';
12746:     }
12747: }
12748: // ]]>
12749: </script>
12750: 
12751: END
12752: }
12753: 
12754: sub upload_embedded {
12755:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12756:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12757:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12758:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12759:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12760:         my $orig_uploaded_filename =
12761:             $env{'form.embedded_item_'.$i.'.filename'};
12762:         foreach my $type ('orig','ref','attrib','codebase') {
12763:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12764:                 $env{'form.embedded_'.$type.'_'.$i} =
12765:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12766:             }
12767:         }
12768:         my ($path,$fname) =
12769:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12770:         # no path, whole string is fname
12771:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12772:         $fname = &Apache::lonnet::clean_filename($fname);
12773:         # See if there is anything left
12774:         next if ($fname eq '');
12775: 
12776:         # Check if file already exists as a file or directory.
12777:         my ($state,$msg);
12778:         if ($context eq 'portfolio') {
12779:             my $port_path = $dirpath;
12780:             if ($group ne '') {
12781:                 $port_path = "groups/$group/$port_path";
12782:             }
12783:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12784:                                               $fname,$group,'embedded_item_'.$i,
12785:                                               $dir_root,$port_path,$disk_quota,
12786:                                               $current_disk_usage,$uname,$udom);
12787:             if ($state eq 'will_exceed_quota'
12788:                 || $state eq 'file_locked') {
12789:                 $output .= $msg;
12790:                 next;
12791:             }
12792:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12793:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12794:             if ($state eq 'exists') {
12795:                 $output .= $msg;
12796:                 next;
12797:             }
12798:         }
12799:         # Check if extension is valid
12800:         if (($fname =~ /\.(\w+)$/) &&
12801:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12802:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12803:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12804:             next;
12805:         } elsif (($fname =~ /\.(\w+)$/) &&
12806:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12807:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12808:             next;
12809:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12810:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12811:             next;
12812:         }
12813:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12814:         my $subdir = $path;
12815:         $subdir =~ s{/+$}{};
12816:         if ($context eq 'portfolio') {
12817:             my $result;
12818:             if ($state eq 'existingfile') {
12819:                 $result=
12820:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12821:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12822:             } else {
12823:                 $result=
12824:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12825:                                                     $dirpath.
12826:                                                     $env{'form.currentpath'}.$subdir);
12827:                 if ($result !~ m|^/uploaded/|) {
12828:                     $output .= '<span class="LC_error">'
12829:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12830:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12831:                                .'</span><br />';
12832:                     next;
12833:                 } else {
12834:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12835:                                $path.$fname.'</span>').'<br />';     
12836:                 }
12837:             }
12838:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12839:             my $extendedsubdir = $dirpath.'/'.$subdir;
12840:             $extendedsubdir =~ s{/+$}{};
12841:             my $result =
12842:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12843:             if ($result !~ m|^/uploaded/|) {
12844:                 $output .= '<span class="LC_error">'
12845:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12846:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12847:                            .'</span><br />';
12848:                     next;
12849:             } else {
12850:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12851:                            $path.$fname.'</span>').'<br />';
12852:                 if ($context eq 'syllabus') {
12853:                     &Apache::lonnet::make_public_indefinitely($result);
12854:                 }
12855:             }
12856:         } else {
12857: # Save the file
12858:             my $target = $env{'form.embedded_item_'.$i};
12859:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12860:             my $dest = $fullpath.$fname;
12861:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12862:             my @parts=split(/\//,"$dirpath/$path");
12863:             my $count;
12864:             my $filepath = $dir_root;
12865:             foreach my $subdir (@parts) {
12866:                 $filepath .= "/$subdir";
12867:                 if (!-e $filepath) {
12868:                     mkdir($filepath,0770);
12869:                 }
12870:             }
12871:             my $fh;
12872:             if (!open($fh,'>'.$dest)) {
12873:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12874:                 $output .= '<span class="LC_error">'.
12875:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12876:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12877:                            '</span><br />';
12878:             } else {
12879:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12880:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12881:                     $output .= '<span class="LC_error">'.
12882:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12883:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12884:                               '</span><br />';
12885:                 } else {
12886:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12887:                                $url.'</span>').'<br />';
12888:                     unless ($context eq 'testbank') {
12889:                         $footer .= &mt('View embedded file: [_1]',
12890:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12891:                     }
12892:                 }
12893:                 close($fh);
12894:             }
12895:         }
12896:         if ($env{'form.embedded_ref_'.$i}) {
12897:             $pathchange{$i} = 1;
12898:         }
12899:     }
12900:     if ($output) {
12901:         $output = '<p>'.$output.'</p>';
12902:     }
12903:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12904:     $returnflag = 'ok';
12905:     my $numpathchgs = scalar(keys(%pathchange));
12906:     if ($numpathchgs > 0) {
12907:         if ($context eq 'portfolio') {
12908:             $output .= '<p>'.&mt('or').'</p>';
12909:         } elsif ($context eq 'testbank') {
12910:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12911:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12912:             $returnflag = 'modify_orightml';
12913:         }
12914:     }
12915:     return ($output.$footer,$returnflag,$numpathchgs);
12916: }
12917: 
12918: sub modify_html_form {
12919:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12920:     my $end = 0;
12921:     my $modifyform;
12922:     if ($context eq 'upload_embedded') {
12923:         return unless (ref($pathchange) eq 'HASH');
12924:         if ($env{'form.number_embedded_items'}) {
12925:             $end += $env{'form.number_embedded_items'};
12926:         }
12927:         if ($env{'form.number_pathchange_items'}) {
12928:             $end += $env{'form.number_pathchange_items'};
12929:         }
12930:         if ($end) {
12931:             for (my $i=0; $i<$end; $i++) {
12932:                 if ($i < $env{'form.number_embedded_items'}) {
12933:                     next unless($pathchange->{$i});
12934:                 }
12935:                 $modifyform .=
12936:                     &start_data_table_row().
12937:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12938:                     'checked="checked" /></td>'.
12939:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12940:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12941:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12942:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12943:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12944:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12945:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12946:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12947:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12948:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12949:                     &end_data_table_row();
12950:             }
12951:         }
12952:     } else {
12953:         $modifyform = $pathchgtable;
12954:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12955:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12956:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12957:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12958:         }
12959:     }
12960:     if ($modifyform) {
12961:         if ($actionurl eq '/adm/dependencies') {
12962:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12963:         }
12964:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12965:                '<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".
12966:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12967:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12968:                '</ol></p>'."\n".'<p>'.
12969:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12970:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12971:                &start_data_table()."\n".
12972:                &start_data_table_header_row().
12973:                '<th>'.&mt('Change?').'</th>'.
12974:                '<th>'.&mt('Current reference').'</th>'.
12975:                '<th>'.&mt('Required reference').'</th>'.
12976:                &end_data_table_header_row()."\n".
12977:                $modifyform.
12978:                &end_data_table().'<br />'."\n".$hiddenstate.
12979:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12980:                '</form>'."\n";
12981:     }
12982:     return;
12983: }
12984: 
12985: sub modify_html_refs {
12986:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12987:     my $container;
12988:     if ($context eq 'portfolio') {
12989:         $container = $env{'form.container'};
12990:     } elsif ($context eq 'coursedoc') {
12991:         $container = $env{'form.primaryurl'};
12992:     } elsif ($context eq 'manage_dependencies') {
12993:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12994:         $container = "/$container";
12995:     } elsif ($context eq 'syllabus') {
12996:         $container = $url;
12997:     } else {
12998:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12999:     }
13000:     my (%allfiles,%codebase,$output,$content);
13001:     my @changes = &get_env_multiple('form.namechange');
13002:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13003:         if (wantarray) {
13004:             return ('',0,0); 
13005:         } else {
13006:             return;
13007:         }
13008:     }
13009:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13010:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13011:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13012:             if (wantarray) {
13013:                 return ('',0,0);
13014:             } else {
13015:                 return;
13016:             }
13017:         } 
13018:         $content = &Apache::lonnet::getfile($container);
13019:         if ($content eq '-1') {
13020:             if (wantarray) {
13021:                 return ('',0,0);
13022:             } else {
13023:                 return;
13024:             }
13025:         }
13026:     } else {
13027:         unless ($container =~ /^\Q$dir_root\E/) {
13028:             if (wantarray) {
13029:                 return ('',0,0);
13030:             } else {
13031:                 return;
13032:             }
13033:         } 
13034:         if (open(my $fh,'<',$container)) {
13035:             $content = join('', <$fh>);
13036:             close($fh);
13037:         } else {
13038:             if (wantarray) {
13039:                 return ('',0,0);
13040:             } else {
13041:                 return;
13042:             }
13043:         }
13044:     }
13045:     my ($count,$codebasecount) = (0,0);
13046:     my $mm = new File::MMagic;
13047:     my $mime_type = $mm->checktype_contents($content);
13048:     if ($mime_type eq 'text/html') {
13049:         my $parse_result = 
13050:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13051:                                                     \%codebase,\$content);
13052:         if ($parse_result eq 'ok') {
13053:             foreach my $i (@changes) {
13054:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13055:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13056:                 if ($allfiles{$ref}) {
13057:                     my $newname =  $orig;
13058:                     my ($attrib_regexp,$codebase);
13059:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13060:                     if ($attrib_regexp =~ /:/) {
13061:                         $attrib_regexp =~ s/\:/|/g;
13062:                     }
13063:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13064:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13065:                         $count += $numchg;
13066:                         $allfiles{$newname} = $allfiles{$ref};
13067:                         delete($allfiles{$ref});
13068:                     }
13069:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13070:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13071:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13072:                         $codebasecount ++;
13073:                     }
13074:                 }
13075:             }
13076:             my $skiprewrites;
13077:             if ($count || $codebasecount) {
13078:                 my $saveresult;
13079:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13080:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13081:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13082:                     if ($url eq $container) {
13083:                         my ($fname) = ($container =~ m{/([^/]+)$});
13084:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13085:                                             $count,'<span class="LC_filename">'.
13086:                                             $fname.'</span>').'</p>';
13087:                     } else {
13088:                          $output = '<p class="LC_error">'.
13089:                                    &mt('Error: update failed for: [_1].',
13090:                                    '<span class="LC_filename">'.
13091:                                    $container.'</span>').'</p>';
13092:                     }
13093:                     if ($context eq 'syllabus') {
13094:                         unless ($saveresult eq 'ok') {
13095:                             $skiprewrites = 1;
13096:                         }
13097:                     }
13098:                 } else {
13099:                     if (open(my $fh,'>',$container)) {
13100:                         print $fh $content;
13101:                         close($fh);
13102:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13103:                                   $count,'<span class="LC_filename">'.
13104:                                   $container.'</span>').'</p>';
13105:                     } else {
13106:                          $output = '<p class="LC_error">'.
13107:                                    &mt('Error: could not update [_1].',
13108:                                    '<span class="LC_filename">'.
13109:                                    $container.'</span>').'</p>';
13110:                     }
13111:                 }
13112:             }
13113:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13114:                 my ($actionurl,$state);
13115:                 $actionurl = "/public/$udom/$uname/syllabus";
13116:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13117:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13118:                                               \%codebase,
13119:                                               {'context' => 'rewrites',
13120:                                                'ignore_remote_references' => 1,});
13121:                 if (ref($mapping) eq 'HASH') {
13122:                     my $rewrites = 0;
13123:                     foreach my $key (keys(%{$mapping})) {
13124:                         next if ($key =~ m{^https?://});
13125:                         my $ref = $mapping->{$key};
13126:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13127:                         my $attrib;
13128:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13129:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13130:                         }
13131:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13132:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13133:                             $rewrites += $numchg;
13134:                         }
13135:                     }
13136:                     if ($rewrites) {
13137:                         my $saveresult; 
13138:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13139:                         if ($url eq $container) {
13140:                             my ($fname) = ($container =~ m{/([^/]+)$});
13141:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13142:                                             $count,'<span class="LC_filename">'.
13143:                                             $fname.'</span>').'</p>';
13144:                         } else {
13145:                             $output .= '<p class="LC_error">'.
13146:                                        &mt('Error: could not update links in [_1].',
13147:                                        '<span class="LC_filename">'.
13148:                                        $container.'</span>').'</p>';
13149: 
13150:                         }
13151:                     }
13152:                 }
13153:             }
13154:         } else {
13155:             &logthis('Failed to parse '.$container.
13156:                      ' to modify references: '.$parse_result);
13157:         }
13158:     }
13159:     if (wantarray) {
13160:         return ($output,$count,$codebasecount);
13161:     } else {
13162:         return $output;
13163:     }
13164: }
13165: 
13166: sub check_for_existing {
13167:     my ($path,$fname,$element) = @_;
13168:     my ($state,$msg);
13169:     if (-d $path.'/'.$fname) {
13170:         $state = 'exists';
13171:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13172:     } elsif (-e $path.'/'.$fname) {
13173:         $state = 'exists';
13174:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13175:     }
13176:     if ($state eq 'exists') {
13177:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13178:     }
13179:     return ($state,$msg);
13180: }
13181: 
13182: sub check_for_upload {
13183:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13184:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13185:     my $filesize = length($env{'form.'.$element});
13186:     if (!$filesize) {
13187:         my $msg = '<span class="LC_error">'.
13188:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13189:                       '<span class="LC_filename">'.$fname.'</span>',
13190:                       $filesize).'<br />'.
13191:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13192:                   '</span>';
13193:         return ('zero_bytes',$msg);
13194:     }
13195:     $filesize =  $filesize/1000; #express in k (1024?)
13196:     my $getpropath = 1;
13197:     my ($dirlistref,$listerror) =
13198:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13199:     my $found_file = 0;
13200:     my $locked_file = 0;
13201:     my @lockers;
13202:     my $navmap;
13203:     if ($env{'request.course.id'}) {
13204:         $navmap = Apache::lonnavmaps::navmap->new();
13205:     }
13206:     if (ref($dirlistref) eq 'ARRAY') {
13207:         foreach my $line (@{$dirlistref}) {
13208:             my ($file_name,$rest)=split(/\&/,$line,2);
13209:             if ($file_name eq $fname){
13210:                 $file_name = $path.$file_name;
13211:                 if ($group ne '') {
13212:                     $file_name = $group.$file_name;
13213:                 }
13214:                 $found_file = 1;
13215:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13216:                     foreach my $lock (@lockers) {
13217:                         if (ref($lock) eq 'ARRAY') {
13218:                             my ($symb,$crsid) = @{$lock};
13219:                             if ($crsid eq $env{'request.course.id'}) {
13220:                                 if (ref($navmap)) {
13221:                                     my $res = $navmap->getBySymb($symb);
13222:                                     foreach my $part (@{$res->parts()}) { 
13223:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13224:                                         unless (($slot_status == $res->RESERVED) ||
13225:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13226:                                             $locked_file = 1;
13227:                                         }
13228:                                     }
13229:                                 } else {
13230:                                     $locked_file = 1;
13231:                                 }
13232:                             } else {
13233:                                 $locked_file = 1;
13234:                             }
13235:                         }
13236:                    }
13237:                 } else {
13238:                     my @info = split(/\&/,$rest);
13239:                     my $currsize = $info[6]/1000;
13240:                     if ($currsize < $filesize) {
13241:                         my $extra = $filesize - $currsize;
13242:                         if (($current_disk_usage + $extra) > $disk_quota) {
13243:                             my $msg = '<p class="LC_warning">'.
13244:                                       &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.',
13245:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13246:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13247:                                                    $disk_quota,$current_disk_usage).'</p>';
13248:                             return ('will_exceed_quota',$msg);
13249:                         }
13250:                     }
13251:                 }
13252:             }
13253:         }
13254:     }
13255:     if (($current_disk_usage + $filesize) > $disk_quota){
13256:         my $msg = '<p class="LC_warning">'.
13257:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13258:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13259:         return ('will_exceed_quota',$msg);
13260:     } elsif ($found_file) {
13261:         if ($locked_file) {
13262:             my $msg = '<p class="LC_warning">';
13263:             $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>');
13264:             $msg .= '</p>';
13265:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13266:             return ('file_locked',$msg);
13267:         } else {
13268:             my $msg = '<p class="LC_error">';
13269:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13270:             $msg .= '</p>';
13271:             return ('existingfile',$msg);
13272:         }
13273:     }
13274: }
13275: 
13276: sub check_for_traversal {
13277:     my ($path,$url,$toplevel) = @_;
13278:     my @parts=split(/\//,$path);
13279:     my $cleanpath;
13280:     my $fullpath = $url;
13281:     for (my $i=0;$i<@parts;$i++) {
13282:         next if ($parts[$i] eq '.');
13283:         if ($parts[$i] eq '..') {
13284:             $fullpath =~ s{([^/]+/)$}{};
13285:         } else {
13286:             $fullpath .= $parts[$i].'/';
13287:         }
13288:     }
13289:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13290:         $cleanpath = $1;
13291:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13292:         my $curr_toprel = $1;
13293:         my @parts = split(/\//,$curr_toprel);
13294:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13295:         my @urlparts = split(/\//,$url_toprel);
13296:         my $doubledots;
13297:         my $startdiff = -1;
13298:         for (my $i=0; $i<@urlparts; $i++) {
13299:             if ($startdiff == -1) {
13300:                 unless ($urlparts[$i] eq $parts[$i]) {
13301:                     $startdiff = $i;
13302:                     $doubledots .= '../';
13303:                 }
13304:             } else {
13305:                 $doubledots .= '../';
13306:             }
13307:         }
13308:         if ($startdiff > -1) {
13309:             $cleanpath = $doubledots;
13310:             for (my $i=$startdiff; $i<@parts; $i++) {
13311:                 $cleanpath .= $parts[$i].'/';
13312:             }
13313:         }
13314:     }
13315:     $cleanpath =~ s{(/)$}{};
13316:     return $cleanpath;
13317: }
13318: 
13319: sub is_archive_file {
13320:     my ($mimetype) = @_;
13321:     if (($mimetype eq 'application/octet-stream') ||
13322:         ($mimetype eq 'application/x-stuffit') ||
13323:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13324:         return 1;
13325:     }
13326:     return;
13327: }
13328: 
13329: sub decompress_form {
13330:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13331:     my %lt = &Apache::lonlocal::texthash (
13332:         this => 'This file is an archive file.',
13333:         camt => 'This file is a Camtasia archive file.',
13334:         itsc => 'Its contents are as follows:',
13335:         youm => 'You may wish to extract its contents.',
13336:         extr => 'Extract contents',
13337:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13338:         proa => 'Process automatically?',
13339:         yes  => 'Yes',
13340:         no   => 'No',
13341:         fold => 'Title for folder containing movie',
13342:         movi => 'Title for page containing embedded movie', 
13343:     );
13344:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13345:     my ($is_camtasia,$topdir,%toplevel,@paths);
13346:     my $info = &list_archive_contents($fileloc,\@paths);
13347:     if (@paths) {
13348:         foreach my $path (@paths) {
13349:             $path =~ s{^/}{};
13350:             if ($path =~ m{^([^/]+)/$}) {
13351:                 $topdir = $1;
13352:             }
13353:             if ($path =~ m{^([^/]+)/}) {
13354:                 $toplevel{$1} = $path;
13355:             } else {
13356:                 $toplevel{$path} = $path;
13357:             }
13358:         }
13359:     }
13360:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13361:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13362:                         "$topdir/media/",
13363:                         "$topdir/media/$topdir.mp4",
13364:                         "$topdir/media/FirstFrame.png",
13365:                         "$topdir/media/player.swf",
13366:                         "$topdir/media/swfobject.js",
13367:                         "$topdir/media/expressInstall.swf");
13368:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13369:                          "$topdir/$topdir.mp4",
13370:                          "$topdir/$topdir\_config.xml",
13371:                          "$topdir/$topdir\_controller.swf",
13372:                          "$topdir/$topdir\_embed.css",
13373:                          "$topdir/$topdir\_First_Frame.png",
13374:                          "$topdir/$topdir\_player.html",
13375:                          "$topdir/$topdir\_Thumbnails.png",
13376:                          "$topdir/playerProductInstall.swf",
13377:                          "$topdir/scripts/",
13378:                          "$topdir/scripts/config_xml.js",
13379:                          "$topdir/scripts/handlebars.js",
13380:                          "$topdir/scripts/jquery-1.7.1.min.js",
13381:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13382:                          "$topdir/scripts/modernizr.js",
13383:                          "$topdir/scripts/player-min.js",
13384:                          "$topdir/scripts/swfobject.js",
13385:                          "$topdir/skins/",
13386:                          "$topdir/skins/configuration_express.xml",
13387:                          "$topdir/skins/express_show/",
13388:                          "$topdir/skins/express_show/player-min.css",
13389:                          "$topdir/skins/express_show/spritesheet.png");
13390:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13391:                          "$topdir/$topdir.mp4",
13392:                          "$topdir/$topdir\_config.xml",
13393:                          "$topdir/$topdir\_controller.swf",
13394:                          "$topdir/$topdir\_embed.css",
13395:                          "$topdir/$topdir\_First_Frame.png",
13396:                          "$topdir/$topdir\_player.html",
13397:                          "$topdir/$topdir\_Thumbnails.png",
13398:                          "$topdir/playerProductInstall.swf",
13399:                          "$topdir/scripts/",
13400:                          "$topdir/scripts/config_xml.js",
13401:                          "$topdir/scripts/techsmith-smart-player.min.js",
13402:                          "$topdir/skins/",
13403:                          "$topdir/skins/configuration_express.xml",
13404:                          "$topdir/skins/express_show/",
13405:                          "$topdir/skins/express_show/spritesheet.min.css",
13406:                          "$topdir/skins/express_show/spritesheet.png",
13407:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13408:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13409:         if (@diffs == 0) {
13410:             $is_camtasia = 6;
13411:         } else {
13412:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13413:             if (@diffs == 0) {
13414:                 $is_camtasia = 8;
13415:             } else {
13416:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13417:                 if (@diffs == 0) {
13418:                     $is_camtasia = 8;
13419:                 }
13420:             }
13421:         }
13422:     }
13423:     my $output;
13424:     if ($is_camtasia) {
13425:         $output = <<"ENDCAM";
13426: <script type="text/javascript" language="Javascript">
13427: // <![CDATA[
13428: 
13429: function camtasiaToggle() {
13430:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13431:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13432:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13433:                 document.getElementById('camtasia_titles').style.display='block';
13434:             } else {
13435:                 document.getElementById('camtasia_titles').style.display='none';
13436:             }
13437:         }
13438:     }
13439:     return;
13440: }
13441: 
13442: // ]]>
13443: </script>
13444: <p>$lt{'camt'}</p>
13445: ENDCAM
13446:     } else {
13447:         $output = '<p>'.$lt{'this'};
13448:         if ($info eq '') {
13449:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13450:         } else {
13451:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13452:                        '<div><pre>'.$info.'</pre></div>';
13453:         }
13454:     }
13455:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13456:     my $duplicates;
13457:     my $num = 0;
13458:     if (ref($dirlist) eq 'ARRAY') {
13459:         foreach my $item (@{$dirlist}) {
13460:             if (ref($item) eq 'ARRAY') {
13461:                 if (exists($toplevel{$item->[0]})) {
13462:                     $duplicates .= 
13463:                         &start_data_table_row().
13464:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13465:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13466:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13467:                         'value="1" />'.&mt('Yes').'</label>'.
13468:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13469:                         '<td>'.$item->[0].'</td>';
13470:                     if ($item->[2]) {
13471:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13472:                     } else {
13473:                         $duplicates .= '<td>'.&mt('File').'</td>';
13474:                     }
13475:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13476:                                    '<td>'.
13477:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13478:                                    '</td>'.
13479:                                    &end_data_table_row();
13480:                     $num ++;
13481:                 }
13482:             }
13483:         }
13484:     }
13485:     my $itemcount;
13486:     if (@paths > 0) {
13487:         $itemcount = scalar(@paths);
13488:     } else {
13489:         $itemcount = 1;
13490:     }
13491:     if ($is_camtasia) {
13492:         $output .= $lt{'auto'}.'<br />'.
13493:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13494:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13495:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13496:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13497:                    $lt{'no'}.'</label></span><br />'.
13498:                    '<div id="camtasia_titles" style="display:block">'.
13499:                    &Apache::lonhtmlcommon::start_pick_box().
13500:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13501:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13502:                    &Apache::lonhtmlcommon::row_closure().
13503:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13504:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13505:                    &Apache::lonhtmlcommon::row_closure(1).
13506:                    &Apache::lonhtmlcommon::end_pick_box().
13507:                    '</div>';
13508:     }
13509:     $output .= 
13510:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13511:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13512:         "\n";
13513:     if ($duplicates ne '') {
13514:         $output .= '<p><span class="LC_warning">'.
13515:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13516:                    &start_data_table().
13517:                    &start_data_table_header_row().
13518:                    '<th>'.&mt('Overwrite?').'</th>'.
13519:                    '<th>'.&mt('Name').'</th>'.
13520:                    '<th>'.&mt('Type').'</th>'.
13521:                    '<th>'.&mt('Size').'</th>'.
13522:                    '<th>'.&mt('Last modified').'</th>'.
13523:                    &end_data_table_header_row().
13524:                    $duplicates.
13525:                    &end_data_table().
13526:                    '</p>';
13527:     }
13528:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13529:     if (ref($hiddenelements) eq 'HASH') {
13530:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13531:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13532:         }
13533:     }
13534:     $output .= <<"END";
13535: <br />
13536: <input type="submit" name="decompress" value="$lt{'extr'}" />
13537: </form>
13538: $noextract
13539: END
13540:     return $output;
13541: }
13542: 
13543: sub decompression_utility {
13544:     my ($program) = @_;
13545:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13546:     my $location;
13547:     if (grep(/^\Q$program\E$/,@utilities)) { 
13548:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13549:                          '/usr/sbin/') {
13550:             if (-x $dir.$program) {
13551:                 $location = $dir.$program;
13552:                 last;
13553:             }
13554:         }
13555:     }
13556:     return $location;
13557: }
13558: 
13559: sub list_archive_contents {
13560:     my ($file,$pathsref) = @_;
13561:     my (@cmd,$output);
13562:     my $needsregexp;
13563:     if ($file =~ /\.zip$/) {
13564:         @cmd = (&decompression_utility('unzip'),"-l");
13565:         $needsregexp = 1;
13566:     } elsif (($file =~ m/\.tar\.gz$/) ||
13567:              ($file =~ /\.tgz$/)) {
13568:         @cmd = (&decompression_utility('tar'),"-ztf");
13569:     } elsif ($file =~ /\.tar\.bz2$/) {
13570:         @cmd = (&decompression_utility('tar'),"-jtf");
13571:     } elsif ($file =~ m|\.tar$|) {
13572:         @cmd = (&decompression_utility('tar'),"-tf");
13573:     }
13574:     if (@cmd) {
13575:         undef($!);
13576:         undef($@);
13577:         if (open(my $fh,"-|", @cmd, $file)) {
13578:             while (my $line = <$fh>) {
13579:                 $output .= $line;
13580:                 chomp($line);
13581:                 my $item;
13582:                 if ($needsregexp) {
13583:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13584:                 } else {
13585:                     $item = $line;
13586:                 }
13587:                 if ($item ne '') {
13588:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13589:                         push(@{$pathsref},$item);
13590:                     } 
13591:                 }
13592:             }
13593:             close($fh);
13594:         }
13595:     }
13596:     return $output;
13597: }
13598: 
13599: sub decompress_uploaded_file {
13600:     my ($file,$dir) = @_;
13601:     &Apache::lonnet::appenv({'cgi.file' => $file});
13602:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13603:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13604:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13605:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13606:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13607:     my $decompressed = $env{'cgi.decompressed'};
13608:     &Apache::lonnet::delenv('cgi.file');
13609:     &Apache::lonnet::delenv('cgi.dir');
13610:     &Apache::lonnet::delenv('cgi.decompressed');
13611:     return ($decompressed,$result);
13612: }
13613: 
13614: sub process_decompression {
13615:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13616:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13617:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13618:                &mt('Unexpected file path.').'</p>'."\n";
13619:     }
13620:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13621:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13622:                &mt('Unexpected course context.').'</p>'."\n";
13623:     }
13624:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13625:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13626:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13627:     }
13628:     my ($dir,$error,$warning,$output);
13629:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13630:         $error = &mt('Filename not a supported archive file type.').
13631:                  '<br />'.&mt('Filename should end with one of: [_1].',
13632:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13633:     } else {
13634:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13635:         if ($docuhome eq 'no_host') {
13636:             $error = &mt('Could not determine home server for course.');
13637:         } else {
13638:             my @ids=&Apache::lonnet::current_machine_ids();
13639:             my $currdir = "$dir_root/$destination";
13640:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13641:                 $dir = &LONCAPA::propath($docudom,$docuname).
13642:                        "$dir_root/$destination";
13643:             } else {
13644:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13645:                        "$dir_root/$docudom/$docuname/$destination";
13646:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13647:                     $error = &mt('Archive file not found.');
13648:                 }
13649:             }
13650:             my (@to_overwrite,@to_skip);
13651:             if ($env{'form.archive_overwrite_total'} > 0) {
13652:                 my $total = $env{'form.archive_overwrite_total'};
13653:                 for (my $i=0; $i<$total; $i++) {
13654:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13655:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13656:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13657:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13658:                     }
13659:                 }
13660:             }
13661:             my $numskip = scalar(@to_skip);
13662:             my $numoverwrite = scalar(@to_overwrite);
13663:             if (($numskip) && (!$numoverwrite)) { 
13664:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13665:             } elsif ($dir eq '') {
13666:                 $error = &mt('Directory containing archive file unavailable.');
13667:             } elsif (!$error) {
13668:                 my ($decompressed,$display);
13669:                 if (($numskip) || ($numoverwrite)) {
13670:                     my $tempdir = time.'_'.$$.int(rand(10000));
13671:                     mkdir("$dir/$tempdir",0755);
13672:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13673:                         ($decompressed,$display) = 
13674:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13675:                         foreach my $item (@to_skip) {
13676:                             if (($item ne '') && ($item !~ /\.\./)) {
13677:                                 if (-f "$dir/$tempdir/$item") { 
13678:                                     unlink("$dir/$tempdir/$item");
13679:                                 } elsif (-d "$dir/$tempdir/$item") {
13680:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13681:                                 }
13682:                             }
13683:                         }
13684:                         foreach my $item (@to_overwrite) {
13685:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13686:                                 if (($item ne '') && ($item !~ /\.\./)) {
13687:                                     if (-f "$dir/$item") {
13688:                                         unlink("$dir/$item");
13689:                                     } elsif (-d "$dir/$item") {
13690:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13691:                                     }
13692:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13693:                                 }
13694:                             }
13695:                         }
13696:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13697:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13698:                         }
13699:                     }
13700:                 } else {
13701:                     ($decompressed,$display) = 
13702:                         &decompress_uploaded_file($file,$dir);
13703:                 }
13704:                 if ($decompressed eq 'ok') {
13705:                     $output = '<p class="LC_info">'.
13706:                               &mt('Files extracted successfully from archive.').
13707:                               '</p>'."\n";
13708:                     my ($warning,$result,@contents);
13709:                     my ($newdirlistref,$newlisterror) =
13710:                         &Apache::lonnet::dirlist($currdir,$docudom,
13711:                                                  $docuname,1);
13712:                     my (%is_dir,%changes,@newitems);
13713:                     my $dirptr = 16384;
13714:                     if (ref($newdirlistref) eq 'ARRAY') {
13715:                         foreach my $dir_line (@{$newdirlistref}) {
13716:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13717:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13718:                                 push(@newitems,$item);
13719:                                 if ($dirptr&$testdir) {
13720:                                     $is_dir{$item} = 1;
13721:                                 }
13722:                                 $changes{$item} = 1;
13723:                             }
13724:                         }
13725:                     }
13726:                     if (keys(%changes) > 0) {
13727:                         foreach my $item (sort(@newitems)) {
13728:                             if ($changes{$item}) {
13729:                                 push(@contents,$item);
13730:                             }
13731:                         }
13732:                     }
13733:                     if (@contents > 0) {
13734:                         my $wantform;
13735:                         unless ($env{'form.autoextract_camtasia'}) {
13736:                             $wantform = 1;
13737:                         }
13738:                         my (%children,%parent,%dirorder,%titles);
13739:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13740:                                                                 $currdir,\%is_dir,
13741:                                                                 \%children,\%parent,
13742:                                                                 \@contents,\%dirorder,
13743:                                                                 \%titles,$wantform);
13744:                         if ($datatable ne '') {
13745:                             $output .= &archive_options_form('decompressed',$datatable,
13746:                                                              $count,$hiddenelem);
13747:                             my $startcount = 6;
13748:                             $output .= &archive_javascript($startcount,$count,
13749:                                                            \%titles,\%children);
13750:                         }
13751:                         if ($env{'form.autoextract_camtasia'}) {
13752:                             my $version = $env{'form.autoextract_camtasia'};
13753:                             my %displayed;
13754:                             my $total = 1;
13755:                             $env{'form.archive_directory'} = [];
13756:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13757:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13758:                                 $path =~ s{/$}{};
13759:                                 my $item;
13760:                                 if ($path ne '') {
13761:                                     $item = "$path/$titles{$i}";
13762:                                 } else {
13763:                                     $item = $titles{$i};
13764:                                 }
13765:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13766:                                 if ($item eq $contents[0]) {
13767:                                     push(@{$env{'form.archive_directory'}},$i);
13768:                                     $env{'form.archive_'.$i} = 'display';
13769:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13770:                                     $displayed{'folder'} = $i;
13771:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13772:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13773:                                     $env{'form.archive_'.$i} = 'display';
13774:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13775:                                     $displayed{'web'} = $i;
13776:                                 } else {
13777:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13778:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13779:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13780:                                         push(@{$env{'form.archive_directory'}},$i);
13781:                                     }
13782:                                     $env{'form.archive_'.$i} = 'dependency';
13783:                                 }
13784:                                 $total ++;
13785:                             }
13786:                             for (my $i=1; $i<$total; $i++) {
13787:                                 next if ($i == $displayed{'web'});
13788:                                 next if ($i == $displayed{'folder'});
13789:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13790:                             }
13791:                             $env{'form.phase'} = 'decompress_cleanup';
13792:                             $env{'form.archivedelete'} = 1;
13793:                             $env{'form.archive_count'} = $total-1;
13794:                             $output .=
13795:                                 &process_extracted_files('coursedocs',$docudom,
13796:                                                          $docuname,$destination,
13797:                                                          $dir_root,$hiddenelem);
13798:                         }
13799:                     } else {
13800:                         $warning = &mt('No new items extracted from archive file.');
13801:                     }
13802:                 } else {
13803:                     $output = $display;
13804:                     $error = &mt('An error occurred during extraction from the archive file.');
13805:                 }
13806:             }
13807:         }
13808:     }
13809:     if ($error) {
13810:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13811:                    $error.'</p>'."\n";
13812:     }
13813:     if ($warning) {
13814:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13815:     }
13816:     return $output;
13817: }
13818: 
13819: sub get_extracted {
13820:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13821:         $titles,$wantform) = @_;
13822:     my $count = 0;
13823:     my $depth = 0;
13824:     my $datatable;
13825:     my @hierarchy;
13826:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13827:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13828:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13829:     foreach my $item (@{$contents}) {
13830:         $count ++;
13831:         @{$dirorder->{$count}} = @hierarchy;
13832:         $titles->{$count} = $item;
13833:         &archive_hierarchy($depth,$count,$parent,$children);
13834:         if ($wantform) {
13835:             $datatable .= &archive_row($is_dir->{$item},$item,
13836:                                        $currdir,$depth,$count);
13837:         }
13838:         if ($is_dir->{$item}) {
13839:             $depth ++;
13840:             push(@hierarchy,$count);
13841:             $parent->{$depth} = $count;
13842:             $datatable .=
13843:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13844:                                            \$depth,\$count,\@hierarchy,$dirorder,
13845:                                            $children,$parent,$titles,$wantform);
13846:             $depth --;
13847:             pop(@hierarchy);
13848:         }
13849:     }
13850:     return ($count,$datatable);
13851: }
13852: 
13853: sub recurse_extracted_archive {
13854:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13855:         $children,$parent,$titles,$wantform) = @_;
13856:     my $result='';
13857:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13858:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13859:             (ref($dirorder) eq 'HASH')) {
13860:         return $result;
13861:     }
13862:     my $dirptr = 16384;
13863:     my ($newdirlistref,$newlisterror) =
13864:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13865:     if (ref($newdirlistref) eq 'ARRAY') {
13866:         foreach my $dir_line (@{$newdirlistref}) {
13867:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13868:             unless ($item =~ /^\.+$/) {
13869:                 $$count ++;
13870:                 @{$dirorder->{$$count}} = @{$hierarchy};
13871:                 $titles->{$$count} = $item;
13872:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13873: 
13874:                 my $is_dir;
13875:                 if ($dirptr&$testdir) {
13876:                     $is_dir = 1;
13877:                 }
13878:                 if ($wantform) {
13879:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13880:                 }
13881:                 if ($is_dir) {
13882:                     $$depth ++;
13883:                     push(@{$hierarchy},$$count);
13884:                     $parent->{$$depth} = $$count;
13885:                     $result .=
13886:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13887:                                                    $docuname,$depth,$count,
13888:                                                    $hierarchy,$dirorder,$children,
13889:                                                    $parent,$titles,$wantform);
13890:                     $$depth --;
13891:                     pop(@{$hierarchy});
13892:                 }
13893:             }
13894:         }
13895:     }
13896:     return $result;
13897: }
13898: 
13899: sub archive_hierarchy {
13900:     my ($depth,$count,$parent,$children) =@_;
13901:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13902:         if (exists($parent->{$depth})) {
13903:              $children->{$parent->{$depth}} .= $count.':';
13904:         }
13905:     }
13906:     return;
13907: }
13908: 
13909: sub archive_row {
13910:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13911:     my ($name) = ($item =~ m{([^/]+)$});
13912:     my %choices = &Apache::lonlocal::texthash (
13913:                                        'display'    => 'Add as file',
13914:                                        'dependency' => 'Include as dependency',
13915:                                        'discard'    => 'Discard',
13916:                                       );
13917:     if ($is_dir) {
13918:         $choices{'display'} = &mt('Add as folder'); 
13919:     }
13920:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13921:     my $offset = 0;
13922:     foreach my $action ('display','dependency','discard') {
13923:         $offset ++;
13924:         if ($action ne 'display') {
13925:             $offset ++;
13926:         }  
13927:         $output .= '<td><span class="LC_nobreak">'.
13928:                    '<label><input type="radio" name="archive_'.$count.
13929:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13930:         my $text = $choices{$action};
13931:         if ($is_dir) {
13932:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13933:             if ($action eq 'display') {
13934:                 $text = &mt('Add as folder');
13935:             }
13936:         } else {
13937:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13938: 
13939:         }
13940:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13941:         if ($action eq 'dependency') {
13942:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13943:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13944:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13945:                        '<option value=""></option>'."\n".
13946:                        '</select>'."\n".
13947:                        '</div>';
13948:         } elsif ($action eq 'display') {
13949:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13950:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13951:                        '</div>';
13952:         }
13953:         $output .= '</td>';
13954:     }
13955:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13956:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13957:     for (my $i=0; $i<$depth; $i++) {
13958:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13959:     }
13960:     if ($is_dir) {
13961:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13962:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13963:     } else {
13964:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13965:     }
13966:     $output .= '&nbsp;'.$name.'</td>'."\n".
13967:                &end_data_table_row();
13968:     return $output;
13969: }
13970: 
13971: sub archive_options_form {
13972:     my ($form,$display,$count,$hiddenelem) = @_;
13973:     my %lt = &Apache::lonlocal::texthash(
13974:                perm => 'Permanently remove archive file?',
13975:                hows => 'How should each extracted item be incorporated in the course?',
13976:                cont => 'Content actions for all',
13977:                addf => 'Add as folder/file',
13978:                incd => 'Include as dependency for a displayed file',
13979:                disc => 'Discard',
13980:                no   => 'No',
13981:                yes  => 'Yes',
13982:                save => 'Save',
13983:     );
13984:     my $output = <<"END";
13985: <form name="$form" method="post" action="">
13986: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13987: <label>
13988:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13989: </label>
13990: &nbsp;
13991: <label>
13992:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13993: </span>
13994: </p>
13995: <input type="hidden" name="phase" value="decompress_cleanup" />
13996: <br />$lt{'hows'}
13997: <div class="LC_columnSection">
13998:   <fieldset>
13999:     <legend>$lt{'cont'}</legend>
14000:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14001:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14002:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14003:   </fieldset>
14004: </div>
14005: END
14006:     return $output.
14007:            &start_data_table()."\n".
14008:            $display."\n".
14009:            &end_data_table()."\n".
14010:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14011:            $hiddenelem.
14012:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14013:            '</form>';
14014: }
14015: 
14016: sub archive_javascript {
14017:     my ($startcount,$numitems,$titles,$children) = @_;
14018:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14019:     my $maintitle = $env{'form.comment'};
14020:     my $scripttag = <<START;
14021: <script type="text/javascript">
14022: // <![CDATA[
14023: 
14024: function checkAll(form,prefix) {
14025:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14026:     for (var i=0; i < form.elements.length; i++) {
14027:         var id = form.elements[i].id;
14028:         if ((id != '') && (id != undefined)) {
14029:             if (idstr.test(id)) {
14030:                 if (form.elements[i].type == 'radio') {
14031:                     form.elements[i].checked = true;
14032:                     var nostart = i-$startcount;
14033:                     var offset = nostart%7;
14034:                     var count = (nostart-offset)/7;    
14035:                     dependencyCheck(form,count,offset);
14036:                 }
14037:             }
14038:         }
14039:     }
14040: }
14041: 
14042: function propagateCheck(form,count) {
14043:     if (count > 0) {
14044:         var startelement = $startcount + ((count-1) * 7);
14045:         for (var j=1; j<6; j++) {
14046:             if ((j != 2) && (j != 4)) {
14047:                 var item = startelement + j; 
14048:                 if (form.elements[item].type == 'radio') {
14049:                     if (form.elements[item].checked) {
14050:                         containerCheck(form,count,j);
14051:                         break;
14052:                     }
14053:                 }
14054:             }
14055:         }
14056:     }
14057: }
14058: 
14059: numitems = $numitems
14060: var titles = new Array(numitems);
14061: var parents = new Array(numitems);
14062: for (var i=0; i<numitems; i++) {
14063:     parents[i] = new Array;
14064: }
14065: var maintitle = '$maintitle';
14066: 
14067: START
14068: 
14069:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14070:         my @contents = split(/:/,$children->{$container});
14071:         for (my $i=0; $i<@contents; $i ++) {
14072:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14073:         }
14074:     }
14075: 
14076:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14077:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14078:     }
14079: 
14080:     $scripttag .= <<END;
14081: 
14082: function containerCheck(form,count,offset) {
14083:     if (count > 0) {
14084:         dependencyCheck(form,count,offset);
14085:         var item = (offset+$startcount)+7*(count-1);
14086:         form.elements[item].checked = true;
14087:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14088:             if (parents[count].length > 0) {
14089:                 for (var j=0; j<parents[count].length; j++) {
14090:                     containerCheck(form,parents[count][j],offset);
14091:                 }
14092:             }
14093:         }
14094:     }
14095: }
14096: 
14097: function dependencyCheck(form,count,offset) {
14098:     if (count > 0) {
14099:         var chosen = (offset+$startcount)+7*(count-1);
14100:         var depitem = $startcount + ((count-1) * 7) + 4;
14101:         var currtype = form.elements[depitem].type;
14102:         if (form.elements[chosen].value == 'dependency') {
14103:             document.getElementById('arc_depon_'+count).style.display='block'; 
14104:             form.elements[depitem].options.length = 0;
14105:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14106:             for (var i=1; i<=numitems; i++) {
14107:                 if (i == count) {
14108:                     continue;
14109:                 }
14110:                 var startelement = $startcount + (i-1) * 7;
14111:                 for (var j=1; j<6; j++) {
14112:                     if ((j != 2) && (j!= 4)) {
14113:                         var item = startelement + j;
14114:                         if (form.elements[item].type == 'radio') {
14115:                             if (form.elements[item].checked) {
14116:                                 if (form.elements[item].value == 'display') {
14117:                                     var n = form.elements[depitem].options.length;
14118:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14119:                                 }
14120:                             }
14121:                         }
14122:                     }
14123:                 }
14124:             }
14125:         } else {
14126:             document.getElementById('arc_depon_'+count).style.display='none';
14127:             form.elements[depitem].options.length = 0;
14128:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14129:         }
14130:         titleCheck(form,count,offset);
14131:     }
14132: }
14133: 
14134: function propagateSelect(form,count,offset) {
14135:     if (count > 0) {
14136:         var item = (1+offset+$startcount)+7*(count-1);
14137:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14138:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14139:             if (parents[count].length > 0) {
14140:                 for (var j=0; j<parents[count].length; j++) {
14141:                     containerSelect(form,parents[count][j],offset,picked);
14142:                 }
14143:             }
14144:         }
14145:     }
14146: }
14147: 
14148: function containerSelect(form,count,offset,picked) {
14149:     if (count > 0) {
14150:         var item = (offset+$startcount)+7*(count-1);
14151:         if (form.elements[item].type == 'radio') {
14152:             if (form.elements[item].value == 'dependency') {
14153:                 if (form.elements[item+1].type == 'select-one') {
14154:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14155:                         if (form.elements[item+1].options[i].value == picked) {
14156:                             form.elements[item+1].selectedIndex = i;
14157:                             break;
14158:                         }
14159:                     }
14160:                 }
14161:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14162:                     if (parents[count].length > 0) {
14163:                         for (var j=0; j<parents[count].length; j++) {
14164:                             containerSelect(form,parents[count][j],offset,picked);
14165:                         }
14166:                     }
14167:                 }
14168:             }
14169:         }
14170:     }
14171: }
14172: 
14173: function titleCheck(form,count,offset) {
14174:     if (count > 0) {
14175:         var chosen = (offset+$startcount)+7*(count-1);
14176:         var depitem = $startcount + ((count-1) * 7) + 2;
14177:         var currtype = form.elements[depitem].type;
14178:         if (form.elements[chosen].value == 'display') {
14179:             document.getElementById('arc_title_'+count).style.display='block';
14180:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14181:                 document.getElementById('archive_title_'+count).value=maintitle;
14182:             }
14183:         } else {
14184:             document.getElementById('arc_title_'+count).style.display='none';
14185:             if (currtype == 'text') { 
14186:                 document.getElementById('archive_title_'+count).value='';
14187:             }
14188:         }
14189:     }
14190:     return;
14191: }
14192: 
14193: // ]]>
14194: </script>
14195: END
14196:     return $scripttag;
14197: }
14198: 
14199: sub process_extracted_files {
14200:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14201:     my $numitems = $env{'form.archive_count'};
14202:     return if ((!$numitems) || ($numitems =~ /\D/));
14203:     my @ids=&Apache::lonnet::current_machine_ids();
14204:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14205:         %folders,%containers,%mapinner,%prompttofetch);
14206:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14207:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14208:         $prefix = &LONCAPA::propath($docudom,$docuname);
14209:         $pathtocheck = "$dir_root/$destination";
14210:         $dir = $dir_root;
14211:         $ishome = 1;
14212:     } else {
14213:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14214:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14215:         $dir = "$dir_root/$docudom/$docuname";
14216:     }
14217:     my $currdir = "$dir_root/$destination";
14218:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14219:     if ($env{'form.folderpath'}) {
14220:         my @items = split('&',$env{'form.folderpath'});
14221:         $folders{'0'} = $items[-2];
14222:         if ($env{'form.folderpath'} =~ /\:1$/) {
14223:             $containers{'0'}='page';
14224:         } else {  
14225:             $containers{'0'}='sequence';
14226:         }
14227:     }
14228:     my @archdirs = &get_env_multiple('form.archive_directory');
14229:     if ($numitems) {
14230:         for (my $i=1; $i<=$numitems; $i++) {
14231:             my $path = $env{'form.archive_content_'.$i};
14232:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14233:                 my $item = $1;
14234:                 $toplevelitems{$item} = $i;
14235:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14236:                     $is_dir{$item} = 1;
14237:                 }
14238:             }
14239:         }
14240:     }
14241:     my ($output,%children,%parent,%titles,%dirorder,$result);
14242:     if (keys(%toplevelitems) > 0) {
14243:         my @contents = sort(keys(%toplevelitems));
14244:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14245:                                            \%parent,\@contents,\%dirorder,\%titles);
14246:     }
14247:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14248:     if ($numitems) {
14249:         for (my $i=1; $i<=$numitems; $i++) {
14250:             next if ($env{'form.archive_'.$i} eq 'dependency');
14251:             my $path = $env{'form.archive_content_'.$i};
14252:             if ($path =~ /^\Q$pathtocheck\E/) {
14253:                 if ($env{'form.archive_'.$i} eq 'discard') {
14254:                     if ($prefix ne '' && $path ne '') {
14255:                         if (-e $prefix.$path) {
14256:                             if ((@archdirs > 0) && 
14257:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14258:                                 $todeletedir{$prefix.$path} = 1;
14259:                             } else {
14260:                                 $todelete{$prefix.$path} = 1;
14261:                             }
14262:                         }
14263:                     }
14264:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14265:                     my ($docstitle,$title,$url,$outer);
14266:                     ($title) = ($path =~ m{/([^/]+)$});
14267:                     $docstitle = $env{'form.archive_title_'.$i};
14268:                     if ($docstitle eq '') {
14269:                         $docstitle = $title;
14270:                     }
14271:                     $outer = 0;
14272:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14273:                         if (@{$dirorder{$i}} > 0) {
14274:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14275:                                 if ($env{'form.archive_'.$item} eq 'display') {
14276:                                     $outer = $item;
14277:                                     last;
14278:                                 }
14279:                             }
14280:                         }
14281:                     }
14282:                     my ($errtext,$fatal) = 
14283:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14284:                                                '/'.$folders{$outer}.'.'.
14285:                                                $containers{$outer});
14286:                     next if ($fatal);
14287:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14288:                         if ($context eq 'coursedocs') {
14289:                             $mapinner{$i} = time;
14290:                             $folders{$i} = 'default_'.$mapinner{$i};
14291:                             $containers{$i} = 'sequence';
14292:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14293:                                       $folders{$i}.'.'.$containers{$i};
14294:                             my $newidx = &LONCAPA::map::getresidx();
14295:                             $LONCAPA::map::resources[$newidx]=
14296:                                 $docstitle.':'.$url.':false:normal:res';
14297:                             push(@LONCAPA::map::order,$newidx);
14298:                             my ($outtext,$errtext) =
14299:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14300:                                                         $docuname.'/'.$folders{$outer}.
14301:                                                         '.'.$containers{$outer},1,1);
14302:                             $newseqid{$i} = $newidx;
14303:                             unless ($errtext) {
14304:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14305:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14306:                                             '</li>'."\n";
14307:                             }
14308:                         }
14309:                     } else {
14310:                         if ($context eq 'coursedocs') {
14311:                             my $newidx=&LONCAPA::map::getresidx();
14312:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14313:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14314:                                       $title;
14315:                             if (($outer !~ /\D/) &&
14316:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14317:                                 ($newidx !~ /\D/)) {
14318:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14319:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14320:                                 }
14321:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14322:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14323:                                 }
14324:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14325:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14326:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14327:                                         unless ($ishome) {
14328:                                             my $fetch = "$newdest{$i}/$title";
14329:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14330:                                             $prompttofetch{$fetch} = 1;
14331:                                         }
14332:                                     }
14333:                                 }
14334:                                 $LONCAPA::map::resources[$newidx]=
14335:                                     $docstitle.':'.$url.':false:normal:res';
14336:                                 push(@LONCAPA::map::order, $newidx);
14337:                                 my ($outtext,$errtext)=
14338:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14339:                                                             $docuname.'/'.$folders{$outer}.
14340:                                                             '.'.$containers{$outer},1,1);
14341:                                 unless ($errtext) {
14342:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14343:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14344:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14345:                                                    '</li>'."\n";
14346:                                     }
14347:                                 }
14348:                             } else {
14349:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14350:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14351:                             }
14352:                         }
14353:                     }
14354:                 }
14355:             } else {
14356:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14357:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14358:             }
14359:         }
14360:         for (my $i=1; $i<=$numitems; $i++) {
14361:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14362:             my $path = $env{'form.archive_content_'.$i};
14363:             if ($path =~ /^\Q$pathtocheck\E/) {
14364:                 my ($title) = ($path =~ m{/([^/]+)$});
14365:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14366:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14367:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14368:                         my ($itemidx,$fullpath,$relpath);
14369:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14370:                             my $container = $dirorder{$referrer{$i}}->[-1];
14371:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14372:                                 if ($dirorder{$i}->[$j] eq $container) {
14373:                                     $itemidx = $j;
14374:                                 }
14375:                             }
14376:                         }
14377:                         if ($itemidx eq '') {
14378:                             $itemidx =  0;
14379:                         } 
14380:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14381:                             if ($mapinner{$referrer{$i}}) {
14382:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14383:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14384:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14385:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14386:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14387:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14388:                                             if (!-e $fullpath) {
14389:                                                 mkdir($fullpath,0755);
14390:                                             }
14391:                                         }
14392:                                     } else {
14393:                                         last;
14394:                                     }
14395:                                 }
14396:                             }
14397:                         } elsif ($newdest{$referrer{$i}}) {
14398:                             $fullpath = $newdest{$referrer{$i}};
14399:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14400:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14401:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14402:                                     last;
14403:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14404:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14405:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14406:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14407:                                         if (!-e $fullpath) {
14408:                                             mkdir($fullpath,0755);
14409:                                         }
14410:                                     }
14411:                                 } else {
14412:                                     last;
14413:                                 }
14414:                             }
14415:                         }
14416:                         if ($fullpath ne '') {
14417:                             if (-e "$prefix$path") {
14418:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14419:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14420:                                 }
14421:                             }
14422:                             if (-e "$fullpath/$title") {
14423:                                 my $showpath;
14424:                                 if ($relpath ne '') {
14425:                                     $showpath = "$relpath/$title";
14426:                                 } else {
14427:                                     $showpath = "/$title";
14428:                                 } 
14429:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14430:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14431:                                            '</li>'."\n";
14432:                                 unless ($ishome) {
14433:                                     my $fetch = "$fullpath/$title";
14434:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14435:                                     $prompttofetch{$fetch} = 1;
14436:                                 }
14437:                             }
14438:                         }
14439:                     }
14440:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14441:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14442:                                     &HTML::Entities::encode($path,'<>&"'),
14443:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14444:                                 '<br />';
14445:                 }
14446:             } else {
14447:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14448:                                 &HTML::Entities::encode($path)).'<br />';
14449:             }
14450:         }
14451:         if (keys(%todelete)) {
14452:             foreach my $key (keys(%todelete)) {
14453:                 unlink($key);
14454:             }
14455:         }
14456:         if (keys(%todeletedir)) {
14457:             foreach my $key (keys(%todeletedir)) {
14458:                 rmdir($key);
14459:             }
14460:         }
14461:         foreach my $dir (sort(keys(%is_dir))) {
14462:             if (($pathtocheck ne '') && ($dir ne ''))  {
14463:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14464:             }
14465:         }
14466:         if ($result ne '') {
14467:             $output .= '<ul>'."\n".
14468:                        $result."\n".
14469:                        '</ul>';
14470:         }
14471:         unless ($ishome) {
14472:             my $replicationfail;
14473:             foreach my $item (keys(%prompttofetch)) {
14474:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14475:                 unless ($fetchresult eq 'ok') {
14476:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14477:                 }
14478:             }
14479:             if ($replicationfail) {
14480:                 $output .= '<p class="LC_error">'.
14481:                            &mt('Course home server failed to retrieve:').'<ul>'.
14482:                            $replicationfail.
14483:                            '</ul></p>';
14484:             }
14485:         }
14486:     } else {
14487:         $warning = &mt('No items found in archive.');
14488:     }
14489:     if ($error) {
14490:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14491:                    $error.'</p>'."\n";
14492:     }
14493:     if ($warning) {
14494:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14495:     }
14496:     return $output;
14497: }
14498: 
14499: sub cleanup_empty_dirs {
14500:     my ($path) = @_;
14501:     if (($path ne '') && (-d $path)) {
14502:         if (opendir(my $dirh,$path)) {
14503:             my @dircontents = grep(!/^\./,readdir($dirh));
14504:             my $numitems = 0;
14505:             foreach my $item (@dircontents) {
14506:                 if (-d "$path/$item") {
14507:                     &cleanup_empty_dirs("$path/$item");
14508:                     if (-e "$path/$item") {
14509:                         $numitems ++;
14510:                     }
14511:                 } else {
14512:                     $numitems ++;
14513:                 }
14514:             }
14515:             if ($numitems == 0) {
14516:                 rmdir($path);
14517:             }
14518:             closedir($dirh);
14519:         }
14520:     }
14521:     return;
14522: }
14523: 
14524: =pod
14525: 
14526: =item * &get_folder_hierarchy()
14527: 
14528: Provides hierarchy of names of folders/sub-folders containing the current
14529: item,
14530: 
14531: Inputs: 3
14532:      - $navmap - navmaps object
14533: 
14534:      - $map - url for map (either the trigger itself, or map containing
14535:                            the resource, which is the trigger).
14536: 
14537:      - $showitem - 1 => show title for map itself; 0 => do not show.
14538: 
14539: Outputs: 1 @pathitems - array of folder/subfolder names.
14540: 
14541: =cut
14542: 
14543: sub get_folder_hierarchy {
14544:     my ($navmap,$map,$showitem) = @_;
14545:     my @pathitems;
14546:     if (ref($navmap)) {
14547:         my $mapres = $navmap->getResourceByUrl($map);
14548:         if (ref($mapres)) {
14549:             my $pcslist = $mapres->map_hierarchy();
14550:             if ($pcslist ne '') {
14551:                 my @pcs = split(/,/,$pcslist);
14552:                 foreach my $pc (@pcs) {
14553:                     if ($pc == 1) {
14554:                         push(@pathitems,&mt('Main Content'));
14555:                     } else {
14556:                         my $res = $navmap->getByMapPc($pc);
14557:                         if (ref($res)) {
14558:                             my $title = $res->compTitle();
14559:                             $title =~ s/\W+/_/g;
14560:                             if ($title ne '') {
14561:                                 push(@pathitems,$title);
14562:                             }
14563:                         }
14564:                     }
14565:                 }
14566:             }
14567:             if ($showitem) {
14568:                 if ($mapres->{ID} eq '0.0') {
14569:                     push(@pathitems,&mt('Main Content'));
14570:                 } else {
14571:                     my $maptitle = $mapres->compTitle();
14572:                     $maptitle =~ s/\W+/_/g;
14573:                     if ($maptitle ne '') {
14574:                         push(@pathitems,$maptitle);
14575:                     }
14576:                 }
14577:             }
14578:         }
14579:     }
14580:     return @pathitems;
14581: }
14582: 
14583: =pod
14584: 
14585: =item * &get_turnedin_filepath()
14586: 
14587: Determines path in a user's portfolio file for storage of files uploaded
14588: to a specific essayresponse or dropbox item.
14589: 
14590: Inputs: 3 required + 1 optional.
14591: $symb is symb for resource, $uname and $udom are for current user (required).
14592: $caller is optional (can be "submission", if routine is called when storing
14593: an upoaded file when "Submit Answer" button was pressed).
14594: 
14595: Returns array containing $path and $multiresp. 
14596: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14597: than one file upload item.  Callers of routine should append partid as a 
14598: subdirectory to $path in cases where $multiresp is 1.
14599: 
14600: Called by: homework/essayresponse.pm and homework/structuretags.pm
14601: 
14602: =cut
14603: 
14604: sub get_turnedin_filepath {
14605:     my ($symb,$uname,$udom,$caller) = @_;
14606:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14607:     my $turnindir;
14608:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14609:     $turnindir = $userhash{'turnindir'};
14610:     my ($path,$multiresp);
14611:     if ($turnindir eq '') {
14612:         if ($caller eq 'submission') {
14613:             $turnindir = &mt('turned in');
14614:             $turnindir =~ s/\W+/_/g;
14615:             my %newhash = (
14616:                             'turnindir' => $turnindir,
14617:                           );
14618:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14619:         }
14620:     }
14621:     if ($turnindir ne '') {
14622:         $path = '/'.$turnindir.'/';
14623:         my ($multipart,$turnin,@pathitems);
14624:         my $navmap = Apache::lonnavmaps::navmap->new();
14625:         if (defined($navmap)) {
14626:             my $mapres = $navmap->getResourceByUrl($map);
14627:             if (ref($mapres)) {
14628:                 my $pcslist = $mapres->map_hierarchy();
14629:                 if ($pcslist ne '') {
14630:                     foreach my $pc (split(/,/,$pcslist)) {
14631:                         my $res = $navmap->getByMapPc($pc);
14632:                         if (ref($res)) {
14633:                             my $title = $res->compTitle();
14634:                             $title =~ s/\W+/_/g;
14635:                             if ($title ne '') {
14636:                                 if (($pc > 1) && (length($title) > 12)) {
14637:                                     $title = substr($title,0,12);
14638:                                 }
14639:                                 push(@pathitems,$title);
14640:                             }
14641:                         }
14642:                     }
14643:                 }
14644:                 my $maptitle = $mapres->compTitle();
14645:                 $maptitle =~ s/\W+/_/g;
14646:                 if ($maptitle ne '') {
14647:                     if (length($maptitle) > 12) {
14648:                         $maptitle = substr($maptitle,0,12);
14649:                     }
14650:                     push(@pathitems,$maptitle);
14651:                 }
14652:                 unless ($env{'request.state'} eq 'construct') {
14653:                     my $res = $navmap->getBySymb($symb);
14654:                     if (ref($res)) {
14655:                         my $partlist = $res->parts();
14656:                         my $totaluploads = 0;
14657:                         if (ref($partlist) eq 'ARRAY') {
14658:                             foreach my $part (@{$partlist}) {
14659:                                 my @types = $res->responseType($part);
14660:                                 my @ids = $res->responseIds($part);
14661:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14662:                                     if ($types[$i] eq 'essay') {
14663:                                         my $partid = $part.'_'.$ids[$i];
14664:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14665:                                             $totaluploads ++;
14666:                                         }
14667:                                     }
14668:                                 }
14669:                             }
14670:                             if ($totaluploads > 1) {
14671:                                 $multiresp = 1;
14672:                             }
14673:                         }
14674:                     }
14675:                 }
14676:             } else {
14677:                 return;
14678:             }
14679:         } else {
14680:             return;
14681:         }
14682:         my $restitle=&Apache::lonnet::gettitle($symb);
14683:         $restitle =~ s/\W+/_/g;
14684:         if ($restitle eq '') {
14685:             $restitle = ($resurl =~ m{/[^/]+$});
14686:             if ($restitle eq '') {
14687:                 $restitle = time;
14688:             }
14689:         }
14690:         if (length($restitle) > 12) {
14691:             $restitle = substr($restitle,0,12);
14692:         }
14693:         push(@pathitems,$restitle);
14694:         $path .= join('/',@pathitems);
14695:     }
14696:     return ($path,$multiresp);
14697: }
14698: 
14699: =pod
14700: 
14701: =back
14702: 
14703: =head1 CSV Upload/Handling functions
14704: 
14705: =over 4
14706: 
14707: =item * &upfile_store($r)
14708: 
14709: Store uploaded file, $r should be the HTTP Request object,
14710: needs $env{'form.upfile'}
14711: returns $datatoken to be put into hidden field
14712: 
14713: =cut
14714: 
14715: sub upfile_store {
14716:     my $r=shift;
14717:     $env{'form.upfile'}=~s/\r/\n/gs;
14718:     $env{'form.upfile'}=~s/\f/\n/gs;
14719:     $env{'form.upfile'}=~s/\n+/\n/gs;
14720:     $env{'form.upfile'}=~s/\n+$//gs;
14721: 
14722:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14723:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14724:                                      time.'_'.$$);
14725:     return if ($datatoken eq '');
14726: 
14727:     {
14728:         my $datafile = $r->dir_config('lonDaemons').
14729:                            '/tmp/'.$datatoken.'.tmp';
14730:         if ( open(my $fh,'>',$datafile) ) {
14731:             print $fh $env{'form.upfile'};
14732:             close($fh);
14733:         }
14734:     }
14735:     return $datatoken;
14736: }
14737: 
14738: =pod
14739: 
14740: =item * &load_tmp_file($r,$datatoken)
14741: 
14742: Load uploaded file from tmp, $r should be the HTTP Request object,
14743: $datatoken is the name to assign to the temporary file.
14744: sets $env{'form.upfile'} to the contents of the file
14745: 
14746: =cut
14747: 
14748: sub load_tmp_file {
14749:     my ($r,$datatoken) = @_;
14750:     return if ($datatoken eq '');
14751:     my @studentdata=();
14752:     {
14753:         my $studentfile = $r->dir_config('lonDaemons').
14754:                               '/tmp/'.$datatoken.'.tmp';
14755:         if ( open(my $fh,'<',$studentfile) ) {
14756:             @studentdata=<$fh>;
14757:             close($fh);
14758:         }
14759:     }
14760:     $env{'form.upfile'}=join('',@studentdata);
14761: }
14762: 
14763: sub valid_datatoken {
14764:     my ($datatoken) = @_;
14765:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14766:         return $datatoken;
14767:     }
14768:     return;
14769: }
14770: 
14771: =pod
14772: 
14773: =item * &upfile_record_sep()
14774: 
14775: Separate uploaded file into records
14776: returns array of records,
14777: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14778: 
14779: =cut
14780: 
14781: sub upfile_record_sep {
14782:     if ($env{'form.upfiletype'} eq 'xml') {
14783:     } else {
14784: 	my @records;
14785: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14786: 	    if ($line=~/^\s*$/) { next; }
14787: 	    push(@records,$line);
14788: 	}
14789: 	return @records;
14790:     }
14791: }
14792: 
14793: =pod
14794: 
14795: =item * &record_sep($record)
14796: 
14797: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14798: 
14799: =cut
14800: 
14801: sub takeleft {
14802:     my $index=shift;
14803:     return substr('0000'.$index,-4,4);
14804: }
14805: 
14806: sub record_sep {
14807:     my $record=shift;
14808:     my %components=();
14809:     if ($env{'form.upfiletype'} eq 'xml') {
14810:     } elsif ($env{'form.upfiletype'} eq 'space') {
14811:         my $i=0;
14812:         foreach my $field (split(/\s+/,$record)) {
14813:             $field=~s/^(\"|\')//;
14814:             $field=~s/(\"|\')$//;
14815:             $components{&takeleft($i)}=$field;
14816:             $i++;
14817:         }
14818:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14819:         my $i=0;
14820:         foreach my $field (split(/\t/,$record)) {
14821:             $field=~s/^(\"|\')//;
14822:             $field=~s/(\"|\')$//;
14823:             $components{&takeleft($i)}=$field;
14824:             $i++;
14825:         }
14826:     } else {
14827:         my $separator=',';
14828:         if ($env{'form.upfiletype'} eq 'semisv') {
14829:             $separator=';';
14830:         }
14831:         my $i=0;
14832: # the character we are looking for to indicate the end of a quote or a record 
14833:         my $looking_for=$separator;
14834: # do not add the characters to the fields
14835:         my $ignore=0;
14836: # we just encountered a separator (or the beginning of the record)
14837:         my $just_found_separator=1;
14838: # store the field we are working on here
14839:         my $field='';
14840: # work our way through all characters in record
14841:         foreach my $character ($record=~/(.)/g) {
14842:             if ($character eq $looking_for) {
14843:                if ($character ne $separator) {
14844: # Found the end of a quote, again looking for separator
14845:                   $looking_for=$separator;
14846:                   $ignore=1;
14847:                } else {
14848: # Found a separator, store away what we got
14849:                   $components{&takeleft($i)}=$field;
14850: 	          $i++;
14851:                   $just_found_separator=1;
14852:                   $ignore=0;
14853:                   $field='';
14854:                }
14855:                next;
14856:             }
14857: # single or double quotation marks after a separator indicate beginning of a quote
14858: # we are now looking for the end of the quote and need to ignore separators
14859:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14860:                $looking_for=$character;
14861:                next;
14862:             }
14863: # ignore would be true after we reached the end of a quote
14864:             if ($ignore) { next; }
14865:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14866:             $field.=$character;
14867:             $just_found_separator=0; 
14868:         }
14869: # catch the very last entry, since we never encountered the separator
14870:         $components{&takeleft($i)}=$field;
14871:     }
14872:     return %components;
14873: }
14874: 
14875: ######################################################
14876: ######################################################
14877: 
14878: =pod
14879: 
14880: =item * &upfile_select_html()
14881: 
14882: Return HTML code to select a file from the users machine and specify 
14883: the file type.
14884: 
14885: =cut
14886: 
14887: ######################################################
14888: ######################################################
14889: sub upfile_select_html {
14890:     my %Types = (
14891:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14892:                  semisv => &mt('Semicolon separated values'),
14893:                  space => &mt('Space separated'),
14894:                  tab   => &mt('Tabulator separated'),
14895: #                 xml   => &mt('HTML/XML'),
14896:                  );
14897:     my $Str = '<input type="file" name="upfile" size="50" />'.
14898:         '<br />'.&mt('Type').': <select name="upfiletype">';
14899:     foreach my $type (sort(keys(%Types))) {
14900:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14901:     }
14902:     $Str .= "</select>\n";
14903:     return $Str;
14904: }
14905: 
14906: sub get_samples {
14907:     my ($records,$toget) = @_;
14908:     my @samples=({});
14909:     my $got=0;
14910:     foreach my $rec (@$records) {
14911: 	my %temp = &record_sep($rec);
14912: 	if (! grep(/\S/, values(%temp))) { next; }
14913: 	if (%temp) {
14914: 	    $samples[$got]=\%temp;
14915: 	    $got++;
14916: 	    if ($got == $toget) { last; }
14917: 	}
14918:     }
14919:     return \@samples;
14920: }
14921: 
14922: ######################################################
14923: ######################################################
14924: 
14925: =pod
14926: 
14927: =item * &csv_print_samples($r,$records)
14928: 
14929: Prints a table of sample values from each column uploaded $r is an
14930: Apache Request ref, $records is an arrayref from
14931: &Apache::loncommon::upfile_record_sep
14932: 
14933: =cut
14934: 
14935: ######################################################
14936: ######################################################
14937: sub csv_print_samples {
14938:     my ($r,$records) = @_;
14939:     my $samples = &get_samples($records,5);
14940: 
14941:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14942:               &start_data_table_header_row());
14943:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14944:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14945:     $r->print(&end_data_table_header_row());
14946:     foreach my $hash (@$samples) {
14947: 	$r->print(&start_data_table_row());
14948: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14949: 	    $r->print('<td>');
14950: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14951: 	    $r->print('</td>');
14952: 	}
14953: 	$r->print(&end_data_table_row());
14954:     }
14955:     $r->print(&end_data_table().'<br />'."\n");
14956: }
14957: 
14958: ######################################################
14959: ######################################################
14960: 
14961: =pod
14962: 
14963: =item * &csv_print_select_table($r,$records,$d)
14964: 
14965: Prints a table to create associations between values and table columns.
14966: 
14967: $r is an Apache Request ref,
14968: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14969: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14970: 
14971: =cut
14972: 
14973: ######################################################
14974: ######################################################
14975: sub csv_print_select_table {
14976:     my ($r,$records,$d) = @_;
14977:     my $i=0;
14978:     my $samples = &get_samples($records,1);
14979:     $r->print(&mt('Associate columns with student attributes.')."\n".
14980: 	      &start_data_table().&start_data_table_header_row().
14981:               '<th>'.&mt('Attribute').'</th>'.
14982:               '<th>'.&mt('Column').'</th>'.
14983:               &end_data_table_header_row()."\n");
14984:     foreach my $array_ref (@$d) {
14985: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14986: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14987: 
14988: 	$r->print('<td><select name="f'.$i.'"'.
14989: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14990: 	$r->print('<option value="none"></option>');
14991: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14992: 	    $r->print('<option value="'.$sample.'"'.
14993:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14994:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14995: 	}
14996: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14997: 	$i++;
14998:     }
14999:     $r->print(&end_data_table());
15000:     $i--;
15001:     return $i;
15002: }
15003: 
15004: ######################################################
15005: ######################################################
15006: 
15007: =pod
15008: 
15009: =item * &csv_samples_select_table($r,$records,$d)
15010: 
15011: Prints a table of sample values from the upload and can make associate samples to internal names.
15012: 
15013: $r is an Apache Request ref,
15014: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15015: $d is an array of 2 element arrays (internal name, displayed name)
15016: 
15017: =cut
15018: 
15019: ######################################################
15020: ######################################################
15021: sub csv_samples_select_table {
15022:     my ($r,$records,$d) = @_;
15023:     my $i=0;
15024:     #
15025:     my $max_samples = 5;
15026:     my $samples = &get_samples($records,$max_samples);
15027:     $r->print(&start_data_table().
15028:               &start_data_table_header_row().'<th>'.
15029:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15030:               &end_data_table_header_row());
15031: 
15032:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15033: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15034: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15035: 	foreach my $option (@$d) {
15036: 	    my ($value,$display,$defaultcol)=@{ $option };
15037: 	    $r->print('<option value="'.$value.'"'.
15038:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15039:                       $display.'</option>');
15040: 	}
15041: 	$r->print('</select></td><td>');
15042: 	foreach my $line (0..($max_samples-1)) {
15043: 	    if (defined($samples->[$line]{$key})) { 
15044: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15045: 	    }
15046: 	}
15047: 	$r->print('</td>'.&end_data_table_row());
15048: 	$i++;
15049:     }
15050:     $r->print(&end_data_table());
15051:     $i--;
15052:     return($i);
15053: }
15054: 
15055: ######################################################
15056: ######################################################
15057: 
15058: =pod
15059: 
15060: =item * &clean_excel_name($name)
15061: 
15062: Returns a replacement for $name which does not contain any illegal characters.
15063: 
15064: =cut
15065: 
15066: ######################################################
15067: ######################################################
15068: sub clean_excel_name {
15069:     my ($name) = @_;
15070:     $name =~ s/[:\*\?\/\\]//g;
15071:     if (length($name) > 31) {
15072:         $name = substr($name,0,31);
15073:     }
15074:     return $name;
15075: }
15076: 
15077: =pod
15078: 
15079: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15080: 
15081: Returns either 1 or undef
15082: 
15083: 1 if the part is to be hidden, undef if it is to be shown
15084: 
15085: Arguments are:
15086: 
15087: $id the id of the part to be checked
15088: $symb, optional the symb of the resource to check
15089: $udom, optional the domain of the user to check for
15090: $uname, optional the username of the user to check for
15091: 
15092: =cut
15093: 
15094: sub check_if_partid_hidden {
15095:     my ($id,$symb,$udom,$uname) = @_;
15096:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15097: 					 $symb,$udom,$uname);
15098:     my $truth=1;
15099:     #if the string starts with !, then the list is the list to show not hide
15100:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15101:     my @hiddenlist=split(/,/,$hiddenparts);
15102:     foreach my $checkid (@hiddenlist) {
15103: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15104:     }
15105:     return !$truth;
15106: }
15107: 
15108: 
15109: ############################################################
15110: ############################################################
15111: 
15112: =pod
15113: 
15114: =back 
15115: 
15116: =head1 cgi-bin script and graphing routines
15117: 
15118: =over 4
15119: 
15120: =item * &get_cgi_id()
15121: 
15122: Inputs: none
15123: 
15124: Returns an id which can be used to pass environment variables
15125: to various cgi-bin scripts.  These environment variables will
15126: be removed from the users environment after a given time by
15127: the routine &Apache::lonnet::transfer_profile_to_env.
15128: 
15129: =cut
15130: 
15131: ############################################################
15132: ############################################################
15133: my $uniq=0;
15134: sub get_cgi_id {
15135:     $uniq=($uniq+1)%100000;
15136:     return (time.'_'.$$.'_'.$uniq);
15137: }
15138: 
15139: ############################################################
15140: ############################################################
15141: 
15142: =pod
15143: 
15144: =item * &DrawBarGraph()
15145: 
15146: Facilitates the plotting of data in a (stacked) bar graph.
15147: Puts plot definition data into the users environment in order for 
15148: graph.png to plot it.  Returns an <img> tag for the plot.
15149: The bars on the plot are labeled '1','2',...,'n'.
15150: 
15151: Inputs:
15152: 
15153: =over 4
15154: 
15155: =item $Title: string, the title of the plot
15156: 
15157: =item $xlabel: string, text describing the X-axis of the plot
15158: 
15159: =item $ylabel: string, text describing the Y-axis of the plot
15160: 
15161: =item $Max: scalar, the maximum Y value to use in the plot
15162: If $Max is < any data point, the graph will not be rendered.
15163: 
15164: =item $colors: array ref holding the colors to be used for the data sets when
15165: they are plotted.  If undefined, default values will be used.
15166: 
15167: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15168: 
15169: =item @Values: An array of array references.  Each array reference holds data
15170: to be plotted in a stacked bar chart.
15171: 
15172: =item If the final element of @Values is a hash reference the key/value
15173: pairs will be added to the graph definition.
15174: 
15175: =back
15176: 
15177: Returns:
15178: 
15179: An <img> tag which references graph.png and the appropriate identifying
15180: information for the plot.
15181: 
15182: =cut
15183: 
15184: ############################################################
15185: ############################################################
15186: sub DrawBarGraph {
15187:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15188:     #
15189:     if (! defined($colors)) {
15190:         $colors = ['#33ff00', 
15191:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15192:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15193:                   ]; 
15194:     }
15195:     my $extra_settings = {};
15196:     if (ref($Values[-1]) eq 'HASH') {
15197:         $extra_settings = pop(@Values);
15198:     }
15199:     #
15200:     my $identifier = &get_cgi_id();
15201:     my $id = 'cgi.'.$identifier;        
15202:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15203:         return '';
15204:     }
15205:     #
15206:     my @Labels;
15207:     if (defined($labels)) {
15208:         @Labels = @$labels;
15209:     } else {
15210:         for (my $i=0;$i<@{$Values[0]};$i++) {
15211:             push(@Labels,$i+1);
15212:         }
15213:     }
15214:     #
15215:     my $NumBars = scalar(@{$Values[0]});
15216:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15217:     my %ValuesHash;
15218:     my $NumSets=1;
15219:     foreach my $array (@Values) {
15220:         next if (! ref($array));
15221:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15222:             join(',',@$array);
15223:     }
15224:     #
15225:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15226:     if ($NumBars < 3) {
15227:         $width = 120+$NumBars*32;
15228:         $xskip = 1;
15229:         $bar_width = 30;
15230:     } elsif ($NumBars < 5) {
15231:         $width = 120+$NumBars*20;
15232:         $xskip = 1;
15233:         $bar_width = 20;
15234:     } elsif ($NumBars < 10) {
15235:         $width = 120+$NumBars*15;
15236:         $xskip = 1;
15237:         $bar_width = 15;
15238:     } elsif ($NumBars <= 25) {
15239:         $width = 120+$NumBars*11;
15240:         $xskip = 5;
15241:         $bar_width = 8;
15242:     } elsif ($NumBars <= 50) {
15243:         $width = 120+$NumBars*8;
15244:         $xskip = 5;
15245:         $bar_width = 4;
15246:     } else {
15247:         $width = 120+$NumBars*8;
15248:         $xskip = 5;
15249:         $bar_width = 4;
15250:     }
15251:     #
15252:     $Max = 1 if ($Max < 1);
15253:     if ( int($Max) < $Max ) {
15254:         $Max++;
15255:         $Max = int($Max);
15256:     }
15257:     $Title  = '' if (! defined($Title));
15258:     $xlabel = '' if (! defined($xlabel));
15259:     $ylabel = '' if (! defined($ylabel));
15260:     $ValuesHash{$id.'.title'}    = &escape($Title);
15261:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15262:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15263:     $ValuesHash{$id.'.y_max_value'} = $Max;
15264:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15265:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15266:     $ValuesHash{$id.'.PlotType'} = 'bar';
15267:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15268:     $ValuesHash{$id.'.height'}   = $height;
15269:     $ValuesHash{$id.'.width'}    = $width;
15270:     $ValuesHash{$id.'.xskip'}    = $xskip;
15271:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15272:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15273:     #
15274:     # Deal with other parameters
15275:     while (my ($key,$value) = each(%$extra_settings)) {
15276:         $ValuesHash{$id.'.'.$key} = $value;
15277:     }
15278:     #
15279:     &Apache::lonnet::appenv(\%ValuesHash);
15280:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15281: }
15282: 
15283: ############################################################
15284: ############################################################
15285: 
15286: =pod
15287: 
15288: =item * &DrawXYGraph()
15289: 
15290: Facilitates the plotting of data in an XY graph.
15291: Puts plot definition data into the users environment in order for 
15292: graph.png to plot it.  Returns an <img> tag for the plot.
15293: 
15294: Inputs:
15295: 
15296: =over 4
15297: 
15298: =item $Title: string, the title of the plot
15299: 
15300: =item $xlabel: string, text describing the X-axis of the plot
15301: 
15302: =item $ylabel: string, text describing the Y-axis of the plot
15303: 
15304: =item $Max: scalar, the maximum Y value to use in the plot
15305: If $Max is < any data point, the graph will not be rendered.
15306: 
15307: =item $colors: Array ref containing the hex color codes for the data to be 
15308: plotted in.  If undefined, default values will be used.
15309: 
15310: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15311: 
15312: =item $Ydata: Array ref containing Array refs.  
15313: Each of the contained arrays will be plotted as a separate curve.
15314: 
15315: =item %Values: hash indicating or overriding any default values which are 
15316: passed to graph.png.  
15317: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15318: 
15319: =back
15320: 
15321: Returns:
15322: 
15323: An <img> tag which references graph.png and the appropriate identifying
15324: information for the plot.
15325: 
15326: =cut
15327: 
15328: ############################################################
15329: ############################################################
15330: sub DrawXYGraph {
15331:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15332:     #
15333:     # Create the identifier for the graph
15334:     my $identifier = &get_cgi_id();
15335:     my $id = 'cgi.'.$identifier;
15336:     #
15337:     $Title  = '' if (! defined($Title));
15338:     $xlabel = '' if (! defined($xlabel));
15339:     $ylabel = '' if (! defined($ylabel));
15340:     my %ValuesHash = 
15341:         (
15342:          $id.'.title'  => &escape($Title),
15343:          $id.'.xlabel' => &escape($xlabel),
15344:          $id.'.ylabel' => &escape($ylabel),
15345:          $id.'.y_max_value'=> $Max,
15346:          $id.'.labels'     => join(',',@$Xlabels),
15347:          $id.'.PlotType'   => 'XY',
15348:          );
15349:     #
15350:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15351:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15352:     }
15353:     #
15354:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15355:         return '';
15356:     }
15357:     my $NumSets=1;
15358:     foreach my $array (@{$Ydata}){
15359:         next if (! ref($array));
15360:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15361:     }
15362:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15363:     #
15364:     # Deal with other parameters
15365:     while (my ($key,$value) = each(%Values)) {
15366:         $ValuesHash{$id.'.'.$key} = $value;
15367:     }
15368:     #
15369:     &Apache::lonnet::appenv(\%ValuesHash);
15370:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15371: }
15372: 
15373: ############################################################
15374: ############################################################
15375: 
15376: =pod
15377: 
15378: =item * &DrawXYYGraph()
15379: 
15380: Facilitates the plotting of data in an XY graph with two Y axes.
15381: Puts plot definition data into the users environment in order for 
15382: graph.png to plot it.  Returns an <img> tag for the plot.
15383: 
15384: Inputs:
15385: 
15386: =over 4
15387: 
15388: =item $Title: string, the title of the plot
15389: 
15390: =item $xlabel: string, text describing the X-axis of the plot
15391: 
15392: =item $ylabel: string, text describing the Y-axis of the plot
15393: 
15394: =item $colors: Array ref containing the hex color codes for the data to be 
15395: plotted in.  If undefined, default values will be used.
15396: 
15397: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15398: 
15399: =item $Ydata1: The first data set
15400: 
15401: =item $Min1: The minimum value of the left Y-axis
15402: 
15403: =item $Max1: The maximum value of the left Y-axis
15404: 
15405: =item $Ydata2: The second data set
15406: 
15407: =item $Min2: The minimum value of the right Y-axis
15408: 
15409: =item $Max2: The maximum value of the left Y-axis
15410: 
15411: =item %Values: hash indicating or overriding any default values which are 
15412: passed to graph.png.  
15413: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15414: 
15415: =back
15416: 
15417: Returns:
15418: 
15419: An <img> tag which references graph.png and the appropriate identifying
15420: information for the plot.
15421: 
15422: =cut
15423: 
15424: ############################################################
15425: ############################################################
15426: sub DrawXYYGraph {
15427:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15428:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15429:     #
15430:     # Create the identifier for the graph
15431:     my $identifier = &get_cgi_id();
15432:     my $id = 'cgi.'.$identifier;
15433:     #
15434:     $Title  = '' if (! defined($Title));
15435:     $xlabel = '' if (! defined($xlabel));
15436:     $ylabel = '' if (! defined($ylabel));
15437:     my %ValuesHash = 
15438:         (
15439:          $id.'.title'  => &escape($Title),
15440:          $id.'.xlabel' => &escape($xlabel),
15441:          $id.'.ylabel' => &escape($ylabel),
15442:          $id.'.labels' => join(',',@$Xlabels),
15443:          $id.'.PlotType' => 'XY',
15444:          $id.'.NumSets' => 2,
15445:          $id.'.two_axes' => 1,
15446:          $id.'.y1_max_value' => $Max1,
15447:          $id.'.y1_min_value' => $Min1,
15448:          $id.'.y2_max_value' => $Max2,
15449:          $id.'.y2_min_value' => $Min2,
15450:          );
15451:     #
15452:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15453:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15454:     }
15455:     #
15456:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15457:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15458:         return '';
15459:     }
15460:     my $NumSets=1;
15461:     foreach my $array ($Ydata1,$Ydata2){
15462:         next if (! ref($array));
15463:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15464:     }
15465:     #
15466:     # Deal with other parameters
15467:     while (my ($key,$value) = each(%Values)) {
15468:         $ValuesHash{$id.'.'.$key} = $value;
15469:     }
15470:     #
15471:     &Apache::lonnet::appenv(\%ValuesHash);
15472:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15473: }
15474: 
15475: ############################################################
15476: ############################################################
15477: 
15478: =pod
15479: 
15480: =back 
15481: 
15482: =head1 Statistics helper routines?  
15483: 
15484: Bad place for them but what the hell.
15485: 
15486: =over 4
15487: 
15488: =item * &chartlink()
15489: 
15490: Returns a link to the chart for a specific student.  
15491: 
15492: Inputs:
15493: 
15494: =over 4
15495: 
15496: =item $linktext: The text of the link
15497: 
15498: =item $sname: The students username
15499: 
15500: =item $sdomain: The students domain
15501: 
15502: =back
15503: 
15504: =back
15505: 
15506: =cut
15507: 
15508: ############################################################
15509: ############################################################
15510: sub chartlink {
15511:     my ($linktext, $sname, $sdomain) = @_;
15512:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15513:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15514:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15515:        '">'.$linktext.'</a>';
15516: }
15517: 
15518: #######################################################
15519: #######################################################
15520: 
15521: =pod
15522: 
15523: =head1 Course Environment Routines
15524: 
15525: =over 4
15526: 
15527: =item * &restore_course_settings()
15528: 
15529: =item * &store_course_settings()
15530: 
15531: Restores/Store indicated form parameters from the course environment.
15532: Will not overwrite existing values of the form parameters.
15533: 
15534: Inputs: 
15535: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15536: 
15537: a hash ref describing the data to be stored.  For example:
15538:    
15539: %Save_Parameters = ('Status' => 'scalar',
15540:     'chartoutputmode' => 'scalar',
15541:     'chartoutputdata' => 'scalar',
15542:     'Section' => 'array',
15543:     'Group' => 'array',
15544:     'StudentData' => 'array',
15545:     'Maps' => 'array');
15546: 
15547: Returns: both routines return nothing
15548: 
15549: =back
15550: 
15551: =cut
15552: 
15553: #######################################################
15554: #######################################################
15555: sub store_course_settings {
15556:     return &store_settings($env{'request.course.id'},@_);
15557: }
15558: 
15559: sub store_settings {
15560:     # save to the environment
15561:     # appenv the same items, just to be safe
15562:     my $udom  = $env{'user.domain'};
15563:     my $uname = $env{'user.name'};
15564:     my ($context,$prefix,$Settings) = @_;
15565:     my %SaveHash;
15566:     my %AppHash;
15567:     while (my ($setting,$type) = each(%$Settings)) {
15568:         my $basename = join('.','internal',$context,$prefix,$setting);
15569:         my $envname = 'environment.'.$basename;
15570:         if (exists($env{'form.'.$setting})) {
15571:             # Save this value away
15572:             if ($type eq 'scalar' &&
15573:                 (! exists($env{$envname}) || 
15574:                  $env{$envname} ne $env{'form.'.$setting})) {
15575:                 $SaveHash{$basename} = $env{'form.'.$setting};
15576:                 $AppHash{$envname}   = $env{'form.'.$setting};
15577:             } elsif ($type eq 'array') {
15578:                 my $stored_form;
15579:                 if (ref($env{'form.'.$setting})) {
15580:                     $stored_form = join(',',
15581:                                         map {
15582:                                             &escape($_);
15583:                                         } sort(@{$env{'form.'.$setting}}));
15584:                 } else {
15585:                     $stored_form = 
15586:                         &escape($env{'form.'.$setting});
15587:                 }
15588:                 # Determine if the array contents are the same.
15589:                 if ($stored_form ne $env{$envname}) {
15590:                     $SaveHash{$basename} = $stored_form;
15591:                     $AppHash{$envname}   = $stored_form;
15592:                 }
15593:             }
15594:         }
15595:     }
15596:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15597:                                           $udom,$uname);
15598:     if ($put_result !~ /^(ok|delayed)/) {
15599:         &Apache::lonnet::logthis('unable to save form parameters, '.
15600:                                  'got error:'.$put_result);
15601:     }
15602:     # Make sure these settings stick around in this session, too
15603:     &Apache::lonnet::appenv(\%AppHash);
15604:     return;
15605: }
15606: 
15607: sub restore_course_settings {
15608:     return &restore_settings($env{'request.course.id'},@_);
15609: }
15610: 
15611: sub restore_settings {
15612:     my ($context,$prefix,$Settings) = @_;
15613:     while (my ($setting,$type) = each(%$Settings)) {
15614:         next if (exists($env{'form.'.$setting}));
15615:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15616:             '.'.$setting;
15617:         if (exists($env{$envname})) {
15618:             if ($type eq 'scalar') {
15619:                 $env{'form.'.$setting} = $env{$envname};
15620:             } elsif ($type eq 'array') {
15621:                 $env{'form.'.$setting} = [ 
15622:                                            map { 
15623:                                                &unescape($_); 
15624:                                            } split(',',$env{$envname})
15625:                                            ];
15626:             }
15627:         }
15628:     }
15629: }
15630: 
15631: #######################################################
15632: #######################################################
15633: 
15634: =pod
15635: 
15636: =head1 Domain E-mail Routines  
15637: 
15638: =over 4
15639: 
15640: =item * &build_recipient_list()
15641: 
15642: Build recipient lists for following types of e-mail:
15643: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15644: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15645: module change checking, student/employee ID conflict checks, as
15646: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15647: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15648: 
15649: Inputs:
15650: defmail (scalar - email address of default recipient), 
15651: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15652: requestsmail, updatesmail, or idconflictsmail).
15653: 
15654: defdom (domain for which to retrieve configuration settings),
15655: 
15656: origmail (scalar - email address of recipient from loncapa.conf, 
15657: i.e., predates configuration by DC via domainprefs.pm
15658: 
15659: $requname username of requester (if mailing type is helpdeskmail)
15660: 
15661: $requdom domain of requester (if mailing type is helpdeskmail)
15662: 
15663: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15664: 
15665: 
15666: Returns: comma separated list of addresses to which to send e-mail.
15667: 
15668: =back
15669: 
15670: =cut
15671: 
15672: ############################################################
15673: ############################################################
15674: sub build_recipient_list {
15675:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15676:     my @recipients;
15677:     my ($otheremails,$lastresort,$allbcc,$addtext);
15678:     my %domconfig =
15679:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15680:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15681:         if (exists($domconfig{'contacts'}{$mailing})) {
15682:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15683:                 my @contacts = ('adminemail','supportemail');
15684:                 foreach my $item (@contacts) {
15685:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15686:                         my $addr = $domconfig{'contacts'}{$item}; 
15687:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15688:                             push(@recipients,$addr);
15689:                         }
15690:                     }
15691:                 }
15692:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15693:                 if ($mailing eq 'helpdeskmail') {
15694:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15695:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15696:                         my @ok_bccs;
15697:                         foreach my $bcc (@bccs) {
15698:                             $bcc =~ s/^\s+//g;
15699:                             $bcc =~ s/\s+$//g;
15700:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15701:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15702:                                     push(@ok_bccs,$bcc);
15703:                                 }
15704:                             }
15705:                         }
15706:                         if (@ok_bccs > 0) {
15707:                             $allbcc = join(', ',@ok_bccs);
15708:                         }
15709:                     }
15710:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15711:                 }
15712:             }
15713:         } elsif ($origmail ne '') {
15714:             $lastresort = $origmail;
15715:         }
15716:         if ($mailing eq 'helpdeskmail') {
15717:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15718:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15719:                 my ($inststatus,$inststatus_checked);
15720:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15721:                     ($env{'user.domain'} ne 'public')) {
15722:                     $inststatus_checked = 1;
15723:                     $inststatus = $env{'environment.inststatus'};
15724:                 }
15725:                 unless ($inststatus_checked) {
15726:                     if (($requname ne '') && ($requdom ne '')) {
15727:                         if (($requname =~ /^$match_username$/) &&
15728:                             ($requdom =~ /^$match_domain$/) &&
15729:                             (&Apache::lonnet::domain($requdom))) {
15730:                             my $requhome = &Apache::lonnet::homeserver($requname,
15731:                                                                       $requdom);
15732:                             unless ($requhome eq 'no_host') {
15733:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15734:                                 $inststatus = $userenv{'inststatus'};
15735:                                 $inststatus_checked = 1;
15736:                             }
15737:                         }
15738:                     }
15739:                 }
15740:                 unless ($inststatus_checked) {
15741:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15742:                         my %srch = (srchby     => 'email',
15743:                                     srchdomain => $defdom,
15744:                                     srchterm   => $reqemail,
15745:                                     srchtype   => 'exact');
15746:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15747:                         foreach my $uname (keys(%srch_results)) {
15748:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15749:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15750:                                 $inststatus_checked = 1;
15751:                                 last;
15752:                             }
15753:                         }
15754:                         unless ($inststatus_checked) {
15755:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15756:                             if ($dirsrchres eq 'ok') {
15757:                                 foreach my $uname (keys(%srch_results)) {
15758:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15759:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15760:                                         $inststatus_checked = 1;
15761:                                         last;
15762:                                     }
15763:                                 }
15764:                             }
15765:                         }
15766:                     }
15767:                 }
15768:                 if ($inststatus ne '') {
15769:                     foreach my $status (split(/\:/,$inststatus)) {
15770:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15771:                             my @contacts = ('adminemail','supportemail');
15772:                             foreach my $item (@contacts) {
15773:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15774:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15775:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15776:                                         push(@recipients,$addr);
15777:                                     }
15778:                                 }
15779:                             }
15780:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15781:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15782:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15783:                                 my @ok_bccs;
15784:                                 foreach my $bcc (@bccs) {
15785:                                     $bcc =~ s/^\s+//g;
15786:                                     $bcc =~ s/\s+$//g;
15787:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15788:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15789:                                             push(@ok_bccs,$bcc);
15790:                                         }
15791:                                     }
15792:                                 }
15793:                                 if (@ok_bccs > 0) {
15794:                                     $allbcc = join(', ',@ok_bccs);
15795:                                 }
15796:                             }
15797:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15798:                             last;
15799:                         }
15800:                     }
15801:                 }
15802:             }
15803:         }
15804:     } elsif ($origmail ne '') {
15805:         $lastresort = $origmail;
15806:     }
15807:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15808:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15809:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15810:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15811:             my %what = (
15812:                           perlvar => 1,
15813:                        );
15814:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15815:             if ($primary) {
15816:                 my $gotaddr;
15817:                 my ($result,$returnhash) =
15818:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15819:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15820:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15821:                         $lastresort = $returnhash->{'lonSupportEMail'};
15822:                         $gotaddr = 1;
15823:                     }
15824:                 }
15825:                 unless ($gotaddr) {
15826:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15827:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15828:                     unless ($uintdom eq $intdom) {
15829:                         my %domconfig =
15830:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15831:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15832:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15833:                                 my @contacts = ('adminemail','supportemail');
15834:                                 foreach my $item (@contacts) {
15835:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15836:                                         my $addr = $domconfig{'contacts'}{$item};
15837:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15838:                                             push(@recipients,$addr);
15839:                                         }
15840:                                     }
15841:                                 }
15842:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15843:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15844:                                 }
15845:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15846:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15847:                                     my @ok_bccs;
15848:                                     foreach my $bcc (@bccs) {
15849:                                         $bcc =~ s/^\s+//g;
15850:                                         $bcc =~ s/\s+$//g;
15851:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15852:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15853:                                                 push(@ok_bccs,$bcc);
15854:                                             }
15855:                                         }
15856:                                     }
15857:                                     if (@ok_bccs > 0) {
15858:                                         $allbcc = join(', ',@ok_bccs);
15859:                                     }
15860:                                 }
15861:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15862:                             }
15863:                         }
15864:                     }
15865:                 }
15866:             }
15867:         }
15868:     }
15869:     if (defined($defmail)) {
15870:         if ($defmail ne '') {
15871:             push(@recipients,$defmail);
15872:         }
15873:     }
15874:     if ($otheremails) {
15875:         my @others;
15876:         if ($otheremails =~ /,/) {
15877:             @others = split(/,/,$otheremails);
15878:         } else {
15879:             push(@others,$otheremails);
15880:         }
15881:         foreach my $addr (@others) {
15882:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15883:                 push(@recipients,$addr);
15884:             }
15885:         }
15886:     }
15887:     if ($mailing eq 'helpdeskmail') {
15888:         if ((!@recipients) && ($lastresort ne '')) {
15889:             push(@recipients,$lastresort);
15890:         }
15891:     } elsif ($lastresort ne '') {
15892:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15893:             push(@recipients,$lastresort);
15894:         }
15895:     }
15896:     my $recipientlist = join(',',@recipients);
15897:     if (wantarray) {
15898:         return ($recipientlist,$allbcc,$addtext);
15899:     } else {
15900:         return $recipientlist;
15901:     }
15902: }
15903: 
15904: ############################################################
15905: ############################################################
15906: 
15907: =pod
15908: 
15909: =over 4
15910: 
15911: =item * &mime_email()
15912: 
15913: Sends an email with a possible attachment
15914: 
15915: Inputs:
15916: 
15917: =over 4
15918: 
15919: from -              Sender's email address
15920: 
15921: replyto -           Reply-To email address
15922: 
15923: to -                Email address of recipient
15924: 
15925: subject -           Subject of email
15926: 
15927: body -              Body of email
15928: 
15929: cc_string -         Carbon copy email address
15930: 
15931: bcc -               Blind carbon copy email address
15932: 
15933: attachment_path -   Path of file to be attached
15934: 
15935: file_name -         Name of file to be attached
15936: 
15937: attachment_text -   The body of an attachment of type "TEXT"
15938: 
15939: =back
15940: 
15941: =back
15942: 
15943: =cut
15944: 
15945: ############################################################
15946: ############################################################
15947: 
15948: sub mime_email {
15949:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
15950:         $file_name,$attachment_text) = @_;
15951:  
15952:     my $msg = MIME::Lite->new(
15953:              From    => $from,
15954:              To      => $to,
15955:              Subject => $subject,
15956:              Type    =>'TEXT',
15957:              Data    => $body,
15958:              );
15959:     if ($replyto ne '') {
15960:         $msg->add("Reply-To" => $replyto);
15961:     }
15962:     if ($cc_string ne '') {
15963:         $msg->add("Cc" => $cc_string);
15964:     }
15965:     if ($bcc ne '') {
15966:         $msg->add("Bcc" => $bcc);
15967:     }
15968:     $msg->attr("content-type"         => "text/plain");
15969:     $msg->attr("content-type.charset" => "UTF-8");
15970:     # Attach file if given
15971:     if ($attachment_path) {
15972:         unless ($file_name) {
15973:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15974:         }
15975:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15976:         $msg->attach(Type     => $type,
15977:                      Path     => $attachment_path,
15978:                      Filename => $file_name
15979:                      );
15980:     # Otherwise attach text if given
15981:     } elsif ($attachment_text) {
15982:         $msg->attach(Type => 'TEXT',
15983:                      Data => $attachment_text);
15984:     }
15985:     # Send it
15986:     $msg->send('sendmail');
15987: }
15988: 
15989: ############################################################
15990: ############################################################
15991: 
15992: =pod
15993: 
15994: =head1 Course Catalog Routines
15995: 
15996: =over 4
15997: 
15998: =item * &gather_categories()
15999: 
16000: Converts category definitions - keys of categories hash stored in  
16001: coursecategories in configuration.db on the primary library server in a 
16002: domain - to an array.  Also generates javascript and idx hash used to 
16003: generate Domain Coordinator interface for editing Course Categories.
16004: 
16005: Inputs:
16006: 
16007: categories (reference to hash of category definitions).
16008: 
16009: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16010:       categories and subcategories).
16011: 
16012: idx (reference to hash of counters used in Domain Coordinator interface for 
16013:       editing Course Categories).
16014: 
16015: jsarray (reference to array of categories used to create Javascript arrays for
16016:          Domain Coordinator interface for editing Course Categories).
16017: 
16018: Returns: nothing
16019: 
16020: Side effects: populates cats, idx and jsarray. 
16021: 
16022: =cut
16023: 
16024: sub gather_categories {
16025:     my ($categories,$cats,$idx,$jsarray) = @_;
16026:     my %counters;
16027:     my $num = 0;
16028:     foreach my $item (keys(%{$categories})) {
16029:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16030:         if ($container eq '' && $depth == 0) {
16031:             $cats->[$depth][$categories->{$item}] = $cat;
16032:         } else {
16033:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16034:         }
16035:         my ($escitem,$tail) = split(/:/,$item,2);
16036:         if ($counters{$tail} eq '') {
16037:             $counters{$tail} = $num;
16038:             $num ++;
16039:         }
16040:         if (ref($idx) eq 'HASH') {
16041:             $idx->{$item} = $counters{$tail};
16042:         }
16043:         if (ref($jsarray) eq 'ARRAY') {
16044:             push(@{$jsarray->[$counters{$tail}]},$item);
16045:         }
16046:     }
16047:     return;
16048: }
16049: 
16050: =pod
16051: 
16052: =item * &extract_categories()
16053: 
16054: Used to generate breadcrumb trails for course categories.
16055: 
16056: Inputs:
16057: 
16058: categories (reference to hash of category definitions).
16059: 
16060: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16061:       categories and subcategories).
16062: 
16063: trails (reference to array of breacrumb trails for each category).
16064: 
16065: allitems (reference to hash - key is category key 
16066:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16067: 
16068: idx (reference to hash of counters used in Domain Coordinator interface for
16069:       editing Course Categories).
16070: 
16071: jsarray (reference to array of categories used to create Javascript arrays for
16072:          Domain Coordinator interface for editing Course Categories).
16073: 
16074: subcats (reference to hash of arrays containing all subcategories within each 
16075:          category, -recursive)
16076: 
16077: maxd (reference to hash used to hold max depth for all top-level categories).
16078: 
16079: Returns: nothing
16080: 
16081: Side effects: populates trails and allitems hash references.
16082: 
16083: =cut
16084: 
16085: sub extract_categories {
16086:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16087:     if (ref($categories) eq 'HASH') {
16088:         &gather_categories($categories,$cats,$idx,$jsarray);
16089:         if (ref($cats->[0]) eq 'ARRAY') {
16090:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16091:                 my $name = $cats->[0][$i];
16092:                 my $item = &escape($name).'::0';
16093:                 my $trailstr;
16094:                 if ($name eq 'instcode') {
16095:                     $trailstr = &mt('Official courses (with institutional codes)');
16096:                 } elsif ($name eq 'communities') {
16097:                     $trailstr = &mt('Communities');
16098:                 } elsif ($name eq 'placement') {
16099:                     $trailstr = &mt('Placement Tests');
16100:                 } else {
16101:                     $trailstr = $name;
16102:                 }
16103:                 if ($allitems->{$item} eq '') {
16104:                     push(@{$trails},$trailstr);
16105:                     $allitems->{$item} = scalar(@{$trails})-1;
16106:                 }
16107:                 my @parents = ($name);
16108:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16109:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16110:                         my $category = $cats->[1]{$name}[$j];
16111:                         if (ref($subcats) eq 'HASH') {
16112:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16113:                         }
16114:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16115:                     }
16116:                 } else {
16117:                     if (ref($subcats) eq 'HASH') {
16118:                         $subcats->{$item} = [];
16119:                     }
16120:                     if (ref($maxd) eq 'HASH') {
16121:                         $maxd->{$name} = 1;
16122:                     }
16123:                 }
16124:             }
16125:         }
16126:     }
16127:     return;
16128: }
16129: 
16130: =pod
16131: 
16132: =item * &recurse_categories()
16133: 
16134: Recursively used to generate breadcrumb trails for course categories.
16135: 
16136: Inputs:
16137: 
16138: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16139:       categories and subcategories).
16140: 
16141: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16142: 
16143: category (current course category, for which breadcrumb trail is being generated).
16144: 
16145: trails (reference to array of breadcrumb trails for each category).
16146: 
16147: allitems (reference to hash - key is category key
16148:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16149: 
16150: parents (array containing containers directories for current category, 
16151:          back to top level). 
16152: 
16153: Returns: nothing
16154: 
16155: Side effects: populates trails and allitems hash references
16156: 
16157: =cut
16158: 
16159: sub recurse_categories {
16160:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16161:     my $shallower = $depth - 1;
16162:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16163:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16164:             my $name = $cats->[$depth]{$category}[$k];
16165:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16166:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16167:             if ($allitems->{$item} eq '') {
16168:                 push(@{$trails},$trailstr);
16169:                 $allitems->{$item} = scalar(@{$trails})-1;
16170:             }
16171:             my $deeper = $depth+1;
16172:             push(@{$parents},$category);
16173:             if (ref($subcats) eq 'HASH') {
16174:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16175:                 for (my $j=@{$parents}; $j>=0; $j--) {
16176:                     my $higher;
16177:                     if ($j > 0) {
16178:                         $higher = &escape($parents->[$j]).':'.
16179:                                   &escape($parents->[$j-1]).':'.$j;
16180:                     } else {
16181:                         $higher = &escape($parents->[$j]).'::'.$j;
16182:                     }
16183:                     push(@{$subcats->{$higher}},$subcat);
16184:                 }
16185:             }
16186:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16187:                                 $subcats,$maxd);
16188:             pop(@{$parents});
16189:         }
16190:     } else {
16191:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16192:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16193:         if ($allitems->{$item} eq '') {
16194:             push(@{$trails},$trailstr);
16195:             $allitems->{$item} = scalar(@{$trails})-1;
16196:         }
16197:         if (ref($maxd) eq 'HASH') {
16198:             if ($depth > $maxd->{$parents->[0]}) {
16199:                 $maxd->{$parents->[0]} = $depth;
16200:             }
16201:         }
16202:     }
16203:     return;
16204: }
16205: 
16206: =pod
16207: 
16208: =item * &assign_categories_table()
16209: 
16210: Create a datatable for display of hierarchical categories in a domain,
16211: with checkboxes to allow a course to be categorized. 
16212: 
16213: Inputs:
16214: 
16215: cathash - reference to hash of categories defined for the domain (from
16216:           configuration.db)
16217: 
16218: currcat - scalar with an & separated list of categories assigned to a course. 
16219: 
16220: type    - scalar contains course type (Course or Community).
16221: 
16222: disabled - scalar (optional) contains disabled="disabled" if input elements are
16223:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16224: 
16225: Returns: $output (markup to be displayed) 
16226: 
16227: =cut
16228: 
16229: sub assign_categories_table {
16230:     my ($cathash,$currcat,$type,$disabled) = @_;
16231:     my $output;
16232:     if (ref($cathash) eq 'HASH') {
16233:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16234:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16235:         $maxdepth = scalar(@cats);
16236:         if (@cats > 0) {
16237:             my $itemcount = 0;
16238:             if (ref($cats[0]) eq 'ARRAY') {
16239:                 my @currcategories;
16240:                 if ($currcat ne '') {
16241:                     @currcategories = split('&',$currcat);
16242:                 }
16243:                 my $table;
16244:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16245:                     my $parent = $cats[0][$i];
16246:                     next if ($parent eq 'instcode');
16247:                     if ($type eq 'Community') {
16248:                         next unless ($parent eq 'communities');
16249:                     } elsif ($type eq 'Placement') {
16250:                         next unless ($parent eq 'placement');
16251:                     } else {
16252:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16253:                     }
16254:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16255:                     my $item = &escape($parent).'::0';
16256:                     my $checked = '';
16257:                     if (@currcategories > 0) {
16258:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16259:                             $checked = ' checked="checked"';
16260:                         }
16261:                     }
16262:                     my $parent_title = $parent;
16263:                     if ($parent eq 'communities') {
16264:                         $parent_title = &mt('Communities');
16265:                     } elsif ($parent eq 'placement') {
16266:                         $parent_title = &mt('Placement Tests');
16267:                     }
16268:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16269:                               '<input type="checkbox" name="usecategory" value="'.
16270:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16271:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16272:                     my $depth = 1;
16273:                     push(@path,$parent);
16274:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16275:                     pop(@path);
16276:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16277:                     $itemcount ++;
16278:                 }
16279:                 if ($itemcount) {
16280:                     $output = &Apache::loncommon::start_data_table().
16281:                               $table.
16282:                               &Apache::loncommon::end_data_table();
16283:                 }
16284:             }
16285:         }
16286:     }
16287:     return $output;
16288: }
16289: 
16290: =pod
16291: 
16292: =item * &assign_category_rows()
16293: 
16294: Create a datatable row for display of nested categories in a domain,
16295: with checkboxes to allow a course to be categorized,called recursively.
16296: 
16297: Inputs:
16298: 
16299: itemcount - track row number for alternating colors
16300: 
16301: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16302:       categories and subcategories.
16303: 
16304: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16305: 
16306: parent - parent of current category item
16307: 
16308: path - Array containing all categories back up through the hierarchy from the
16309:        current category to the top level.
16310: 
16311: currcategories - reference to array of current categories assigned to the course
16312: 
16313: disabled - scalar (optional) contains disabled="disabled" if input elements are
16314:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16315: 
16316: Returns: $output (markup to be displayed).
16317: 
16318: =cut
16319: 
16320: sub assign_category_rows {
16321:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16322:     my ($text,$name,$item,$chgstr);
16323:     if (ref($cats) eq 'ARRAY') {
16324:         my $maxdepth = scalar(@{$cats});
16325:         if (ref($cats->[$depth]) eq 'HASH') {
16326:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16327:                 my $numchildren = @{$cats->[$depth]{$parent}};
16328:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16329:                 $text .= '<td><table class="LC_data_table">';
16330:                 for (my $j=0; $j<$numchildren; $j++) {
16331:                     $name = $cats->[$depth]{$parent}[$j];
16332:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16333:                     my $deeper = $depth+1;
16334:                     my $checked = '';
16335:                     if (ref($currcategories) eq 'ARRAY') {
16336:                         if (@{$currcategories} > 0) {
16337:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16338:                                 $checked = ' checked="checked"';
16339:                             }
16340:                         }
16341:                     }
16342:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16343:                              '<input type="checkbox" name="usecategory" value="'.
16344:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16345:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16346:                              '</td><td>';
16347:                     if (ref($path) eq 'ARRAY') {
16348:                         push(@{$path},$name);
16349:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16350:                         pop(@{$path});
16351:                     }
16352:                     $text .= '</td></tr>';
16353:                 }
16354:                 $text .= '</table></td>';
16355:             }
16356:         }
16357:     }
16358:     return $text;
16359: }
16360: 
16361: =pod
16362: 
16363: =back
16364: 
16365: =cut
16366: 
16367: ############################################################
16368: ############################################################
16369: 
16370: 
16371: sub commit_customrole {
16372:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
16373:     my $result = &Apache::lonnet::assigncustomrole(
16374:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context);
16375:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16376:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16377:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16378:     if (wantarray) {
16379:         return ($output,$result);
16380:     } else {
16381:         return $output;
16382:     }
16383: }
16384: 
16385: sub commit_standardrole {
16386:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
16387:     my ($output,$logmsg,$linefeed,$result);
16388:     if ($context eq 'auto') {
16389:         $linefeed = "\n";
16390:     } else {
16391:         $linefeed = "<br />\n";
16392:     }  
16393:     if ($three eq 'st') {
16394:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16395:                                       $one,$two,$sec,$context,$credits);
16396:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16397:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16398:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16399:         } else {
16400:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16401:                ($start?', '.&mt('starting').' '.localtime($start):'').
16402:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16403:             if ($context eq 'auto') {
16404:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16405:             } else {
16406:                $output .= '<b>'.$result.'</b>'.$linefeed.
16407:                &mt('Add to classlist').': <b>ok</b>';
16408:             }
16409:             $output .= $linefeed;
16410:         }
16411:     } else {
16412:         $output = &mt('Assigning').' '.$three.' in '.$url.
16413:                ($start?', '.&mt('starting').' '.localtime($start):'').
16414:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16415:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16416:         if ($context eq 'auto') {
16417:             $output .= $result.$linefeed;
16418:         } else {
16419:             $output .= '<b>'.$result.'</b>'.$linefeed;
16420:         }
16421:     }
16422:     if (wantarray) {
16423:         return ($output,$result);
16424:     } else {
16425:         return $output;
16426:     }
16427: }
16428: 
16429: sub commit_studentrole {
16430:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16431:         $credits) = @_;
16432:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16433:     if ($context eq 'auto') {
16434:         $linefeed = "\n";
16435:     } else {
16436:         $linefeed = '<br />'."\n";
16437:     }
16438:     if (defined($one) && defined($two)) {
16439:         my $cid=$one.'_'.$two;
16440:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16441:         my $secchange = 0;
16442:         my $expire_role_result;
16443:         my $modify_section_result;
16444:         if ($oldsec ne '-1') { 
16445:             if ($oldsec ne $sec) {
16446:                 $secchange = 1;
16447:                 my $now = time;
16448:                 my $uurl='/'.$cid;
16449:                 $uurl=~s/\_/\//g;
16450:                 if ($oldsec) {
16451:                     $uurl.='/'.$oldsec;
16452:                 }
16453:                 $oldsecurl = $uurl;
16454:                 $expire_role_result = 
16455:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
16456:                 if ($env{'request.course.sec'} ne '') { 
16457:                     if ($expire_role_result eq 'refused') {
16458:                         my @roles = ('st');
16459:                         my @statuses = ('previous');
16460:                         my @roledoms = ($one);
16461:                         my $withsec = 1;
16462:                         my %roleshash = 
16463:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16464:                                               \@statuses,\@roles,\@roledoms,$withsec);
16465:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16466:                             my ($oldstart,$oldend) = 
16467:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16468:                             if ($oldend > 0 && $oldend <= $now) {
16469:                                 $expire_role_result = 'ok';
16470:                             }
16471:                         }
16472:                     }
16473:                 }
16474:                 $result = $expire_role_result;
16475:             }
16476:         }
16477:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16478:             $modify_section_result = 
16479:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16480:                                                            undef,undef,undef,$sec,
16481:                                                            $end,$start,'','',$cid,
16482:                                                            '',$context,$credits);
16483:             if ($modify_section_result =~ /^ok/) {
16484:                 if ($secchange == 1) {
16485:                     if ($sec eq '') {
16486:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16487:                     } else {
16488:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16489:                     }
16490:                 } elsif ($oldsec eq '-1') {
16491:                     if ($sec eq '') {
16492:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16493:                     } else {
16494:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16495:                     }
16496:                 } else {
16497:                     if ($sec eq '') {
16498:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16499:                     } else {
16500:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16501:                     }
16502:                 }
16503:             } else {
16504:                 if ($secchange) { 
16505:                     $$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;
16506:                 } else {
16507:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16508:                 }
16509:             }
16510:             $result = $modify_section_result;
16511:         } elsif ($secchange == 1) {
16512:             if ($oldsec eq '') {
16513:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16514:             } else {
16515:                 $$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;
16516:             }
16517:             if ($expire_role_result eq 'refused') {
16518:                 my $newsecurl = '/'.$cid;
16519:                 $newsecurl =~ s/\_/\//g;
16520:                 if ($sec ne '') {
16521:                     $newsecurl.='/'.$sec;
16522:                 }
16523:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16524:                     if ($sec eq '') {
16525:                         $$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;
16526:                     } else {
16527:                         $$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;
16528:                     }
16529:                 }
16530:             }
16531:         }
16532:     } else {
16533:         $$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;
16534:         $result = "error: incomplete course id\n";
16535:     }
16536:     return $result;
16537: }
16538: 
16539: sub show_role_extent {
16540:     my ($scope,$context,$role) = @_;
16541:     $scope =~ s{^/}{};
16542:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16543:     push(@courseroles,'co');
16544:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16545:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16546:         $scope =~ s{/}{_};
16547:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16548:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16549:         my ($audom,$auname) = split(/\//,$scope);
16550:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16551:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16552:     } else {
16553:         $scope =~ s{/$}{};
16554:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16555:                    &Apache::lonnet::domain($scope,'description').'</span>');
16556:     }
16557: }
16558: 
16559: ############################################################
16560: ############################################################
16561: 
16562: sub check_clone {
16563:     my ($args,$linefeed) = @_;
16564:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16565:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16566:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16567:     my $clonetitle;
16568:     my @clonemsg;
16569:     my $can_clone = 0;
16570:     my $lctype = lc($args->{'crstype'});
16571:     if ($lctype ne 'community') {
16572:         $lctype = 'course';
16573:     }
16574:     if ($clonehome eq 'no_host') {
16575:         if ($args->{'crstype'} eq 'Community') {
16576:             push(@clonemsg,({
16577:                               mt => 'No new community created.',
16578:                               args => [],
16579:                             },
16580:                             {
16581:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16582:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16583:                             }));
16584:         } else {
16585:             push(@clonemsg,({
16586:                               mt => 'No new course created.',
16587:                               args => [],
16588:                             },
16589:                             {
16590:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16591:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16592:                             }));
16593:         }
16594:     } else {
16595: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16596:         $clonetitle = $clonedesc{'description'};
16597:         if ($args->{'crstype'} eq 'Community') {
16598:             if ($clonedesc{'type'} ne 'Community') {
16599:                 push(@clonemsg,({
16600:                                   mt => 'No new community created.',
16601:                                   args => [],
16602:                                 },
16603:                                 {
16604:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16605:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16606:                                 }));
16607:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16608:             }
16609:         }
16610: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16611:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16612: 	    $can_clone = 1;
16613: 	} else {
16614: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16615: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16616:             if ($clonehash{'cloners'} eq '') {
16617:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16618:                 if ($domdefs{'canclone'}) {
16619:                     unless ($domdefs{'canclone'} eq 'none') {
16620:                         if ($domdefs{'canclone'} eq 'domain') {
16621:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16622:                                 $can_clone = 1;
16623:                             }
16624:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16625:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16626:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16627:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16628:                                 $can_clone = 1;
16629:                             }
16630:                         }
16631:                     }
16632:                 }
16633:             } else {
16634: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16635:                 if (grep(/^\*$/,@cloners)) {
16636:                     $can_clone = 1;
16637:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16638:                     $can_clone = 1;
16639:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16640:                     $can_clone = 1;
16641:                 }
16642:                 unless ($can_clone) {
16643:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16644:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16645:                         my (%gotdomdefaults,%gotcodedefaults);
16646:                         foreach my $cloner (@cloners) {
16647:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16648:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16649:                                 my (%codedefaults,@code_order);
16650:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16651:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16652:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16653:                                     }
16654:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16655:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16656:                                     }
16657:                                 } else {
16658:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16659:                                                                             \%codedefaults,
16660:                                                                             \@code_order);
16661:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16662:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16663:                                 }
16664:                                 if (@code_order > 0) {
16665:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16666:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16667:                                                                                 $args->{'crscode'})) {
16668:                                         $can_clone = 1;
16669:                                         last;
16670:                                     }
16671:                                 }
16672:                             }
16673:                         }
16674:                     }
16675:                 }
16676:             }
16677:             unless ($can_clone) {
16678:                 my $ccrole = 'cc';
16679:                 if ($args->{'crstype'} eq 'Community') {
16680:                     $ccrole = 'co';
16681:                 }
16682: 	        my %roleshash =
16683: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16684: 					          $args->{'ccdomain'},
16685:                                                   'userroles',['active'],[$ccrole],
16686: 					          [$args->{'clonedomain'}]);
16687: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16688:                     $can_clone = 1;
16689:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16690:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16691:                     $can_clone = 1;
16692:                 }
16693:             }
16694:             unless ($can_clone) {
16695:                 if ($args->{'crstype'} eq 'Community') {
16696:                     push(@clonemsg,({
16697:                                       mt => 'No new community created.',
16698:                                       args => [],
16699:                                     },
16700:                                     {
16701:                                       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]).',
16702:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16703:                                     }));
16704:                 } else {
16705:                     push(@clonemsg,({
16706:                                       mt => 'No new course created.',
16707:                                       args => [],
16708:                                     },
16709:                                     {
16710:                                       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]).',
16711:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16712:                                     }));
16713:                 }
16714: 	    }
16715:         }
16716:     }
16717:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16718: }
16719: 
16720: sub construct_course {
16721:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16722:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16723:     my ($outcome,$msgref,$clonemsgref);
16724:     my $linefeed =  '<br />'."\n";
16725:     if ($context eq 'auto') {
16726:         $linefeed = "\n";
16727:     }
16728: 
16729: #
16730: # Are we cloning?
16731: #
16732:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16733:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16734: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16735:         if (!$can_clone) {
16736: 	    return (0,$outcome,$clonemsgref);
16737: 	}
16738:     }
16739: 
16740: #
16741: # Open course
16742: #
16743:     my $showncrstype;
16744:     if ($args->{'crstype'} eq 'Placement') {
16745:         $showncrstype = 'placement test'; 
16746:     } else {  
16747:         $showncrstype = lc($args->{'crstype'});
16748:     }
16749:     my %cenv=();
16750:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16751:                                              $args->{'cdescr'},
16752:                                              $args->{'curl'},
16753:                                              $args->{'course_home'},
16754:                                              $args->{'nonstandard'},
16755:                                              $args->{'crscode'},
16756:                                              $args->{'ccuname'}.':'.
16757:                                              $args->{'ccdomain'},
16758:                                              $args->{'crstype'},
16759:                                              $cnum,$context,$category,
16760:                                              $callercontext);
16761: 
16762:     # Note: The testing routines depend on this being output; see 
16763:     # Utils::Course. This needs to at least be output as a comment
16764:     # if anyone ever decides to not show this, and Utils::Course::new
16765:     # will need to be suitably modified.
16766:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16767:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16768:     } else {
16769:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16770:     }
16771:     if ($$courseid =~ /^error:/) {
16772:         return (0,$outcome,$clonemsgref);
16773:     }
16774: 
16775: #
16776: # Check if created correctly
16777: #
16778:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16779:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16780:     if ($crsuhome eq 'no_host') {
16781:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16782:             $outcome .= &mt_user($user_lh,
16783:                             'Course creation failed, unrecognized course home server.');
16784:         } else {
16785:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16786:         }
16787:         $outcome .= $linefeed;
16788:         return (0,$outcome,$clonemsgref);
16789:     }
16790:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16791: 
16792: #
16793: # Do the cloning
16794: #   
16795:     my @clonemsg;
16796:     if ($can_clone && $cloneid) {
16797:         push(@clonemsg,
16798:                       {
16799:                           mt => 'Created [_1] by cloning from [_2]',
16800:                           args => [$showncrstype,$clonetitle],
16801:                       });
16802: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16803: # Copy all files
16804:         my @info =
16805: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16806: 	                                             $args->{'dateshift'},$args->{'crscode'},
16807:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16808:                                                      $args->{'tinyurls'});
16809:         if (@info) {
16810:             push(@clonemsg,@info);
16811:         }
16812: # Restore URL
16813: 	$cenv{'url'}=$oldcenv{'url'};
16814: # Restore title
16815: 	$cenv{'description'}=$oldcenv{'description'};
16816: # Restore creation date, creator and creation context.
16817:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16818:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16819:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16820: # Mark as cloned
16821: 	$cenv{'clonedfrom'}=$cloneid;
16822: # Need to clone grading mode
16823:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16824:         $cenv{'grading'}=$newenv{'grading'};
16825: # Do not clone these environment entries
16826:         &Apache::lonnet::del('environment',
16827:                   ['default_enrollment_start_date',
16828:                    'default_enrollment_end_date',
16829:                    'question.email',
16830:                    'policy.email',
16831:                    'comment.email',
16832:                    'pch.users.denied',
16833:                    'plc.users.denied',
16834:                    'hidefromcat',
16835:                    'checkforpriv',
16836:                    'categories'],
16837:                    $$crsudom,$$crsunum);
16838:         if ($args->{'textbook'}) {
16839:             $cenv{'internal.textbook'} = $args->{'textbook'};
16840:         }
16841:     }
16842: 
16843: #
16844: # Set environment (will override cloned, if existing)
16845: #
16846:     my @sections = ();
16847:     my @xlists = ();
16848:     if ($args->{'crstype'}) {
16849:         $cenv{'type'}=$args->{'crstype'};
16850:     }
16851:     if ($args->{'lti'}) {
16852:         $cenv{'internal.lti'}=$args->{'lti'};
16853:     }
16854:     if ($args->{'crsid'}) {
16855:         $cenv{'courseid'}=$args->{'crsid'};
16856:     }
16857:     if ($args->{'crscode'}) {
16858:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16859:     }
16860:     if ($args->{'crsquota'} ne '') {
16861:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16862:     } else {
16863:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16864:     }
16865:     if ($args->{'ccuname'}) {
16866:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16867:                                         ':'.$args->{'ccdomain'};
16868:     } else {
16869:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16870:     }
16871:     if ($args->{'defaultcredits'}) {
16872:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16873:     }
16874:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16875:     if ($args->{'crssections'}) {
16876:         $cenv{'internal.sectionnums'} = '';
16877:         if ($args->{'crssections'} =~ m/,/) {
16878:             @sections = split/,/,$args->{'crssections'};
16879:         } else {
16880:             $sections[0] = $args->{'crssections'};
16881:         }
16882:         if (@sections > 0) {
16883:             foreach my $item (@sections) {
16884:                 my ($sec,$gp) = split/:/,$item;
16885:                 my $class = $args->{'crscode'}.$sec;
16886:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16887:                 $cenv{'internal.sectionnums'} .= $item.',';
16888:                 unless ($addcheck eq 'ok') {
16889:                     push(@badclasses,$class);
16890:                 }
16891:             }
16892:             $cenv{'internal.sectionnums'} =~ s/,$//;
16893:         }
16894:     }
16895: # do not hide course coordinator from staff listing, 
16896: # even if privileged
16897:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16898: # add course coordinator's domain to domains to check for privileged users
16899: # if different to course domain
16900:     if ($$crsudom ne $args->{'ccdomain'}) {
16901:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16902:     }
16903: # add crosslistings
16904:     if ($args->{'crsxlist'}) {
16905:         $cenv{'internal.crosslistings'}='';
16906:         if ($args->{'crsxlist'} =~ m/,/) {
16907:             @xlists = split/,/,$args->{'crsxlist'};
16908:         } else {
16909:             $xlists[0] = $args->{'crsxlist'};
16910:         }
16911:         if (@xlists > 0) {
16912:             foreach my $item (@xlists) {
16913:                 my ($xl,$gp) = split/:/,$item;
16914:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16915:                 $cenv{'internal.crosslistings'} .= $item.',';
16916:                 unless ($addcheck eq 'ok') {
16917:                     push(@badclasses,$xl);
16918:                 }
16919:             }
16920:             $cenv{'internal.crosslistings'} =~ s/,$//;
16921:         }
16922:     }
16923:     if ($args->{'autoadds'}) {
16924:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16925:     }
16926:     if ($args->{'autodrops'}) {
16927:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16928:     }
16929: # check for notification of enrollment changes
16930:     my @notified = ();
16931:     if ($args->{'notify_owner'}) {
16932:         if ($args->{'ccuname'} ne '') {
16933:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16934:         }
16935:     }
16936:     if ($args->{'notify_dc'}) {
16937:         if ($uname ne '') { 
16938:             push(@notified,$uname.':'.$udom);
16939:         }
16940:     }
16941:     if (@notified > 0) {
16942:         my $notifylist;
16943:         if (@notified > 1) {
16944:             $notifylist = join(',',@notified);
16945:         } else {
16946:             $notifylist = $notified[0];
16947:         }
16948:         $cenv{'internal.notifylist'} = $notifylist;
16949:     }
16950:     if (@badclasses > 0) {
16951:         my %lt=&Apache::lonlocal::texthash(
16952:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16953:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16954:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16955:         );
16956:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16957:                            &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'};
16958:         if ($context eq 'auto') {
16959:             $outcome .= $badclass_msg.$linefeed;
16960:         } else {
16961:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16962:         }
16963:         foreach my $item (@badclasses) {
16964:             if ($context eq 'auto') {
16965:                 $outcome .= " - $item\n";
16966:             } else {
16967:                 $outcome .= "<li>$item</li>\n";
16968:             }
16969:         }
16970:         if ($context eq 'auto') {
16971:             $outcome .= $linefeed;
16972:         } else {
16973:             $outcome .= "</ul><br /><br /></div>\n";
16974:         } 
16975:     }
16976:     if ($args->{'no_end_date'}) {
16977:         $args->{'endaccess'} = 0;
16978:     }
16979:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16980:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16981:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16982:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16983:     if ($args->{'showphotos'}) {
16984:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16985:     }
16986:     $cenv{'internal.authtype'} = $args->{'authtype'};
16987:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16988:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16989:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16990:             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'); 
16991:             if ($context eq 'auto') {
16992:                 $outcome .= $krb_msg;
16993:             } else {
16994:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16995:             }
16996:             $outcome .= $linefeed;
16997:         }
16998:     }
16999:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17000:        if ($args->{'setpolicy'}) {
17001:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17002:        }
17003:        if ($args->{'setcontent'}) {
17004:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17005:        }
17006:        if ($args->{'setcomment'}) {
17007:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17008:        }
17009:     }
17010:     if ($args->{'reshome'}) {
17011: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17012: 	$cenv{'reshome'}=~s/\/+$/\//;
17013:     }
17014: #
17015: # course has keyed access
17016: #
17017:     if ($args->{'setkeys'}) {
17018:        $cenv{'keyaccess'}='yes';
17019:     }
17020: # if specified, key authority is not course, but user
17021: # only active if keyaccess is yes
17022:     if ($args->{'keyauth'}) {
17023: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17024: 	$user = &LONCAPA::clean_username($user);
17025: 	$domain = &LONCAPA::clean_username($domain);
17026: 	if ($user ne '' && $domain ne '') {
17027: 	    $cenv{'keyauth'}=$user.':'.$domain;
17028: 	}
17029:     }
17030: 
17031: #
17032: #  generate and store uniquecode (available to course requester), if course should have one.
17033: #
17034:     if ($args->{'uniquecode'}) {
17035:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17036:         if ($code) {
17037:             $cenv{'internal.uniquecode'} = $code;
17038:             my %crsinfo =
17039:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17040:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17041:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17042:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17043:             } 
17044:             if (ref($coderef)) {
17045:                 $$coderef = $code;
17046:             }
17047:         }
17048:     }
17049: 
17050:     if ($args->{'disresdis'}) {
17051:         $cenv{'pch.roles.denied'}='st';
17052:     }
17053:     if ($args->{'disablechat'}) {
17054:         $cenv{'plc.roles.denied'}='st';
17055:     }
17056: 
17057:     # Record we've not yet viewed the Course Initialization Helper for this 
17058:     # course
17059:     $cenv{'course.helper.not.run'} = 1;
17060:     #
17061:     # Use new Randomseed
17062:     #
17063:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17064:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17065:     #
17066:     # The encryption code and receipt prefix for this course
17067:     #
17068:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17069:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17070:     #
17071:     # By default, use standard grading
17072:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17073: 
17074:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17075:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17076: #
17077: # Open all assignments
17078: #
17079:     if ($args->{'openall'}) {
17080:        my $opendate = time;
17081:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17082:            $opendate = $args->{'openallfrom'};
17083:        }
17084:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17085:        my %storecontent = ($storeunder         => $opendate,
17086:                            $storeunder.'.type' => 'date_start');
17087:        $outcome .= &mt('All assignments open starting [_1]',
17088:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17089:                    &Apache::lonnet::cput
17090:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17091:    }
17092: #
17093: # Set first page
17094: #
17095:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17096: 	    || ($cloneid)) {
17097: 	$outcome .= &mt('Setting first resource').': ';
17098: 
17099: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17100:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17101: 
17102:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17103:         my $title; my $url;
17104:         if ($args->{'firstres'} eq 'syl') {
17105: 	    $title=&mt('Syllabus');
17106:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17107:         } else {
17108:             $title=&mt('Table of Contents');
17109:             $url='/adm/navmaps';
17110:         }
17111: 
17112:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17113: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17114: 
17115: 	if ($errtext) { $fatal=2; }
17116:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17117:     }
17118: 
17119: # 
17120: # Set params for Placement Tests
17121: #
17122:     if ($args->{'crstype'} eq 'Placement') {
17123:        my %storecontent; 
17124:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17125:        my %defaults = (
17126:                         buttonshide   => { value => 'yes',
17127:                                            type => 'string_yesno',},
17128:                         type          => { value => 'randomizetry',
17129:                                            type  => 'string_questiontype',},
17130:                         maxtries      => { value => 1,
17131:                                            type => 'int_pos',},
17132:                         problemstatus => { value => 'no',
17133:                                            type  => 'string_problemstatus',},
17134:                       );
17135:        foreach my $key (keys(%defaults)) {
17136:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17137:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17138:        }
17139:        &Apache::lonnet::cput
17140:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17141:     }
17142: 
17143:     return (1,$outcome,\@clonemsg);
17144: }
17145: 
17146: sub make_unique_code {
17147:     my ($cdom,$cnum) = @_;
17148:     # get lock on uniquecodes db
17149:     my $lockhash = {
17150:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17151:                                                   ':'.$env{'user.domain'},
17152:                    };
17153:     my $tries = 0;
17154:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17155:     my ($code,$error);
17156:   
17157:     while (($gotlock ne 'ok') && ($tries<3)) {
17158:         $tries ++;
17159:         sleep 1;
17160:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17161:     }
17162:     if ($gotlock eq 'ok') {
17163:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17164:         my $gotcode;
17165:         my $attempts = 0;
17166:         while ((!$gotcode) && ($attempts < 100)) {
17167:             $code = &generate_code();
17168:             if (!exists($currcodes{$code})) {
17169:                 $gotcode = 1;
17170:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17171:                     $error = 'nostore';
17172:                 }
17173:             }
17174:             $attempts ++;
17175:         }
17176:         my @del_lock = ($cnum."\0".'uniquecodes');
17177:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17178:     } else {
17179:         $error = 'nolock';
17180:     }
17181:     return ($code,$error);
17182: }
17183: 
17184: sub generate_code {
17185:     my $code;
17186:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17187:     for (my $i=0; $i<6; $i++) {
17188:         my $lettnum = int (rand 2);
17189:         my $item = '';
17190:         if ($lettnum) {
17191:             $item = $letts[int( rand(18) )];
17192:         } else {
17193:             $item = 1+int( rand(8) );
17194:         }
17195:         $code .= $item;
17196:     }
17197:     return $code;
17198: }
17199: 
17200: ############################################################
17201: ############################################################
17202: 
17203: # Community, Course and Placement Test
17204: sub course_type {
17205:     my ($cid) = @_;
17206:     if (!defined($cid)) {
17207:         $cid = $env{'request.course.id'};
17208:     }
17209:     if (defined($env{'course.'.$cid.'.type'})) {
17210:         return $env{'course.'.$cid.'.type'};
17211:     } else {
17212:         return 'Course';
17213:     }
17214: }
17215: 
17216: sub group_term {
17217:     my $crstype = &course_type();
17218:     my %names = (
17219:                   'Course' => 'group',
17220:                   'Community' => 'group',
17221:                   'Placement' => 'group',
17222:                 );
17223:     return $names{$crstype};
17224: }
17225: 
17226: sub course_types {
17227:     my @types = ('official','unofficial','community','textbook','placement','lti');
17228:     my %typename = (
17229:                          official   => 'Official course',
17230:                          unofficial => 'Unofficial course',
17231:                          community  => 'Community',
17232:                          textbook   => 'Textbook course',
17233:                          placement  => 'Placement test',
17234:                          lti        => 'LTI provider',
17235:                    );
17236:     return (\@types,\%typename);
17237: }
17238: 
17239: sub icon {
17240:     my ($file)=@_;
17241:     my $curfext = lc((split(/\./,$file))[-1]);
17242:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17243:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17244:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17245: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17246: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17247: 	            $curfext.".gif") {
17248: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17249: 		$curfext.".gif";
17250: 	}
17251:     }
17252:     return &lonhttpdurl($iconname);
17253: } 
17254: 
17255: sub lonhttpdurl {
17256: #
17257: # Had been used for "small fry" static images on separate port 8080.
17258: # Modify here if lightweight http functionality desired again.
17259: # Currently eliminated due to increasing firewall issues.
17260: #
17261:     my ($url)=@_;
17262:     return $url;
17263: }
17264: 
17265: sub connection_aborted {
17266:     my ($r)=@_;
17267:     $r->print(" ");$r->rflush();
17268:     my $c = $r->connection;
17269:     return $c->aborted();
17270: }
17271: 
17272: #    Escapes strings that may have embedded 's that will be put into
17273: #    strings as 'strings'.
17274: sub escape_single {
17275:     my ($input) = @_;
17276:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17277:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17278:     return $input;
17279: }
17280: 
17281: #  Same as escape_single, but escape's "'s  This 
17282: #  can be used for  "strings"
17283: sub escape_double {
17284:     my ($input) = @_;
17285:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17286:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17287:     return $input;
17288: }
17289:  
17290: #   Escapes the last element of a full URL.
17291: sub escape_url {
17292:     my ($url)   = @_;
17293:     my @urlslices = split(/\//, $url,-1);
17294:     my $lastitem = &escape(pop(@urlslices));
17295:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17296: }
17297: 
17298: sub compare_arrays {
17299:     my ($arrayref1,$arrayref2) = @_;
17300:     my (@difference,%count);
17301:     @difference = ();
17302:     %count = ();
17303:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17304:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17305:         foreach my $element (keys(%count)) {
17306:             if ($count{$element} == 1) {
17307:                 push(@difference,$element);
17308:             }
17309:         }
17310:     }
17311:     return @difference;
17312: }
17313: 
17314: sub lon_status_items {
17315:     my %defaults = (
17316:                      E         => 100,
17317:                      W         => 4,
17318:                      N         => 1,
17319:                      U         => 5,
17320:                      threshold => 200,
17321:                      sysmail   => 2500,
17322:                    );
17323:     my %names = (
17324:                    E => 'Errors',
17325:                    W => 'Warnings',
17326:                    N => 'Notices',
17327:                    U => 'Unsent',
17328:                 );
17329:     return (\%defaults,\%names);
17330: }
17331: 
17332: # -------------------------------------------------------- Initialize user login
17333: sub init_user_environment {
17334:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17335:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17336: 
17337:     my $public=($username eq 'public' && $domain eq 'public');
17338: 
17339:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17340:     my $now=time;
17341: 
17342:     if ($public) {
17343: 	my $max_public=100;
17344: 	my $oldest;
17345: 	my $oldest_time=0;
17346: 	for(my $next=1;$next<=$max_public;$next++) {
17347: 	    if (-e $lonids."/publicuser_$next.id") {
17348: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17349: 		if ($mtime<$oldest_time || !$oldest_time) {
17350: 		    $oldest_time=$mtime;
17351: 		    $oldest=$next;
17352: 		}
17353: 	    } else {
17354: 		$cookie="publicuser_$next";
17355: 		last;
17356: 	    }
17357: 	}
17358: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17359:     } else {
17360: 	# See if old ID present, if so, remove if this isn't a robot,
17361: 	# killing any existing non-robot sessions
17362: 	if (!$args->{'robot'}) {
17363: 	    opendir(DIR,$lonids);
17364: 	    while ($filename=readdir(DIR)) {
17365: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17366:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17367:                             &GDBM_READER(),0640)) {
17368:                         my $linkedfile;
17369:                         if (exists($oldenv{'user.linkedenv'})) {
17370:                             $linkedfile = $oldenv{'user.linkedenv'};
17371:                         }
17372:                         untie(%oldenv);
17373:                         if (unlink("$lonids/$filename")) {
17374:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17375:                                 if (-l "$lonids/$linkedfile.id") {
17376:                                     unlink("$lonids/$linkedfile.id");
17377:                                 }
17378:                             }
17379:                         }
17380:                     } else {
17381:                         unlink($lonids.'/'.$filename);
17382:                     }
17383: 		}
17384: 	    }
17385: 	    closedir(DIR);
17386: # If there is a undeleted lockfile for the user's paste buffer remove it.
17387:             my $namespace = 'nohist_courseeditor';
17388:             my $lockingkey = 'paste'."\0".'locked_num';
17389:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17390:                                                 $domain,$username);
17391:             if (exists($lockhash{$lockingkey})) {
17392:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17393:                 unless ($delresult eq 'ok') {
17394:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17395:                 }
17396:             }
17397: 	}
17398: # Give them a new cookie
17399: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17400: 		                   : $now.$$.int(rand(10000)));
17401: 	$cookie="$username\_$id\_$domain\_$authhost";
17402:     
17403: # Initialize roles
17404: 
17405: 	($userroles,$firstaccenv,$timerintenv) = 
17406:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17407:     }
17408: # ------------------------------------ Check browser type and MathML capability
17409: 
17410:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17411:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17412: 
17413: # ------------------------------------------------------------- Get environment
17414: 
17415:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17416:     my ($tmp) = keys(%userenv);
17417:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17418: 	undef(%userenv);
17419:     }
17420:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17421: 	$form->{'interface'}=$userenv{'interface'};
17422:     }
17423:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17424: 
17425: # --------------- Do not trust query string to be put directly into environment
17426:     foreach my $option ('interface','localpath','localres') {
17427:         $form->{$option}=~s/[\n\r\=]//gs;
17428:     }
17429: # --------------------------------------------------------- Write first profile
17430: 
17431:     {
17432:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17433: 	my %initial_env = 
17434: 	    ("user.name"          => $username,
17435: 	     "user.domain"        => $domain,
17436: 	     "user.home"          => $authhost,
17437: 	     "browser.type"       => $clientbrowser,
17438: 	     "browser.version"    => $clientversion,
17439: 	     "browser.mathml"     => $clientmathml,
17440: 	     "browser.unicode"    => $clientunicode,
17441: 	     "browser.os"         => $clientos,
17442:              "browser.mobile"     => $clientmobile,
17443:              "browser.info"       => $clientinfo,
17444:              "browser.osversion"  => $clientosversion,
17445: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17446: 	     "request.course.fn"  => '',
17447: 	     "request.course.uri" => '',
17448: 	     "request.course.sec" => '',
17449: 	     "request.role"       => 'cm',
17450: 	     "request.role.adv"   => $env{'user.adv'},
17451: 	     "request.host"       => $ip,);
17452: 
17453:         if ($form->{'localpath'}) {
17454: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17455: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17456:         }
17457: 	
17458: 	if ($form->{'interface'}) {
17459: 	    $form->{'interface'}=~s/\W//gs;
17460: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17461: 	    $env{'browser.interface'}=$form->{'interface'};
17462: 	}
17463: 
17464:         if ($form->{'iptoken'}) {
17465:             my $lonhost = $r->dir_config('lonHostID');
17466:             $initial_env{"user.noloadbalance"} = $lonhost;
17467:             $env{'user.noloadbalance'} = $lonhost;
17468:         }
17469: 
17470:         if ($form->{'noloadbalance'}) {
17471:             my @hosts = &Apache::lonnet::current_machine_ids();
17472:             my $hosthere = $form->{'noloadbalance'};
17473:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17474:                 $initial_env{"user.noloadbalance"} = $hosthere;
17475:                 $env{'user.noloadbalance'} = $hosthere;
17476:             }
17477:         }
17478: 
17479:         unless ($domain eq 'public') {
17480:             my %is_adv = ( is_adv => $env{'user.adv'} );
17481:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17482: 
17483:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17484:                 $userenv{'availabletools.'.$tool} = 
17485:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17486:                                                       undef,\%userenv,\%domdef,\%is_adv);
17487:             }
17488: 
17489:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17490:                 $userenv{'canrequest.'.$crstype} =
17491:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17492:                                                       'reload','requestcourses',
17493:                                                       \%userenv,\%domdef,\%is_adv);
17494:             }
17495: 
17496:             $userenv{'canrequest.author'} =
17497:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17498:                                                   'reload','requestauthor',
17499:                                                   \%userenv,\%domdef,\%is_adv);
17500:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17501:                                                  $domain,$username);
17502:             my $reqstatus = $reqauthor{'author_status'};
17503:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17504:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17505:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17506:                                                       $reqauthor{'author'}{'timestamp'};
17507:                 }
17508:             }
17509:             my ($types,$typename) = &course_types();
17510:             if (ref($types) eq 'ARRAY') {
17511:                 my @options = ('approval','validate','autolimit');
17512:                 my $optregex = join('|',@options);
17513:                 my (%willtrust,%trustchecked);
17514:                 foreach my $type (@{$types}) {
17515:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17516:                     if ($dom_str ne '') {
17517:                         my $updatedstr = '';
17518:                         my @possdomains = split(',',$dom_str);
17519:                         foreach my $entry (@possdomains) {
17520:                             my ($extdom,$extopt) = split(':',$entry);
17521:                             unless ($trustchecked{$extdom}) {
17522:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17523:                                 $trustchecked{$extdom} = 1;
17524:                             }
17525:                             if ($willtrust{$extdom}) {
17526:                                 $updatedstr .= $entry.',';
17527:                             }
17528:                         }
17529:                         $updatedstr =~ s/,$//;
17530:                         if ($updatedstr) {
17531:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17532:                         } else {
17533:                             delete($userenv{'reqcrsotherdom.'.$type});
17534:                         }
17535:                     }
17536:                 }
17537:             }
17538:         }
17539: 	$env{'user.environment'} = "$lonids/$cookie.id";
17540: 
17541: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17542: 		 &GDBM_WRCREAT(),0640)) {
17543: 	    &_add_to_env(\%disk_env,\%initial_env);
17544: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17545: 	    &_add_to_env(\%disk_env,$userroles);
17546:             if (ref($firstaccenv) eq 'HASH') {
17547:                 &_add_to_env(\%disk_env,$firstaccenv);
17548:             }
17549:             if (ref($timerintenv) eq 'HASH') {
17550:                 &_add_to_env(\%disk_env,$timerintenv);
17551:             }
17552: 	    if (ref($args->{'extra_env'})) {
17553: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17554: 	    }
17555: 	    untie(%disk_env);
17556: 	} else {
17557: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17558: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17559: 	    return 'error: '.$!;
17560: 	}
17561:     }
17562:     $env{'request.role'}='cm';
17563:     $env{'request.role.adv'}=$env{'user.adv'};
17564:     $env{'browser.type'}=$clientbrowser;
17565: 
17566:     return $cookie;
17567: 
17568: }
17569: 
17570: sub _add_to_env {
17571:     my ($idf,$env_data,$prefix) = @_;
17572:     if (ref($env_data) eq 'HASH') {
17573:         while (my ($key,$value) = each(%$env_data)) {
17574: 	    $idf->{$prefix.$key} = $value;
17575: 	    $env{$prefix.$key}   = $value;
17576:         }
17577:     }
17578: }
17579: 
17580: # --- Get the symbolic name of a problem and the url
17581: sub get_symb {
17582:     my ($request,$silent) = @_;
17583:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17584:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17585:     if ($symb eq '') {
17586:         if (!$silent) {
17587:             if (ref($request)) { 
17588:                 $request->print("Unable to handle ambiguous references:$url:.");
17589:             }
17590:             return ();
17591:         }
17592:     }
17593:     &Apache::lonenc::check_decrypt(\$symb);
17594:     return ($symb);
17595: }
17596: 
17597: # --------------------------------------------------------------Get annotation
17598: 
17599: sub get_annotation {
17600:     my ($symb,$enc) = @_;
17601: 
17602:     my $key = $symb;
17603:     if (!$enc) {
17604:         $key =
17605:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17606:     }
17607:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17608:     return $annotation{$key};
17609: }
17610: 
17611: sub clean_symb {
17612:     my ($symb,$delete_enc) = @_;
17613: 
17614:     &Apache::lonenc::check_decrypt(\$symb);
17615:     my $enc = $env{'request.enc'};
17616:     if ($delete_enc) {
17617:         delete($env{'request.enc'});
17618:     }
17619: 
17620:     return ($symb,$enc);
17621: }
17622: 
17623: ############################################################
17624: ############################################################
17625: 
17626: =pod
17627: 
17628: =head1 Routines for building display used to search for courses
17629: 
17630: 
17631: =over 4
17632: 
17633: =item * &build_filters()
17634: 
17635: Create markup for a table used to set filters to use when selecting
17636: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17637: and quotacheck.pl
17638: 
17639: 
17640: Inputs:
17641: 
17642: filterlist - anonymous array of fields to include as potential filters 
17643: 
17644: crstype - course type
17645: 
17646: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17647:               to pop-open a course selector (will contain "extra element"). 
17648: 
17649: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17650: 
17651: filter - anonymous hash of criteria and their values
17652: 
17653: action - form action
17654: 
17655: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17656: 
17657: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17658: 
17659: cloneruname - username of owner of new course who wants to clone
17660: 
17661: clonerudom - domain of owner of new course who wants to clone
17662: 
17663: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17664: 
17665: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17666: 
17667: codedom - domain
17668: 
17669: formname - value of form element named "form". 
17670: 
17671: fixeddom - domain, if fixed.
17672: 
17673: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17674: 
17675: cnameelement - name of form element in form on opener page which will receive title of selected course 
17676: 
17677: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17678: 
17679: cdomelement - name of form element in form on opener page which will receive domain of selected course
17680: 
17681: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17682: 
17683: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17684: 
17685: clonewarning - warning message about missing information for intended course owner when DC creates a course
17686: 
17687: 
17688: Returns: $output - HTML for display of search criteria, and hidden form elements.
17689: 
17690: 
17691: Side Effects: None
17692: 
17693: =cut
17694: 
17695: # ---------------------------------------------- search for courses based on last activity etc.
17696: 
17697: sub build_filters {
17698:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17699:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17700:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17701:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17702:         $clonetext,$clonewarning) = @_;
17703:     my ($list,$jscript);
17704:     my $onchange = 'javascript:updateFilters(this)';
17705:     my ($domainselectform,$sincefilterform,$createdfilterform,
17706:         $ownerdomselectform,$persondomselectform,$instcodeform,
17707:         $typeselectform,$instcodetitle);
17708:     if ($formname eq '') {
17709:         $formname = $caller;
17710:     }
17711:     foreach my $item (@{$filterlist}) {
17712:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17713:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17714:             if ($item eq 'domainfilter') {
17715:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17716:             } elsif ($item eq 'coursefilter') {
17717:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17718:             } elsif ($item eq 'ownerfilter') {
17719:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17720:             } elsif ($item eq 'ownerdomfilter') {
17721:                 $filter->{'ownerdomfilter'} =
17722:                     &LONCAPA::clean_domain($filter->{$item});
17723:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17724:                                                        'ownerdomfilter',1);
17725:             } elsif ($item eq 'personfilter') {
17726:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17727:             } elsif ($item eq 'persondomfilter') {
17728:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17729:                                                         'persondomfilter',1);
17730:             } else {
17731:                 $filter->{$item} =~ s/\W//g;
17732:             }
17733:             if (!$filter->{$item}) {
17734:                 $filter->{$item} = '';
17735:             }
17736:         }
17737:         if ($item eq 'domainfilter') {
17738:             my $allow_blank = 1;
17739:             if ($formname eq 'portform') {
17740:                 $allow_blank=0;
17741:             } elsif ($formname eq 'studentform') {
17742:                 $allow_blank=0;
17743:             }
17744:             if ($fixeddom) {
17745:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17746:                                     ' value="'.$codedom.'" />'.
17747:                                     &Apache::lonnet::domain($codedom,'description');
17748:             } else {
17749:                 $domainselectform = &select_dom_form($filter->{$item},
17750:                                                      'domainfilter',
17751:                                                       $allow_blank,'',$onchange);
17752:             }
17753:         } else {
17754:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17755:         }
17756:     }
17757: 
17758:     # last course activity filter and selection
17759:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17760: 
17761:     # course created filter and selection
17762:     if (exists($filter->{'createdfilter'})) {
17763:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17764:     }
17765: 
17766:     my $prefix = $crstype;
17767:     if ($crstype eq 'Placement') {
17768:         $prefix = 'Placement Test'
17769:     }
17770:     my %lt = &Apache::lonlocal::texthash(
17771:                 'cac' => "$prefix Activity",
17772:                 'ccr' => "$prefix Created",
17773:                 'cde' => "$prefix Title",
17774:                 'cdo' => "$prefix Domain",
17775:                 'ins' => 'Institutional Code',
17776:                 'inc' => 'Institutional Categorization',
17777:                 'cow' => "$prefix Owner/Co-owner",
17778:                 'cop' => "$prefix Personnel Includes",
17779:                 'cog' => 'Type',
17780:              );
17781: 
17782:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17783:         my $typeval = 'Course';
17784:         if ($crstype eq 'Community') {
17785:             $typeval = 'Community';
17786:         } elsif ($crstype eq 'Placement') {
17787:             $typeval = 'Placement';
17788:         }
17789:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17790:     } else {
17791:         $typeselectform =  '<select name="type" size="1"';
17792:         if ($onchange) {
17793:             $typeselectform .= ' onchange="'.$onchange.'"';
17794:         }
17795:         $typeselectform .= '>'."\n";
17796:         foreach my $posstype ('Course','Community','Placement') {
17797:             my $shown;
17798:             if ($posstype eq 'Placement') {
17799:                 $shown = &mt('Placement Test');
17800:             } else {
17801:                 $shown = &mt($posstype);
17802:             }
17803:             $typeselectform.='<option value="'.$posstype.'"'.
17804:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17805:         }
17806:         $typeselectform.="</select>";
17807:     }
17808: 
17809:     my ($cloneableonlyform,$cloneabletitle);
17810:     if (exists($filter->{'cloneableonly'})) {
17811:         my $cloneableon = '';
17812:         my $cloneableoff = ' checked="checked"';
17813:         if ($filter->{'cloneableonly'}) {
17814:             $cloneableon = $cloneableoff;
17815:             $cloneableoff = '';
17816:         }
17817:         $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>';
17818:         if ($formname eq 'ccrs') {
17819:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17820:         } else {
17821:             $cloneabletitle = &mt('Cloneable by you');
17822:         }
17823:     }
17824:     my $officialjs;
17825:     if ($crstype eq 'Course') {
17826:         if (exists($filter->{'instcodefilter'})) {
17827: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17828: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17829:             if ($codedom) { 
17830:                 $officialjs = 1;
17831:                 ($instcodeform,$jscript,$$numtitlesref) =
17832:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17833:                                                                   $officialjs,$codetitlesref);
17834:                 if ($jscript) {
17835:                     $jscript = '<script type="text/javascript">'."\n".
17836:                                '// <![CDATA['."\n".
17837:                                $jscript."\n".
17838:                                '// ]]>'."\n".
17839:                                '</script>'."\n";
17840:                 }
17841:             }
17842:             if ($instcodeform eq '') {
17843:                 $instcodeform =
17844:                     '<input type="text" name="instcodefilter" size="10" value="'.
17845:                     $list->{'instcodefilter'}.'" />';
17846:                 $instcodetitle = $lt{'ins'};
17847:             } else {
17848:                 $instcodetitle = $lt{'inc'};
17849:             }
17850:             if ($fixeddom) {
17851:                 $instcodetitle .= '<br />('.$codedom.')';
17852:             }
17853:         }
17854:     }
17855:     my $output = qq|
17856: <form method="post" name="filterpicker" action="$action">
17857: <input type="hidden" name="form" value="$formname" />
17858: |;
17859:     if ($formname eq 'modifycourse') {
17860:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17861:                    '<input type="hidden" name="prevphase" value="'.
17862:                    $prevphase.'" />'."\n";
17863:     } elsif ($formname eq 'quotacheck') {
17864:         $output .= qq|
17865: <input type="hidden" name="sortby" value="" />
17866: <input type="hidden" name="sortorder" value="" />
17867: |;
17868:     } else {
17869:         my $name_input;
17870:         if ($cnameelement ne '') {
17871:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17872:                           $cnameelement.'" />';
17873:         }
17874:         $output .= qq|
17875: <input type="hidden" name="cnumelement" value="$cnumelement" />
17876: <input type="hidden" name="cdomelement" value="$cdomelement" />
17877: $name_input
17878: $roleelement
17879: $multelement
17880: $typeelement
17881: |;
17882:         if ($formname eq 'portform') {
17883:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17884:         }
17885:     }
17886:     if ($fixeddom) {
17887:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17888:     }
17889:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17890:     if ($sincefilterform) {
17891:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17892:                   .$sincefilterform
17893:                   .&Apache::lonhtmlcommon::row_closure();
17894:     }
17895:     if ($createdfilterform) {
17896:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17897:                   .$createdfilterform
17898:                   .&Apache::lonhtmlcommon::row_closure();
17899:     }
17900:     if ($domainselectform) {
17901:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17902:                   .$domainselectform
17903:                   .&Apache::lonhtmlcommon::row_closure();
17904:     }
17905:     if ($typeselectform) {
17906:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17907:             $output .= $typeselectform;
17908:         } else {
17909:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17910:                       .$typeselectform
17911:                       .&Apache::lonhtmlcommon::row_closure();
17912:         }
17913:     }
17914:     if ($instcodeform) {
17915:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17916:                   .$instcodeform
17917:                   .&Apache::lonhtmlcommon::row_closure();
17918:     }
17919:     if (exists($filter->{'ownerfilter'})) {
17920:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17921:                    '<table><tr><td>'.&mt('Username').'<br />'.
17922:                    '<input type="text" name="ownerfilter" size="20" value="'.
17923:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17924:                    $ownerdomselectform.'</td></tr></table>'.
17925:                    &Apache::lonhtmlcommon::row_closure();
17926:     }
17927:     if (exists($filter->{'personfilter'})) {
17928:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17929:                    '<table><tr><td>'.&mt('Username').'<br />'.
17930:                    '<input type="text" name="personfilter" size="20" value="'.
17931:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17932:                    $persondomselectform.'</td></tr></table>'.
17933:                    &Apache::lonhtmlcommon::row_closure();
17934:     }
17935:     if (exists($filter->{'coursefilter'})) {
17936:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17937:                   .'<input type="text" name="coursefilter" size="25" value="'
17938:                   .$list->{'coursefilter'}.'" />'
17939:                   .&Apache::lonhtmlcommon::row_closure();
17940:     }
17941:     if ($cloneableonlyform) {
17942:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17943:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17944:     }
17945:     if (exists($filter->{'descriptfilter'})) {
17946:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17947:                   .'<input type="text" name="descriptfilter" size="40" value="'
17948:                   .$list->{'descriptfilter'}.'" />'
17949:                   .&Apache::lonhtmlcommon::row_closure(1);
17950:     }
17951:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17952:                '<input type="hidden" name="updater" value="" />'."\n".
17953:                '<input type="submit" name="gosearch" value="'.
17954:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17955:     return $jscript.$clonewarning.$output;
17956: }
17957: 
17958: =pod 
17959: 
17960: =item * &timebased_select_form()
17961: 
17962: Create markup for a dropdown list used to select a time-based
17963: filter e.g., Course Activity, Course Created, when searching for courses
17964: or communities
17965: 
17966: Inputs:
17967: 
17968: item - name of form element (sincefilter or createdfilter)
17969: 
17970: filter - anonymous hash of criteria and their values
17971: 
17972: Returns: HTML for a select box contained a blank, then six time selections,
17973:          with value set in incoming form variables currently selected. 
17974: 
17975: Side Effects: None
17976: 
17977: =cut
17978: 
17979: sub timebased_select_form {
17980:     my ($item,$filter) = @_;
17981:     if (ref($filter) eq 'HASH') {
17982:         $filter->{$item} =~ s/[^\d-]//g;
17983:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17984:         return &select_form(
17985:                             $filter->{$item},
17986:                             $item,
17987:                             {      '-1' => '',
17988:                                 '86400' => &mt('today'),
17989:                                '604800' => &mt('last week'),
17990:                               '2592000' => &mt('last month'),
17991:                               '7776000' => &mt('last three months'),
17992:                              '15552000' => &mt('last six months'),
17993:                              '31104000' => &mt('last year'),
17994:                     'select_form_order' =>
17995:                            ['-1','86400','604800','2592000','7776000',
17996:                             '15552000','31104000']});
17997:     }
17998: }
17999: 
18000: =pod
18001: 
18002: =item * &js_changer()
18003: 
18004: Create script tag containing Javascript used to submit course search form
18005: when course type or domain is changed, and also to hide 'Searching ...' on
18006: page load completion for page showing search result.
18007: 
18008: Inputs: None
18009: 
18010: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18011: 
18012: Side Effects: None
18013: 
18014: =cut
18015: 
18016: sub js_changer {
18017:     return <<ENDJS;
18018: <script type="text/javascript">
18019: // <![CDATA[
18020: function updateFilters(caller) {
18021:     if (typeof(caller) != "undefined") {
18022:         document.filterpicker.updater.value = caller.name;
18023:     }
18024:     document.filterpicker.submit();
18025: }
18026: 
18027: function hideSearching() {
18028:     if (document.getElementById('searching')) {
18029:         document.getElementById('searching').style.display = 'none';
18030:     }
18031:     return;
18032: }
18033: 
18034: // ]]>
18035: </script>
18036: 
18037: ENDJS
18038: }
18039: 
18040: =pod
18041: 
18042: =item * &search_courses()
18043: 
18044: Process selected filters form course search form and pass to lonnet::courseiddump
18045: to retrieve a hash for which keys are courseIDs which match the selected filters.
18046: 
18047: Inputs:
18048: 
18049: dom - domain being searched 
18050: 
18051: type - course type ('Course' or 'Community' or '.' if any).
18052: 
18053: filter - anonymous hash of criteria and their values
18054: 
18055: numtitles - for institutional codes - number of categories
18056: 
18057: cloneruname - optional username of new course owner
18058: 
18059: clonerudom - optional domain of new course owner
18060: 
18061: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18062:             (used when DC is using course creation form)
18063: 
18064: codetitles - reference to array of titles of components in institutional codes (official courses).
18065: 
18066: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18067:            (and so can clone automatically)
18068: 
18069: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18070: 
18071: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18072:               courses to clone 
18073: 
18074: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18075: 
18076: 
18077: Side Effects: None
18078: 
18079: =cut
18080: 
18081: 
18082: sub search_courses {
18083:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18084:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18085:     my (%courses,%showcourses,$cloner);
18086:     if (($filter->{'ownerfilter'} ne '') ||
18087:         ($filter->{'ownerdomfilter'} ne '')) {
18088:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18089:                                        $filter->{'ownerdomfilter'};
18090:     }
18091:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18092:         if (!$filter->{$item}) {
18093:             $filter->{$item}='.';
18094:         }
18095:     }
18096:     my $now = time;
18097:     my $timefilter =
18098:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18099:     my ($createdbefore,$createdafter);
18100:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18101:         $createdbefore = $now;
18102:         $createdafter = $now-$filter->{'createdfilter'};
18103:     }
18104:     my ($instcodefilter,$regexpok);
18105:     if ($numtitles) {
18106:         if ($env{'form.official'} eq 'on') {
18107:             $instcodefilter =
18108:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18109:             $regexpok = 1;
18110:         } elsif ($env{'form.official'} eq 'off') {
18111:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18112:             unless ($instcodefilter eq '') {
18113:                 $regexpok = -1;
18114:             }
18115:         }
18116:     } else {
18117:         $instcodefilter = $filter->{'instcodefilter'};
18118:     }
18119:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18120:     if ($type eq '') { $type = '.'; }
18121: 
18122:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18123:         $cloner = $cloneruname.':'.$clonerudom;
18124:     }
18125:     %courses = &Apache::lonnet::courseiddump($dom,
18126:                                              $filter->{'descriptfilter'},
18127:                                              $timefilter,
18128:                                              $instcodefilter,
18129:                                              $filter->{'combownerfilter'},
18130:                                              $filter->{'coursefilter'},
18131:                                              undef,undef,$type,$regexpok,undef,undef,
18132:                                              undef,undef,$cloner,$cc_clone,
18133:                                              $filter->{'cloneableonly'},
18134:                                              $createdbefore,$createdafter,undef,
18135:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18136:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18137:         my $ccrole;
18138:         if ($type eq 'Community') {
18139:             $ccrole = 'co';
18140:         } else {
18141:             $ccrole = 'cc';
18142:         }
18143:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18144:                                                      $filter->{'persondomfilter'},
18145:                                                      'userroles',undef,
18146:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18147:                                                      $dom);
18148:         foreach my $role (keys(%rolehash)) {
18149:             my ($cnum,$cdom,$courserole) = split(':',$role);
18150:             my $cid = $cdom.'_'.$cnum;
18151:             if (exists($courses{$cid})) {
18152:                 if (ref($courses{$cid}) eq 'HASH') {
18153:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18154:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18155:                             push(@{$courses{$cid}{roles}},$courserole);
18156:                         }
18157:                     } else {
18158:                         $courses{$cid}{roles} = [$courserole];
18159:                     }
18160:                     $showcourses{$cid} = $courses{$cid};
18161:                 }
18162:             }
18163:         }
18164:         %courses = %showcourses;
18165:     }
18166:     return %courses;
18167: }
18168: 
18169: =pod
18170: 
18171: =back
18172: 
18173: =head1 Routines for version requirements for current course.
18174: 
18175: =over 4
18176: 
18177: =item * &check_release_required()
18178: 
18179: Compares required LON-CAPA version with version on server, and
18180: if required version is newer looks for a server with the required version.
18181: 
18182: Looks first at servers in user's owen domain; if none suitable, looks at
18183: servers in course's domain are permitted to host sessions for user's domain.
18184: 
18185: Inputs:
18186: 
18187: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18188: 
18189: $courseid - Course ID of current course
18190: 
18191: $rolecode - User's current role in course (for switchserver query string).
18192: 
18193: $required - LON-CAPA version needed by course (format: Major.Minor).
18194: 
18195: 
18196: Returns:
18197: 
18198: $switchserver - query string tp append to /adm/switchserver call (if 
18199:                 current server's LON-CAPA version is too old. 
18200: 
18201: $warning - Message is displayed if no suitable server could be found.
18202: 
18203: =cut
18204: 
18205: sub check_release_required {
18206:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18207:     my ($switchserver,$warning);
18208:     if ($required ne '') {
18209:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18210:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18211:         if ($reqdmajor ne '' && $reqdminor ne '') {
18212:             my $otherserver;
18213:             if (($major eq '' && $minor eq '') ||
18214:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18215:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18216:                 my $switchlcrev =
18217:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18218:                                                            $userdomserver);
18219:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18220:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18221:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18222:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18223:                     if ($cdom ne $env{'user.domain'}) {
18224:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18225:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18226:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18227:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18228:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18229:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18230:                         my $canhost =
18231:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18232:                                                               $coursedomserver,
18233:                                                               $remoterev,
18234:                                                               $udomdefaults{'remotesessions'},
18235:                                                               $defdomdefaults{'hostedsessions'});
18236: 
18237:                         if ($canhost) {
18238:                             $otherserver = $coursedomserver;
18239:                         } else {
18240:                             $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.");
18241:                         }
18242:                     } else {
18243:                         $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).");
18244:                     }
18245:                 } else {
18246:                     $otherserver = $userdomserver;
18247:                 }
18248:             }
18249:             if ($otherserver ne '') {
18250:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18251:             }
18252:         }
18253:     }
18254:     return ($switchserver,$warning);
18255: }
18256: 
18257: =pod
18258: 
18259: =item * &check_release_result()
18260: 
18261: Inputs:
18262: 
18263: $switchwarning - Warning message if no suitable server found to host session.
18264: 
18265: $switchserver - query string to append to /adm/switchserver containing lonHostID
18266:                 and current role.
18267: 
18268: Returns: HTML to display with information about requirement to switch server.
18269:          Either displaying warning with link to Roles/Courses screen or
18270:          display link to switchserver.
18271: 
18272: =cut
18273: 
18274: sub check_release_result {
18275:     my ($switchwarning,$switchserver) = @_;
18276:     my $output = &start_page('Selected course unavailable on this server').
18277:                  '<p class="LC_warning">';
18278:     if ($switchwarning) {
18279:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18280:         if (&show_course()) {
18281:             $output .= &mt('Display courses');
18282:         } else {
18283:             $output .= &mt('Display roles');
18284:         }
18285:         $output .= '</a>';
18286:     } elsif ($switchserver) {
18287:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18288:                    '<br />'.
18289:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18290:                    &mt('Switch Server').
18291:                    '</a>';
18292:     }
18293:     $output .= '</p>'.&end_page();
18294:     return $output;
18295: }
18296: 
18297: =pod
18298: 
18299: =item * &needs_coursereinit()
18300: 
18301: Determine if course contents stored for user's session needs to be
18302: refreshed, because content has changed since "Big Hash" last tied.
18303: 
18304: Check for change is made if time last checked is more than 10 minutes ago
18305: (by default).
18306: 
18307: Inputs:
18308: 
18309: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18310: 
18311: $interval (optional) - Time which may elapse (in s) between last check for content
18312:                        change in current course. (default: 600 s).  
18313: 
18314: Returns: an array; first element is:
18315: 
18316: =over 4
18317: 
18318: 'switch' - if content updates mean user's session
18319:            needs to be switched to a server running a newer LON-CAPA version
18320:  
18321: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18322:            on current server hosting user's session                
18323: 
18324: ''       - if no action required.
18325: 
18326: =back
18327: 
18328: If first item element is 'switch':
18329: 
18330: second item is $switchwarning - Warning message if no suitable server found to host session. 
18331: 
18332: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18333:                               and current role. 
18334: 
18335: otherwise: no other elements returned.
18336: 
18337: =back
18338: 
18339: =cut
18340: 
18341: sub needs_coursereinit {
18342:     my ($loncaparev,$interval) = @_;
18343:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18344:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18345:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18346:     my $now = time;
18347:     if ($interval eq '') {
18348:         $interval = 600;
18349:     }
18350:     if (($now-$env{'request.course.timechecked'})>$interval) {
18351:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18352:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18353:         if ($blocked) {
18354:             return ();
18355:         }
18356:         my $update;
18357:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18358:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18359:         if ($lastmainchange > $env{'request.course.tied'}) {
18360:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18361:             if ($needswitch) {
18362:                 return ('switch',$switchwarning,$switchserver);
18363:             }
18364:             $update = 'main';
18365:         }
18366:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18367:             if ($update) {
18368:                 $update = 'both';
18369:             } else {
18370:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18371:                 if ($needswitch) {
18372:                     return ('switch',$switchwarning,$switchserver);
18373:                 } else {
18374:                     $update = 'supp';
18375:                 }
18376:             }
18377:             return ($update);
18378:         }
18379:     }
18380:     return ();
18381: }
18382: 
18383: sub switch_for_update {
18384:     my ($loncaparev,$cdom,$cnum) = @_;
18385:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18386:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18387:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18388:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18389:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18390:                                     $curr_reqd_hash{'internal.releaserequired'}});
18391:             my ($switchserver,$switchwarning) =
18392:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18393:                                         $curr_reqd_hash{'internal.releaserequired'});
18394:             if ($switchwarning ne '' || $switchserver ne '') {
18395:                 return ('switch',$switchwarning,$switchserver);
18396:             }
18397:         }
18398:     }
18399:     return ();
18400: }
18401: 
18402: sub update_content_constraints {
18403:     my ($cdom,$cnum,$chome,$cid) = @_;
18404:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18405:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18406:     my (%checkresponsetypes,%checkcrsrestypes);
18407:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18408:         my ($item,$name,$value) = split(/:/,$key);
18409:         if ($item eq 'resourcetag') {
18410:             if ($name eq 'responsetype') {
18411:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18412:             }
18413:         } elsif ($item eq 'course') {
18414:             if ($name eq 'courserestype') {
18415:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18416:             }
18417:         }
18418:     }
18419:     my $navmap = Apache::lonnavmaps::navmap->new();
18420:     if (defined($navmap)) {
18421:         my (%allresponses,%allcrsrestypes);
18422:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18423:             if ($res->is_tool()) {
18424:                 if ($allcrsrestypes{'exttool'}) {
18425:                     $allcrsrestypes{'exttool'} ++;
18426:                 } else {
18427:                     $allcrsrestypes{'exttool'} = 1;
18428:                 }
18429:                 next;
18430:             }
18431:             my %responses = $res->responseTypes();
18432:             foreach my $key (keys(%responses)) {
18433:                 next unless(exists($checkresponsetypes{$key}));
18434:                 $allresponses{$key} += $responses{$key};
18435:             }
18436:         }
18437:         foreach my $key (keys(%allresponses)) {
18438:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18439:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18440:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18441:             }
18442:         }
18443:         foreach my $key (keys(%allcrsrestypes)) {
18444:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18445:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18446:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18447:             }
18448:         }
18449:         undef($navmap);
18450:     }
18451:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18452:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18453:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18454:             ($reqdmajor,$reqdminor) = ($major,$minor);
18455:         }
18456:     }
18457:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18458:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18459:     }
18460:     return;
18461: }
18462: 
18463: sub allmaps_incourse {
18464:     my ($cdom,$cnum,$chome,$cid) = @_;
18465:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18466:         $cid = $env{'request.course.id'};
18467:         $cdom = $env{'course.'.$cid.'.domain'};
18468:         $cnum = $env{'course.'.$cid.'.num'};
18469:         $chome = $env{'course.'.$cid.'.home'};
18470:     }
18471:     my %allmaps = ();
18472:     my $lastchange =
18473:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18474:     if ($lastchange > $env{'request.course.tied'}) {
18475:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18476:         unless ($ferr) {
18477:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18478:         }
18479:     }
18480:     my $navmap = Apache::lonnavmaps::navmap->new();
18481:     if (defined($navmap)) {
18482:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18483:             $allmaps{$res->src()} = 1;
18484:         }
18485:     }
18486:     return \%allmaps;
18487: }
18488: 
18489: sub parse_supplemental_title {
18490:     my ($title) = @_;
18491: 
18492:     my ($foldertitle,$renametitle);
18493:     if ($title =~ /&amp;&amp;&amp;/) {
18494:         $title = &HTML::Entites::decode($title);
18495:     }
18496:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18497:         $renametitle=$4;
18498:         my ($time,$uname,$udom) = ($1,$2,$3);
18499:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18500:         my $name =  &plainname($uname,$udom);
18501:         $name = &HTML::Entities::encode($name,'"<>&\'');
18502:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18503:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
18504:             $name.': <br />'.$foldertitle;
18505:     }
18506:     if (wantarray) {
18507:         return ($title,$foldertitle,$renametitle);
18508:     }
18509:     return $title;
18510: }
18511: 
18512: sub get_supplemental {
18513:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18514:     my $hashid=$cnum.':'.$cdom;
18515:     my ($supplemental,$cached,$set_httprefs);
18516:     unless ($ignorecache) {
18517:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18518:     }
18519:     unless (defined($cached)) {
18520:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18521:         unless ($chome eq 'no_host') {
18522:             my @order = @LONCAPA::map::order;
18523:             my @resources = @LONCAPA::map::resources;
18524:             my @resparms = @LONCAPA::map::resparms;
18525:             my @zombies = @LONCAPA::map::zombies;
18526:             my ($errors,%ids,%hidden);
18527:             $errors =
18528:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18529:                                       $errors,$possdel,\%ids,\%hidden);
18530:             @LONCAPA::map::order = @order;
18531:             @LONCAPA::map::resources = @resources;
18532:             @LONCAPA::map::resparms = @resparms;
18533:             @LONCAPA::map::zombies = @zombies;
18534:             $set_httprefs = 1;
18535:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18536:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18537:             }
18538:             $supplemental = {
18539:                                ids => \%ids,
18540:                                hidden => \%hidden,
18541:                             };
18542:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18543:         }
18544:     }
18545:     return ($supplemental,$set_httprefs);
18546: }
18547: 
18548: sub recurse_supplemental {
18549:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18550:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18551:         my $mapnum;
18552:         if ($suppmap eq 'supplemental.sequence') {
18553:             $mapnum = 0;
18554:         } else {
18555:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18556:         }
18557:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18558:         if ($fatal) {
18559:             $errors ++;
18560:         } else {
18561:             my @order = @LONCAPA::map::order;
18562:             if (@order > 0) {
18563:                 my @resources = @LONCAPA::map::resources;
18564:                 my @resparms = @LONCAPA::map::resparms;
18565:                 foreach my $idx (@order) {
18566:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18567:                     if (($src ne '') && ($status eq 'res')) {
18568:                         my $id = $mapnum.':'.$idx;
18569:                         push(@{$suppids->{$src}},$id);
18570:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18571:                             $hiddensupp->{$id} = 1;
18572:                         }
18573:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18574:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18575:                                                             $hiddensupp,$hiddensupp->{$id});
18576:                         } else {
18577:                             my $allowed;
18578:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18579:                                 $allowed = 1;
18580:                             } elsif ($possdel) {
18581:                                 foreach my $item (@{$suppids->{$src}}) {
18582:                                     next if ($item eq $id);
18583:                                     unless ($hiddensupp->{$item}) {
18584:                                        $allowed = 1;
18585:                                        last;
18586:                                     }
18587:                                 }
18588:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18589:                                     &Apache::lonnet::delenv('httpref.'.$src);
18590:                                 }
18591:                             }
18592:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
18593:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18594:                             }
18595:                         }
18596:                     }
18597:                 }
18598:             }
18599:         }
18600:     }
18601:     return $errors;
18602: }
18603: 
18604: sub set_supp_httprefs {
18605:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
18606:     if (ref($supplemental) eq 'HASH') {
18607:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18608:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
18609:                 next if ($src =~ /\.sequence$/);
18610:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18611:                     my $allowed;
18612:                     if ($env{'request.role.adv'}) {
18613:                         $allowed = 1;
18614:                     } else {
18615:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18616:                             unless ($supplemental->{'hidden'}->{$id}) {
18617:                                 $allowed = 1;
18618:                                 last;
18619:                             }
18620:                         }
18621:                     }
18622:                     if (exists($env{'httpref.'.$src})) {
18623:                         if ($possdel) {
18624:                             unless ($allowed) {
18625:                                 &Apache::lonnet::delenv('httpref.'.$src);
18626:                             }
18627:                         }
18628:                     } elsif ($allowed) {
18629:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18630:                     }
18631:                 }
18632:             }
18633:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18634:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18635:             }
18636:         }
18637:     }
18638: }
18639: 
18640: sub get_supp_parameter {
18641:     my ($resparm,$name)=@_;
18642:     return if ($resparm eq '');
18643:     my $value=undef;
18644:     my $ptype=undef;
18645:     foreach (split('&&&',$resparm)) {
18646:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
18647:         if ($thisname eq $name) {
18648:             $value=$thisvalue;
18649:             $ptype=$thistype;
18650:         }
18651:     }
18652:     return $value;
18653: }
18654: 
18655: sub symb_to_docspath {
18656:     my ($symb,$navmapref) = @_;
18657:     return unless ($symb && ref($navmapref));
18658:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18659:     if ($resurl=~/\.(sequence|page)$/) {
18660:         $mapurl=$resurl;
18661:     } elsif ($resurl eq 'adm/navmaps') {
18662:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18663:     }
18664:     my $mapresobj;
18665:     unless (ref($$navmapref)) {
18666:         $$navmapref = Apache::lonnavmaps::navmap->new();
18667:     }
18668:     if (ref($$navmapref)) {
18669:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18670:     }
18671:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18672:     my $type=$2;
18673:     my $path;
18674:     if (ref($mapresobj)) {
18675:         my $pcslist = $mapresobj->map_hierarchy();
18676:         if ($pcslist ne '') {
18677:             foreach my $pc (split(/,/,$pcslist)) {
18678:                 next if ($pc <= 1);
18679:                 my $res = $$navmapref->getByMapPc($pc);
18680:                 if (ref($res)) {
18681:                     my $thisurl = $res->src();
18682:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18683:                     my $thistitle = $res->title();
18684:                     $path .= '&'.
18685:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18686:                              &escape($thistitle).
18687:                              ':'.$res->randompick().
18688:                              ':'.$res->randomout().
18689:                              ':'.$res->encrypted().
18690:                              ':'.$res->randomorder().
18691:                              ':'.$res->is_page();
18692:                 }
18693:             }
18694:         }
18695:         $path =~ s/^\&//;
18696:         my $maptitle = $mapresobj->title();
18697:         if ($mapurl eq 'default') {
18698:             $maptitle = 'Main Content';
18699:         }
18700:         $path .= (($path ne '')? '&' : '').
18701:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18702:                  &escape($maptitle).
18703:                  ':'.$mapresobj->randompick().
18704:                  ':'.$mapresobj->randomout().
18705:                  ':'.$mapresobj->encrypted().
18706:                  ':'.$mapresobj->randomorder().
18707:                  ':'.$mapresobj->is_page();
18708:     } else {
18709:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18710:         my $ispage = (($type eq 'page')? 1 : '');
18711:         if ($mapurl eq 'default') {
18712:             $maptitle = 'Main Content';
18713:         }
18714:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18715:                 &escape($maptitle).':::::'.$ispage;
18716:     }
18717:     unless ($mapurl eq 'default') {
18718:         $path = 'default&'.
18719:                 &escape('Main Content').
18720:                 ':::::&'.$path;
18721:     }
18722:     return $path;
18723: }
18724: 
18725: sub validate_folderpath {
18726:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18727:     if ($env{'form.folderpath'} ne '') {
18728:         my @items = split(/\&/,$env{'form.folderpath'});
18729:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18730:         for (my $i=0; $i<@items; $i++) {
18731:             my $odd = $i%2;
18732:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18733:                 $badpath = 1;
18734:             } elsif ($odd && $supplementalflag) {
18735:                 my $idx = $i-1;
18736:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18737:                     my $esc_name = $1;
18738:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18739:                         $supppath .= '&'.$esc_name;
18740:                         $changed = 1;
18741:                     } else {
18742:                         $supppath .= '&'.$items[$i];
18743:                     }
18744:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18745:                     $changed = 1;
18746:                     my $is_hidden;
18747:                     unless ($got_supp) {
18748:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18749:                         if (ref($supplemental) eq 'HASH') {
18750:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
18751:                                 %supphidden = %{$supplemental->{'hidden'}};
18752:                             }
18753:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
18754:                                 %suppids = %{$supplemental->{'ids'}};
18755:                             }
18756:                         }
18757:                         $got_supp = 1;
18758:                     }
18759:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18760:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18761:                         if ($supphidden{$mapid}) {
18762:                             $is_hidden = 1;
18763:                         }
18764:                     }
18765:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18766:                 } else {
18767:                     $supppath .= '&'.$items[$i];
18768:                 }
18769:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18770:                 $badpath = 1;
18771:             } elsif ($supplementalflag) {
18772:                 $supppath .= '&'.$items[$i];
18773:             }
18774:             last if ($badpath);
18775:         }
18776:         if ($badpath) {
18777:             delete($env{'form.folderpath'});
18778:         } elsif ($changed && $supplementalflag) {
18779:             $supppath =~ s/^\&//;
18780:             $env{'form.folderpath'} = $supppath;
18781:         }
18782:     }
18783:     return;
18784: }
18785: 
18786: sub captcha_display {
18787:     my ($context,$lonhost,$defdom) = @_;
18788:     my ($output,$error);
18789:     my ($captcha,$pubkey,$privkey,$version) = 
18790:         &get_captcha_config($context,$lonhost,$defdom);
18791:     if ($captcha eq 'original') {
18792:         $output = &create_captcha();
18793:         unless ($output) {
18794:             $error = 'captcha';
18795:         }
18796:     } elsif ($captcha eq 'recaptcha') {
18797:         $output = &create_recaptcha($pubkey,$version);
18798:         unless ($output) {
18799:             $error = 'recaptcha';
18800:         }
18801:     }
18802:     return ($output,$error,$captcha,$version);
18803: }
18804: 
18805: sub captcha_response {
18806:     my ($context,$lonhost,$defdom) = @_;
18807:     my ($captcha_chk,$captcha_error);
18808:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18809:     if ($captcha eq 'original') {
18810:         ($captcha_chk,$captcha_error) = &check_captcha();
18811:     } elsif ($captcha eq 'recaptcha') {
18812:         $captcha_chk = &check_recaptcha($privkey,$version);
18813:     } else {
18814:         $captcha_chk = 1;
18815:     }
18816:     return ($captcha_chk,$captcha_error);
18817: }
18818: 
18819: sub get_captcha_config {
18820:     my ($context,$lonhost,$dom_in_effect) = @_;
18821:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18822:     my $hostname = &Apache::lonnet::hostname($lonhost);
18823:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18824:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18825:     if ($context eq 'usercreation') {
18826:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18827:         if (ref($domconfig{$context}) eq 'HASH') {
18828:             $hashtocheck = $domconfig{$context}{'cancreate'};
18829:             if (ref($hashtocheck) eq 'HASH') {
18830:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18831:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18832:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18833:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18834:                     }
18835:                     if ($privkey && $pubkey) {
18836:                         $captcha = 'recaptcha';
18837:                         $version = $hashtocheck->{'recaptchaversion'};
18838:                         if ($version ne '2') {
18839:                             $version = 1;
18840:                         }
18841:                     } else {
18842:                         $captcha = 'original';
18843:                     }
18844:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18845:                     $captcha = 'original';
18846:                 }
18847:             }
18848:         } else {
18849:             $captcha = 'captcha';
18850:         }
18851:     } elsif ($context eq 'login') {
18852:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18853:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18854:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18855:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18856:             if ($privkey && $pubkey) {
18857:                 $captcha = 'recaptcha';
18858:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18859:                 if ($version ne '2') {
18860:                     $version = 1; 
18861:                 }
18862:             } else {
18863:                 $captcha = 'original';
18864:             }
18865:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18866:             $captcha = 'original';
18867:         }
18868:     } elsif ($context eq 'passwords') {
18869:         if ($dom_in_effect) {
18870:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18871:             if ($passwdconf{'captcha'} eq 'recaptcha') {
18872:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18873:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18874:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
18875:                 }
18876:                 if ($privkey && $pubkey) {
18877:                     $captcha = 'recaptcha';
18878:                     $version = $passwdconf{'recaptchaversion'};
18879:                     if ($version ne '2') {
18880:                         $version = 1;
18881:                     }
18882:                 } else {
18883:                     $captcha = 'original';
18884:                 }
18885:             } elsif ($passwdconf{'captcha'} ne 'notused') {
18886:                 $captcha = 'original';
18887:             }
18888:         }
18889:     } 
18890:     return ($captcha,$pubkey,$privkey,$version);
18891: }
18892: 
18893: sub create_captcha {
18894:     my %captcha_params = &captcha_settings();
18895:     my ($output,$maxtries,$tries) = ('',10,0);
18896:     while ($tries < $maxtries) {
18897:         $tries ++;
18898:         my $captcha = Authen::Captcha->new (
18899:                                            output_folder => $captcha_params{'output_dir'},
18900:                                            data_folder   => $captcha_params{'db_dir'},
18901:                                           );
18902:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18903: 
18904:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18905:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18906:                       '<span class="LC_nobreak">'.
18907:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
18908:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
18909:                       '</span><br />'.
18910:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18911:             last;
18912:         }
18913:     }
18914:     if ($output eq '') {
18915:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18916:     }
18917:     return $output;
18918: }
18919: 
18920: sub captcha_settings {
18921:     my %captcha_params = (
18922:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18923:                            www_output_dir => "/captchaspool",
18924:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18925:                            numchars       => '5',
18926:                          );
18927:     return %captcha_params;
18928: }
18929: 
18930: sub check_captcha {
18931:     my ($captcha_chk,$captcha_error);
18932:     my $code = $env{'form.code'};
18933:     my $md5sum = $env{'form.crypt'};
18934:     my %captcha_params = &captcha_settings();
18935:     my $captcha = Authen::Captcha->new(
18936:                       output_folder => $captcha_params{'output_dir'},
18937:                       data_folder   => $captcha_params{'db_dir'},
18938:                   );
18939:     $captcha_chk = $captcha->check_code($code,$md5sum);
18940:     my %captcha_hash = (
18941:                         0       => 'Code not checked (file error)',
18942:                        -1      => 'Failed: code expired',
18943:                        -2      => 'Failed: invalid code (not in database)',
18944:                        -3      => 'Failed: invalid code (code does not match crypt)',
18945:     );
18946:     if ($captcha_chk != 1) {
18947:         $captcha_error = $captcha_hash{$captcha_chk}
18948:     }
18949:     return ($captcha_chk,$captcha_error);
18950: }
18951: 
18952: sub create_recaptcha {
18953:     my ($pubkey,$version) = @_;
18954:     if ($version >= 2) {
18955:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18956:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18957:     } else {
18958:         my $use_ssl;
18959:         if ($ENV{'SERVER_PORT'} == 443) {
18960:             $use_ssl = 1;
18961:         }
18962:         my $captcha = Captcha::reCAPTCHA->new;
18963:         return $captcha->get_options_setter({theme => 'white'})."\n".
18964:                $captcha->get_html($pubkey,undef,$use_ssl).
18965:                &mt('If the text is hard to read, [_1] will replace them.',
18966:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18967:                '<br /><br />';
18968:     }
18969: }
18970: 
18971: sub check_recaptcha {
18972:     my ($privkey,$version) = @_;
18973:     my $captcha_chk;
18974:     my $ip = &Apache::lonnet::get_requestor_ip();
18975:     if ($version >= 2) {
18976:         my %info = (
18977:                      secret   => $privkey, 
18978:                      response => $env{'form.g-recaptcha-response'},
18979:                      remoteip => $ip,
18980:                    );
18981:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
18982:         $request->content(join('&',map {
18983:                          my $name = escape($_);
18984:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
18985:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
18986:                          : &escape($info{$_}) );
18987:         } keys(%info)));
18988:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18989:         if ($response->is_success)  {
18990:             my $data = JSON::DWIW->from_json($response->decoded_content);
18991:             if (ref($data) eq 'HASH') {
18992:                 if ($data->{'success'}) {
18993:                     $captcha_chk = 1;
18994:                 }
18995:             }
18996:         }
18997:     } else {
18998:         my $captcha = Captcha::reCAPTCHA->new;
18999:         my $captcha_result =
19000:             $captcha->check_answer(
19001:                                     $privkey,
19002:                                     $ip,
19003:                                     $env{'form.recaptcha_challenge_field'},
19004:                                     $env{'form.recaptcha_response_field'},
19005:                                   );
19006:         if ($captcha_result->{is_valid}) {
19007:             $captcha_chk = 1;
19008:         }
19009:     }
19010:     return $captcha_chk;
19011: }
19012: 
19013: sub emailusername_info {
19014:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19015:     my %titles = &Apache::lonlocal::texthash (
19016:                      lastname      => 'Last Name',
19017:                      firstname     => 'First Name',
19018:                      institution   => 'School/college/university',
19019:                      location      => "School's city, state/province, country",
19020:                      web           => "School's web address",
19021:                      officialemail => 'E-mail address at institution (if different)',
19022:                      id            => 'Student/Employee ID',
19023:                  );
19024:     return (\@fields,\%titles);
19025: }
19026: 
19027: sub cleanup_html {
19028:     my ($incoming) = @_;
19029:     my $outgoing;
19030:     if ($incoming ne '') {
19031:         $outgoing = $incoming;
19032:         $outgoing =~ s/;/&#059;/g;
19033:         $outgoing =~ s/\#/&#035;/g;
19034:         $outgoing =~ s/\&/&#038;/g;
19035:         $outgoing =~ s/</&#060;/g;
19036:         $outgoing =~ s/>/&#062;/g;
19037:         $outgoing =~ s/\(/&#040/g;
19038:         $outgoing =~ s/\)/&#041;/g;
19039:         $outgoing =~ s/"/&#034;/g;
19040:         $outgoing =~ s/'/&#039;/g;
19041:         $outgoing =~ s/\$/&#036;/g;
19042:         $outgoing =~ s{/}{&#047;}g;
19043:         $outgoing =~ s/=/&#061;/g;
19044:         $outgoing =~ s/\\/&#092;/g
19045:     }
19046:     return $outgoing;
19047: }
19048: 
19049: # Checks for critical messages and returns a redirect url if one exists.
19050: # $interval indicates how often to check for messages.
19051: # $context is the calling context -- roles, grades, contents, menu or flip. 
19052: sub critical_redirect {
19053:     my ($interval,$context) = @_;
19054:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19055:         return ();
19056:     }
19057:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19058:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19059:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19060:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19061:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19062:             if ($blocked) {
19063:                 my $checkrole = "cm./$cdom/$cnum";
19064:                 if ($env{'request.course.sec'} ne '') {
19065:                     $checkrole .= "/$env{'request.course.sec'}";
19066:                 }
19067:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19068:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19069:                     return;
19070:                 }
19071:             }
19072:         }
19073:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19074:                                         $env{'user.name'});
19075:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19076:         my $redirecturl;
19077:         if ($what[0]) {
19078: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19079: 	        $redirecturl='/adm/email?critical=display';
19080: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19081:                 return (1, $url);
19082:             }
19083:         }
19084:     } 
19085:     return ();
19086: }
19087: 
19088: # Use:
19089: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19090: #
19091: ##################################################
19092: #          password associated functions         #
19093: ##################################################
19094: sub des_keys {
19095:     # Make a new key for DES encryption.
19096:     # Each key has two parts which are returned separately.
19097:     # Please note:  Each key must be passed through the &hex function
19098:     # before it is output to the web browser.  The hex versions cannot
19099:     # be used to decrypt.
19100:     my @hexstr=('0','1','2','3','4','5','6','7',
19101:                 '8','9','a','b','c','d','e','f');
19102:     my $lkey='';
19103:     for (0..7) {
19104:         $lkey.=$hexstr[rand(15)];
19105:     }
19106:     my $ukey='';
19107:     for (0..7) {
19108:         $ukey.=$hexstr[rand(15)];
19109:     }
19110:     return ($lkey,$ukey);
19111: }
19112: 
19113: sub des_decrypt {
19114:     my ($key,$cyphertext) = @_;
19115:     my $keybin=pack("H16",$key);
19116:     my $cypher;
19117:     if ($Crypt::DES::VERSION>=2.03) {
19118:         $cypher=new Crypt::DES $keybin;
19119:     } else {
19120:         $cypher=new DES $keybin;
19121:     }
19122:     my $plaintext='';
19123:     my $cypherlength = length($cyphertext);
19124:     my $numchunks = int($cypherlength/32);
19125:     for (my $j=0; $j<$numchunks; $j++) {
19126:         my $start = $j*32;
19127:         my $cypherblock = substr($cyphertext,$start,32);
19128:         my $chunk =
19129:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19130:         $chunk .=
19131:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19132:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19133:         $plaintext .= $chunk;
19134:     }
19135:     return $plaintext;
19136: }
19137: 
19138: sub get_requested_shorturls {
19139:     my ($cdom,$cnum,$navmap) = @_;
19140:     return unless (ref($navmap));
19141:     my ($numnew,$errors);
19142:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19143:     if (@toshorten) {
19144:         my (%maps,%resources,%titles);
19145:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19146:                                                                'shorturls',$cdom,$cnum);
19147:         if (keys(%resources)) {
19148:             my %tocreate;
19149:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19150:                 my $symb = $resources{$item};
19151:                 if ($symb) {
19152:                     $tocreate{$cnum.'&'.$symb} = 1;
19153:                 }
19154:             }
19155:             if (keys(%tocreate)) {
19156:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19157:                                                       \%tocreate);
19158:             }
19159:         }
19160:     }
19161:     return ($numnew,$errors);
19162: }
19163: 
19164: sub make_short_symbs {
19165:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19166:     my ($numnew,@errors);
19167:     if (ref($tocreateref) eq 'HASH') {
19168:         my %tocreate = %{$tocreateref};
19169:         if (keys(%tocreate)) {
19170:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19171:             my $su = Short::URL->new(no_vowels => 1);
19172:             my $init = '';
19173:             my (%newunique,%addcourse,%courseonly,%failed);
19174:             # get lock on tiny db
19175:             my $now = time;
19176:             if ($lockuser eq '') {
19177:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19178:             }
19179:             my $lockhash = {
19180:                                 "lock\0$now" => $lockuser,
19181:                             };
19182:             my $tries = 0;
19183:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19184:             my ($code,$error);
19185:             while (($gotlock ne 'ok') && ($tries<3)) {
19186:                 $tries ++;
19187:                 sleep 1;
19188:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19189:             }
19190:             if ($gotlock eq 'ok') {
19191:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19192:                                        \%addcourse,\%courseonly,\%failed);
19193:                 if (keys(%failed)) {
19194:                     my $numfailed = scalar(keys(%failed));
19195:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19196:                 }
19197:                 if (keys(%newunique)) {
19198:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19199:                     if ($putres eq 'ok') {
19200:                         $numnew = scalar(keys(%newunique));
19201:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19202:                         unless ($newputres eq 'ok') {
19203:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19204:                         }
19205:                     } else {
19206:                         push(@errors,&mt('error: could not store unique six character URLs'));
19207:                     }
19208:                 }
19209:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19210:                 unless ($dellockres eq 'ok') {
19211:                     push(@errors,&mt('error: could not release lockfile'));
19212:                 }
19213:             } else {
19214:                 push(@errors,&mt('error: could not obtain lockfile'));
19215:             }
19216:             if (keys(%courseonly)) {
19217:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19218:                 if ($result ne 'ok') {
19219:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19220:                 }
19221:             }
19222:         }
19223:     }
19224:     return ($numnew,\@errors);
19225: }
19226: 
19227: sub shorten_symbs {
19228:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19229:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19230:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19231:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19232:     my (%possibles,%collisions);
19233:     foreach my $key (keys(%{$tocreate})) {
19234:         my $num = String::CRC32::crc32($key);
19235:         my $tiny = $su->encode($num,$init);
19236:         if ($tiny) {
19237:             $possibles{$tiny} = $key;
19238:         }
19239:     }
19240:     if (!$init) {
19241:         $init = 1;
19242:     } else {
19243:         $init ++;
19244:     }
19245:     if (keys(%possibles)) {
19246:         my @posstiny = keys(%possibles);
19247:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19248:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19249:         if (keys(%currtiny)) {
19250:             foreach my $key (keys(%currtiny)) {
19251:                 next if ($currtiny{$key} eq '');
19252:                 if ($currtiny{$key} eq $possibles{$key}) {
19253:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19254:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19255:                         $courseonly->{$tsymb} = $key;
19256:                     }
19257:                 } else {
19258:                     $collisions{$possibles{$key}} = 1;
19259:                 }
19260:                 delete($possibles{$key});
19261:             }
19262:         }
19263:         foreach my $key (keys(%possibles)) {
19264:             $newunique->{$key} = $possibles{$key};
19265:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19266:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19267:                 $addcourse->{$tsymb} = $key;
19268:             }
19269:         }
19270:     }
19271:     if (keys(%collisions)) {
19272:         if ($init <5) {
19273:             if (!$init) {
19274:                 $init = 1;
19275:             } else {
19276:                 $init ++;
19277:             }
19278:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19279:                                    $newunique,$addcourse,$courseonly,$failed);
19280:         } else {
19281:             foreach my $key (keys(%collisions)) {
19282:                 $failed->{$key} = 1;
19283:             }
19284:         }
19285:     }
19286:     return $init;
19287: }
19288: 
19289: sub is_nonframeable {
19290:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19291:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19292:     return if (($remprotocol eq '') || ($remhost eq ''));
19293: 
19294:     $remprotocol = lc($remprotocol);
19295:     $remhost = lc($remhost);
19296:     my $remport = 80;
19297:     if ($remprotocol eq 'https') {
19298:         $remport = 443;
19299:     }
19300:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19301:     if ($cached) {
19302:         unless ($nocache) {
19303:             if ($result) {
19304:                 return 1;
19305:             } else {
19306:                 return 0;
19307:             }
19308:         }
19309:     }
19310:     my $uselink;
19311:     my $request = new HTTP::Request('HEAD',$url);
19312:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19313:     if ($response->is_success()) {
19314:         my $secpolicy = lc($response->header('content-security-policy'));
19315:         my $xframeop = lc($response->header('x-frame-options'));
19316:         $secpolicy =~ s/^\s+|\s+$//g;
19317:         $xframeop =~ s/^\s+|\s+$//g;
19318:         if (($secpolicy ne '') || ($xframeop ne '')) {
19319:             my $remotehost = $remprotocol.'://'.$remhost;
19320:             my ($origin,$protocol,$port);
19321:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19322:                 $port = $ENV{'SERVER_PORT'};
19323:             } else {
19324:                 $port = 80;
19325:             }
19326:             if ($absolute eq '') {
19327:                 $protocol = 'http:';
19328:                 if ($port == 443) {
19329:                     $protocol = 'https:';
19330:                 }
19331:                 $origin = $protocol.'//'.lc($hostname);
19332:             } else {
19333:                 $origin = lc($absolute);
19334:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19335:             }
19336:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19337:                 my $framepolicy = $1;
19338:                 $framepolicy =~ s/^\s+|\s+$//g;
19339:                 my @policies = split(/\s+/,$framepolicy);
19340:                 if (@policies) {
19341:                     if (grep(/^\Q'none'\E$/,@policies)) {
19342:                         $uselink = 1;
19343:                     } else {
19344:                         $uselink = 1;
19345:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19346:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19347:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19348:                             undef($uselink);
19349:                         }
19350:                         if ($uselink) {
19351:                             if (grep(/^\Q'self'\E$/,@policies)) {
19352:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19353:                                     undef($uselink);
19354:                                 }
19355:                             }
19356:                         }
19357:                         if ($uselink) {
19358:                             my @possok;
19359:                             if ($ip ne '') {
19360:                                 push(@possok,$ip);
19361:                             }
19362:                             my $hoststr = '';
19363:                             foreach my $part (reverse(split(/\./,$hostname))) {
19364:                                 if ($hoststr eq '') {
19365:                                     $hoststr = $part;
19366:                                 } else {
19367:                                     $hoststr = "$part.$hoststr";
19368:                                 }
19369:                                 if ($hoststr eq $hostname) {
19370:                                     push(@possok,$hostname);
19371:                                 } else {
19372:                                     push(@possok,"*.$hoststr");
19373:                                 }
19374:                             }
19375:                             if (@possok) {
19376:                                 foreach my $poss (@possok) {
19377:                                     last if (!$uselink);
19378:                                     foreach my $policy (@policies) {
19379:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19380:                                             undef($uselink);
19381:                                             last;
19382:                                         }
19383:                                     }
19384:                                 }
19385:                             }
19386:                         }
19387:                     }
19388:                 }
19389:             } elsif ($xframeop ne '') {
19390:                 $uselink = 1;
19391:                 my @policies = split(/\s*,\s*/,$xframeop);
19392:                 if (@policies) {
19393:                     unless (grep(/^deny$/,@policies)) {
19394:                         if ($origin ne '') {
19395:                             if (grep(/^sameorigin$/,@policies)) {
19396:                                 if ($remotehost eq $origin) {
19397:                                     undef($uselink);
19398:                                 }
19399:                             }
19400:                             if ($uselink) {
19401:                                 foreach my $policy (@policies) {
19402:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19403:                                         my $allowfrom = $1;
19404:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19405:                                             undef($uselink);
19406:                                             last;
19407:                                         }
19408:                                     }
19409:                                 }
19410:                             }
19411:                         }
19412:                     }
19413:                 }
19414:             }
19415:         }
19416:     }
19417:     if ($nocache) {
19418:         if ($cached) {
19419:             my $devalidate;
19420:             if ($uselink && !$result) {
19421:                 $devalidate = 1;
19422:             } elsif (!$uselink && $result) {
19423:                 $devalidate = 1;
19424:             }
19425:             if ($devalidate) {
19426:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19427:             }
19428:         }
19429:     } else {
19430:         if ($uselink) {
19431:             $result = 1;
19432:         } else {
19433:             $result = 0;
19434:         }
19435:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19436:     }
19437:     return $uselink;
19438: }
19439: 
19440: sub page_menu {
19441:     my ($menucolls,$menunum) = @_;
19442:     my %menu;
19443:     foreach my $item (split(/;/,$menucolls)) {
19444:         my ($num,$value) = split(/\%/,$item);
19445:         if ($num eq $menunum) {
19446:             my @entries = split(/\&/,$value);
19447:             foreach my $entry (@entries) {
19448:                 my ($name,$fields) = split(/=/,$entry);
19449:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19450:                     $menu{$name} = $fields;
19451:                 } else {
19452:                     my @shown;
19453:                     if ($fields =~ /,/) {
19454:                         @shown = split(/,/,$fields);
19455:                     } else {
19456:                         @shown = ($fields);
19457:                     }
19458:                     if (@shown) {
19459:                         foreach my $field (@shown) {
19460:                             next if ($field eq '');
19461:                             $menu{$field} = 1;
19462:                         }
19463:                     }
19464:                 }
19465:             }
19466:         }
19467:     }
19468:     return %menu;
19469: }
19470: 
19471: 1;
19472: __END__;
19473: 

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