File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1413: download - view: text, annotated - select for diffs
Thu Sep 28 15:56:48 2023 UTC (7 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6979 Work in progress.
  Reduce width of "View As" form in Functions menu by removing dropdown
  list for domain, and only displaying textbox for either username or ID
  (radio buttons to toggle between the two). Default domain is course's
  domain.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1413 2023/09/28 15:56:48 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::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::ltiutils;
   75: use LONCAPA::LWPReq;
   76: use LONCAPA::map();
   77: use HTTP::Request;
   78: use DateTime::TimeZone;
   79: use DateTime::Locale;
   80: use Encode();
   81: use Text::Aspell;
   82: use Authen::Captcha;
   83: use Captcha::reCAPTCHA;
   84: use JSON::DWIW;
   85: use Crypt::DES;
   86: use DynaLoader; # for Crypt::DES version
   87: use MIME::Lite;
   88: use MIME::Types;
   89: use File::Copy();
   90: use File::Path();
   91: use String::CRC32();
   92: use Short::URL();
   93: 
   94: # ---------------------------------------------- Designs
   95: use vars qw(%defaultdesign);
   96: 
   97: my $readit;
   98: 
   99: 
  100: ##
  101: ## Global Variables
  102: ##
  103: 
  104: 
  105: # ----------------------------------------------- SSI with retries:
  106: #
  107: 
  108: =pod
  109: 
  110: =head1 Server Side include with retries:
  111: 
  112: =over 4
  113: 
  114: =item * &ssi_with_retries(resource,retries form)
  115: 
  116: Performs an ssi with some number of retries.  Retries continue either
  117: until the result is ok or until the retry count supplied by the
  118: caller is exhausted.  
  119: 
  120: Inputs:
  121: 
  122: =over 4
  123: 
  124: resource   - Identifies the resource to insert.
  125: 
  126: retries    - Count of the number of retries allowed.
  127: 
  128: form       - Hash that identifies the rendering options.
  129: 
  130: =back
  131: 
  132: Returns:
  133: 
  134: =over 4
  135: 
  136: content    - The content of the response.  If retries were exhausted this is empty.
  137: 
  138: response   - The response from the last attempt (which may or may not have been successful.
  139: 
  140: =back
  141: 
  142: =back
  143: 
  144: =cut
  145: 
  146: sub ssi_with_retries {
  147:     my ($resource, $retries, %form) = @_;
  148: 
  149: 
  150:     my $ok = 0;			# True if we got a good response.
  151:     my $content;
  152:     my $response;
  153: 
  154:     # Try to get the ssi done. within the retries count:
  155: 
  156:     do {
  157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  158: 	$ok      = $response->is_success;
  159:         if (!$ok) {
  160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  161:         }
  162: 	$retries--;
  163:     } while (!$ok && ($retries > 0));
  164: 
  165:     if (!$ok) {
  166: 	$content = '';		# On error return an empty content.
  167:     }
  168:     return ($content, $response);
  169: 
  170: }
  171: 
  172: 
  173: 
  174: # ----------------------------------------------- Filetypes/Languages/Copyright
  175: my %language;
  176: my %supported_language;
  177: my %supported_codes;
  178: my %latex_language;		# For choosing hyphenation in <transl..>
  179: my %latex_language_bykey;	# for choosing hyphenation from metadata
  180: my %cprtag;
  181: my %scprtag;
  182: my %fe; my %fd; my %fm;
  183: my %category_extensions;
  184: 
  185: # ---------------------------------------------- Thesaurus variables
  186: #
  187: # %Keywords:
  188: #      A hash used by &keyword to determine if a word is considered a keyword.
  189: # $thesaurus_db_file 
  190: #      Scalar containing the full path to the thesaurus database.
  191: 
  192: my %Keywords;
  193: my $thesaurus_db_file;
  194: 
  195: #
  196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  197: # thesaurus.tab, and filecategories.tab.
  198: #
  199: BEGIN {
  200:     # Variable initialization
  201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  202:     #
  203:     unless ($readit) {
  204: # ------------------------------------------------------------------- languages
  205:     {
  206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  207:                                    '/language.tab';
  208:         if ( open(my $fh,'<',$langtabfile) ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  213:                 $language{$key}=$val.' - '.$enc;
  214:                 if ($sup) {
  215:                     $supported_language{$key}=$sup;
  216: 		    $supported_codes{$key}   = $code;
  217:                 }
  218: 		if ($latex) {
  219: 		    $latex_language_bykey{$key} = $latex;
  220: 		    $latex_language{$code} = $latex;
  221: 		}
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: # ------------------------------------------------------------------ copyrights
  227:     {
  228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  229:                                   '/copyright.tab';
  230:         if ( open (my $fh,'<',$copyrightfile) ) {
  231:             while (my $line = <$fh>) {
  232:                 next if ($line=~/^\#/);
  233:                 chomp($line);
  234:                 my ($key,$val)=(split(/\s+/,$line,2));
  235:                 $cprtag{$key}=$val;
  236:             }
  237:             close($fh);
  238:         }
  239:     }
  240: # ----------------------------------------------------------- source copyrights
  241:     {
  242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  243:                                   '/source_copyright.tab';
  244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  245:             while (my $line = <$fh>) {
  246:                 next if ($line =~ /^\#/);
  247:                 chomp($line);
  248:                 my ($key,$val)=(split(/\s+/,$line,2));
  249:                 $scprtag{$key}=$val;
  250:             }
  251:             close($fh);
  252:         }
  253:     }
  254: 
  255: # -------------------------------------------------------------- default domain designs
  256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  257:     my $designfile = $designdir.'/default.tab';
  258:     if ( open (my $fh,'<',$designfile) ) {
  259:         while (my $line = <$fh>) {
  260:             next if ($line =~ /^\#/);
  261:             chomp($line);
  262:             my ($key,$val)=(split(/\=/,$line));
  263:             if ($val) { $defaultdesign{$key}=$val; }
  264:         }
  265:         close($fh);
  266:     }
  267: 
  268: # ------------------------------------------------------------- file categories
  269:     {
  270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                                   '/filecategories.tab';
  272:         if ( open (my $fh,'<',$categoryfile) ) {
  273: 	    while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($extension,$category)=(split(/\s+/,$line,2));
  277:                 push(@{$category_extensions{lc($category)}},$extension);
  278:             }
  279:             close($fh);
  280:         }
  281: 
  282:     }
  283: # ------------------------------------------------------------------ file types
  284:     {
  285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  286:                '/filetypes.tab';
  287:         if ( open (my $fh,'<',$typesfile) ) {
  288:             while (my $line = <$fh>) {
  289: 		next if ($line =~ /^\#/);
  290: 		chomp($line);
  291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  292:                 if ($descr ne '') {
  293:                     $fe{$ending}=lc($emb);
  294:                     $fd{$ending}=$descr;
  295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  296:                 }
  297:             }
  298:             close($fh);
  299:         }
  300:     }
  301:     &Apache::lonnet::logthis(
  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
  303:     $readit=1;
  304:     }  # end of unless($readit) 
  305:     
  306: }
  307: 
  308: ###############################################################
  309: ##           HTML and Javascript Helper Functions            ##
  310: ###############################################################
  311: 
  312: =pod 
  313: 
  314: =head1 HTML and Javascript Functions
  315: 
  316: =over 4
  317: 
  318: =item * &browser_and_searcher_javascript()
  319: 
  320: X<browsing, javascript>X<searching, javascript>Returns a string
  321: containing javascript with two functions, C<openbrowser> and
  322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  323: tags.
  324: 
  325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  326: 
  327: inputs: formname, elementname, only, omit
  328: 
  329: formname and elementname indicate the name of the html form and name of
  330: the element that the results of the browsing selection are to be placed in. 
  331: 
  332: Specifying 'only' will restrict the browser to displaying only files
  333: with the given extension.  Can be a comma separated list.
  334: 
  335: Specifying 'omit' will restrict the browser to NOT displaying files
  336: with the given extension.  Can be a comma separated list.
  337: 
  338: =item * &opensearcher(formname,elementname) [javascript]
  339: 
  340: Inputs: formname, elementname
  341: 
  342: formname and elementname specify the name of the html form and the name
  343: of the element the selection from the search results will be placed in.
  344: 
  345: =cut
  346: 
  347: sub browser_and_searcher_javascript {
  348:     my ($mode)=@_;
  349:     if (!defined($mode)) { $mode='edit'; }
  350:     my $resurl=&escape_single(&lastresurl());
  351:     return <<END;
  352: // <!-- BEGIN LON-CAPA Internal
  353:     var editbrowser = null;
  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
  355:         var url = '$resurl/?';
  356:         if (editbrowser == null) {
  357:             url += 'launch=1&';
  358:         }
  359:         url += 'catalogmode=interactive&';
  360:         url += 'mode=$mode&';
  361:         url += 'inhibitmenu=yes&';
  362:         url += 'form=' + formname + '&';
  363:         if (only != null) {
  364:             url += 'only=' + only + '&';
  365:         } else {
  366:             url += 'only=&';
  367: 	}
  368:         if (omit != null) {
  369:             url += 'omit=' + omit + '&';
  370:         } else {
  371:             url += 'omit=&';
  372: 	}
  373:         if (titleelement != null) {
  374:             url += 'titleelement=' + titleelement + '&';
  375:         } else {
  376: 	    url += 'titleelement=&';
  377: 	}
  378:         url += 'element=' + elementname + '';
  379:         var title = 'Browser';
  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  381:         options += ',width=700,height=600';
  382:         editbrowser = open(url,title,options,'1');
  383:         editbrowser.focus();
  384:     }
  385:     var editsearcher;
  386:     function opensearcher(formname,elementname,titleelement) {
  387:         var url = '/adm/searchcat?';
  388:         if (editsearcher == null) {
  389:             url += 'launch=1&';
  390:         }
  391:         url += 'catalogmode=interactive&';
  392:         url += 'mode=$mode&';
  393:         url += 'form=' + formname + '&';
  394:         if (titleelement != null) {
  395:             url += 'titleelement=' + titleelement + '&';
  396:         } else {
  397: 	    url += 'titleelement=&';
  398: 	}
  399:         url += 'element=' + elementname + '';
  400:         var title = 'Search';
  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  402:         options += ',width=700,height=600';
  403:         editsearcher = open(url,title,options,'1');
  404:         editsearcher.focus();
  405:     }
  406: // END LON-CAPA Internal -->
  407: END
  408: }
  409: 
  410: sub lastresurl {
  411:     if ($env{'environment.lastresurl'}) {
  412: 	return $env{'environment.lastresurl'}
  413:     } else {
  414: 	return '/res';
  415:     }
  416: }
  417: 
  418: sub storeresurl {
  419:     my $resurl=&Apache::lonnet::clutter(shift);
  420:     unless ($resurl=~/^\/res/) { return 0; }
  421:     $resurl=~s/\/$//;
  422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  424:     return 1;
  425: }
  426: 
  427: sub studentbrowser_javascript {
  428:    unless (
  429:             (($env{'request.course.id'}) && 
  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  432: 					  '/'.$env{'request.course.sec'})
  433: 	      ))
  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
  435:           ) { return ''; }  
  436:    return (<<'ENDSTDBRW');
  437: <script type="text/javascript" language="Javascript">
  438: // <![CDATA[
  439:     var stdeditbrowser;
  440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
  441:         var url = '/adm/pickstudent?';
  442:         var filter;
  443: 	if (!ignorefilter) {
  444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  445: 	}
  446:         if (filter != null) {
  447:            if (filter != '') {
  448:                url += 'filter='+filter+'&';
  449: 	   }
  450:         }
  451:         url += 'form=' + formname + '&unameelement='+uname+
  452:                                     '&udomelement='+udom+
  453:                                     '&clicker='+clicker;
  454: 	if (roleflag) { url+="&roles=1"; }
  455:         if (courseadv == 'condition') {
  456:             if (document.getElementById('courseadv')) {
  457:                 courseadv = document.getElementById('courseadv').value;
  458:             }
  459:         }
  460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
  461:         if (uident !== '') { url+="&identelement="+uident; } 
  462:         var title = 'Student_Browser';
  463:         var options = 'scrollbars=1,resizable=1,menubar=0';
  464:         options += ',width=700,height=600';
  465:         stdeditbrowser = open(url,title,options,'1');
  466:         stdeditbrowser.focus();
  467:     }
  468: // ]]>
  469: </script>
  470: ENDSTDBRW
  471: }
  472: 
  473: sub resourcebrowser_javascript {
  474:    unless ($env{'request.course.id'}) { return ''; }
  475:    return (<<'ENDRESBRW');
  476: <script type="text/javascript" language="Javascript">
  477: // <![CDATA[
  478:     var reseditbrowser;
  479:     function openresbrowser(formname,reslink) {
  480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  481:         var title = 'Resource_Browser';
  482:         var options = 'scrollbars=1,resizable=1,menubar=0';
  483:         options += ',width=700,height=500';
  484:         reseditbrowser = open(url,title,options,'1');
  485:         reseditbrowser.focus();
  486:     }
  487: // ]]>
  488: </script>
  489: ENDRESBRW
  490: }
  491: 
  492: sub selectstudent_link {
  493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
  494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  497:    if ($env{'request.course.id'}) {  
  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  500: 					'/'.$env{'request.course.sec'})) {
  501: 	   return '';
  502:        }
  503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  504:        if ($courseadv eq 'only') {
  505:            $callargs .= ",'',1,'$courseadv'";
  506:        } elsif ($courseadv eq 'none') {
  507:            $callargs .= ",'','','$courseadv'";
  508:        } elsif ($courseadv eq 'condition') {
  509:            $callargs .= ",'','','$courseadv'";
  510:        } elsif ($identelem ne '') {
  511:            $callargs .= ",'','',''";
  512:        }
  513:        if ($identelem ne '') {
  514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
  515:        }
  516:        return '<span class="LC_nobreak">'.
  517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  518:               &mt('Select User').'</a></span>';
  519:    }
  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  521:        $callargs .= ",'',1"; 
  522:        return '<span class="LC_nobreak">'.
  523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  524:               &mt('Select User').'</a></span>';
  525:    }
  526:    return '';
  527: }
  528: 
  529: sub selectresource_link {
  530:    my ($form,$reslink,$arg)=@_;
  531:    
  532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  534:    unless ($env{'request.course.id'}) { return $arg; }
  535:    return '<span class="LC_nobreak">'.
  536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  537:               $arg.'</a></span>';
  538: }
  539: 
  540: 
  541: 
  542: sub authorbrowser_javascript {
  543:     return <<"ENDAUTHORBRW";
  544: <script type="text/javascript" language="JavaScript">
  545: // <![CDATA[
  546: var stdeditbrowser;
  547: 
  548: function openauthorbrowser(formname,udom) {
  549:     var url = '/adm/pickauthor?';
  550:     url += 'form='+formname+'&roledom='+udom;
  551:     var title = 'Author_Browser';
  552:     var options = 'scrollbars=1,resizable=1,menubar=0';
  553:     options += ',width=700,height=600';
  554:     stdeditbrowser = open(url,title,options,'1');
  555:     stdeditbrowser.focus();
  556: }
  557: 
  558: // ]]>
  559: </script>
  560: ENDAUTHORBRW
  561: }
  562: 
  563: sub coursebrowser_javascript {
  564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  565:         $credits_element,$instcode) = @_;
  566:     my $wintitle = 'Course_Browser';
  567:     if ($crstype eq 'Community') {
  568:         $wintitle = 'Community_Browser';
  569:     }
  570:     my $id_functions = &javascript_index_functions();
  571:     my $output = '
  572: <script type="text/javascript" language="JavaScript">
  573: // <![CDATA[
  574:     var stdeditbrowser;'."\n";
  575: 
  576:     $output .= <<"ENDSTDBRW";
  577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  578:         var url = '/adm/pickcourse?';
  579:         var formid = getFormIdByName(formname);
  580:         var domainfilter = getDomainFromSelectbox(formname,udom);
  581:         if (domainfilter != null) {
  582:            if (domainfilter != '') {
  583:                url += 'domainfilter='+domainfilter+'&';
  584: 	   }
  585:         }
  586:         url += 'form=' + formname + '&cnumelement='+uname+
  587: 	                            '&cdomelement='+udom+
  588:                                     '&cnameelement='+desc;
  589:         if (extra_element !=null && extra_element != '') {
  590:             if (formname == 'rolechoice' || formname == 'studentform') {
  591:                 url += '&roleelement='+extra_element;
  592:                 if (domainfilter == null || domainfilter == '') {
  593:                     url += '&domainfilter='+extra_element;
  594:                 }
  595:             }
  596:             else {
  597:                 if (formname == 'portform') {
  598:                     url += '&setroles='+extra_element;
  599:                 } else {
  600:                     if (formname == 'rules') {
  601:                         url += '&fixeddom='+extra_element; 
  602:                     }
  603:                 }
  604:             }     
  605:         }
  606:         if (type != null && type != '') {
  607:             url += '&type='+type;
  608:         }
  609:         if (type_elem != null && type_elem != '') {
  610:             url += '&typeelement='+type_elem;
  611:         }
  612:         if (formname == 'ccrs') {
  613:             var ownername = document.forms[formid].ccuname.value;
  614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  615:             url += '&cloner='+ownername+':'+ownerdom;
  616:             if (type == 'Course') {
  617:                 url += '&crscode='+document.forms[formid].crscode.value;
  618:             }
  619:         }
  620:         if (formname == 'requestcrs') {
  621:             url += '&crsdom=$domainfilter&crscode=$instcode';
  622:         }
  623:         if (multflag !=null && multflag != '') {
  624:             url += '&multiple='+multflag;
  625:         }
  626:         var title = '$wintitle';
  627:         var options = 'scrollbars=1,resizable=1,menubar=0';
  628:         options += ',width=700,height=600';
  629:         stdeditbrowser = open(url,title,options,'1');
  630:         stdeditbrowser.focus();
  631:     }
  632: $id_functions
  633: ENDSTDBRW
  634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  636:                                       $credits_element);
  637:     }
  638:     $output .= '
  639: // ]]>
  640: </script>';
  641:     return $output;
  642: }
  643: 
  644: sub javascript_index_functions {
  645:     return <<"ENDJS";
  646: 
  647: function getFormIdByName(formname) {
  648:     for (var i=0;i<document.forms.length;i++) {
  649:         if (document.forms[i].name == formname) {
  650:             return i;
  651:         }
  652:     }
  653:     return -1;
  654: }
  655: 
  656: function getIndexByName(formid,item) {
  657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  658:         if (document.forms[formid].elements[i].name == item) {
  659:             return i;
  660:         }
  661:     }
  662:     return -1;
  663: }
  664: 
  665: function getDomainFromSelectbox(formname,udom) {
  666:     var userdom;
  667:     var formid = getFormIdByName(formname);
  668:     if (formid > -1) {
  669:         var domid = getIndexByName(formid,udom);
  670:         if (domid > -1) {
  671:             if (document.forms[formid].elements[domid].type == 'select-one') {
  672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  673:             }
  674:             if (document.forms[formid].elements[domid].type == 'hidden') {
  675:                 userdom=document.forms[formid].elements[domid].value;
  676:             }
  677:         }
  678:     }
  679:     return userdom;
  680: }
  681: 
  682: ENDJS
  683: 
  684: }
  685: 
  686: sub javascript_array_indexof {
  687:     return <<ENDJS;
  688: <script type="text/javascript" language="JavaScript">
  689: // <![CDATA[
  690: 
  691: if (!Array.prototype.indexOf) {
  692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  693:         "use strict";
  694:         if (this === void 0 || this === null) {
  695:             throw new TypeError();
  696:         }
  697:         var t = Object(this);
  698:         var len = t.length >>> 0;
  699:         if (len === 0) {
  700:             return -1;
  701:         }
  702:         var n = 0;
  703:         if (arguments.length > 0) {
  704:             n = Number(arguments[1]);
  705:             if (n !== n) { // shortcut for verifying if it is NaN
  706:                 n = 0;
  707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  709:             }
  710:         }
  711:         if (n >= len) {
  712:             return -1;
  713:         }
  714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  715:         for (; k < len; k++) {
  716:             if (k in t && t[k] === searchElement) {
  717:                 return k;
  718:             }
  719:         }
  720:         return -1;
  721:     }
  722: }
  723: 
  724: // ]]>
  725: </script>
  726: 
  727: ENDJS
  728: 
  729: }
  730: 
  731: sub userbrowser_javascript {
  732:     my $id_functions = &javascript_index_functions();
  733:     return <<"ENDUSERBRW";
  734: 
  735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  736:     var url = '/adm/pickuser?';
  737:     var userdom = getDomainFromSelectbox(formname,udom);
  738:     if (userdom != null) {
  739:        if (userdom != '') {
  740:            url += 'srchdom='+userdom+'&';
  741:        }
  742:     }
  743:     url += 'form=' + formname + '&unameelement='+uname+
  744:                                 '&udomelement='+udom+
  745:                                 '&ulastelement='+ulast+
  746:                                 '&ufirstelement='+ufirst+
  747:                                 '&uemailelement='+uemail+
  748:                                 '&hideudomelement='+hideudom+
  749:                                 '&coursedom='+crsdom;
  750:     if ((caller != null) && (caller != undefined)) {
  751:         url += '&caller='+caller;
  752:     }
  753:     var title = 'User_Browser';
  754:     var options = 'scrollbars=1,resizable=1,menubar=0';
  755:     options += ',width=700,height=600';
  756:     var stdeditbrowser = open(url,title,options,'1');
  757:     stdeditbrowser.focus();
  758: }
  759: 
  760: function fix_domain (formname,udom,origdom,uname) {
  761:     var formid = getFormIdByName(formname);
  762:     if (formid > -1) {
  763:         var unameid = getIndexByName(formid,uname);
  764:         var domid = getIndexByName(formid,udom);
  765:         var hidedomid = getIndexByName(formid,origdom);
  766:         if (hidedomid > -1) {
  767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  768:             var unameval = document.forms[formid].elements[unameid].value;
  769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  770:                 if (domid > -1) {
  771:                     var slct = document.forms[formid].elements[domid];
  772:                     if (slct.type == 'select-one') {
  773:                         var i;
  774:                         for (i=0;i<slct.length;i++) {
  775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  776:                         }
  777:                     }
  778:                     if (slct.type == 'hidden') {
  779:                         slct.value = fixeddom;
  780:                     }
  781:                 }
  782:             }
  783:         }
  784:     }
  785:     return;
  786: }
  787: 
  788: $id_functions
  789: ENDUSERBRW
  790: }
  791: 
  792: sub setsec_javascript {
  793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  795:         $communityrolestr);
  796:     if ($role_element ne '') {
  797:         my @allroles = ('st','ta','ep','in','ad');
  798:         foreach my $crstype ('Course','Community') {
  799:             if ($crstype eq 'Community') {
  800:                 foreach my $role (@allroles) {
  801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  802:                 }
  803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  804:             } else {
  805:                 foreach my $role (@allroles) {
  806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  807:                 }
  808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  809:             }
  810:         }
  811:         $rolestr = '"'.join('","',@allroles).'"';
  812:         $courserolestr = '"'.join('","',@courserolenames).'"';
  813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  814:     }
  815:     my $setsections = qq|
  816: function setSect(sectionlist) {
  817:     var sectionsArray = new Array();
  818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  819:         sectionsArray = sectionlist.split(",");
  820:     }
  821:     var numSections = sectionsArray.length;
  822:     document.$formname.$sec_element.length = 0;
  823:     if (numSections == 0) {
  824:         document.$formname.$sec_element.multiple=false;
  825:         document.$formname.$sec_element.size=1;
  826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  827:     } else {
  828:         if (numSections == 1) {
  829:             document.$formname.$sec_element.multiple=false;
  830:             document.$formname.$sec_element.size=1;
  831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  834:         } else {
  835:             for (var i=0; i<numSections; i++) {
  836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  837:             }
  838:             document.$formname.$sec_element.multiple=true
  839:             if (numSections < 3) {
  840:                 document.$formname.$sec_element.size=numSections;
  841:             } else {
  842:                 document.$formname.$sec_element.size=3;
  843:             }
  844:             document.$formname.$sec_element.options[0].selected = false
  845:         }
  846:     }
  847: }
  848: 
  849: function setRole(crstype) {
  850: |;
  851:     if ($role_element eq '') {
  852:         $setsections .= '    return;
  853: }
  854: ';
  855:     } else {
  856:         $setsections .= qq|
  857:     var elementLength = document.$formname.$role_element.length;
  858:     var allroles = Array($rolestr);
  859:     var courserolenames = Array($courserolestr);
  860:     var communityrolenames = Array($communityrolestr);
  861:     if (elementLength != undefined) {
  862:         if (document.$formname.$role_element.options[5].value == 'cc') {
  863:             if (crstype == 'Course') {
  864:                 return;
  865:             } else {
  866:                 allroles[5] = 'co';
  867:                 for (var i=0; i<6; i++) {
  868:                     document.$formname.$role_element.options[i].value = allroles[i];
  869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  870:                 }
  871:             }
  872:         } else {
  873:             if (crstype == 'Community') {
  874:                 return;
  875:             } else {
  876:                 allroles[5] = 'cc';
  877:                 for (var i=0; i<6; i++) {
  878:                     document.$formname.$role_element.options[i].value = allroles[i];
  879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  880:                 }
  881:             }
  882:         }
  883:     }
  884:     return;
  885: }
  886: |;
  887:     }
  888:     if ($credits_element) {
  889:         $setsections .= qq|
  890: function setCredits(defaultcredits) {
  891:     document.$formname.$credits_element.value = defaultcredits;
  892:     return;
  893: }
  894: |;
  895:     }
  896:     return $setsections;
  897: }
  898: 
  899: sub selectcourse_link {
  900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  901:        $typeelement) = @_;
  902:    my $type = $selecttype;
  903:    my $linktext = &mt('Select Course');
  904:    if ($selecttype eq 'Community') {
  905:        $linktext = &mt('Select Community');
  906:    } elsif ($selecttype eq 'Placement') {
  907:        $linktext = &mt('Select Placement Test'); 
  908:    } elsif ($selecttype eq 'Course/Community') {
  909:        $linktext = &mt('Select Course/Community');
  910:        $type = '';
  911:    } elsif ($selecttype eq 'Select') {
  912:        $linktext = &mt('Select');
  913:        $type = '';
  914:    }
  915:    return '<span class="LC_nobreak">'
  916:          ."<a href='"
  917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  920:          ."'>".$linktext.'</a>'
  921:          .'</span>';
  922: }
  923: 
  924: sub selectauthor_link {
  925:    my ($form,$udom)=@_;
  926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  927:           &mt('Select Author').'</a>';
  928: }
  929: 
  930: sub selectuser_link {
  931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  932:         $coursedom,$linktext,$caller) = @_;
  933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  935:            ');">'.$linktext.'</a>';
  936: }
  937: 
  938: sub check_uncheck_jscript {
  939:     my $jscript = <<"ENDSCRT";
  940: function checkAll(field) {
  941:     if (field.length > 0) {
  942:         for (i = 0; i < field.length; i++) {
  943:             if (!field[i].disabled) { 
  944:                 field[i].checked = true;
  945:             }
  946:         }
  947:     } else {
  948:         if (!field.disabled) { 
  949:             field.checked = true;
  950:         }
  951:     }
  952: }
  953:  
  954: function uncheckAll(field) {
  955:     if (field.length > 0) {
  956:         for (i = 0; i < field.length; i++) {
  957:             field[i].checked = false ;
  958:         }
  959:     } else {
  960:         field.checked = false ;
  961:     }
  962: }
  963: ENDSCRT
  964:     return $jscript;
  965: }
  966: 
  967: sub select_timezone {
  968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
  969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
  970:    if ($includeempty) {
  971:        $output .= '<option value=""';
  972:        if (($selected eq '') || ($selected eq 'local')) {
  973:            $output .= ' selected="selected" ';
  974:        }
  975:        $output .= '> </option>';
  976:    }
  977:    my @timezones = DateTime::TimeZone->all_names;
  978:    foreach my $tzone (@timezones) {
  979:        $output.= '<option value="'.$tzone.'"';
  980:        if ($tzone eq $selected) {
  981:            $output.=' selected="selected"';
  982:        }
  983:        $output.=">$tzone</option>\n";
  984:    }
  985:    $output.="</select>";
  986:    return $output;
  987: }
  988: 
  989: sub select_datelocale {
  990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  992:     if ($includeempty) {
  993:         $output .= '<option value=""';
  994:         if ($selected eq '') {
  995:             $output .= ' selected="selected" ';
  996:         }
  997:         $output .= '> </option>';
  998:     }
  999:     my @languages = &Apache::lonlocal::preferred_languages();
 1000:     my (@possibles,%locale_names);
 1001:     my @locales = DateTime::Locale->ids();
 1002:     foreach my $id (@locales) {
 1003:         if ($id ne '') {
 1004:             my ($en_terr,$native_terr);
 1005:             my $loc = DateTime::Locale->load($id);
 1006:             if (ref($loc)) {
 1007:                 $en_terr = $loc->name();
 1008:                 $native_terr = $loc->native_name();
 1009:                 if (grep(/^en$/,@languages) || !@languages) {
 1010:                     if ($en_terr ne '') {
 1011:                         $locale_names{$id} = '('.$en_terr.')';
 1012:                     } elsif ($native_terr ne '') {
 1013:                         $locale_names{$id} = $native_terr;
 1014:                     }
 1015:                 } else {
 1016:                     if ($native_terr ne '') {
 1017:                         $locale_names{$id} = $native_terr.' ';
 1018:                     } elsif ($en_terr ne '') {
 1019:                         $locale_names{$id} = '('.$en_terr.')';
 1020:                     }
 1021:                 }
 1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1023:                 push(@possibles,$id);
 1024:             } 
 1025:         }
 1026:     }
 1027:     foreach my $item (sort(@possibles)) {
 1028:         $output.= '<option value="'.$item.'"';
 1029:         if ($item eq $selected) {
 1030:             $output.=' selected="selected"';
 1031:         }
 1032:         $output.=">$item";
 1033:         if ($locale_names{$item} ne '') {
 1034:             $output.='  '.$locale_names{$item};
 1035:         }
 1036:         $output.="</option>\n";
 1037:     }
 1038:     $output.="</select>";
 1039:     return $output;
 1040: }
 1041: 
 1042: sub select_language {
 1043:     my ($name,$selected,$includeempty,$noedit) = @_;
 1044:     my %langchoices;
 1045:     if ($includeempty) {
 1046:         %langchoices = ('' => 'No language preference');
 1047:     }
 1048:     foreach my $id (&languageids()) {
 1049:         my $code = &supportedlanguagecode($id);
 1050:         if ($code) {
 1051:             $langchoices{$code} = &plainlanguagedescription($id);
 1052:         }
 1053:     }
 1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1056: }
 1057: 
 1058: =pod
 1059: 
 1060: 
 1061: =item * &list_languages()
 1062: 
 1063: Returns an array reference that is suitable for use in language prompters.
 1064: Each array element is itself a two element array.  The first element
 1065: is the language code.  The second element a descsriptiuon of the 
 1066: language itself.  This is suitable for use in e.g.
 1067: &Apache::edit::select_arg (once dereferenced that is).
 1068: 
 1069: =cut 
 1070: 
 1071: sub list_languages {
 1072:     my @lang_choices;
 1073: 
 1074:     foreach my $id (&languageids()) {
 1075: 	my $code = &supportedlanguagecode($id);
 1076: 	if ($code) {
 1077: 	    my $selector    = $supported_codes{$id};
 1078: 	    my $description = &plainlanguagedescription($id);
 1079: 	    push(@lang_choices, [$selector, $description]);
 1080: 	}
 1081:     }
 1082:     return \@lang_choices;
 1083: }
 1084: 
 1085: =pod
 1086: 
 1087: =item * &linked_select_forms(...)
 1088: 
 1089: linked_select_forms returns a string containing a <script></script> block
 1090: and html for two <select> menus.  The select menus will be linked in that
 1091: changing the value of the first menu will result in new values being placed
 1092: in the second menu.  The values in the select menu will appear in alphabetical
 1093: order unless a defined order is provided.
 1094: 
 1095: linked_select_forms takes the following ordered inputs:
 1096: 
 1097: =over 4
 1098: 
 1099: =item * $formname, the name of the <form> tag
 1100: 
 1101: =item * $middletext, the text which appears between the <select> tags
 1102: 
 1103: =item * $firstdefault, the default value for the first menu
 1104: 
 1105: =item * $firstselectname, the name of the first <select> tag
 1106: 
 1107: =item * $secondselectname, the name of the second <select> tag
 1108: 
 1109: =item * $hashref, a reference to a hash containing the data for the menus.
 1110: 
 1111: =item * $menuorder, the order of values in the first menu
 1112: 
 1113: =item * $onchangefirst, additional javascript call to execute for an onchange
 1114:         event for the first <select> tag
 1115: 
 1116: =item * $onchangesecond, additional javascript call to execute for an onchange
 1117:         event for the second <select> tag
 1118: 
 1119: =item * $suffix, to differentiate separate uses of select2data javascript
 1120:         objects in a page.
 1121: 
 1122: =back 
 1123: 
 1124: Below is an example of such a hash.  Only the 'text', 'default', and 
 1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1126: values for the first select menu.  The text that coincides with the 
 1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1128: and text for the second menu are given in the hash pointed to by 
 1129: $menu{$choice1}->{'select2'}.  
 1130: 
 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
 1132:                        default => "B3",
 1133:                        select2 => { 
 1134:                            B1 => "Choice B1",
 1135:                            B2 => "Choice B2",
 1136:                            B3 => "Choice B3",
 1137:                            B4 => "Choice B4"
 1138:                            },
 1139:                        order => ['B4','B3','B1','B2'],
 1140:                    },
 1141:                A2 => { text =>"Choice A2" ,
 1142:                        default => "C2",
 1143:                        select2 => { 
 1144:                            C1 => "Choice C1",
 1145:                            C2 => "Choice C2",
 1146:                            C3 => "Choice C3"
 1147:                            },
 1148:                        order => ['C2','C1','C3'],
 1149:                    },
 1150:                A3 => { text =>"Choice A3" ,
 1151:                        default => "D6",
 1152:                        select2 => { 
 1153:                            D1 => "Choice D1",
 1154:                            D2 => "Choice D2",
 1155:                            D3 => "Choice D3",
 1156:                            D4 => "Choice D4",
 1157:                            D5 => "Choice D5",
 1158:                            D6 => "Choice D6",
 1159:                            D7 => "Choice D7"
 1160:                            },
 1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1162:                    }
 1163:                );
 1164: 
 1165: =cut
 1166: 
 1167: sub linked_select_forms {
 1168:     my ($formname,
 1169:         $middletext,
 1170:         $firstdefault,
 1171:         $firstselectname,
 1172:         $secondselectname, 
 1173:         $hashref,
 1174:         $menuorder,
 1175:         $onchangefirst,
 1176:         $onchangesecond,
 1177:         $suffix
 1178:         ) = @_;
 1179:     my $second = "document.$formname.$secondselectname";
 1180:     my $first = "document.$formname.$firstselectname";
 1181:     # output the javascript to do the changing
 1182:     my $result = '';
 1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1184:     $result.="// <![CDATA[\n";
 1185:     $result.="var select2data${suffix} = new Object();\n";
 1186:     $" = '","';
 1187:     my $debug = '';
 1188:     foreach my $s1 (sort(keys(%$hashref))) {
 1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1191:             $hashref->{$s1}->{'default'}."');\n";
 1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1195:             @s2values = @{$hashref->{$s1}->{'order'}};
 1196:         }
 1197:         $result.="\"@s2values\");\n";
 1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1199:         my @s2texts;
 1200:         foreach my $value (@s2values) {
 1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1202:         }
 1203:         $result.="\"@s2texts\");\n";
 1204:     }
 1205:     $"=' ';
 1206:     $result.= <<"END";
 1207: 
 1208: function select1${suffix}_changed() {
 1209:     // Determine new choice
 1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1211:     // update select2
 1212:     var values     = select2data${suffix}[newvalue].values;
 1213:     var texts      = select2data${suffix}[newvalue].texts;
 1214:     var select2def = select2data${suffix}[newvalue].def;
 1215:     var i;
 1216:     // out with the old
 1217:     $second.options.length = 0;
 1218:     // in with the new
 1219:     for (i=0;i<values.length; i++) {
 1220:         $second.options[i] = new Option(values[i]);
 1221:         $second.options[i].value = values[i];
 1222:         $second.options[i].text = texts[i];
 1223:         if (values[i] == select2def) {
 1224:             $second.options[i].selected = true;
 1225:         }
 1226:     }
 1227: }
 1228: // ]]>
 1229: </script>
 1230: END
 1231:     # output the initial values for the selection lists
 1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1233:     my @order = sort(keys(%{$hashref}));
 1234:     if (ref($menuorder) eq 'ARRAY') {
 1235:         @order = @{$menuorder};
 1236:     }
 1237:     foreach my $value (@order) {
 1238:         $result.="    <option value=\"$value\" ";
 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1241:     }
 1242:     $result .= "</select>\n";
 1243:     my %select2;
 1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
 1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
 1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1247:         }
 1248:     }
 1249:     $result .= $middletext;
 1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1251:     if ($onchangesecond) {
 1252:         $result .= ' onchange="'.$onchangesecond.'"';
 1253:     }
 1254:     $result .= ">\n";
 1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1256:     
 1257:     my @secondorder = sort(keys(%select2));
 1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1260:     }
 1261:     foreach my $value (@secondorder) {
 1262:         $result.="    <option value=\"$value\" ";        
 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1264:         $result.=">".&mt($select2{$value})."</option>\n";
 1265:     }
 1266:     $result .= "</select>\n";
 1267:     #    return $debug;
 1268:     return $result;
 1269: }   #  end of sub linked_select_forms {
 1270: 
 1271: =pod
 1272: 
 1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
 1274: 
 1275: Returns a string corresponding to an HTML link to the given help
 1276: $topic, where $topic corresponds to the name of a .tex file in
 1277: /home/httpd/html/adm/help/tex, with underscores replaced by
 1278: spaces. 
 1279: 
 1280: $text will optionally be linked to the same topic, allowing you to
 1281: link text in addition to the graphic. If you do not want to link
 1282: text, but wish to specify one of the later parameters, pass an
 1283: empty string. 
 1284: 
 1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1286: the link will not open a new window. If false, the link will open
 1287: a new window using Javascript. (Default is false.) 
 1288: 
 1289: $width and $height are optional numerical parameters that will
 1290: override the width and height of the popped up window, which may
 1291: be useful for certain help topics with big pictures included.
 1292: 
 1293: $imgid is the id of the img tag used for the help icon. This may be
 1294: used in a javascript call to switch the image src.  See 
 1295: lonhtmlcommon::htmlareaselectactive() for an example.
 1296: 
 1297: $links_target will optionally be set to a target (_top, _parent or _self).
 1298: 
 1299: =cut
 1300: 
 1301: sub help_open_topic {
 1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
 1303:     $text = "" if (not defined $text);
 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
 1305:     $width = 500 if (not defined $width);
 1306:     $height = 400 if (not defined $height);
 1307:     my $filename = $topic;
 1308:     $filename =~ s/ /_/g;
 1309: 
 1310:     my $template = "";
 1311:     my $link;
 1312:     
 1313:     $topic=~s/\W/\_/g;
 1314: 
 1315:     if (!$stayOnPage) {
 1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1317:     } elsif ($stayOnPage eq 'popup') {
 1318:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1319:     } else {
 1320: 	$link = "/adm/help/${filename}.hlp";
 1321:     }
 1322: 
 1323:     # Add the text
 1324:     my $target = ' target="_top"';
 1325:     if ($links_target) {
 1326:         $target = ' target="'.$links_target.'"';
 1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1329:         $target = '';
 1330:     }
 1331:     if ($text ne "") {
 1332: 	$template.='<span class="LC_help_open_topic">'
 1333:                   .'<a'.$target.' href="'.$link.'">'
 1334:                   .$text.'</a>';
 1335:     }
 1336: 
 1337:     # (Always) Add the graphic
 1338:     my $title = &mt('Online Help');
 1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1340:     if ($imgid ne '') {
 1341:         $imgid = ' id="'.$imgid.'"';
 1342:     }
 1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
 1344:               .'<img src="'.$helpicon.'" border="0"'
 1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1347:               .' /></a>';
 1348:     if ($text ne "") {	
 1349:         $template.='</span>';
 1350:     }
 1351:     return $template;
 1352: 
 1353: }
 1354: 
 1355: # This is a quicky function for Latex cheatsheet editing, since it 
 1356: # appears in at least four places
 1357: sub helpLatexCheatsheet {
 1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1359:     my $out;
 1360:     my $addOther = '';
 1361:     if ($topic) {
 1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1363:     }
 1364:     $out = '<span>' # Start cheatsheet
 1365: 	  .$addOther
 1366:           .'<span>'
 1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1368: 	  .'</span> <span>'
 1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1370: 	  .'</span>';
 1371:     unless ($not_author) {
 1372:         $out .= '<span>'
 1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1374:                .'</span> <span>'
 1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1376: 	       .'</span>';
 1377:     }
 1378:     $out .= '</span>'; # End cheatsheet
 1379:     return $out;
 1380: }
 1381: 
 1382: sub general_help {
 1383:     my $helptopic='Student_Intro';
 1384:     if ($env{'request.role'}=~/^(ca|au)/) {
 1385: 	$helptopic='Authoring_Intro';
 1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1387: 	$helptopic='Course_Coordination_Intro';
 1388:     } elsif ($env{'request.role'}=~/^dc/) {
 1389:         $helptopic='Domain_Coordination_Intro';
 1390:     }
 1391:     return $helptopic;
 1392: }
 1393: 
 1394: sub update_help_link {
 1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1396:     my $origurl = $ENV{'REQUEST_URI'};
 1397:     $origurl=~s|^/~|/priv/|;
 1398:     my $timestamp = time;
 1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1400:         $$datum = &escape($$datum);
 1401:     }
 1402: 
 1403:     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";
 1404:     my $output .= <<"ENDOUTPUT";
 1405: <script type="text/javascript">
 1406: // <![CDATA[
 1407: banner_link = '$banner_link';
 1408: // ]]>
 1409: </script>
 1410: ENDOUTPUT
 1411:     return $output;
 1412: }
 1413: 
 1414: # now just updates the help link and generates a blue icon
 1415: sub help_open_menu {
 1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
 1417: 	= @_;    
 1418:     $stayOnPage = 1;
 1419:     my $output;
 1420:     if ($component_help) {
 1421: 	if (!$text) {
 1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1423: 				       $width,$height,'',$links_target);
 1424: 	} else {
 1425: 	    my $help_text;
 1426: 	    $help_text=&unescape($topic);
 1427: 	    $output='<table><tr><td>'.
 1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
 1430: 	}
 1431:     }
 1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1433:     return $output.$banner_link;
 1434: }
 1435: 
 1436: sub top_nav_help {
 1437:     my ($text,$linkattr) = @_;
 1438:     $text = &mt($text);
 1439:     my $stay_on_page = 1;
 1440: 
 1441:     my ($link,$banner_link);
 1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1444: 	                         : "javascript:helpMenu('open')";
 1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1446:     }
 1447:     my $title = &mt('Get help');
 1448:     if ($link) {
 1449:         return <<"END";
 1450: $banner_link
 1451: <a href="$link" title="$title" $linkattr>$text</a>
 1452: END
 1453:     } else {
 1454:         return '&nbsp;'.$text.'&nbsp;';
 1455:     }
 1456: }
 1457: 
 1458: sub help_menu_js {
 1459:     my ($httphost) = @_;
 1460:     my $stayOnPage = 1;
 1461:     my $width = 620;
 1462:     my $height = 600;
 1463:     my $helptopic=&general_help();
 1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1466:     my $start_page =
 1467:         &Apache::loncommon::start_page('Help Menu', undef,
 1468: 				       {'frameset'    => 1,
 1469: 					'js_ready'    => 1,
 1470:                                         'use_absolute' => $httphost,
 1471: 					'add_entries' => {
 1472: 					    'border' => '0', 
 1473: 					    'rows'   => "110,*",},});
 1474:     my $end_page =
 1475:         &Apache::loncommon::end_page({'frameset' => 1,
 1476: 				      'js_ready' => 1,});
 1477: 
 1478:     my $template .= <<"ENDTEMPLATE";
 1479: <script type="text/javascript">
 1480: // <![CDATA[
 1481: // <!-- BEGIN LON-CAPA Internal
 1482: var banner_link = '';
 1483: function helpMenu(target) {
 1484:     var caller = this;
 1485:     if (target == 'open') {
 1486:         var newWindow = null;
 1487:         try {
 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1489:         }
 1490:         catch(error) {
 1491:             writeHelp(caller);
 1492:             return;
 1493:         }
 1494:         if (newWindow) {
 1495:             caller = newWindow;
 1496:         }
 1497:     }
 1498:     writeHelp(caller);
 1499:     return;
 1500: }
 1501: function writeHelp(caller) {
 1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1504:     caller.document.close();
 1505:     caller.focus();
 1506: }
 1507: // END LON-CAPA Internal -->
 1508: // ]]>
 1509: </script>
 1510: ENDTEMPLATE
 1511:     return $template;
 1512: }
 1513: 
 1514: sub help_open_bug {
 1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1516:     unless ($env{'user.adv'}) { return ''; }
 1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1518:     $text = "" if (not defined $text);
 1519: 	$stayOnPage=1;
 1520:     $width = 600 if (not defined $width);
 1521:     $height = 600 if (not defined $height);
 1522: 
 1523:     $topic=~s/\W+/\+/g;
 1524:     my $link='';
 1525:     my $template='';
 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1528:     if (!$stayOnPage)
 1529:     {
 1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1531:     }
 1532:     else
 1533:     {
 1534: 	$link = $url;
 1535:     }
 1536: 
 1537:     my $target = '_top';
 1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
 1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
 1540:         $target = '_blank';
 1541:     }
 1542: 
 1543:     # Add the text
 1544:     if ($text ne "")
 1545:     {
 1546: 	$template .= 
 1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1549:     }
 1550: 
 1551:     # Add the graphic
 1552:     my $title = &mt('Report a Bug');
 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1554:     $template .= <<"ENDTEMPLATE";
 1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1556: ENDTEMPLATE
 1557:     if ($text ne '') { $template.='</td></tr></table>' };
 1558:     return $template;
 1559: 
 1560: }
 1561: 
 1562: sub help_open_faq {
 1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1564:     unless ($env{'user.adv'}) { return ''; }
 1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1566:     $text = "" if (not defined $text);
 1567: 	$stayOnPage=1;
 1568:     $width = 350 if (not defined $width);
 1569:     $height = 400 if (not defined $height);
 1570: 
 1571:     $topic=~s/\W+/\+/g;
 1572:     my $link='';
 1573:     my $template='';
 1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1575:     if (!$stayOnPage)
 1576:     {
 1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1578:     }
 1579:     else
 1580:     {
 1581: 	$link = $url;
 1582:     }
 1583: 
 1584:     # Add the text
 1585:     if ($text ne "")
 1586:     {
 1587: 	$template .= 
 1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1590:     }
 1591: 
 1592:     # Add the graphic
 1593:     my $title = &mt('View the FAQ');
 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1595:     $template .= <<"ENDTEMPLATE";
 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1597: ENDTEMPLATE
 1598:     if ($text ne '') { $template.='</td></tr></table>' };
 1599:     return $template;
 1600: 
 1601: }
 1602: 
 1603: ###############################################################
 1604: ###############################################################
 1605: 
 1606: =pod
 1607: 
 1608: =item * &change_content_javascript():
 1609: 
 1610: This and the next function allow you to create small sections of an
 1611: otherwise static HTML page that you can update on the fly with
 1612: Javascript, even in Netscape 4.
 1613: 
 1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1615: must be written to the HTML page once. It will prove the Javascript
 1616: function "change(name, content)". Calling the change function with the
 1617: name of the section 
 1618: you want to update, matching the name passed to C<changable_area>, and
 1619: the new content you want to put in there, will put the content into
 1620: that area.
 1621: 
 1622: B<Note>: Netscape 4 only reserves enough space for the changable area
 1623: to contain room for the original contents. You need to "make space"
 1624: for whatever changes you wish to make, and be B<sure> to check your
 1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1626: it's adequate for updating a one-line status display, but little more.
 1627: This script will set the space to 100% width, so you only need to
 1628: worry about height in Netscape 4.
 1629: 
 1630: Modern browsers are much less limiting, and if you can commit to the
 1631: user not using Netscape 4, this feature may be used freely with
 1632: pretty much any HTML.
 1633: 
 1634: =cut
 1635: 
 1636: sub change_content_javascript {
 1637:     # If we're on Netscape 4, we need to use Layer-based code
 1638:     if ($env{'browser.type'} eq 'netscape' &&
 1639: 	$env{'browser.version'} =~ /^4\./) {
 1640: 	return (<<NETSCAPE4);
 1641: 	function change(name, content) {
 1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1643: 	    doc.open();
 1644: 	    doc.write(content);
 1645: 	    doc.close();
 1646: 	}
 1647: NETSCAPE4
 1648:     } else {
 1649: 	# Otherwise, we need to use semi-standards-compliant code
 1650: 	# (technically, "innerHTML" isn't standard but the equivalent
 1651: 	# is really scary, and every useful browser supports it
 1652: 	return (<<DOMBASED);
 1653: 	function change(name, content) {
 1654: 	    element = document.getElementById(name);
 1655: 	    element.innerHTML = content;
 1656: 	}
 1657: DOMBASED
 1658:     }
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &changable_area($name,$origContent):
 1664: 
 1665: This provides a "changable area" that can be modified on the fly via
 1666: the Javascript code provided in C<change_content_javascript>. $name is
 1667: the name you will use to reference the area later; do not repeat the
 1668: same name on a given HTML page more then once. $origContent is what
 1669: the area will originally contain, which can be left blank.
 1670: 
 1671: =cut
 1672: 
 1673: sub changable_area {
 1674:     my ($name, $origContent) = @_;
 1675: 
 1676:     if ($env{'browser.type'} eq 'netscape' &&
 1677: 	$env{'browser.version'} =~ /^4\./) {
 1678: 	# If this is netscape 4, we need to use the Layer tag
 1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1680:     } else {
 1681: 	return "<span id='$name'>$origContent</span>";
 1682:     }
 1683: }
 1684: 
 1685: =pod
 1686: 
 1687: =item * &viewport_geometry_js 
 1688: 
 1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1690: 
 1691: =cut
 1692: 
 1693: 
 1694: sub viewport_geometry_js { 
 1695:     return <<"GEOMETRY";
 1696: var Geometry = {};
 1697: function init_geometry() {
 1698:     if (Geometry.init) { return };
 1699:     Geometry.init=1;
 1700:     if (window.innerHeight) {
 1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1705:     }
 1706:     else if (document.documentElement && document.documentElement.clientHeight) {
 1707:         Geometry.getViewportHeight =
 1708:             function() { return document.documentElement.clientHeight; };
 1709:         Geometry.getViewportWidth =
 1710:             function() { return document.documentElement.clientWidth; };
 1711: 
 1712:         Geometry.getHorizontalScroll =
 1713:             function() { return document.documentElement.scrollLeft; };
 1714:         Geometry.getVerticalScroll =
 1715:             function() { return document.documentElement.scrollTop; };
 1716:     }
 1717:     else if (document.body.clientHeight) {
 1718:         Geometry.getViewportHeight =
 1719:             function() { return document.body.clientHeight; };
 1720:         Geometry.getViewportWidth =
 1721:             function() { return document.body.clientWidth; };
 1722:         Geometry.getHorizontalScroll =
 1723:             function() { return document.body.scrollLeft; };
 1724:         Geometry.getVerticalScroll =
 1725:             function() { return document.body.scrollTop; };
 1726:     }
 1727: }
 1728: 
 1729: GEOMETRY
 1730: }
 1731: 
 1732: =pod
 1733: 
 1734: =item * &viewport_size_js()
 1735: 
 1736: 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. 
 1737: 
 1738: =cut
 1739: 
 1740: sub viewport_size_js {
 1741:     my $geometry = &viewport_geometry_js();
 1742:     return <<"DIMS";
 1743: 
 1744: $geometry
 1745: 
 1746: function getViewportDims(width,height) {
 1747:     init_geometry();
 1748:     width.value = Geometry.getViewportWidth();
 1749:     height.value = Geometry.getViewportHeight();
 1750:     return;
 1751: }
 1752: 
 1753: DIMS
 1754: }
 1755: 
 1756: =pod
 1757: 
 1758: =item * &resize_textarea_js()
 1759: 
 1760: emits the needed javascript to resize a textarea to be as big as possible
 1761: 
 1762: creates a function resize_textrea that takes two IDs first should be
 1763: the id of the element to resize, second should be the id of a div that
 1764: surrounds everything that comes after the textarea, this routine needs
 1765: to be attached to the <body> for the onload and onresize events.
 1766: 
 1767: =back
 1768: 
 1769: =cut
 1770: 
 1771: sub resize_textarea_js {
 1772:     my $geometry = &viewport_geometry_js();
 1773:     return <<"RESIZE";
 1774:     <script type="text/javascript">
 1775: // <![CDATA[
 1776: $geometry
 1777: 
 1778: function getX(element) {
 1779:     var x = 0;
 1780:     while (element) {
 1781: 	x += element.offsetLeft;
 1782: 	element = element.offsetParent;
 1783:     }
 1784:     return x;
 1785: }
 1786: function getY(element) {
 1787:     var y = 0;
 1788:     while (element) {
 1789: 	y += element.offsetTop;
 1790: 	element = element.offsetParent;
 1791:     }
 1792:     return y;
 1793: }
 1794: 
 1795: 
 1796: function resize_textarea(textarea_id,bottom_id) {
 1797:     init_geometry();
 1798:     var textarea        = document.getElementById(textarea_id);
 1799:     //alert(textarea);
 1800: 
 1801:     var textarea_top    = getY(textarea);
 1802:     var textarea_height = textarea.offsetHeight;
 1803:     var bottom          = document.getElementById(bottom_id);
 1804:     var bottom_top      = getY(bottom);
 1805:     var bottom_height   = bottom.offsetHeight;
 1806:     var window_height   = Geometry.getViewportHeight();
 1807:     var fudge           = 23;
 1808:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1809:     if (new_height < 300) {
 1810: 	new_height = 300;
 1811:     }
 1812:     textarea.style.height=new_height+'px';
 1813: }
 1814: // ]]>
 1815: </script>
 1816: RESIZE
 1817: 
 1818: }
 1819: 
 1820: sub colorfuleditor_js {
 1821:     my $browse_or_search;
 1822:     my $respath;
 1823:     my ($cnum,$cdom) = &crsauthor_url();
 1824:     if ($cnum) {
 1825:         $respath = "/res/$cdom/$cnum/";
 1826:         my %js_lt = &Apache::lonlocal::texthash(
 1827:             sunm => 'Sub-directory name',
 1828:             save => 'Save page to make this permanent',
 1829:         );
 1830:         &js_escape(\%js_lt);
 1831:         my $showfile_js = &show_crsfiles_js();
 1832:         $browse_or_search = <<"END";
 1833: 
 1834:     $showfile_js
 1835: 
 1836:     function toggleChooser(form,element,titleid,only,search) {
 1837:         var disp = 'none';
 1838:         if (document.getElementById('chooser_'+element)) {
 1839:             var curr = document.getElementById('chooser_'+element).style.display;
 1840:             if (curr == 'none') {
 1841:                 disp='inline';
 1842:                 if (form.elements['chooser_'+element].length) {
 1843:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1844:                         form.elements['chooser_'+element][i].checked = false;
 1845:                     }
 1846:                 }
 1847:                 toggleResImport(form,element);
 1848:             }
 1849:             document.getElementById('chooser_'+element).style.display = disp;
 1850:             var dirsel = '';
 1851:             var filesel = '';
 1852:             if (document.getElementById('chooser_'+element+'_crsres')) {
 1853:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
 1854:                 if (currcrsres == 'none') {
 1855:                     dirsel = 'coursepath_'+element;
 1856:                     var filesel = 'coursefile_'+element;
 1857:                     var include;
 1858:                     if (document.getElementById('crsres_include_'+element)) {
 1859:                         include = document.getElementById('crsres_include_'+element).value;
 1860:                     }
 1861:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
 1862:                 }
 1863:             }
 1864:             if (document.getElementById('chooser_'+element+'_upload')) {
 1865:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
 1866:                 if (currcrsupload == 'none') {
 1867:                     dirsel = 'crsauthorpath_'+element;
 1868:                     filesel = '';
 1869:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
 1870:                 }
 1871:             }
 1872:         }
 1873:     }
 1874: 
 1875:     function toggleCrsFile(form,element) {
 1876:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1877:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1878:             if (curr == 'none') {
 1879:                 if (document.getElementById('coursepath_'+element)) {
 1880:                     var numdirs;
 1881:                     if (document.getElementById('coursepath_'+element).length) {
 1882:                         numdirs = document.getElementById('coursepath_'+element).length;
 1883:                     }
 1884:                     if ((document.getElementById('hascrsres_'+element)) &&
 1885:                         (document.getElementById('nocrsres_'+element))) {
 1886:                         if (numdirs) {
 1887:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
 1888:                             document.getElementById('nocrsres_'+element).style.display='none';
 1889:                         } else {
 1890:                             document.getElementById('hascrsres_'+element).style.display='none';
 1891:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
 1892:                         }
 1893:                     }
 1894:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1895:                     if (numdirs > 1) {
 1896:                         var selelem = form.elements['coursefile_'+element];
 1897:                         var i, len = selelem.options.length -1;
 1898:                         if (len >=0) {
 1899:                             for (i = len; i >= 0; i--) {
 1900:                                 selelem.remove(i);
 1901:                             }
 1902:                             selelem.options[0] = new Option('','');
 1903:                         }
 1904:                     }
 1905:                 }
 1906:             }
 1907:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1908:         }
 1909:         if (document.getElementById('chooser_'+element+'_upload')) {
 1910:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1911:             if (document.getElementById('uploadcrsres_'+element)) {
 1912:                 document.getElementById('uploadcrsres_'+element).value = '';
 1913:             }
 1914:         }
 1915:         return;
 1916:     }
 1917: 
 1918:     function toggleCrsUpload(form,element) {
 1919:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1920:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1921:         }
 1922:         if (document.getElementById('chooser_'+element+'_upload')) {
 1923:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1924:             if (curr == 'none') {
 1925:                 form.elements['newsubdir_'+element][0].checked = true;
 1926:                 toggleNewsubdir(form,element);
 1927:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1928:                 if (document.getElementById('uploadcrsres_'+element)) {
 1929:                     document.getElementById('uploadcrsres_'+element).value = '';
 1930:                 }
 1931:             }
 1932:         }
 1933:         return;
 1934:     }
 1935: 
 1936:     function toggleResImport(form,element) {
 1937:         var choices = new Array('crsres','upload');
 1938:         for (var i=0; i<choices.length; i++) {
 1939:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1940:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1941:             }
 1942:         }
 1943:     }
 1944: 
 1945:     function toggleNewsubdir(form,element) {
 1946:         var newsub = form.elements['newsubdir_'+element];
 1947:         if (newsub) {
 1948:             if (newsub.length) {
 1949:                 for (var j=0; j<newsub.length; j++) {
 1950:                     if (newsub[j].checked) {
 1951:                         if (document.getElementById('newsubdirname_'+element)) {
 1952:                             if (newsub[j].value == '1') {
 1953:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1954:                                 if (document.getElementById('newsubdir_'+element)) {
 1955:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1956:                                 }
 1957:                             } else {
 1958:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1959:                                 document.getElementById('newsubdirname_'+element).value = "";
 1960:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1961:                             }
 1962:                         }
 1963:                         break; 
 1964:                     }
 1965:                 }
 1966:             }
 1967:         }
 1968:     }
 1969: 
 1970:     function updateCrsFile(form,element) {
 1971:         var directory = form.elements['coursepath_'+element];
 1972:         var filename = form.elements['coursefile_'+element];
 1973:         var path = directory.options[directory.selectedIndex].value;
 1974:         var file = filename.options[filename.selectedIndex].value;
 1975:         if (file != '') {
 1976:             form.elements[element].value = '$respath';
 1977:             if (path == '/') {
 1978:                 form.elements[element].value += file;
 1979:             } else {
 1980:                 form.elements[element].value += path+'/'+file;
 1981:             }
 1982:             unClean();
 1983:             if (document.getElementById('previewimg_'+element)) {
 1984:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1985:                 var newsrc = document.getElementById('previewimg_'+element).src; 
 1986:             }
 1987:             if (document.getElementById('showimg_'+element)) {
 1988:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1989:             }
 1990:         }
 1991:         toggleChooser(form,element);
 1992:         return;
 1993:     }
 1994: 
 1995:     function uploadDone(suffix,name) {
 1996:         if (name) {
 1997: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1998:             unClean();
 1999:             toggleChooser(document.forms["lonhomework"],suffix);
 2000:         }
 2001:     }
 2002: 
 2003: \$(document).ready(function(){
 2004: 
 2005:     \$(document).delegate('form :submit', 'click', function( event ) {
 2006:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 2007:             var buttonId = this.id;
 2008:             var suffix = buttonId.toString();
 2009:             suffix = suffix.replace(/^crsupload_/,'');
 2010:             event.preventDefault();
 2011:             document.lonhomework.target = 'crsupload_target_'+suffix;
 2012:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 2013:             \$(this.form).submit();
 2014:             document.lonhomework.target = '';
 2015:             if (document.getElementById('crsuploadto_'+suffix)) {
 2016:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 2017:             }
 2018:             return false;
 2019:         }
 2020:     });
 2021: });
 2022: END
 2023:     }
 2024:     return <<"COLORFULEDIT"
 2025: <script type="text/javascript">
 2026: // <![CDATA[>
 2027:     function fold_box(curDepth, lastresource){
 2028: 
 2029:     // we need a list because there can be several blocks you need to fold in one tag
 2030:         var block = document.getElementsByName('foldblock_'+curDepth);
 2031:     // but there is only one folding button per tag
 2032:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 2033: 
 2034:         if(block.item(0).style.display == 'none'){
 2035: 
 2036:             foldbutton.value = '@{[&mt("Hide")]}';
 2037:             for (i = 0; i < block.length; i++){
 2038:                 block.item(i).style.display = '';
 2039:             }
 2040:         }else{
 2041: 
 2042:             foldbutton.value = '@{[&mt("Show")]}';
 2043:             for (i = 0; i < block.length; i++){
 2044:                 // block.item(i).style.visibility = 'collapse';
 2045:                 block.item(i).style.display = 'none';
 2046:             }
 2047:         };
 2048:         saveState(lastresource);
 2049:     }
 2050: 
 2051:     function saveState (lastresource) {
 2052: 
 2053:         var tag_list = getTagList();
 2054:         if(tag_list != null){
 2055:             var timestamp = new Date().getTime();
 2056:             var key = lastresource;
 2057: 
 2058:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 2059:             // starting with timestamp
 2060:             var value = timestamp+';';
 2061: 
 2062:             // building the list of key-value pairs
 2063:             for(var i = 0; i < tag_list.length; i++){
 2064:                 value += tag_list[i]+',';
 2065:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 2066:             }
 2067: 
 2068:             // only iterate whole storage if nothing to override
 2069:             if(localStorage.getItem(key) == null){        
 2070: 
 2071:                 // prevent storage from growing large
 2072:                 if(localStorage.length > 50){
 2073:                     var regex_getTimestamp = /^(?:\d)+;/;
 2074:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 2075:                     var oldest_key;
 2076:                     
 2077:                     for(var i = 1; i < localStorage.length; i++){
 2078:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 2079:                             oldest_key = localStorage.key(i);
 2080:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 2081:                         }
 2082:                     }
 2083:                     localStorage.removeItem(oldest_key);
 2084:                 }
 2085:             }
 2086:             localStorage.setItem(key,value);
 2087:         }
 2088:     }
 2089: 
 2090:     // restore folding status of blocks (on page load)
 2091:     function restoreState (lastresource) {
 2092:         if(localStorage.getItem(lastresource) != null){
 2093:             var key = lastresource;
 2094:             var value = localStorage.getItem(key);
 2095:             var regex_delTimestamp = /^\d+;/;
 2096: 
 2097:             value.replace(regex_delTimestamp, '');
 2098: 
 2099:             var valueArr = value.split(';');
 2100:             var pairs;
 2101:             var elements;
 2102:             for (var i = 0; i < valueArr.length; i++){
 2103:                 pairs = valueArr[i].split(',');
 2104:                 elements = document.getElementsByName(pairs[0]);
 2105: 
 2106:                 for (var j = 0; j < elements.length; j++){  
 2107:                     elements[j].style.display = pairs[1];
 2108:                     if (pairs[1] == "none"){
 2109:                         var regex_id = /([_\\d]+)\$/;
 2110:                         regex_id.exec(pairs[0]);
 2111:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2112:                     }
 2113:                 }
 2114:             }
 2115:         }
 2116:     }
 2117: 
 2118:     function getTagList () {
 2119:         
 2120:         var stringToSearch = document.lonhomework.innerHTML;
 2121: 
 2122:         var ret = new Array();
 2123:         var regex_findBlock = /(foldblock_.*?)"/g;
 2124:         var tag_list = stringToSearch.match(regex_findBlock);
 2125: 
 2126:         if(tag_list != null){
 2127:             for(var i = 0; i < tag_list.length; i++){            
 2128:                 ret.push(tag_list[i].replace(/"/, ''));
 2129:             }
 2130:         }
 2131:         return ret;
 2132:     }
 2133: 
 2134:     function saveScrollPosition (resource) {
 2135:         var tag_list = getTagList();
 2136: 
 2137:         // we dont always want to jump to the first block
 2138:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2139:         if(\$(window).scrollTop() > 170){
 2140:             if(tag_list != null){
 2141:                 var result;
 2142:                 for(var i = 0; i < tag_list.length; i++){
 2143:                     if(isElementInViewport(tag_list[i])){
 2144:                         result += tag_list[i]+';';
 2145:                     }
 2146:                 }
 2147:                 sessionStorage.setItem('anchor_'+resource, result);
 2148:             }
 2149:         } else {
 2150:             // we dont need to save zero, just delete the item to leave everything tidy
 2151:             sessionStorage.removeItem('anchor_'+resource);
 2152:         }
 2153:     }
 2154: 
 2155:     function restoreScrollPosition(resource){
 2156: 
 2157:         var elem = sessionStorage.getItem('anchor_'+resource);
 2158:         if(elem != null){
 2159:             var tag_list = elem.split(';');
 2160:             var elem_list;
 2161: 
 2162:             for(var i = 0; i < tag_list.length; i++){
 2163:                 elem_list = document.getElementsByName(tag_list[i]);
 2164:                 
 2165:                 if(elem_list.length > 0){
 2166:                     elem = elem_list[0];
 2167:                     break;
 2168:                 }
 2169:             }
 2170:             elem.scrollIntoView();
 2171:         }
 2172:     }
 2173: 
 2174:     function isElementInViewport(el) {
 2175: 
 2176:         // change to last element instead of first
 2177:         var elem = document.getElementsByName(el);
 2178:         var rect = elem[0].getBoundingClientRect();
 2179: 
 2180:         return (
 2181:             rect.top >= 0 &&
 2182:             rect.left >= 0 &&
 2183:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2184:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2185:         );
 2186:     }
 2187:     
 2188:     function autosize(depth){
 2189:         var cmInst = window['cm'+depth];
 2190:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2191: 
 2192:         // is fixed size, switching to dynamic
 2193:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2194:             cmInst.setSize("","auto");
 2195:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2196:             sessionStorage.setItem("autosized_"+depth, "yes");
 2197: 
 2198:         // is dynamic size, switching to fixed
 2199:         } else {
 2200:             cmInst.setSize("","300px");
 2201:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2202:             sessionStorage.removeItem("autosized_"+depth);
 2203:         }
 2204:     }
 2205: 
 2206: $browse_or_search
 2207: 
 2208: // ]]>
 2209: </script>
 2210: COLORFULEDIT
 2211: }
 2212: 
 2213: sub xmleditor_js {
 2214:     return <<XMLEDIT
 2215: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2216: <script type="text/javascript">
 2217: // <![CDATA[>
 2218: 
 2219:     function saveScrollPosition (resource) {
 2220: 
 2221:         var scrollPos = \$(window).scrollTop();
 2222:         sessionStorage.setItem(resource,scrollPos);
 2223:     }
 2224: 
 2225:     function restoreScrollPosition(resource){
 2226: 
 2227:         var scrollPos = sessionStorage.getItem(resource);
 2228:         \$(window).scrollTop(scrollPos);
 2229:     }
 2230: 
 2231:     // unless internet explorer
 2232:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2233: 
 2234:         \$(document).ready(function() {
 2235:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2236:         });
 2237:     }
 2238: 
 2239:     // inserts text at cursor position into codemirror (xml editor only)
 2240:     function insertText(text){
 2241:         cm.focus();
 2242:         var curPos = cm.getCursor();
 2243:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2244:     }
 2245: // ]]>
 2246: </script>
 2247: XMLEDIT
 2248: }
 2249: 
 2250: sub insert_folding_button {
 2251:     my $curDepth = $Apache::lonxml::curdepth;
 2252:     my $lastresource = $env{'request.ambiguous'};
 2253: 
 2254:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2255:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2256: }
 2257: 
 2258: sub crsauthor_url {
 2259:     my ($url) = @_;
 2260:     if ($url eq '') {
 2261:         $url = $ENV{'REQUEST_URI'};
 2262:     }
 2263:     my ($cnum,$cdom);
 2264:     if ($env{'request.course.id'}) {
 2265:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2266:         if ($audom ne '' && $auname ne '') {
 2267:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2268:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2269:                 $cnum = $auname;
 2270:                 $cdom = $audom;
 2271:             }
 2272:         }
 2273:     }
 2274:     return ($cnum,$cdom);
 2275: }
 2276: 
 2277: sub import_crsauthor_form {
 2278:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2279:     return (0) unless ($env{'request.course.id'});
 2280:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2281:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2282:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2283:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2284:     my @ids=&Apache::lonnet::current_machine_ids();
 2285:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
 2286: 
 2287:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2288:         $is_home = 1;
 2289:     }
 2290:     $toppath = "/priv/$cdom/$cnum";
 2291:     my $nonemptydir = 1;
 2292:     my $js_only;
 2293:     if ($only) {
 2294:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
 2295:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
 2296:     }
 2297:     $exclude = &Apache::lonnet::priv_exclude();
 2298:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
 2299:     my $numdirs = scalar(keys(%files));
 2300:     my %lt = &Apache::lonlocal::texthash (
 2301:         fnam => 'Filename',
 2302:         dire => 'Directory',
 2303:         se   => 'Select',
 2304:     );
 2305:     $output = $lt{'dire'}.':&nbsp;'.
 2306:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
 2307:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
 2308:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
 2309:     if ($files{'/'}) {
 2310:         $output .= '<option value="/">/</option>'."\n";
 2311:     }
 2312:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2313:         next if ($key eq '/');
 2314:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
 2315:     }
 2316:     $output .= '</select><br />'."\n".
 2317:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
 2318:                '<option value="" selected="selected"></option>'."\n".
 2319:                '</select>'."\n".
 2320:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
 2321:     return ($numdirs,$output);
 2322: }
 2323: 
 2324: sub show_crsfiles_js {
 2325:     my $excluderef = &Apache::lonnet::priv_exclude();
 2326:     my $se = &js_escape(&mt('Select'));
 2327:     my $exclude;
 2328:     if (ref($excluderef) eq 'HASH') {
 2329:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
 2330:     }
 2331:     my $js = <<"END";
 2332: 
 2333: 
 2334:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
 2335:         var relpath = '';
 2336:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2337:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
 2338:             if (currdir == '') {
 2339:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2340:                     selelem = form.elements[filesel];
 2341:                     var j, numfiles = selelem.options.length -1;
 2342:                     if (numfiles >=0) {
 2343:                         for (j = numfiles; j >= 0; j--) {
 2344:                             selelem.remove(j);
 2345:                         }
 2346:                     }
 2347:                     if (selelem.options.length == 0) {
 2348:                         selelem.options[selelem.options.length] = new Option('','');
 2349:                         selelem.selectedIndex = 0;
 2350:                     }
 2351:                 }
 2352:                 return;
 2353:             } else {
 2354:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
 2355:             }
 2356:         }
 2357:         var http = new XMLHttpRequest();
 2358:         var url = "/adm/courseauthor";
 2359:         var crsrole = "$env{'request.role'}";
 2360:         var exclude = '';
 2361:         if (exc) {
 2362:             exclude = '$exclude';
 2363:         }
 2364:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
 2365:         http.open("POST", url, true);
 2366:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 2367:         http.onreadystatechange = function() {
 2368:             if (http.readyState == 4 && http.status == 200) {
 2369:                 var data = JSON.parse(http.responseText);
 2370:                 var selelem;
 2371:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
 2372:                     if (Array.isArray(data.dirs)) {
 2373:                         selelem = form.elements[dirsel];
 2374:                         var i, numdirs = selelem.options.length -1;
 2375:                         if (numdirs >=0) {
 2376:                             for (i = numdirs; i >= 0; i--) {
 2377:                                 selelem.remove(i);
 2378:                             }
 2379:                         }
 2380:                         var len = data.dirs.length;
 2381:                         if (len) {
 2382:                             selelem.options[selelem.options.length] = new Option('$se','');
 2383:                             var j;
 2384:                             for (j = 0; j < len; j++) {
 2385:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
 2386:                             }
 2387:                             selelem.selectedIndex = 0;
 2388:                         }
 2389:                         if (!setfile) {
 2390:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2391:                                 selelem = form.elements[filesel];
 2392:                                 var j, numfiles = selelem.options.length -1;
 2393:                                 if (numfiles >=0) {
 2394:                                     for (j = numfiles; j >= 0; j--) {
 2395:                                         selelem.remove(j);
 2396:                                     }
 2397:                                 }
 2398:                                 if (selelem.options.length == 0) {
 2399:                                     selelem.options[selelem.options.length] = new Option('','');
 2400:                                     selelem.selectedIndex = 0;
 2401:                                 }
 2402:                             }
 2403:                         }
 2404:                     }
 2405:                 }
 2406:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
 2407:                     selelem = form.elements[filesel];
 2408:                     var i, numfiles = selelem.options.length -1;
 2409:                     if (numfiles >=0) {
 2410:                         for (i = numfiles; i >= 0; i--) {
 2411:                             selelem.remove(i);
 2412:                         }
 2413:                     }
 2414:                     var x;
 2415:                     for (x in data.files) {
 2416:                         if (Array.isArray(data.files[x])) {
 2417:                             if (data.files[x].length > 1) {
 2418:                                 selelem.options[selelem.options.length] = new Option('$se','');
 2419:                             }
 2420:                             var len = data.files[x].length;
 2421:                             if (len) {
 2422:                                 var k;
 2423:                                 for (k = 0; k < len; k++) {
 2424:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
 2425:                                 }
 2426:                                 selelem.selectedIndex = 0;
 2427:                             }
 2428:                         }
 2429:                     }
 2430:                     if (selelem.options.length == 0) {
 2431:                         selelem.options[selelem.options.length] = new Option('','');
 2432:                         selelem.selectedIndex = 0;
 2433:                     }
 2434:                 }
 2435:             }
 2436:         }
 2437:         http.send(params);
 2438:     }
 2439: END
 2440: }
 2441: 
 2442: =pod
 2443: 
 2444: =head1 Excel and CSV file utility routines
 2445: 
 2446: =cut
 2447: 
 2448: ###############################################################
 2449: ###############################################################
 2450: 
 2451: =pod
 2452: 
 2453: =over 4
 2454: 
 2455: =item * &csv_translate($text) 
 2456: 
 2457: Translate $text to allow it to be output as a 'comma separated values' 
 2458: format.
 2459: 
 2460: =cut
 2461: 
 2462: ###############################################################
 2463: ###############################################################
 2464: sub csv_translate {
 2465:     my $text = shift;
 2466:     $text =~ s/\"/\"\"/g;
 2467:     $text =~ s/\n/ /g;
 2468:     return $text;
 2469: }
 2470: 
 2471: ###############################################################
 2472: ###############################################################
 2473: 
 2474: =pod
 2475: 
 2476: =item * &define_excel_formats()
 2477: 
 2478: Define some commonly used Excel cell formats.
 2479: 
 2480: Currently supported formats:
 2481: 
 2482: =over 4
 2483: 
 2484: =item header
 2485: 
 2486: =item bold
 2487: 
 2488: =item h1
 2489: 
 2490: =item h2
 2491: 
 2492: =item h3
 2493: 
 2494: =item h4
 2495: 
 2496: =item i
 2497: 
 2498: =item date
 2499: 
 2500: =back
 2501: 
 2502: Inputs: $workbook
 2503: 
 2504: Returns: $format, a hash reference.
 2505: 
 2506: 
 2507: =cut
 2508: 
 2509: ###############################################################
 2510: ###############################################################
 2511: sub define_excel_formats {
 2512:     my ($workbook) = @_;
 2513:     my $format;
 2514:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2515:                                                 bottom    => 1,
 2516:                                                 align     => 'center');
 2517:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2518:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2519:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2520:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2521:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2522:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2523:     $format->{'date'} = $workbook->add_format(num_format=>
 2524:                                             'mm/dd/yyyy hh:mm:ss');
 2525:     return $format;
 2526: }
 2527: 
 2528: ###############################################################
 2529: ###############################################################
 2530: 
 2531: =pod
 2532: 
 2533: =item * &create_workbook()
 2534: 
 2535: Create an Excel worksheet.  If it fails, output message on the
 2536: request object and return undefs.
 2537: 
 2538: Inputs: Apache request object
 2539: 
 2540: Returns (undef) on failure, 
 2541:     Excel worksheet object, scalar with filename, and formats 
 2542:     from &Apache::loncommon::define_excel_formats on success
 2543: 
 2544: =cut
 2545: 
 2546: ###############################################################
 2547: ###############################################################
 2548: sub create_workbook {
 2549:     my ($r) = @_;
 2550:         #
 2551:     # Create the excel spreadsheet
 2552:     my $filename = '/prtspool/'.
 2553:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2554:         time.'_'.rand(1000000000).'.xls';
 2555:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2556:     if (! defined($workbook)) {
 2557:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2558:         $r->print(
 2559:             '<p class="LC_error">'
 2560:            .&mt('Problems occurred in creating the new Excel file.')
 2561:            .' '.&mt('This error has been logged.')
 2562:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2563:            .'</p>'
 2564:         );
 2565:         return (undef);
 2566:     }
 2567:     #
 2568:     $workbook->set_tempdir(LONCAPA::tempdir());
 2569:     #
 2570:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2571:     return ($workbook,$filename,$format);
 2572: }
 2573: 
 2574: ###############################################################
 2575: ###############################################################
 2576: 
 2577: =pod
 2578: 
 2579: =item * &create_text_file()
 2580: 
 2581: Create a file to write to and eventually make available to the user.
 2582: If file creation fails, outputs an error message on the request object and 
 2583: return undefs.
 2584: 
 2585: Inputs: Apache request object, and file suffix
 2586: 
 2587: Returns (undef) on failure, 
 2588:     Filehandle and filename on success.
 2589: 
 2590: =cut
 2591: 
 2592: ###############################################################
 2593: ###############################################################
 2594: sub create_text_file {
 2595:     my ($r,$suffix) = @_;
 2596:     if (! defined($suffix)) { $suffix = 'txt'; };
 2597:     my $fh;
 2598:     my $filename = '/prtspool/'.
 2599:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2600:         time.'_'.rand(1000000000).'.'.$suffix;
 2601:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2602:     if (! defined($fh)) {
 2603:         $r->log_error("Couldn't open $filename for output $!");
 2604:         $r->print(
 2605:             '<p class="LC_error">'
 2606:            .&mt('Problems occurred in creating the output file.')
 2607:            .' '.&mt('This error has been logged.')
 2608:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2609:            .'</p>'
 2610:         );
 2611:     }
 2612:     return ($fh,$filename)
 2613: }
 2614: 
 2615: 
 2616: =pod 
 2617: 
 2618: =back
 2619: 
 2620: =cut
 2621: 
 2622: ###############################################################
 2623: ##        Home server <option> list generating code          ##
 2624: ###############################################################
 2625: 
 2626: # ------------------------------------------
 2627: 
 2628: sub domain_select {
 2629:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
 2630:     my @possdoms;
 2631:     if (ref($incdoms) eq 'ARRAY') {
 2632:         @possdoms = @{$incdoms};
 2633:     } else {
 2634:         @possdoms = &Apache::lonnet::all_domains();
 2635:     }
 2636: 
 2637:     my %domains=map { 
 2638: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2639:     } @possdoms;
 2640: 
 2641:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
 2642:         foreach my $dom (@{$excdoms}) {
 2643:             delete($domains{$dom});
 2644:         }
 2645:     }
 2646: 
 2647:     if ($multiple) {
 2648: 	$domains{''}=&mt('Any domain');
 2649: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2650: 	return &multiple_select_form($name,$value,4,\%domains);
 2651:     } else {
 2652: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2653: 	return &select_form($name,$value,\%domains);
 2654:     }
 2655: }
 2656: 
 2657: #-------------------------------------------
 2658: 
 2659: =pod
 2660: 
 2661: =head1 Routines for form select boxes
 2662: 
 2663: =over 4
 2664: 
 2665: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2666: 
 2667: Returns a string containing a <select> element int multiple mode
 2668: 
 2669: 
 2670: Args:
 2671:   $name - name of the <select> element
 2672:   $value - scalar or array ref of values that should already be selected
 2673:   $size - number of rows long the select element is
 2674:   $hash - the elements should be 'option' => 'shown text'
 2675:           (shown text should already have been &mt())
 2676:   $order - (optional) array ref of the order to show the elements in
 2677: 
 2678: =cut
 2679: 
 2680: #-------------------------------------------
 2681: sub multiple_select_form {
 2682:     my ($name,$value,$size,$hash,$order)=@_;
 2683:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2684:     my $output='';
 2685:     if (! defined($size)) {
 2686:         $size = 4;
 2687:         if (scalar(keys(%$hash))<4) {
 2688:             $size = scalar(keys(%$hash));
 2689:         }
 2690:     }
 2691:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2692:     my @order;
 2693:     if (ref($order) eq 'ARRAY')  {
 2694:         @order = @{$order};
 2695:     } else {
 2696:         @order = sort(keys(%$hash));
 2697:     }
 2698:     if (exists($$hash{'select_form_order'})) {
 2699:         @order = @{$$hash{'select_form_order'}};
 2700:     }
 2701:         
 2702:     foreach my $key (@order) {
 2703:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2704:         $output.='selected="selected" ' if ($selected{$key});
 2705:         $output.='>'.$hash->{$key}."</option>\n";
 2706:     }
 2707:     $output.="</select>\n";
 2708:     return $output;
 2709: }
 2710: 
 2711: #-------------------------------------------
 2712: 
 2713: =pod
 2714: 
 2715: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2716: 
 2717: Returns a string containing a <select name='$name' size='1'> form to 
 2718: allow a user to select options from a ref to a hash containing:
 2719: option_name => displayed text. An optional $onchange can include
 2720: a javascript onchange item, e.g., onchange="this.form.submit();".
 2721: An optional arg -- $readonly -- if true will cause the select form
 2722: to be disabled, e.g., for the case where an instructor has a section-
 2723: specific role, and is viewing/modifying parameters. 
 2724: 
 2725: See lonrights.pm for an example invocation and use.
 2726: 
 2727: =cut
 2728: 
 2729: #-------------------------------------------
 2730: sub select_form {
 2731:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2732:     return unless (ref($hashref) eq 'HASH');
 2733:     if ($onchange) {
 2734:         $onchange = ' onchange="'.$onchange.'"';
 2735:     }
 2736:     my $disabled;
 2737:     if ($readonly) {
 2738:         $disabled = ' disabled="disabled"';
 2739:     }
 2740:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2741:     my @keys;
 2742:     if (exists($hashref->{'select_form_order'})) {
 2743: 	@keys=@{$hashref->{'select_form_order'}};
 2744:     } else {
 2745: 	@keys=sort(keys(%{$hashref}));
 2746:     }
 2747:     foreach my $key (@keys) {
 2748:         $selectform.=
 2749: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2750:             ($key eq $def ? 'selected="selected" ' : '').
 2751:                 ">".$hashref->{$key}."</option>\n";
 2752:     }
 2753:     $selectform.="</select>";
 2754:     return $selectform;
 2755: }
 2756: 
 2757: # For display filters
 2758: 
 2759: sub display_filter {
 2760:     my ($context) = @_;
 2761:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2762:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2763:     my $phraseinput = 'hidden';
 2764:     my $includeinput = 'hidden';
 2765:     my ($checked,$includetypestext);
 2766:     if ($env{'form.displayfilter'} eq 'containing') {
 2767:         $phraseinput = 'text'; 
 2768:         if ($context eq 'parmslog') {
 2769:             $includeinput = 'checkbox';
 2770:             if ($env{'form.includetypes'}) {
 2771:                 $checked = ' checked="checked"';
 2772:             }
 2773:             $includetypestext = &mt('Include parameter types');
 2774:         }
 2775:     } else {
 2776:         $includetypestext = '&nbsp;';
 2777:     }
 2778:     my ($additional,$secondid,$thirdid);
 2779:     if ($context eq 'parmslog') {
 2780:         $additional = 
 2781:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2782:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2783:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2784:             '</label>';
 2785:         $secondid = 'includetypes';
 2786:         $thirdid = 'includetypestext';
 2787:     }
 2788:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2789:                                                     '$secondid','$thirdid')";
 2790:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2791: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
 2792: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2793: 	   '</label></span> <span class="LC_nobreak">'.
 2794:            &mt('Filter: [_1]',
 2795: 	   &select_form($env{'form.displayfilter'},
 2796: 			'displayfilter',
 2797: 			{'currentfolder' => 'Current folder/page',
 2798: 			 'containing' => 'Containing phrase',
 2799: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2800: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2801:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2802:                          '" />'.$additional;
 2803: }
 2804: 
 2805: sub display_filter_js {
 2806:     my $includetext = &mt('Include parameter types');
 2807:     return <<"ENDJS";
 2808:   
 2809: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2810:     var firstType = 'hidden';
 2811:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2812:         firstType = 'text';
 2813:     }
 2814:     firstObject = document.getElementById(firstid);
 2815:     if (typeof(firstObject) == 'object') {
 2816:         if (firstObject.type != firstType) {
 2817:             changeInputType(firstObject,firstType);
 2818:         }
 2819:     }
 2820:     if (context == 'parmslog') {
 2821:         var secondType = 'hidden';
 2822:         if (firstType == 'text') {
 2823:             secondType = 'checkbox';
 2824:         }
 2825:         secondObject = document.getElementById(secondid);  
 2826:         if (typeof(secondObject) == 'object') {
 2827:             if (secondObject.type != secondType) {
 2828:                 changeInputType(secondObject,secondType);
 2829:             }
 2830:         }
 2831:         var textItem = document.getElementById(thirdid);
 2832:         var currtext = textItem.innerHTML;
 2833:         var newtext;
 2834:         if (firstType == 'text') {
 2835:             newtext = '$includetext';
 2836:         } else {
 2837:             newtext = '&nbsp;';
 2838:         }
 2839:         if (currtext != newtext) {
 2840:             textItem.innerHTML = newtext;
 2841:         }
 2842:     }
 2843:     return;
 2844: }
 2845: 
 2846: function changeInputType(oldObject,newType) {
 2847:     var newObject = document.createElement('input');
 2848:     newObject.type = newType;
 2849:     if (oldObject.size) {
 2850:         newObject.size = oldObject.size;
 2851:     }
 2852:     if (oldObject.value) {
 2853:         newObject.value = oldObject.value;
 2854:     }
 2855:     if (oldObject.name) {
 2856:         newObject.name = oldObject.name;
 2857:     }
 2858:     if (oldObject.id) {
 2859:         newObject.id = oldObject.id;
 2860:     }
 2861:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2862:     return;
 2863: }
 2864: 
 2865: ENDJS
 2866: }
 2867: 
 2868: sub gradeleveldescription {
 2869:     my $gradelevel=shift;
 2870:     my %gradelevels=(0 => 'Not specified',
 2871: 		     1 => 'Grade 1',
 2872: 		     2 => 'Grade 2',
 2873: 		     3 => 'Grade 3',
 2874: 		     4 => 'Grade 4',
 2875: 		     5 => 'Grade 5',
 2876: 		     6 => 'Grade 6',
 2877: 		     7 => 'Grade 7',
 2878: 		     8 => 'Grade 8',
 2879: 		     9 => 'Grade 9',
 2880: 		     10 => 'Grade 10',
 2881: 		     11 => 'Grade 11',
 2882: 		     12 => 'Grade 12',
 2883: 		     13 => 'Grade 13',
 2884: 		     14 => '100 Level',
 2885: 		     15 => '200 Level',
 2886: 		     16 => '300 Level',
 2887: 		     17 => '400 Level',
 2888: 		     18 => 'Graduate Level');
 2889:     return &mt($gradelevels{$gradelevel});
 2890: }
 2891: 
 2892: sub select_level_form {
 2893:     my ($deflevel,$name)=@_;
 2894:     unless ($deflevel) { $deflevel=0; }
 2895:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2896:     for (my $i=0; $i<=18; $i++) {
 2897:         $selectform.="<option value=\"$i\" ".
 2898:             ($i==$deflevel ? 'selected="selected" ' : '').
 2899:                 ">".&gradeleveldescription($i)."</option>\n";
 2900:     }
 2901:     $selectform.="</select>";
 2902:     return $selectform;
 2903: }
 2904: 
 2905: #-------------------------------------------
 2906: 
 2907: =pod
 2908: 
 2909: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2910: 
 2911: Returns a string containing a <select name='$name' size='1'> form to 
 2912: allow a user to select the domain to preform an operation in.  
 2913: See loncreateuser.pm for an example invocation and use.
 2914: 
 2915: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2916: selected");
 2917: 
 2918: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2919: 
 2920: 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.
 2921: 
 2922: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2923: 
 2924: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2925: 
 2926: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2927: 
 2928: =cut
 2929: 
 2930: #-------------------------------------------
 2931: sub select_dom_form {
 2932:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2933:     if ($onchange) {
 2934:         $onchange = ' onchange="'.$onchange.'"';
 2935:     }
 2936:     if ($disabled) {
 2937:         $disabled = ' disabled="disabled"';
 2938:     }
 2939:     my (@domains,%exclude);
 2940:     if (ref($incdoms) eq 'ARRAY') {
 2941:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2942:     } else {
 2943:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2944:     }
 2945:     if ($includeempty) { @domains=('',@domains); }
 2946:     if (ref($excdoms) eq 'ARRAY') {
 2947:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2948:     }
 2949:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2950:     foreach my $dom (@domains) {
 2951:         next if ($exclude{$dom});
 2952:         $selectdomain.="<option value=\"$dom\" ".
 2953:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2954:         if ($showdomdesc) {
 2955:             if ($dom ne '') {
 2956:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2957:                 if ($domdesc ne '') {
 2958:                     $selectdomain .= ' ('.$domdesc.')';
 2959:                 }
 2960:             } 
 2961:         }
 2962:         $selectdomain .= "</option>\n";
 2963:     }
 2964:     $selectdomain.="</select>";
 2965:     return $selectdomain;
 2966: }
 2967: 
 2968: #-------------------------------------------
 2969: 
 2970: =pod
 2971: 
 2972: =item * &home_server_form_item($domain,$name,$defaultflag)
 2973: 
 2974: input: 4 arguments (two required, two optional) - 
 2975:     $domain - domain of new user
 2976:     $name - name of form element
 2977:     $default - Value of 'default' causes a default item to be first 
 2978:                             option, and selected by default. 
 2979:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2980:                             if 1 server found, or default, if 0 found.
 2981: output: returns 2 items: 
 2982: (a) form element which contains either:
 2983:    (i) <select name="$name">
 2984:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2985:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2986:        </select>
 2987:        form item if there are multiple library servers in $domain, or
 2988:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2989:        if there is only one library server in $domain.
 2990: 
 2991: (b) number of library servers found.
 2992: 
 2993: See loncreateuser.pm for example of use.
 2994: 
 2995: =cut
 2996: 
 2997: #-------------------------------------------
 2998: sub home_server_form_item {
 2999:     my ($domain,$name,$default,$hide) = @_;
 3000:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 3001:     my $result;
 3002:     my $numlib = keys(%servers);
 3003:     if ($numlib > 1) {
 3004:         $result .= '<select name="'.$name.'" />'."\n";
 3005:         if ($default) {
 3006:             $result .= '<option value="default" selected="selected">'.&mt('default').
 3007:                        '</option>'."\n";
 3008:         }
 3009:         foreach my $hostid (sort(keys(%servers))) {
 3010:             $result.= '<option value="'.$hostid.'">'.
 3011: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 3012:         }
 3013:         $result .= '</select>'."\n";
 3014:     } elsif ($numlib == 1) {
 3015:         my $hostid;
 3016:         foreach my $item (keys(%servers)) {
 3017:             $hostid = $item;
 3018:         }
 3019:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 3020:                    $hostid.'" />';
 3021:                    if (!$hide) {
 3022:                        $result .= $hostid.' '.$servers{$hostid};
 3023:                    }
 3024:                    $result .= "\n";
 3025:     } elsif ($default) {
 3026:         $result .= '<input type="hidden" name="'.$name.
 3027:                    '" value="default" />';
 3028:                    if (!$hide) {
 3029:                        $result .= &mt('default');
 3030:                    }
 3031:                    $result .= "\n";
 3032:     }
 3033:     return ($result,$numlib);
 3034: }
 3035: 
 3036: =pod
 3037: 
 3038: =back 
 3039: 
 3040: =cut
 3041: 
 3042: ###############################################################
 3043: ##                  Decoding User Agent                      ##
 3044: ###############################################################
 3045: 
 3046: =pod
 3047: 
 3048: =head1 Decoding the User Agent
 3049: 
 3050: =over 4
 3051: 
 3052: =item * &decode_user_agent()
 3053: 
 3054: Inputs: $r
 3055: 
 3056: Outputs:
 3057: 
 3058: =over 4
 3059: 
 3060: =item * $httpbrowser
 3061: 
 3062: =item * $clientbrowser
 3063: 
 3064: =item * $clientversion
 3065: 
 3066: =item * $clientmathml
 3067: 
 3068: =item * $clientunicode
 3069: 
 3070: =item * $clientos
 3071: 
 3072: =item * $clientmobile
 3073: 
 3074: =item * $clientinfo
 3075: 
 3076: =item * $clientosversion
 3077: 
 3078: =back
 3079: 
 3080: =back 
 3081: 
 3082: =cut
 3083: 
 3084: ###############################################################
 3085: ###############################################################
 3086: sub decode_user_agent {
 3087:     my ($r)=@_;
 3088:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 3089:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 3090:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 3091:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 3092:     my $clientbrowser='unknown';
 3093:     my $clientversion='0';
 3094:     my $clientmathml='';
 3095:     my $clientunicode='0';
 3096:     my $clientmobile=0;
 3097:     my $clientosversion='';
 3098:     for (my $i=0;$i<=$#browsertype;$i++) {
 3099:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 3100: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 3101: 	    $clientbrowser=$bname;
 3102:             $httpbrowser=~/$vreg/i;
 3103: 	    $clientversion=$1;
 3104:             $clientmathml=($clientversion>=$minv);
 3105:             $clientunicode=($clientversion>=$univ);
 3106: 	}
 3107:     }
 3108:     my $clientos='unknown';
 3109:     my $clientinfo;
 3110:     if (($httpbrowser=~/linux/i) ||
 3111:         ($httpbrowser=~/unix/i) ||
 3112:         ($httpbrowser=~/ux/i) ||
 3113:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 3114:     if (($httpbrowser=~/vax/i) ||
 3115:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 3116:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 3117:     if (($httpbrowser=~/mac/i) ||
 3118:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 3119:     if ($httpbrowser=~/win/i) {
 3120:         $clientos='win';
 3121:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 3122:             $clientosversion = $1;
 3123:         }
 3124:     }
 3125:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 3126:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 3127:         $clientmobile=lc($1);
 3128:     }
 3129:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 3130:         $clientinfo = 'firefox-'.$1;
 3131:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 3132:         $clientinfo = 'chromeframe-'.$1;
 3133:     }
 3134:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 3135:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 3136:             $clientosversion);
 3137: }
 3138: 
 3139: ###############################################################
 3140: ##    Authentication changing form generation subroutines    ##
 3141: ###############################################################
 3142: ##
 3143: ## All of the authform_xxxxxxx subroutines take their inputs in a
 3144: ## hash, and have reasonable default values.
 3145: ##
 3146: ##    formname = the name given in the <form> tag.
 3147: #-------------------------------------------
 3148: 
 3149: =pod
 3150: 
 3151: =head1 Authentication Routines
 3152: 
 3153: =over 4
 3154: 
 3155: =item * &authform_xxxxxx()
 3156: 
 3157: The authform_xxxxxx subroutines provide javascript and html forms which 
 3158: handle some of the conveniences required for authentication forms.  
 3159: This is not an optimal method, but it works.  
 3160: 
 3161: =over 4
 3162: 
 3163: =item * authform_header
 3164: 
 3165: =item * authform_authorwarning
 3166: 
 3167: =item * authform_nochange
 3168: 
 3169: =item * authform_kerberos
 3170: 
 3171: =item * authform_internal
 3172: 
 3173: =item * authform_filesystem
 3174: 
 3175: =item * authform_lti
 3176: 
 3177: =back
 3178: 
 3179: See loncreateuser.pm for invocation and use examples.
 3180: 
 3181: =cut
 3182: 
 3183: #-------------------------------------------
 3184: sub authform_header{  
 3185:     my %in = (
 3186:         formname => 'cu',
 3187:         kerb_def_dom => '',
 3188:         @_,
 3189:     );
 3190:     $in{'formname'} = 'document.' . $in{'formname'};
 3191:     my $result='';
 3192: 
 3193: #---------------------------------------------- Code for upper case translation
 3194:     my $Javascript_toUpperCase;
 3195:     unless ($in{kerb_def_dom}) {
 3196:         $Javascript_toUpperCase =<<"END";
 3197:         switch (choice) {
 3198:            case 'krb': currentform.elements[choicearg].value =
 3199:                currentform.elements[choicearg].value.toUpperCase();
 3200:                break;
 3201:            default:
 3202:         }
 3203: END
 3204:     } else {
 3205:         $Javascript_toUpperCase = "";
 3206:     }
 3207: 
 3208:     my $radioval = "'nochange'";
 3209:     if (defined($in{'curr_authtype'})) {
 3210:         if ($in{'curr_authtype'} ne '') {
 3211:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3212:         }
 3213:     }
 3214:     my $argfield = 'null';
 3215:     if (defined($in{'mode'})) {
 3216:         if ($in{'mode'} eq 'modifycourse')  {
 3217:             if (defined($in{'curr_autharg'})) {
 3218:                 if ($in{'curr_autharg'} ne '') {
 3219:                     $argfield = "'$in{'curr_autharg'}'";
 3220:                 }
 3221:             }
 3222:         }
 3223:     }
 3224: 
 3225:     $result.=<<"END";
 3226: var current = new Object();
 3227: current.radiovalue = $radioval;
 3228: current.argfield = $argfield;
 3229: 
 3230: function changed_radio(choice,currentform) {
 3231:     var choicearg = choice + 'arg';
 3232:     // If a radio button in changed, we need to change the argfield
 3233:     if (current.radiovalue != choice) {
 3234:         current.radiovalue = choice;
 3235:         if (current.argfield != null) {
 3236:             currentform.elements[current.argfield].value = '';
 3237:         }
 3238:         if (choice == 'nochange') {
 3239:             current.argfield = null;
 3240:         } else {
 3241:             current.argfield = choicearg;
 3242:             switch(choice) {
 3243:                 case 'krb': 
 3244:                     currentform.elements[current.argfield].value = 
 3245:                         "$in{'kerb_def_dom'}";
 3246:                 break;
 3247:               default:
 3248:                 break;
 3249:             }
 3250:         }
 3251:     }
 3252:     return;
 3253: }
 3254: 
 3255: function changed_text(choice,currentform) {
 3256:     var choicearg = choice + 'arg';
 3257:     if (currentform.elements[choicearg].value !='') {
 3258:         $Javascript_toUpperCase
 3259:         // clear old field
 3260:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3261:             currentform.elements[current.argfield].value = '';
 3262:         }
 3263:         current.argfield = choicearg;
 3264:     }
 3265:     set_auth_radio_buttons(choice,currentform);
 3266:     return;
 3267: }
 3268: 
 3269: function set_auth_radio_buttons(newvalue,currentform) {
 3270:     var numauthchoices = currentform.login.length;
 3271:     if (typeof numauthchoices  == "undefined") {
 3272:         return;
 3273:     } 
 3274:     var i=0;
 3275:     while (i < numauthchoices) {
 3276:         if (currentform.login[i].value == newvalue) { break; }
 3277:         i++;
 3278:     }
 3279:     if (i == numauthchoices) {
 3280:         return;
 3281:     }
 3282:     current.radiovalue = newvalue;
 3283:     currentform.login[i].checked = true;
 3284:     return;
 3285: }
 3286: END
 3287:     return $result;
 3288: }
 3289: 
 3290: sub authform_authorwarning {
 3291:     my $result='';
 3292:     $result='<i>'.
 3293:         &mt('As a general rule, only authors or co-authors should be '.
 3294:             'filesystem authenticated '.
 3295:             '(which allows access to the server filesystem).')."</i>\n";
 3296:     return $result;
 3297: }
 3298: 
 3299: sub authform_nochange {
 3300:     my %in = (
 3301:               formname => 'document.cu',
 3302:               kerb_def_dom => 'MSU.EDU',
 3303:               @_,
 3304:           );
 3305:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3306:     my $result;
 3307:     if (!$authnum) {
 3308:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3309:     } else {
 3310:         $result = '<label>'.&mt('[_1] Do not change login data',
 3311:                   '<input type="radio" name="login" value="nochange" '.
 3312:                   'checked="checked" onclick="'.
 3313:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3314: 	    '</label>';
 3315:     }
 3316:     return $result;
 3317: }
 3318: 
 3319: sub authform_kerberos {
 3320:     my %in = (
 3321:               formname => 'document.cu',
 3322:               kerb_def_dom => 'MSU.EDU',
 3323:               kerb_def_auth => 'krb4',
 3324:               @_,
 3325:               );
 3326:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3327:         $autharg,$jscall,$disabled);
 3328:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3329:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3330:        $check5 = ' checked="checked"';
 3331:     } else {
 3332:        $check4 = ' checked="checked"';
 3333:     }
 3334:     if ($in{'readonly'}) {
 3335:         $disabled = ' disabled="disabled"';
 3336:     }
 3337:     $krbarg = $in{'kerb_def_dom'};
 3338:     if (defined($in{'curr_authtype'})) {
 3339:         if ($in{'curr_authtype'} eq 'krb') {
 3340:             $krbcheck = ' checked="checked"';
 3341:             if (defined($in{'mode'})) {
 3342:                 if ($in{'mode'} eq 'modifyuser') {
 3343:                     $krbcheck = '';
 3344:                 }
 3345:             }
 3346:             if (defined($in{'curr_kerb_ver'})) {
 3347:                 if ($in{'curr_krb_ver'} eq '5') {
 3348:                     $check5 = ' checked="checked"';
 3349:                     $check4 = '';
 3350:                 } else {
 3351:                     $check4 = ' checked="checked"';
 3352:                     $check5 = '';
 3353:                 }
 3354:             }
 3355:             if (defined($in{'curr_autharg'})) {
 3356:                 $krbarg = $in{'curr_autharg'};
 3357:             }
 3358:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3359:                 if (defined($in{'curr_autharg'})) {
 3360:                     $result = 
 3361:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3362:         $in{'curr_autharg'},$krbver);
 3363:                 } else {
 3364:                     $result =
 3365:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3366:                 }
 3367:                 return $result; 
 3368:             }
 3369:         }
 3370:     } else {
 3371:         if ($authnum == 1) {
 3372:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3373:         }
 3374:     }
 3375:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3376:         return;
 3377:     } elsif ($authtype eq '') {
 3378:         if (defined($in{'mode'})) {
 3379:             if ($in{'mode'} eq 'modifycourse') {
 3380:                 if ($authnum == 1) {
 3381:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3382:                 }
 3383:             }
 3384:         }
 3385:     }
 3386:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3387:     if ($authtype eq '') {
 3388:         $authtype = '<input type="radio" name="login" value="krb" '.
 3389:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3390:                     $krbcheck.$disabled.' />';
 3391:     }
 3392:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3393:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3394:          $in{'curr_authtype'} eq 'krb5') ||
 3395:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3396:          $in{'curr_authtype'} eq 'krb4')) {
 3397:         $result .= &mt
 3398:         ('[_1] Kerberos authenticated with domain [_2] '.
 3399:          '[_3] Version 4 [_4] Version 5 [_5]',
 3400:          '<label>'.$authtype,
 3401:          '</label><input type="text" size="10" name="krbarg" '.
 3402:              'value="'.$krbarg.'" '.
 3403:              'onchange="'.$jscall.'"'.$disabled.' />',
 3404:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3405:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3406: 	 '</label>');
 3407:     } elsif ($can_assign{'krb4'}) {
 3408:         $result .= &mt
 3409:         ('[_1] Kerberos authenticated with domain [_2] '.
 3410:          '[_3] Version 4 [_4]',
 3411:          '<label>'.$authtype,
 3412:          '</label><input type="text" size="10" name="krbarg" '.
 3413:              'value="'.$krbarg.'" '.
 3414:              'onchange="'.$jscall.'"'.$disabled.' />',
 3415:          '<label><input type="hidden" name="krbver" value="4" />',
 3416:          '</label>');
 3417:     } elsif ($can_assign{'krb5'}) {
 3418:         $result .= &mt
 3419:         ('[_1] Kerberos authenticated with domain [_2] '.
 3420:          '[_3] Version 5 [_4]',
 3421:          '<label>'.$authtype,
 3422:          '</label><input type="text" size="10" name="krbarg" '.
 3423:              'value="'.$krbarg.'" '.
 3424:              'onchange="'.$jscall.'"'.$disabled.' />',
 3425:          '<label><input type="hidden" name="krbver" value="5" />',
 3426:          '</label>');
 3427:     }
 3428:     return $result;
 3429: }
 3430: 
 3431: sub authform_internal {
 3432:     my %in = (
 3433:                 formname => 'document.cu',
 3434:                 kerb_def_dom => 'MSU.EDU',
 3435:                 @_,
 3436:                 );
 3437:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3438:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3439:     if ($in{'readonly'}) {
 3440:         $disabled = ' disabled="disabled"';
 3441:     }
 3442:     if (defined($in{'curr_authtype'})) {
 3443:         if ($in{'curr_authtype'} eq 'int') {
 3444:             if ($can_assign{'int'}) {
 3445:                 $intcheck = 'checked="checked" ';
 3446:                 if (defined($in{'mode'})) {
 3447:                     if ($in{'mode'} eq 'modifyuser') {
 3448:                         $intcheck = '';
 3449:                     }
 3450:                 }
 3451:                 if (defined($in{'curr_autharg'})) {
 3452:                     $intarg = $in{'curr_autharg'};
 3453:                 }
 3454:             } else {
 3455:                 $result = &mt('Currently internally authenticated.');
 3456:                 return $result;
 3457:             }
 3458:         }
 3459:     } else {
 3460:         if ($authnum == 1) {
 3461:             $authtype = '<input type="hidden" name="login" value="int" />';
 3462:         }
 3463:     }
 3464:     if (!$can_assign{'int'}) {
 3465:         return;
 3466:     } elsif ($authtype eq '') {
 3467:         if (defined($in{'mode'})) {
 3468:             if ($in{'mode'} eq 'modifycourse') {
 3469:                 if ($authnum == 1) {
 3470:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3471:                 }
 3472:             }
 3473:         }
 3474:     }
 3475:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3476:     if ($authtype eq '') {
 3477:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3478:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3479:     }
 3480:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3481:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3482:     $result = &mt
 3483:         ('[_1] Internally authenticated (with initial password [_2])',
 3484:          '<label>'.$authtype,'</label>'.$autharg);
 3485:     $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>';
 3486:     return $result;
 3487: }
 3488: 
 3489: sub authform_local {
 3490:     my %in = (
 3491:               formname => 'document.cu',
 3492:               kerb_def_dom => 'MSU.EDU',
 3493:               @_,
 3494:               );
 3495:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3496:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3497:     if ($in{'readonly'}) {
 3498:         $disabled = ' disabled="disabled"';
 3499:     } 
 3500:     if (defined($in{'curr_authtype'})) {
 3501:         if ($in{'curr_authtype'} eq 'loc') {
 3502:             if ($can_assign{'loc'}) {
 3503:                 $loccheck = 'checked="checked" ';
 3504:                 if (defined($in{'mode'})) {
 3505:                     if ($in{'mode'} eq 'modifyuser') {
 3506:                         $loccheck = '';
 3507:                     }
 3508:                 }
 3509:                 if (defined($in{'curr_autharg'})) {
 3510:                     $locarg = $in{'curr_autharg'};
 3511:                 }
 3512:             } else {
 3513:                 $result = &mt('Currently using local (institutional) authentication.');
 3514:                 return $result;
 3515:             }
 3516:         }
 3517:     } else {
 3518:         if ($authnum == 1) {
 3519:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3520:         }
 3521:     }
 3522:     if (!$can_assign{'loc'}) {
 3523:         return;
 3524:     } elsif ($authtype eq '') {
 3525:         if (defined($in{'mode'})) {
 3526:             if ($in{'mode'} eq 'modifycourse') {
 3527:                 if ($authnum == 1) {
 3528:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3529:                 }
 3530:             }
 3531:         }
 3532:     }
 3533:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3534:     if ($authtype eq '') {
 3535:         $authtype = '<input type="radio" name="login" value="loc" '.
 3536:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3537:                     $jscall.'"'.$disabled.' />';
 3538:     }
 3539:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3540:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3541:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3542:                   '<label>'.$authtype,'</label>'.$autharg);
 3543:     return $result;
 3544: }
 3545: 
 3546: sub authform_filesystem {
 3547:     my %in = (
 3548:               formname => 'document.cu',
 3549:               kerb_def_dom => 'MSU.EDU',
 3550:               @_,
 3551:               );
 3552:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3553:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3554:     if ($in{'readonly'}) {
 3555:         $disabled = ' disabled="disabled"';
 3556:     }
 3557:     if (defined($in{'curr_authtype'})) {
 3558:         if ($in{'curr_authtype'} eq 'fsys') {
 3559:             if ($can_assign{'fsys'}) {
 3560:                 $fsyscheck = 'checked="checked" ';
 3561:                 if (defined($in{'mode'})) {
 3562:                     if ($in{'mode'} eq 'modifyuser') {
 3563:                         $fsyscheck = '';
 3564:                     }
 3565:                 }
 3566:             } else {
 3567:                 $result = &mt('Currently Filesystem Authenticated.');
 3568:                 return $result;
 3569:             }
 3570:         }
 3571:     } else {
 3572:         if ($authnum == 1) {
 3573:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3574:         }
 3575:     }
 3576:     if (!$can_assign{'fsys'}) {
 3577:         return;
 3578:     } elsif ($authtype eq '') {
 3579:         if (defined($in{'mode'})) {
 3580:             if ($in{'mode'} eq 'modifycourse') {
 3581:                 if ($authnum == 1) {
 3582:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3583:                 }
 3584:             }
 3585:         }
 3586:     }
 3587:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3588:     if ($authtype eq '') {
 3589:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3590:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3591:                     $jscall.'"'.$disabled.' />';
 3592:     }
 3593:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
 3594:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3595:     $result = &mt
 3596:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3597:          '<label>'.$authtype,'</label>'.$autharg);
 3598:     return $result;
 3599: }
 3600: 
 3601: sub authform_lti {
 3602:     my %in = (
 3603:               formname => 'document.cu',
 3604:               kerb_def_dom => 'MSU.EDU',
 3605:               @_,
 3606:               );
 3607:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
 3608:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3609:     if ($in{'readonly'}) {
 3610:         $disabled = ' disabled="disabled"';
 3611:     }
 3612:     if (defined($in{'curr_authtype'})) {
 3613:         if ($in{'curr_authtype'} eq 'lti') {
 3614:             if ($can_assign{'lti'}) {
 3615:                 $lticheck = 'checked="checked" ';
 3616:                 if (defined($in{'mode'})) {
 3617:                     if ($in{'mode'} eq 'modifyuser') {
 3618:                         $lticheck = '';
 3619:                     }
 3620:                 }
 3621:             } else {
 3622:                 $result = &mt('Currently LTI Authenticated.');
 3623:                 return $result;
 3624:             }
 3625:         }
 3626:     } else {
 3627:         if ($authnum == 1) {
 3628:             $authtype = '<input type="hidden" name="login" value="lti" />';
 3629:         }
 3630:     }
 3631:     if (!$can_assign{'lti'}) {
 3632:         return;
 3633:     } elsif ($authtype eq '') {
 3634:         if (defined($in{'mode'})) {
 3635:             if ($in{'mode'} eq 'modifycourse') {
 3636:                 if ($authnum == 1) {
 3637:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
 3638:                 }
 3639:             }
 3640:         }
 3641:     }
 3642:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
 3643:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
 3644:         $authtype = '<input type="radio" name="login" value="lti" '.
 3645:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
 3646:                     $jscall.'"'.$disabled.' />';
 3647:     }
 3648:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
 3649:     if ($authtype) {
 3650:         $result = &mt('[_1] LTI Authenticated',
 3651:                       '<label>'.$authtype.'</label>'.$autharg);
 3652:     } else {
 3653:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
 3654:                   $autharg;
 3655:     }
 3656:     return $result;
 3657: }
 3658: 
 3659: sub get_assignable_auth {
 3660:     my ($dom) = @_;
 3661:     if ($dom eq '') {
 3662:         $dom = $env{'request.role.domain'};
 3663:     }
 3664:     my %can_assign = (
 3665:                           krb4 => 1,
 3666:                           krb5 => 1,
 3667:                           int  => 1,
 3668:                           loc  => 1,
 3669:                           lti  => 1,
 3670:                      );
 3671:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3672:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3673:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3674:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3675:             my $context;
 3676:             if ($env{'request.role'} =~ /^au/) {
 3677:                 $context = 'author';
 3678:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3679:                 $context = 'domain';
 3680:             } elsif ($env{'request.course.id'}) {
 3681:                 $context = 'course';
 3682:             }
 3683:             if ($context) {
 3684:                 if (ref($authhash->{$context}) eq 'HASH') {
 3685:                    %can_assign = %{$authhash->{$context}}; 
 3686:                 }
 3687:             }
 3688:         }
 3689:     }
 3690:     my $authnum = 0;
 3691:     foreach my $key (keys(%can_assign)) {
 3692:         if ($can_assign{$key}) {
 3693:             $authnum ++;
 3694:         }
 3695:     }
 3696:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3697:         $authnum --;
 3698:     }
 3699:     return ($authnum,%can_assign);
 3700: }
 3701: 
 3702: sub check_passwd_rules {
 3703:     my ($domain,$plainpass) = @_;
 3704:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3705:     my ($min,$max,@chars,@brokerule,$warning);
 3706:     $min = $Apache::lonnet::passwdmin;
 3707:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3708:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3709:             if ($passwdconf{'min'} > $min) {
 3710:                 $min = $passwdconf{'min'};
 3711:             }
 3712:         }
 3713:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3714:             $max = $passwdconf{'max'};
 3715:         }
 3716:         @chars = @{$passwdconf{'chars'}};
 3717:     }
 3718:     if (($min) && (length($plainpass) < $min)) {
 3719:         push(@brokerule,'min');
 3720:     }
 3721:     if (($max) && (length($plainpass) > $max)) {
 3722:         push(@brokerule,'max');
 3723:     }
 3724:     if (@chars) {
 3725:         my %rules;
 3726:         map { $rules{$_} = 1; } @chars;
 3727:         if ($rules{'uc'}) {
 3728:             unless ($plainpass =~ /[A-Z]/) {
 3729:                 push(@brokerule,'uc');
 3730:             }
 3731:         }
 3732:         if ($rules{'lc'}) {
 3733:             unless ($plainpass =~ /[a-z]/) {
 3734:                 push(@brokerule,'lc');
 3735:             }
 3736:         }
 3737:         if ($rules{'num'}) {
 3738:             unless ($plainpass =~ /\d/) {
 3739:                 push(@brokerule,'num');
 3740:             }
 3741:         }
 3742:         if ($rules{'spec'}) {
 3743:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
 3744:                 push(@brokerule,'spec');
 3745:             }
 3746:         }
 3747:     }
 3748:     if (@brokerule) {
 3749:         my %rulenames = &Apache::lonlocal::texthash(
 3750:             uc   => 'At least one upper case letter',
 3751:             lc   => 'At least one lower case letter',
 3752:             num  => 'At least one number',
 3753:             spec => 'At least one non-alphanumeric',
 3754:         );
 3755:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 3756:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
 3757:         $rulenames{'num'} .= ': 0123456789';
 3758:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
 3759:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
 3760:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
 3761:         $warning = &mt('Password did not satisfy the following:').'<ul>';
 3762:         foreach my $rule ('min','max','uc','lc','num','spec') {
 3763:             if (grep(/^$rule$/,@brokerule)) {
 3764:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
 3765:             }
 3766:         }
 3767:         $warning .= '</ul>';
 3768:     }
 3769:     if (wantarray) {
 3770:         return @brokerule;
 3771:     }
 3772:     return $warning;
 3773: }
 3774: 
 3775: sub passwd_validation_js {
 3776:     my ($currpasswdval,$domain,$context,$id) = @_;
 3777:     my (%passwdconf,$alertmsg);
 3778:     if ($context eq 'linkprot') {
 3779:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
 3780:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
 3781:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
 3782:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
 3783:             }
 3784:         }
 3785:         if ($id eq 'add') {
 3786:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
 3787:         } elsif ($id =~ /^\d+$/) {
 3788:             my $pos = $id+1;
 3789:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
 3790:         } else {
 3791:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
 3792:         }
 3793:     } else {
 3794:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 3795:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
 3796:     }
 3797:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
 3798:     $numrules = 0;
 3799:     $min = $Apache::lonnet::passwdmin;
 3800:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
 3801:         if ($passwdconf{'min'} =~ /^\d+$/) {
 3802:             if ($passwdconf{'min'} > $min) {
 3803:                 $min = $passwdconf{'min'};
 3804:             }
 3805:         }
 3806:         if ($passwdconf{'max'} =~ /^\d+$/) {
 3807:             $max = $passwdconf{'max'};
 3808:             $numrules ++;
 3809:         }
 3810:         @chars = @{$passwdconf{'chars'}};
 3811:         if (@chars) {
 3812:             $numrules ++;
 3813:         }
 3814:     }
 3815:     if ($min > 0) {
 3816:         $numrules ++;
 3817:     }
 3818:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
 3819:         if ($min) {
 3820:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
 3821:         }
 3822:         if ($max) {
 3823:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
 3824:         }
 3825:         my (@charalerts,@charrules);
 3826:         if (@chars) {
 3827:             if (grep(/^uc$/,@chars)) {
 3828:                 push(@charalerts,&mt('contain at least one upper case letter'));
 3829:                 push(@charrules,'uc');
 3830:             }
 3831:             if (grep(/^lc$/,@chars)) {
 3832:                 push(@charalerts,&mt('contain at least one lower case letter'));
 3833:                 push(@charrules,'lc');
 3834:             }
 3835:             if (grep(/^num$/,@chars)) {
 3836:                 push(@charalerts,&mt('contain at least one number'));
 3837:                 push(@charrules,'num');
 3838:             }
 3839:             if (grep(/^spec$/,@chars)) {
 3840:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
 3841:                 push(@charrules,'spec');
 3842:             }
 3843:         }
 3844:         $intargjs = qq|            var rulesmsg = '';\n|.
 3845:                     qq|            var currpwval = $currpasswdval;\n|;
 3846:             if ($min) {
 3847:                 $intargjs .= qq|
 3848:             if (currpwval.length < $min) {
 3849:                 rulesmsg += ' - $alert{min}';
 3850:             }
 3851: |;
 3852:             }
 3853:             if ($max) {
 3854:                 $intargjs .= qq|
 3855:             if (currpwval.length > $max) {
 3856:                 rulesmsg += ' - $alert{max}';
 3857:             }
 3858: |;
 3859:             }
 3860:             if (@chars > 0) {
 3861:                 my $charrulestr = '"'.join('","',@charrules).'"';
 3862:                 my $charalertstr = '"'.join('","',@charalerts).'"';
 3863:                 $intargjs .= qq|            var brokerules = new Array();\n|.
 3864:                              qq|            var charrules = new Array($charrulestr);\n|.
 3865:                              qq|            var charalerts = new Array($charalertstr);\n|;
 3866:                 my %rules;
 3867:                 map { $rules{$_} = 1; } @chars;
 3868:                 if ($rules{'uc'}) {
 3869:                     $intargjs .= qq|
 3870:             var ucRegExp = /[A-Z]/;
 3871:             if (!ucRegExp.test(currpwval)) {
 3872:                 brokerules.push('uc');
 3873:             }
 3874: |;
 3875:                 }
 3876:                 if ($rules{'lc'}) {
 3877:                     $intargjs .= qq|
 3878:             var lcRegExp = /[a-z]/;
 3879:             if (!lcRegExp.test(currpwval)) {
 3880:                 brokerules.push('lc');
 3881:             }
 3882: |;
 3883:                 }
 3884:                 if ($rules{'num'}) {
 3885:                      $intargjs .= qq|
 3886:             var numRegExp = /[0-9]/;
 3887:             if (!numRegExp.test(currpwval)) {
 3888:                 brokerules.push('num');
 3889:             }
 3890: |;
 3891:                 }
 3892:                 if ($rules{'spec'}) {
 3893:                      $intargjs .= q|
 3894:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
 3895:             if (!specRegExp.test(currpwval)) {
 3896:                 brokerules.push('spec');
 3897:             }
 3898: |;
 3899:                 }
 3900:                 $intargjs .= qq|
 3901:             if (brokerules.length > 0) {
 3902:                 for (var i=0; i<brokerules.length; i++) {
 3903:                     for (var j=0; j<charrules.length; j++) {
 3904:                         if (brokerules[i] == charrules[j]) {
 3905:                             rulesmsg += ' - '+charalerts[j]+'\\n';
 3906:                             break;
 3907:                         }
 3908:                     }
 3909:                 }
 3910:             }
 3911: |;
 3912:             }
 3913:             $intargjs .= qq|
 3914:             if (rulesmsg != '') {
 3915:                 rulesmsg = '$alertmsg'+rulesmsg;
 3916:                 alert(rulesmsg);
 3917:                 return false;
 3918:             }
 3919: |;
 3920:     }
 3921:     return ($numrules,$intargjs);
 3922: }
 3923: 
 3924: ###############################################################
 3925: ##    Get Kerberos Defaults for Domain                 ##
 3926: ###############################################################
 3927: ##
 3928: ## Returns default kerberos version and an associated argument
 3929: ## as listed in file domain.tab. If not listed, provides
 3930: ## appropriate default domain and kerberos version.
 3931: ##
 3932: #-------------------------------------------
 3933: 
 3934: =pod
 3935: 
 3936: =item * &get_kerberos_defaults()
 3937: 
 3938: get_kerberos_defaults($target_domain) returns the default kerberos
 3939: version and domain. If not found, it defaults to version 4 and the 
 3940: domain of the server.
 3941: 
 3942: =over 4
 3943: 
 3944: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3945: 
 3946: =back
 3947: 
 3948: =back
 3949: 
 3950: =cut
 3951: 
 3952: #-------------------------------------------
 3953: sub get_kerberos_defaults {
 3954:     my $domain=shift;
 3955:     my ($krbdef,$krbdefdom);
 3956:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3957:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3958:         $krbdef = $domdefaults{'auth_def'};
 3959:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3960:     } else {
 3961:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3962:         my $krbdefdom=$1;
 3963:         $krbdefdom=~tr/a-z/A-Z/;
 3964:         $krbdef = "krb4";
 3965:     }
 3966:     return ($krbdef,$krbdefdom);
 3967: }
 3968: 
 3969: 
 3970: ###############################################################
 3971: ##                Thesaurus Functions                        ##
 3972: ###############################################################
 3973: 
 3974: =pod
 3975: 
 3976: =head1 Thesaurus Functions
 3977: 
 3978: =over 4
 3979: 
 3980: =item * &initialize_keywords()
 3981: 
 3982: Initializes the package variable %Keywords if it is empty.  Uses the
 3983: package variable $thesaurus_db_file.
 3984: 
 3985: =cut
 3986: 
 3987: ###################################################
 3988: 
 3989: sub initialize_keywords {
 3990:     return 1 if (scalar keys(%Keywords));
 3991:     # If we are here, %Keywords is empty, so fill it up
 3992:     #   Make sure the file we need exists...
 3993:     if (! -e $thesaurus_db_file) {
 3994:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3995:                                  " failed because it does not exist");
 3996:         return 0;
 3997:     }
 3998:     #   Set up the hash as a database
 3999:     my %thesaurus_db;
 4000:     if (! tie(%thesaurus_db,'GDBM_File',
 4001:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4002:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 4003:                                  $thesaurus_db_file);
 4004:         return 0;
 4005:     } 
 4006:     #  Get the average number of appearances of a word.
 4007:     my $avecount = $thesaurus_db{'average.count'};
 4008:     #  Put keywords (those that appear > average) into %Keywords
 4009:     while (my ($word,$data)=each (%thesaurus_db)) {
 4010:         my ($count,undef) = split /:/,$data;
 4011:         $Keywords{$word}++ if ($count > $avecount);
 4012:     }
 4013:     untie %thesaurus_db;
 4014:     # Remove special values from %Keywords.
 4015:     foreach my $value ('total.count','average.count') {
 4016:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 4017:   }
 4018:     return 1;
 4019: }
 4020: 
 4021: ###################################################
 4022: 
 4023: =pod
 4024: 
 4025: =item * &keyword($word)
 4026: 
 4027: Returns true if $word is a keyword.  A keyword is a word that appears more 
 4028: than the average number of times in the thesaurus database.  Calls 
 4029: &initialize_keywords
 4030: 
 4031: =cut
 4032: 
 4033: ###################################################
 4034: 
 4035: sub keyword {
 4036:     return if (!&initialize_keywords());
 4037:     my $word=lc(shift());
 4038:     $word=~s/\W//g;
 4039:     return exists($Keywords{$word});
 4040: }
 4041: 
 4042: ###############################################################
 4043: 
 4044: =pod 
 4045: 
 4046: =item * &get_related_words()
 4047: 
 4048: Look up a word in the thesaurus.  Takes a scalar argument and returns
 4049: an array of words.  If the keyword is not in the thesaurus, an empty array
 4050: will be returned.  The order of the words returned is determined by the
 4051: database which holds them.
 4052: 
 4053: Uses global $thesaurus_db_file.
 4054: 
 4055: 
 4056: =cut
 4057: 
 4058: ###############################################################
 4059: sub get_related_words {
 4060:     my $keyword = shift;
 4061:     my %thesaurus_db;
 4062:     if (! -e $thesaurus_db_file) {
 4063:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 4064:                                  "failed because the file does not exist");
 4065:         return ();
 4066:     }
 4067:     if (! tie(%thesaurus_db,'GDBM_File',
 4068:               $thesaurus_db_file,&GDBM_READER(),0640)){
 4069:         return ();
 4070:     } 
 4071:     my @Words=();
 4072:     my $count=0;
 4073:     if (exists($thesaurus_db{$keyword})) {
 4074: 	# The first element is the number of times
 4075: 	# the word appears.  We do not need it now.
 4076: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 4077: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 4078: 	my $threshold=$mostfrequentcount/10;
 4079:         foreach my $possibleword (@RelatedWords) {
 4080:             my ($word,$wordcount)=split(/\,/,$possibleword);
 4081:             if ($wordcount>$threshold) {
 4082: 		push(@Words,$word);
 4083:                 $count++;
 4084:                 if ($count>10) { last; }
 4085: 	    }
 4086:         }
 4087:     }
 4088:     untie %thesaurus_db;
 4089:     return @Words;
 4090: }
 4091: ###############################################################
 4092: #
 4093: #  Spell checking
 4094: #
 4095: 
 4096: =pod
 4097: 
 4098: =back
 4099: 
 4100: =head1 Spell checking
 4101: 
 4102: =over 4
 4103: 
 4104: =item * &check_spelling($wordlist $language)
 4105: 
 4106: Takes a string containing words and feeds it to an external
 4107: spellcheck program via a pipeline. Returns a string containing
 4108: them mis-spelled words.
 4109: 
 4110: Parameters:
 4111: 
 4112: =over 4
 4113: 
 4114: =item - $wordlist
 4115: 
 4116: String that will be fed into the spellcheck program.
 4117: 
 4118: =item - $language
 4119: 
 4120: Language string that specifies the language for which the spell
 4121: check will be performed.
 4122: 
 4123: =back
 4124: 
 4125: =back
 4126: 
 4127: Note: This sub assumes that aspell is installed.
 4128: 
 4129: 
 4130: =cut
 4131: 
 4132: 
 4133: sub check_spelling {
 4134:     my ($wordlist, $language) = @_;
 4135:     my @misspellings;
 4136:     
 4137:     # Generate the speller and set the langauge.
 4138:     # if explicitly selected:
 4139: 
 4140:     my $speller = Text::Aspell->new;
 4141:     if ($language) {
 4142: 	$speller->set_option('lang', $language);
 4143:     }
 4144: 
 4145:     # Turn the word list into an array of words by splittingon whitespace
 4146: 
 4147:     my @words = split(/\s+/, $wordlist);
 4148: 
 4149:     foreach my $word (@words) {
 4150: 	if(! $speller->check($word)) {
 4151: 	    push(@misspellings, $word);
 4152: 	}
 4153:     }
 4154:     return join(' ', @misspellings);
 4155:     
 4156: }
 4157: 
 4158: # -------------------------------------------------------------- Plaintext name
 4159: =pod
 4160: 
 4161: =head1 User Name Functions
 4162: 
 4163: =over 4
 4164: 
 4165: =item * &plainname($uname,$udom,$first)
 4166: 
 4167: Takes a users logon name and returns it as a string in
 4168: "first middle last generation" form 
 4169: if $first is set to 'lastname' then it returns it as
 4170: 'lastname generation, firstname middlename' if their is a lastname
 4171: 
 4172: =cut
 4173: 
 4174: 
 4175: ###############################################################
 4176: sub plainname {
 4177:     my ($uname,$udom,$first)=@_;
 4178:     return if (!defined($uname) || !defined($udom));
 4179:     my %names=&getnames($uname,$udom);
 4180:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 4181: 					  $names{'middlename'},
 4182: 					  $names{'lastname'},
 4183: 					  $names{'generation'},$first);
 4184:     $name=~s/^\s+//;
 4185:     $name=~s/\s+$//;
 4186:     $name=~s/\s+/ /g;
 4187:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 4188:     return $name;
 4189: }
 4190: 
 4191: # -------------------------------------------------------------------- Nickname
 4192: =pod
 4193: 
 4194: =item * &nickname($uname,$udom)
 4195: 
 4196: Gets a users name and returns it as a string as
 4197: 
 4198: "&quot;nickname&quot;"
 4199: 
 4200: if the user has a nickname or
 4201: 
 4202: "first middle last generation"
 4203: 
 4204: if the user does not
 4205: 
 4206: =cut
 4207: 
 4208: sub nickname {
 4209:     my ($uname,$udom)=@_;
 4210:     return if (!defined($uname) || !defined($udom));
 4211:     my %names=&getnames($uname,$udom);
 4212:     my $name=$names{'nickname'};
 4213:     if ($name) {
 4214:        $name='&quot;'.$name.'&quot;'; 
 4215:     } else {
 4216:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 4217: 	     $names{'lastname'}.' '.$names{'generation'};
 4218:        $name=~s/\s+$//;
 4219:        $name=~s/\s+/ /g;
 4220:     }
 4221:     return $name;
 4222: }
 4223: 
 4224: sub getnames {
 4225:     my ($uname,$udom)=@_;
 4226:     return if (!defined($uname) || !defined($udom));
 4227:     if ($udom eq 'public' && $uname eq 'public') {
 4228: 	return ('lastname' => &mt('Public'));
 4229:     }
 4230:     my $id=$uname.':'.$udom;
 4231:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 4232:     if ($cached) {
 4233: 	return %{$names};
 4234:     } else {
 4235: 	my %loadnames=&Apache::lonnet::get('environment',
 4236:                     ['firstname','middlename','lastname','generation','nickname'],
 4237: 					 $udom,$uname);
 4238: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 4239: 	return %loadnames;
 4240:     }
 4241: }
 4242: 
 4243: # -------------------------------------------------------------------- getemails
 4244: 
 4245: =pod
 4246: 
 4247: =item * &getemails($uname,$udom)
 4248: 
 4249: Gets a user's email information and returns it as a hash with keys:
 4250: notification, critnotification, permanentemail
 4251: 
 4252: For notification and critnotification, values are comma-separated lists 
 4253: of e-mail addresses; for permanentemail, value is a single e-mail address.
 4254:  
 4255: 
 4256: =cut
 4257: 
 4258: 
 4259: sub getemails {
 4260:     my ($uname,$udom)=@_;
 4261:     if ($udom eq 'public' && $uname eq 'public') {
 4262: 	return;
 4263:     }
 4264:     if (!$udom) { $udom=$env{'user.domain'}; }
 4265:     if (!$uname) { $uname=$env{'user.name'}; }
 4266:     my $id=$uname.':'.$udom;
 4267:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 4268:     if ($cached) {
 4269: 	return %{$names};
 4270:     } else {
 4271: 	my %loadnames=&Apache::lonnet::get('environment',
 4272:                     			   ['notification','critnotification',
 4273: 					    'permanentemail'],
 4274: 					   $udom,$uname);
 4275: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 4276: 	return %loadnames;
 4277:     }
 4278: }
 4279: 
 4280: sub flush_email_cache {
 4281:     my ($uname,$udom)=@_;
 4282:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4283:     if (!$uname) { $uname=$env{'user.name'};   }
 4284:     return if ($udom eq 'public' && $uname eq 'public');
 4285:     my $id=$uname.':'.$udom;
 4286:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 4287: }
 4288: 
 4289: # -------------------------------------------------------------------- getlangs
 4290: 
 4291: =pod
 4292: 
 4293: =item * &getlangs($uname,$udom)
 4294: 
 4295: Gets a user's language preference and returns it as a hash with key:
 4296: language.
 4297: 
 4298: =cut
 4299: 
 4300: 
 4301: sub getlangs {
 4302:     my ($uname,$udom) = @_;
 4303:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4304:     if (!$uname) { $uname=$env{'user.name'};   }
 4305:     my $id=$uname.':'.$udom;
 4306:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 4307:     if ($cached) {
 4308:         return %{$langs};
 4309:     } else {
 4310:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 4311:                                            $udom,$uname);
 4312:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 4313:         return %loadlangs;
 4314:     }
 4315: }
 4316: 
 4317: sub flush_langs_cache {
 4318:     my ($uname,$udom)=@_;
 4319:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4320:     if (!$uname) { $uname=$env{'user.name'};   }
 4321:     return if ($udom eq 'public' && $uname eq 'public');
 4322:     my $id=$uname.':'.$udom;
 4323:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 4324: }
 4325: 
 4326: # ------------------------------------------------------------------ Screenname
 4327: 
 4328: =pod
 4329: 
 4330: =item * &screenname($uname,$udom)
 4331: 
 4332: Gets a users screenname and returns it as a string
 4333: 
 4334: =cut
 4335: 
 4336: sub screenname {
 4337:     my ($uname,$udom)=@_;
 4338:     if ($uname eq $env{'user.name'} &&
 4339: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 4340:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 4341:     return $names{'screenname'};
 4342: }
 4343: 
 4344: 
 4345: # ------------------------------------------------------------- Confirm Wrapper
 4346: =pod
 4347: 
 4348: =item * &confirmwrapper($message)
 4349: 
 4350: Wrap messages about completion of operation in box
 4351: 
 4352: =cut
 4353: 
 4354: sub confirmwrapper {
 4355:     my ($message)=@_;
 4356:     if ($message) {
 4357:         return "\n".'<div class="LC_confirm_box">'."\n"
 4358:                .$message."\n"
 4359:                .'</div>'."\n";
 4360:     } else {
 4361:         return $message;
 4362:     }
 4363: }
 4364: 
 4365: # ------------------------------------------------------------- Message Wrapper
 4366: 
 4367: sub messagewrapper {
 4368:     my ($link,$username,$domain,$subject,$text)=@_;
 4369:     return 
 4370:         '<a href="/adm/email?compose=individual&amp;'.
 4371:         'recname='.$username.'&amp;recdom='.$domain.
 4372: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 4373:         'title="'.&mt('Send message').'">'.$link.'</a>';
 4374: }
 4375: 
 4376: # --------------------------------------------------------------- Notes Wrapper
 4377: 
 4378: sub noteswrapper {
 4379:     my ($link,$un,$do)=@_;
 4380:     return 
 4381: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 4382: }
 4383: 
 4384: # ------------------------------------------------------------- Aboutme Wrapper
 4385: 
 4386: sub aboutmewrapper {
 4387:     my ($link,$username,$domain,$target,$class)=@_;
 4388:     if (!defined($username)  && !defined($domain)) {
 4389:         return;
 4390:     }
 4391:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 4392: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 4393: }
 4394: 
 4395: # ------------------------------------------------------------ Syllabus Wrapper
 4396: 
 4397: sub syllabuswrapper {
 4398:     my ($linktext,$coursedir,$domain)=@_;
 4399:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 4400: }
 4401: 
 4402: # -----------------------------------------------------------------------------
 4403: 
 4404: sub aboutme_on {
 4405:     my ($uname,$udom)=@_;
 4406:     unless ($uname) { $uname=$env{'user.name'}; }
 4407:     unless ($udom)  { $udom=$env{'user.domain'}; }
 4408:     return if ($udom eq 'public' && $uname eq 'public');
 4409:     my $hashkey=$uname.':'.$udom;
 4410:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
 4411:     if ($cached) {
 4412:         return $aboutme;
 4413:     }
 4414:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
 4415:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
 4416:     return $aboutme;
 4417: }
 4418: 
 4419: sub devalidate_aboutme_cache {
 4420:     my ($uname,$udom)=@_;
 4421:     if (!$udom)  { $udom =$env{'user.domain'}; }
 4422:     if (!$uname) { $uname=$env{'user.name'};   }
 4423:     return if ($udom eq 'public' && $uname eq 'public');
 4424:     my $id=$uname.':'.$udom;
 4425:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
 4426: }
 4427: 
 4428: sub track_student_link {
 4429:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 4430:     my $link ="/adm/trackstudent?";
 4431:     my $title = 'View recent activity';
 4432:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4433:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4434:         $link .= "selected_student=$sname:$sdom";
 4435:         $title .= ' of this student';
 4436:     } 
 4437:     if (defined($target) && $target !~ /^\s*$/) {
 4438:         $target = qq{target="$target"};
 4439:     } else {
 4440:         $target = '';
 4441:     }
 4442:     if ($start) { $link.='&amp;start='.$start; }
 4443:     if ($only_body) { $link .= '&amp;only_body=1'; }
 4444:     $title = &mt($title);
 4445:     $linktext = &mt($linktext);
 4446:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 4447: 	&help_open_topic('View_recent_activity');
 4448: }
 4449: 
 4450: sub slot_reservations_link {
 4451:     my ($linktext,$sname,$sdom,$target) = @_;
 4452:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 4453:     my $title = 'View slot reservation history';
 4454:     if (defined($sname) && $sname !~ /^\s*$/ &&
 4455:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 4456:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 4457:         $title .= ' of this student';
 4458:     }
 4459:     if (defined($target) && $target !~ /^\s*$/) {
 4460:         $target = qq{target="$target"};
 4461:     } else {
 4462:         $target = '';
 4463:     }
 4464:     $title = &mt($title);
 4465:     $linktext = &mt($linktext);
 4466:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4467: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4468: 
 4469: }
 4470: 
 4471: # ===================================================== Display a student photo
 4472: 
 4473: 
 4474: sub student_image_tag {
 4475:     my ($domain,$user)=@_;
 4476:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4477:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4478: 	return '<img src="'.$imgsrc.'" align="right" />';
 4479:     } else {
 4480: 	return '';
 4481:     }
 4482: }
 4483: 
 4484: =pod
 4485: 
 4486: =back
 4487: 
 4488: =head1 Access .tab File Data
 4489: 
 4490: =over 4
 4491: 
 4492: =item * &languageids() 
 4493: 
 4494: returns list of all language ids
 4495: 
 4496: =cut
 4497: 
 4498: sub languageids {
 4499:     return sort(keys(%language));
 4500: }
 4501: 
 4502: =pod
 4503: 
 4504: =item * &languagedescription() 
 4505: 
 4506: returns description of a specified language id
 4507: 
 4508: =cut
 4509: 
 4510: sub languagedescription {
 4511:     my $code=shift;
 4512:     return  ($supported_language{$code}?'* ':'').
 4513:             $language{$code}.
 4514: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4515: }
 4516: 
 4517: =pod
 4518: 
 4519: =item * &plainlanguagedescription
 4520: 
 4521: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4522: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4523: 
 4524: =cut
 4525: 
 4526: sub plainlanguagedescription {
 4527:     my $code=shift;
 4528:     return $language{$code};
 4529: }
 4530: 
 4531: =pod
 4532: 
 4533: =item * &supportedlanguagecode
 4534: 
 4535: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4536: code.
 4537: 
 4538: =cut
 4539: 
 4540: sub supportedlanguagecode {
 4541:     my $code=shift;
 4542:     return $supported_language{$code};
 4543: }
 4544: 
 4545: =pod
 4546: 
 4547: =item * &latexlanguage()
 4548: 
 4549: Given a language key code returns the correspondnig language to use
 4550: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4551: is no supported hyphenation for the language code.
 4552: 
 4553: =cut
 4554: 
 4555: sub latexlanguage {
 4556:     my $code = shift;
 4557:     return $latex_language{$code};
 4558: }
 4559: 
 4560: =pod
 4561: 
 4562: =item * &latexhyphenation()
 4563: 
 4564: Same as above but what's supplied is the language as it might be stored
 4565: in the metadata.
 4566: 
 4567: =cut
 4568: 
 4569: sub latexhyphenation {
 4570:     my $key = shift;
 4571:     return $latex_language_bykey{$key};
 4572: }
 4573: 
 4574: =pod
 4575: 
 4576: =item * &copyrightids() 
 4577: 
 4578: returns list of all copyrights
 4579: 
 4580: =cut
 4581: 
 4582: sub copyrightids {
 4583:     return sort(keys(%cprtag));
 4584: }
 4585: 
 4586: =pod
 4587: 
 4588: =item * &copyrightdescription() 
 4589: 
 4590: returns description of a specified copyright id
 4591: 
 4592: =cut
 4593: 
 4594: sub copyrightdescription {
 4595:     return &mt($cprtag{shift(@_)});
 4596: }
 4597: 
 4598: =pod
 4599: 
 4600: =item * &source_copyrightids() 
 4601: 
 4602: returns list of all source copyrights
 4603: 
 4604: =cut
 4605: 
 4606: sub source_copyrightids {
 4607:     return sort(keys(%scprtag));
 4608: }
 4609: 
 4610: =pod
 4611: 
 4612: =item * &source_copyrightdescription() 
 4613: 
 4614: returns description of a specified source copyright id
 4615: 
 4616: =cut
 4617: 
 4618: sub source_copyrightdescription {
 4619:     return &mt($scprtag{shift(@_)});
 4620: }
 4621: 
 4622: =pod
 4623: 
 4624: =item * &filecategories() 
 4625: 
 4626: returns list of all file categories
 4627: 
 4628: =cut
 4629: 
 4630: sub filecategories {
 4631:     return sort(keys(%category_extensions));
 4632: }
 4633: 
 4634: =pod
 4635: 
 4636: =item * &filecategorytypes() 
 4637: 
 4638: returns list of file types belonging to a given file
 4639: category
 4640: 
 4641: =cut
 4642: 
 4643: sub filecategorytypes {
 4644:     my ($cat) = @_;
 4645:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4646:         return @{$category_extensions{lc($cat)}};
 4647:     } else {
 4648:         return ();
 4649:     }
 4650: }
 4651: 
 4652: =pod
 4653: 
 4654: =item * &fileembstyle() 
 4655: 
 4656: returns embedding style for a specified file type
 4657: 
 4658: =cut
 4659: 
 4660: sub fileembstyle {
 4661:     return $fe{lc(shift(@_))};
 4662: }
 4663: 
 4664: sub filemimetype {
 4665:     return $fm{lc(shift(@_))};
 4666: }
 4667: 
 4668: 
 4669: sub filecategoryselect {
 4670:     my ($name,$value)=@_;
 4671:     return &select_form($value,$name,
 4672:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4673: }
 4674: 
 4675: =pod
 4676: 
 4677: =item * &filedescription() 
 4678: 
 4679: returns description for a specified file type
 4680: 
 4681: =cut
 4682: 
 4683: sub filedescription {
 4684:     my $file_description = $fd{lc(shift())};
 4685:     $file_description =~ s:([\[\]]):~$1:g;
 4686:     return &mt($file_description);
 4687: }
 4688: 
 4689: =pod
 4690: 
 4691: =item * &filedescriptionex() 
 4692: 
 4693: returns description for a specified file type with
 4694: extra formatting
 4695: 
 4696: =cut
 4697: 
 4698: sub filedescriptionex {
 4699:     my $ex=shift;
 4700:     my $file_description = $fd{lc($ex)};
 4701:     $file_description =~ s:([\[\]]):~$1:g;
 4702:     return '.'.$ex.' '.&mt($file_description);
 4703: }
 4704: 
 4705: # End of .tab access
 4706: =pod
 4707: 
 4708: =back
 4709: 
 4710: =cut
 4711: 
 4712: # ------------------------------------------------------------------ File Types
 4713: sub fileextensions {
 4714:     return sort(keys(%fe));
 4715: }
 4716: 
 4717: # ----------------------------------------------------------- Display Languages
 4718: # returns a hash with all desired display languages
 4719: #
 4720: 
 4721: sub display_languages {
 4722:     my %languages=();
 4723:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4724: 	$languages{$lang}=1;
 4725:     }
 4726:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4727:     if ($env{'form.displaylanguage'}) {
 4728: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4729: 	    $languages{$lang}=1;
 4730:         }
 4731:     }
 4732:     return %languages;
 4733: }
 4734: 
 4735: sub languages {
 4736:     my ($possible_langs) = @_;
 4737:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4738:     if (!ref($possible_langs)) {
 4739: 	if( wantarray ) {
 4740: 	    return @preferred_langs;
 4741: 	} else {
 4742: 	    return $preferred_langs[0];
 4743: 	}
 4744:     }
 4745:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4746:     my @preferred_possibilities;
 4747:     foreach my $preferred_lang (@preferred_langs) {
 4748: 	if (exists($possibilities{$preferred_lang})) {
 4749: 	    push(@preferred_possibilities, $preferred_lang);
 4750: 	}
 4751:     }
 4752:     if( wantarray ) {
 4753: 	return @preferred_possibilities;
 4754:     }
 4755:     return $preferred_possibilities[0];
 4756: }
 4757: 
 4758: sub user_lang {
 4759:     my ($touname,$toudom,$fromcid) = @_;
 4760:     my @userlangs;
 4761:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4762:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4763:                     $env{'course.'.$fromcid.'.languages'}));
 4764:     } else {
 4765:         my %langhash = &getlangs($touname,$toudom);
 4766:         if ($langhash{'languages'} ne '') {
 4767:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4768:         } else {
 4769:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4770:             if ($domdefs{'lang_def'} ne '') {
 4771:                 @userlangs = ($domdefs{'lang_def'});
 4772:             }
 4773:         }
 4774:     }
 4775:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4776:     my $user_lh = Apache::localize->get_handle(@languages);
 4777:     return $user_lh;
 4778: }
 4779: 
 4780: 
 4781: ###############################################################
 4782: ##               Student Answer Attempts                     ##
 4783: ###############################################################
 4784: 
 4785: =pod
 4786: 
 4787: =head1 Alternate Problem Views
 4788: 
 4789: =over 4
 4790: 
 4791: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4792:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4793: 
 4794: Return string with previous attempt on problem. Arguments:
 4795: 
 4796: =over 4
 4797: 
 4798: =item * $symb: Problem, including path
 4799: 
 4800: =item * $username: username of the desired student
 4801: 
 4802: =item * $domain: domain of the desired student
 4803: 
 4804: =item * $course: Course ID
 4805: 
 4806: =item * $getattempt: Leave blank for all attempts, otherwise put
 4807:     something
 4808: 
 4809: =item * $regexp: if string matches this regexp, the string will be
 4810:     sent to $gradesub
 4811: 
 4812: =item * $gradesub: routine that processes the string if it matches $regexp
 4813: 
 4814: =item * $usec: section of the desired student
 4815: 
 4816: =item * $identifier: counter for student (multiple students one problem) or 
 4817:     problem (one student; whole sequence).
 4818: 
 4819: =back
 4820: 
 4821: The output string is a table containing all desired attempts, if any.
 4822: 
 4823: =cut
 4824: 
 4825: sub get_previous_attempt {
 4826:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4827:   my $prevattempts='';
 4828:   no strict 'refs';
 4829:   if ($symb) {
 4830:     my (%returnhash)=
 4831:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4832:     if ($returnhash{'version'}) {
 4833:       my %lasthash=();
 4834:       my $version;
 4835:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4836:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4837:             if ($key =~ /\.rawrndseed$/) {
 4838:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4839:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4840:             } else {
 4841:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4842:             }
 4843:         }
 4844:       }
 4845:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4846:       $prevattempts.='<th>'.&mt('History').'</th>';
 4847:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4848:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4849:       foreach my $key (sort(keys(%lasthash))) {
 4850: 	my ($ign,@parts) = split(/\./,$key);
 4851: 	if ($#parts > 0) {
 4852: 	  my $data=$parts[-1];
 4853:           next if ($data eq 'foilorder');
 4854: 	  pop(@parts);
 4855:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4856:           if ($data eq 'type') {
 4857:               unless ($showsurv) {
 4858:                   my $id = join(',',@parts);
 4859:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4860:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4861:                       $lasthidden{$ign.'.'.$id} = 1;
 4862:                   }
 4863:               }
 4864:               if ($identifier ne '') {
 4865:                   my $id = join(',',@parts);
 4866:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4867:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4868:                       $hidestatus{$ign.'.'.$id} = 1;
 4869:                   }
 4870:               }
 4871:           } elsif ($data eq 'regrader') {
 4872:               if (($identifier ne '') && (@parts)) {
 4873:                   my $id = join(',',@parts);
 4874:                   $regraded{$ign.'.'.$id} = 1;
 4875:               }
 4876:           } 
 4877: 	} else {
 4878: 	  if ($#parts == 0) {
 4879: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4880: 	  } else {
 4881: 	    $prevattempts.='<th>'.$ign.'</th>';
 4882: 	  }
 4883: 	}
 4884:       }
 4885:       $prevattempts.=&end_data_table_header_row();
 4886:       if ($getattempt eq '') {
 4887:         my (%solved,%resets,%probstatus);
 4888:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4889:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4890:                 foreach my $id (keys(%regraded)) {
 4891:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4892:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4893:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4894:                         push(@{$resets{$id}},$version);
 4895:                     }
 4896:                 }
 4897:             }
 4898:         }
 4899: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4900:             my (@hidden,@unsolved);
 4901:             if (%typeparts) {
 4902:                 foreach my $id (keys(%typeparts)) {
 4903:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4904:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4905:                         push(@hidden,$id);
 4906:                     } elsif ($identifier ne '') {
 4907:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4908:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4909:                                 ($hidestatus{$id})) {
 4910:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4911:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4912:                                 push(@{$solved{$id}},$version);
 4913:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4914:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4915:                                 my $skip;
 4916:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4917:                                     foreach my $reset (@{$resets{$id}}) {
 4918:                                         if ($reset > $solved{$id}[-1]) {
 4919:                                             $skip=1;
 4920:                                             last;
 4921:                                         }
 4922:                                     }
 4923:                                 }
 4924:                                 unless ($skip) {
 4925:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4926:                                     push(@unsolved,$partslist);
 4927:                                 }
 4928:                             }
 4929:                         }
 4930:                     }
 4931:                 }
 4932:             }
 4933:             $prevattempts.=&start_data_table_row().
 4934:                            '<td>'.&mt('Transaction [_1]',$version);
 4935:             if (@unsolved) {
 4936:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4937:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4938:                                  &mt('Hide').'</label></span>';
 4939:             }
 4940:             $prevattempts .= '</td>';
 4941:             if (@hidden) {
 4942:                 foreach my $key (sort(keys(%lasthash))) {
 4943:                     next if ($key =~ /\.foilorder$/);
 4944:                     my $hide;
 4945:                     foreach my $id (@hidden) {
 4946:                         if ($key =~ /^\Q$id\E/) {
 4947:                             $hide = 1;
 4948:                             last;
 4949:                         }
 4950:                     }
 4951:                     if ($hide) {
 4952:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4953:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4954:                             my $value = &format_previous_attempt_value($key,
 4955:                                              $returnhash{$version.':'.$key});
 4956:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4957:                         } else {
 4958:                             $prevattempts.='<td>&nbsp;</td>';
 4959:                         }
 4960:                     } else {
 4961:                         if ($key =~ /\./) {
 4962:                             my $value = $returnhash{$version.':'.$key};
 4963:                             if ($key =~ /\.rndseed$/) {
 4964:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4965:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4966:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4967:                                 }
 4968:                             }
 4969:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4970:                                            '&nbsp;</td>';
 4971:                         } else {
 4972:                             $prevattempts.='<td>&nbsp;</td>';
 4973:                         }
 4974:                     }
 4975:                 }
 4976:             } else {
 4977: 	        foreach my $key (sort(keys(%lasthash))) {
 4978:                     next if ($key =~ /\.foilorder$/);
 4979:                     my $value = $returnhash{$version.':'.$key};
 4980:                     if ($key =~ /\.rndseed$/) {
 4981:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4982:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4983:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4984:                         }
 4985:                     }
 4986:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4987:                                    '&nbsp;</td>';
 4988: 	        }
 4989:             }
 4990: 	    $prevattempts.=&end_data_table_row();
 4991: 	 }
 4992:       }
 4993:       my @currhidden = keys(%lasthidden);
 4994:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4995:       foreach my $key (sort(keys(%lasthash))) {
 4996:           next if ($key =~ /\.foilorder$/);
 4997:           if (%typeparts) {
 4998:               my $hidden;
 4999:               foreach my $id (@currhidden) {
 5000:                   if ($key =~ /^\Q$id\E/) {
 5001:                       $hidden = 1;
 5002:                       last;
 5003:                   }
 5004:               }
 5005:               if ($hidden) {
 5006:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 5007:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 5008:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5009:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5010:                           $value = &$gradesub($value);
 5011:                       }
 5012:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 5013:                   } else {
 5014:                       $prevattempts.='<td>&nbsp;</td>';
 5015:                   }
 5016:               } else {
 5017:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5018:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5019:                       $value = &$gradesub($value);
 5020:                   }
 5021:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5022:               }
 5023:           } else {
 5024: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 5025: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 5026:                   $value = &$gradesub($value);
 5027:               }
 5028: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 5029:           }
 5030:       }
 5031:       $prevattempts.= &end_data_table_row().&end_data_table();
 5032:     } else {
 5033:       my $msg;
 5034:       if ($symb =~ /ext\.tool$/) {
 5035:           $msg = &mt('No grade passed back.');
 5036:       } else {
 5037:           $msg = &mt('Nothing submitted - no attempts.');
 5038:       }
 5039:       $prevattempts=
 5040: 	  &start_data_table().&start_data_table_row().
 5041: 	  '<td>'.$msg.'</td>'.
 5042: 	  &end_data_table_row().&end_data_table();
 5043:     }
 5044:   } else {
 5045:     $prevattempts=
 5046: 	  &start_data_table().&start_data_table_row().
 5047: 	  '<td>'.&mt('No data.').'</td>'.
 5048: 	  &end_data_table_row().&end_data_table();
 5049:   }
 5050: }
 5051: 
 5052: sub format_previous_attempt_value {
 5053:     my ($key,$value) = @_;
 5054:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 5055:         $value = &Apache::lonlocal::locallocaltime($value);
 5056:     } elsif (ref($value) eq 'ARRAY') {
 5057:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 5058:     } elsif ($key =~ /answerstring$/) {
 5059:         my %answers = &Apache::lonnet::str2hash($value);
 5060:         my @answer = %answers;
 5061:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 5062:         my @anskeys = sort(keys(%answers));
 5063:         if (@anskeys == 1) {
 5064:             my $answer = $answers{$anskeys[0]};
 5065:             if ($answer =~ m{\0}) {
 5066:                 $answer =~ s{\0}{,}g;
 5067:             }
 5068:             my $tag_internal_answer_name = 'INTERNAL';
 5069:             if ($anskeys[0] eq $tag_internal_answer_name) {
 5070:                 $value = $answer; 
 5071:             } else {
 5072:                 $value = $anskeys[0].'='.$answer;
 5073:             }
 5074:         } else {
 5075:             foreach my $ans (@anskeys) {
 5076:                 my $answer = $answers{$ans};
 5077:                 if ($answer =~ m{\0}) {
 5078:                     $answer =~ s{\0}{,}g;
 5079:                 }
 5080:                 $value .=  $ans.'='.$answer.'<br />';;
 5081:             } 
 5082:         }
 5083:     } else {
 5084:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 5085:     }
 5086:     return $value;
 5087: }
 5088: 
 5089: 
 5090: sub relative_to_absolute {
 5091:     my ($url,$output)=@_;
 5092:     my $parser=HTML::TokeParser->new(\$output);
 5093:     my $token;
 5094:     my $thisdir=$url;
 5095:     my @rlinks=();
 5096:     while ($token=$parser->get_token) {
 5097: 	if ($token->[0] eq 'S') {
 5098: 	    if ($token->[1] eq 'a') {
 5099: 		if ($token->[2]->{'href'}) {
 5100: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 5101: 		}
 5102: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 5103: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 5104: 	    } elsif ($token->[1] eq 'base') {
 5105: 		$thisdir=$token->[2]->{'href'};
 5106: 	    }
 5107: 	}
 5108:     }
 5109:     $thisdir=~s-/[^/]*$--;
 5110:     foreach my $link (@rlinks) {
 5111: 	unless (($link=~/^https?\:\/\//i) ||
 5112: 		($link=~/^\//) ||
 5113: 		($link=~/^javascript:/i) ||
 5114: 		($link=~/^mailto:/i) ||
 5115: 		($link=~/^\#/)) {
 5116: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 5117: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 5118: 	}
 5119:     }
 5120: # -------------------------------------------------- Deal with Applet codebases
 5121:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 5122:     return $output;
 5123: }
 5124: 
 5125: =pod
 5126: 
 5127: =item * &get_student_view()
 5128: 
 5129: show a snapshot of what student was looking at
 5130: 
 5131: =cut
 5132: 
 5133: sub get_student_view {
 5134:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 5135:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5136:   my (%form);
 5137:   my @elements=('symb','courseid','domain','username');
 5138:   foreach my $element (@elements) {
 5139:       $form{'grade_'.$element}=eval '$'.$element #'
 5140:   }
 5141:   if (defined($moreenv)) {
 5142:       %form=(%form,%{$moreenv});
 5143:   }
 5144:   if (defined($target)) { $form{'grade_target'} = $target; }
 5145:   $feedurl=&Apache::lonnet::clutter($feedurl);
 5146:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
 5147:       $feedurl =~ s{^/adm/wrapper}{};
 5148:   }
 5149:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 5150:   $userview=~s/\<body[^\>]*\>//gi;
 5151:   $userview=~s/\<\/body\>//gi;
 5152:   $userview=~s/\<html\>//gi;
 5153:   $userview=~s/\<\/html\>//gi;
 5154:   $userview=~s/\<head\>//gi;
 5155:   $userview=~s/\<\/head\>//gi;
 5156:   $userview=~s/action\s*\=/would_be_action\=/gi;
 5157:   $userview=&relative_to_absolute($feedurl,$userview);
 5158:   if (wantarray) {
 5159:      return ($userview,$response);
 5160:   } else {
 5161:      return $userview;
 5162:   }
 5163: }
 5164: 
 5165: sub get_student_view_with_retries {
 5166:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 5167: 
 5168:     my $ok = 0;                 # True if we got a good response.
 5169:     my $content;
 5170:     my $response;
 5171: 
 5172:     # Try to get the student_view done. within the retries count:
 5173:     
 5174:     do {
 5175:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 5176:          $ok      = $response->is_success;
 5177:          if (!$ok) {
 5178:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 5179:          }
 5180:          $retries--;
 5181:     } while (!$ok && ($retries > 0));
 5182:     
 5183:     if (!$ok) {
 5184:        $content = '';          # On error return an empty content.
 5185:     }
 5186:     if (wantarray) {
 5187:        return ($content, $response);
 5188:     } else {
 5189:        return $content;
 5190:     }
 5191: }
 5192: 
 5193: sub css_links {
 5194:     my ($currsymb,$level) = @_;
 5195:     my ($links,@symbs,%cssrefs,%httpref);
 5196:     if ($level eq 'map') {
 5197:         my $navmap = Apache::lonnavmaps::navmap->new();
 5198:         if (ref($navmap)) {
 5199:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 5200:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 5201:             foreach my $res (@resources) {
 5202:                 if (ref($res) && $res->symb()) {
 5203:                     push(@symbs,$res->symb());
 5204:                 }
 5205:             }
 5206:         }
 5207:     } else {
 5208:         @symbs = ($currsymb);
 5209:     }
 5210:     foreach my $symb (@symbs) {
 5211:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 5212:         if ($css_href =~ /\S/) {
 5213:             unless ($css_href =~ m{https?://}) {
 5214:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 5215:                 my $proburl =  &Apache::lonnet::clutter($url);
 5216:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 5217:                 unless ($css_href =~ m{^/}) {
 5218:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 5219:                 }
 5220:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 5221:                     unless (($httpref{'httpref.'.$css_href}) ||
 5222:                             (&Apache::lonnet::is_on_map($css_href))) {
 5223:                         my $thisurl = $proburl;
 5224:                         if ($env{'httpref.'.$proburl}) {
 5225:                             $thisurl = $env{'httpref.'.$proburl};
 5226:                         }
 5227:                         $httpref{'httpref.'.$css_href} = $thisurl;
 5228:                     }
 5229:                 }
 5230:             }
 5231:             $cssrefs{$css_href} = 1;
 5232:         }
 5233:     }
 5234:     if (keys(%httpref)) {
 5235:         &Apache::lonnet::appenv(\%httpref);
 5236:     }
 5237:     if (keys(%cssrefs)) {
 5238:         foreach my $css_href (keys(%cssrefs)) {
 5239:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 5240:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 5241:         }
 5242:     }
 5243:     return $links;
 5244: }
 5245: 
 5246: =pod
 5247: 
 5248: =item * &get_student_answers() 
 5249: 
 5250: show a snapshot of how student was answering problem
 5251: 
 5252: =cut
 5253: 
 5254: sub get_student_answers {
 5255:   my ($symb,$username,$domain,$courseid,%form) = @_;
 5256:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 5257:   my (%moreenv);
 5258:   my @elements=('symb','courseid','domain','username');
 5259:   foreach my $element (@elements) {
 5260:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 5261:   }
 5262:   $moreenv{'grade_target'}='answer';
 5263:   %moreenv=(%form,%moreenv);
 5264:   $feedurl = &Apache::lonnet::clutter($feedurl);
 5265:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 5266:   return $userview;
 5267: }
 5268: 
 5269: =pod
 5270: 
 5271: =item * &submlink()
 5272: 
 5273: Inputs: $text $uname $udom $symb $target
 5274: 
 5275: Returns: A link to grades.pm such as to see the SUBM view of a student
 5276: 
 5277: =cut
 5278: 
 5279: ###############################################
 5280: sub submlink {
 5281:     my ($text,$uname,$udom,$symb,$target)=@_;
 5282:     if (!($uname && $udom)) {
 5283: 	(my $cursymb, my $courseid,$udom,$uname)=
 5284: 	    &Apache::lonnet::whichuser($symb);
 5285: 	if (!$symb) { $symb=$cursymb; }
 5286:     }
 5287:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5288:     $symb=&escape($symb);
 5289:     if ($target) { $target=" target=\"$target\""; }
 5290:     return
 5291:         '<a href="/adm/grades?command=submission'.
 5292:         '&amp;symb='.$symb.
 5293:         '&amp;student='.$uname.
 5294:         '&amp;userdom='.$udom.'"'.
 5295:         $target.'>'.$text.'</a>';
 5296: }
 5297: ##############################################
 5298: 
 5299: =pod
 5300: 
 5301: =item * &pgrdlink()
 5302: 
 5303: Inputs: $text $uname $udom $symb $target
 5304: 
 5305: Returns: A link to grades.pm such as to see the PGRD view of a student
 5306: 
 5307: =cut
 5308: 
 5309: ###############################################
 5310: sub pgrdlink {
 5311:     my $link=&submlink(@_);
 5312:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 5313:     return $link;
 5314: }
 5315: ##############################################
 5316: 
 5317: =pod
 5318: 
 5319: =item * &pprmlink()
 5320: 
 5321: Inputs: $text $uname $udom $symb $target
 5322: 
 5323: Returns: A link to parmset.pm such as to see the PPRM view of a
 5324: student and a specific resource
 5325: 
 5326: =cut
 5327: 
 5328: ###############################################
 5329: sub pprmlink {
 5330:     my ($text,$uname,$udom,$symb,$target)=@_;
 5331:     if (!($uname && $udom)) {
 5332: 	(my $cursymb, my $courseid,$udom,$uname)=
 5333: 	    &Apache::lonnet::whichuser($symb);
 5334: 	if (!$symb) { $symb=$cursymb; }
 5335:     }
 5336:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 5337:     $symb=&escape($symb);
 5338:     if ($target) { $target="target=\"$target\""; }
 5339:     return '<a href="/adm/parmset?command=set&amp;'.
 5340: 	'symb='.$symb.'&amp;uname='.$uname.
 5341: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 5342: }
 5343: ##############################################
 5344: 
 5345: =pod
 5346: 
 5347: =back
 5348: 
 5349: =cut
 5350: 
 5351: ###############################################
 5352: 
 5353: 
 5354: sub timehash {
 5355:     my ($thistime) = @_;
 5356:     my $timezone = &Apache::lonlocal::gettimezone();
 5357:     my $dt = DateTime->from_epoch(epoch => $thistime)
 5358:                      ->set_time_zone($timezone);
 5359:     my $wday = $dt->day_of_week();
 5360:     if ($wday == 7) { $wday = 0; }
 5361:     return ( 'second' => $dt->second(),
 5362:              'minute' => $dt->minute(),
 5363:              'hour'   => $dt->hour(),
 5364:              'day'     => $dt->day_of_month(),
 5365:              'month'   => $dt->month(),
 5366:              'year'    => $dt->year(),
 5367:              'weekday' => $wday,
 5368:              'dayyear' => $dt->day_of_year(),
 5369:              'dlsav'   => $dt->is_dst() );
 5370: }
 5371: 
 5372: sub utc_string {
 5373:     my ($date)=@_;
 5374:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 5375: }
 5376: 
 5377: sub maketime {
 5378:     my %th=@_;
 5379:     my ($epoch_time,$timezone,$dt);
 5380:     $timezone = &Apache::lonlocal::gettimezone();
 5381:     eval {
 5382:         $dt = DateTime->new( year   => $th{'year'},
 5383:                              month  => $th{'month'},
 5384:                              day    => $th{'day'},
 5385:                              hour   => $th{'hour'},
 5386:                              minute => $th{'minute'},
 5387:                              second => $th{'second'},
 5388:                              time_zone => $timezone,
 5389:                          );
 5390:     };
 5391:     if (!$@) {
 5392:         $epoch_time = $dt->epoch;
 5393:         if ($epoch_time) {
 5394:             return $epoch_time;
 5395:         }
 5396:     }
 5397:     return POSIX::mktime(
 5398:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 5399:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 5400: }
 5401: 
 5402: #########################################
 5403: 
 5404: sub findallcourses {
 5405:     my ($roles,$uname,$udom) = @_;
 5406:     my %roles;
 5407:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 5408:     my %courses;
 5409:     my $now=time;
 5410:     if (!defined($uname)) {
 5411:         $uname = $env{'user.name'};
 5412:     }
 5413:     if (!defined($udom)) {
 5414:         $udom = $env{'user.domain'};
 5415:     }
 5416:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 5417:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 5418:         if (!%roles) {
 5419:             %roles = (
 5420:                        cc => 1,
 5421:                        co => 1,
 5422:                        in => 1,
 5423:                        ep => 1,
 5424:                        ta => 1,
 5425:                        cr => 1,
 5426:                        st => 1,
 5427:              );
 5428:         }
 5429:         foreach my $entry (keys(%roleshash)) {
 5430:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 5431:             if ($trole =~ /^cr/) { 
 5432:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 5433:             } else {
 5434:                 next if (!exists($roles{$trole}));
 5435:             }
 5436:             if ($tend) {
 5437:                 next if ($tend < $now);
 5438:             }
 5439:             if ($tstart) {
 5440:                 next if ($tstart > $now);
 5441:             }
 5442:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 5443:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 5444:             my $value = $trole.'/'.$cdom.'/';
 5445:             if ($secpart eq '') {
 5446:                 ($cnum,$role) = split(/_/,$cnumpart); 
 5447:                 $sec = 'none';
 5448:                 $value .= $cnum.'/';
 5449:             } else {
 5450:                 $cnum = $cnumpart;
 5451:                 ($sec,$role) = split(/_/,$secpart);
 5452:                 $value .= $cnum.'/'.$sec;
 5453:             }
 5454:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5455:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5456:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5457:                 }
 5458:             } else {
 5459:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5460:             }
 5461:         }
 5462:     } else {
 5463:         foreach my $key (keys(%env)) {
 5464: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 5465:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 5466: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 5467: 	        next if ($role eq 'ca' || $role eq 'aa');
 5468: 	        next if (%roles && !exists($roles{$role}));
 5469: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 5470:                 my $active=1;
 5471:                 if ($starttime) {
 5472: 		    if ($now<$starttime) { $active=0; }
 5473:                 }
 5474:                 if ($endtime) {
 5475:                     if ($now>$endtime) { $active=0; }
 5476:                 }
 5477:                 if ($active) {
 5478:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 5479:                     if ($sec eq '') {
 5480:                         $sec = 'none';
 5481:                     } else {
 5482:                         $value .= $sec;
 5483:                     }
 5484:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 5485:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 5486:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 5487:                         }
 5488:                     } else {
 5489:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 5490:                     }
 5491:                 }
 5492:             }
 5493:         }
 5494:     }
 5495:     return %courses;
 5496: }
 5497: 
 5498: ###############################################
 5499: 
 5500: sub blockcheck {
 5501:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5502:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 5503:         my ($has_evb,$check_ipaccess);
 5504:         my $dom = $env{'user.domain'};
 5505:         if ($env{'request.course.id'}) {
 5506:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5507:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5508:             my $checkrole = "cm./$cdom/$cnum";
 5509:             my $sec = $env{'request.course.sec'};
 5510:             if ($sec ne '') {
 5511:                 $checkrole .= "/$sec";
 5512:             }
 5513:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 5514:                 ($env{'request.role'} !~ /^st/)) {
 5515:                 $has_evb = 1;
 5516:             }
 5517:             unless ($has_evb) {
 5518:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 5519:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 5520:                     if ($udom eq $cdom) {
 5521:                         $check_ipaccess = 1;
 5522:                     }
 5523:                 }
 5524:             }
 5525:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 5526:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 5527:             my $checkrole;
 5528:             if ($env{'request.role.domain'} eq '') {
 5529:                 $checkrole = "cm./$env{'user.domain'}/";
 5530:             } else {
 5531:                 $checkrole = "cm./$env{'request.role.domain'}/";
 5532:             }
 5533:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 5534:                 $has_evb = 1;
 5535:             }
 5536:         }
 5537:         unless ($has_evb || $check_ipaccess) {
 5538:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 5539:             if (($dom eq 'public') && ($activity eq 'port')) {
 5540:                 $dom = $udom;
 5541:             }
 5542:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 5543:                 $check_ipaccess = 1;
 5544:             } else {
 5545:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 5546:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 5547:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 5548:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 5549:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 5550:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 5551:                         $check_ipaccess = 1;
 5552:                     }
 5553:                 }
 5554:             }
 5555:         }
 5556:         if ($check_ipaccess) {
 5557:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 5558:             unless (defined($cached)) {
 5559:                 my %domconfig =
 5560:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 5561:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 5562:             }
 5563:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 5564:                 foreach my $id (keys(%{$ipaccessref})) {
 5565:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 5566:                         my $range = $ipaccessref->{$id}->{'ip'};
 5567:                         if ($range) {
 5568:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 5569:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 5570:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 5571:                                         return ('','','',$id,$dom);
 5572:                                         last;
 5573:                                     }
 5574:                                 }
 5575:                             }
 5576:                         }
 5577:                     }
 5578:                 }
 5579:             }
 5580:         }
 5581:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5582:             return ();
 5583:         }
 5584:     }
 5585:     if (defined($udom) && defined($uname)) {
 5586:         # If uname and udom are for a course, check for blocks in the course.
 5587:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 5588:             my ($startblock,$endblock,$triggerblock) =
 5589:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 5590:             return ($startblock,$endblock,$triggerblock);
 5591:         }
 5592:     } else {
 5593:         $udom = $env{'user.domain'};
 5594:         $uname = $env{'user.name'};
 5595:     }
 5596: 
 5597:     my $startblock = 0;
 5598:     my $endblock = 0;
 5599:     my $triggerblock = '';
 5600:     my %live_courses;
 5601:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 5602:         %live_courses = &findallcourses(undef,$uname,$udom);
 5603:     }
 5604: 
 5605:     # If uname is for a user, and activity is course-specific, i.e.,
 5606:     # boards, chat or groups, check for blocking in current course only.
 5607: 
 5608:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5609:          $activity eq 'groups' || $activity eq 'printout' ||
 5610:          $activity eq 'search' || $activity eq 'reinit' ||
 5611:          $activity eq 'alert') &&
 5612:         ($env{'request.course.id'})) {
 5613:         foreach my $key (keys(%live_courses)) {
 5614:             if ($key ne $env{'request.course.id'}) {
 5615:                 delete($live_courses{$key});
 5616:             }
 5617:         }
 5618:     }
 5619: 
 5620:     my $otheruser = 0;
 5621:     my %own_courses;
 5622:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5623:         # Resource belongs to user other than current user.
 5624:         $otheruser = 1;
 5625:         # Gather courses for current user
 5626:         %own_courses = 
 5627:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5628:     }
 5629: 
 5630:     # Gather active course roles - course coordinator, instructor, 
 5631:     # exam proctor, ta, student, or custom role.
 5632: 
 5633:     foreach my $course (keys(%live_courses)) {
 5634:         my ($cdom,$cnum);
 5635:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5636:             $cdom = $env{'course.'.$course.'.domain'};
 5637:             $cnum = $env{'course.'.$course.'.num'};
 5638:         } else {
 5639:             ($cdom,$cnum) = split(/_/,$course); 
 5640:         }
 5641:         my $no_ownblock = 0;
 5642:         my $no_userblock = 0;
 5643:         if ($otheruser && $activity ne 'com') {
 5644:             # Check if current user has 'evb' priv for this
 5645:             if (defined($own_courses{$course})) {
 5646:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5647:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5648:                     if ($sec ne 'none') {
 5649:                         $checkrole .= '/'.$sec;
 5650:                     }
 5651:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5652:                         $no_ownblock = 1;
 5653:                         last;
 5654:                     }
 5655:                 }
 5656:             }
 5657:             # if they have 'evb' priv and are currently not playing student
 5658:             next if (($no_ownblock) &&
 5659:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5660:         }
 5661:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5662:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5663:             if ($sec ne 'none') {
 5664:                 $checkrole .= '/'.$sec;
 5665:             }
 5666:             if ($otheruser) {
 5667:                 # Resource belongs to user other than current user.
 5668:                 # Assemble privs for that user, and check for 'evb' priv.
 5669:                 my (%allroles,%userroles);
 5670:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5671:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5672:                         my ($trole,$tdom,$tnum,$tsec);
 5673:                         if ($entry =~ /^cr/) {
 5674:                             ($trole,$tdom,$tnum,$tsec) = 
 5675:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5676:                         } else {
 5677:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5678:                         }
 5679:                         my ($spec,$area,$trest);
 5680:                         $area = '/'.$tdom.'/'.$tnum;
 5681:                         $trest = $tnum;
 5682:                         if ($tsec ne '') {
 5683:                             $area .= '/'.$tsec;
 5684:                             $trest .= '/'.$tsec;
 5685:                         }
 5686:                         $spec = $trole.'.'.$area;
 5687:                         if ($trole =~ /^cr/) {
 5688:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5689:                                                               $tdom,$spec,$trest,$area);
 5690:                         } else {
 5691:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5692:                                                                 $tdom,$spec,$trest,$area);
 5693:                         }
 5694:                     }
 5695:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5696:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5697:                         if ($1) {
 5698:                             $no_userblock = 1;
 5699:                             last;
 5700:                         }
 5701:                     }
 5702:                 }
 5703:             } else {
 5704:                 # Resource belongs to current user
 5705:                 # Check for 'evb' priv via lonnet::allowed().
 5706:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5707:                     $no_ownblock = 1;
 5708:                     last;
 5709:                 }
 5710:             }
 5711:         }
 5712:         # if they have the evb priv and are currently not playing student
 5713:         next if (($no_ownblock) &&
 5714:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5715:         next if ($no_userblock);
 5716: 
 5717:         # Retrieve blocking times and identity of blocker for course
 5718:         # of specified user, unless user has 'evb' privilege.
 5719: 
 5720:         my ($start,$end,$trigger) = 
 5721:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5722:         if (($start != 0) && 
 5723:             (($startblock == 0) || ($startblock > $start))) {
 5724:             $startblock = $start;
 5725:             if ($trigger ne '') {
 5726:                 $triggerblock = $trigger;
 5727:             }
 5728:         }
 5729:         if (($end != 0)  &&
 5730:             (($endblock == 0) || ($endblock < $end))) {
 5731:             $endblock = $end;
 5732:             if ($trigger ne '') {
 5733:                 $triggerblock = $trigger;
 5734:             }
 5735:         }
 5736:     }
 5737:     return ($startblock,$endblock,$triggerblock);
 5738: }
 5739: 
 5740: sub get_blocks {
 5741:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5742:     my $startblock = 0;
 5743:     my $endblock = 0;
 5744:     my $triggerblock = '';
 5745:     my $course = $cdom.'_'.$cnum;
 5746:     $setters->{$course} = {};
 5747:     $setters->{$course}{'staff'} = [];
 5748:     $setters->{$course}{'times'} = [];
 5749:     $setters->{$course}{'triggers'} = [];
 5750:     my (@blockers,%triggered);
 5751:     my $now = time;
 5752:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5753:     if ($activity eq 'docs') {
 5754:         my ($blocked,$nosymbcache,$noenccheck);
 5755:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5756:             $blocked = 1;
 5757:             $nosymbcache = 1;
 5758:             $noenccheck = 1;
 5759:         }
 5760:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5761:         foreach my $block (@blockers) {
 5762:             if ($block =~ /^firstaccess____(.+)$/) {
 5763:                 my $item = $1;
 5764:                 my $type = 'map';
 5765:                 my $timersymb = $item;
 5766:                 if ($item eq 'course') {
 5767:                     $type = 'course';
 5768:                 } elsif ($item =~ /___\d+___/) {
 5769:                     $type = 'resource';
 5770:                 } else {
 5771:                     $timersymb = &Apache::lonnet::symbread($item);
 5772:                 }
 5773:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5774:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5775:                 $triggered{$block} = {
 5776:                                        start => $start,
 5777:                                        end   => $end,
 5778:                                        type  => $type,
 5779:                                      };
 5780:             }
 5781:         }
 5782:     } else {
 5783:         foreach my $block (keys(%commblocks)) {
 5784:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5785:                 my ($start,$end) = ($1,$2);
 5786:                 if ($start <= time && $end >= time) {
 5787:                     if (ref($commblocks{$block}) eq 'HASH') {
 5788:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5789:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5790:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5791:                                     push(@blockers,$block);
 5792:                                 }
 5793:                             }
 5794:                         }
 5795:                     }
 5796:                 }
 5797:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5798:                 my $item = $1;
 5799:                 my $timersymb = $item; 
 5800:                 my $type = 'map';
 5801:                 if ($item eq 'course') {
 5802:                     $type = 'course';
 5803:                 } elsif ($item =~ /___\d+___/) {
 5804:                     $type = 'resource';
 5805:                 } else {
 5806:                     $timersymb = &Apache::lonnet::symbread($item);
 5807:                 }
 5808:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5809:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5810:                 if ($start && $end) {
 5811:                     if (($start <= time) && ($end >= time)) {
 5812:                         if (ref($commblocks{$block}) eq 'HASH') {
 5813:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5814:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5815:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5816:                                         push(@blockers,$block);
 5817:                                         $triggered{$block} = {
 5818:                                                                start => $start,
 5819:                                                                end   => $end,
 5820:                                                                type  => $type,
 5821:                                                              };
 5822:                                     }
 5823:                                 }
 5824:                             }
 5825:                         }
 5826:                     }
 5827:                 }
 5828:             }
 5829:         }
 5830:     }
 5831:     foreach my $blocker (@blockers) {
 5832:         my ($staff_name,$staff_dom,$title,$blocks) =
 5833:             &parse_block_record($commblocks{$blocker});
 5834:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5835:         my ($start,$end,$triggertype);
 5836:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5837:             ($start,$end) = ($1,$2);
 5838:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5839:             $start = $triggered{$blocker}{'start'};
 5840:             $end = $triggered{$blocker}{'end'};
 5841:             $triggertype = $triggered{$blocker}{'type'};
 5842:         }
 5843:         if ($start) {
 5844:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5845:             if ($triggertype) {
 5846:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5847:             } else {
 5848:                 push(@{$$setters{$course}{'triggers'}},0);
 5849:             }
 5850:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5851:                 $startblock = $start;
 5852:                 if ($triggertype) {
 5853:                     $triggerblock = $blocker;
 5854:                 }
 5855:             }
 5856:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5857:                $endblock = $end;
 5858:                if ($triggertype) {
 5859:                    $triggerblock = $blocker;
 5860:                }
 5861:             }
 5862:         }
 5863:     }
 5864:     return ($startblock,$endblock,$triggerblock);
 5865: }
 5866: 
 5867: sub parse_block_record {
 5868:     my ($record) = @_;
 5869:     my ($setuname,$setudom,$title,$blocks);
 5870:     if (ref($record) eq 'HASH') {
 5871:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5872:         $title = &unescape($record->{'event'});
 5873:         $blocks = $record->{'blocks'};
 5874:     } else {
 5875:         my @data = split(/:/,$record,3);
 5876:         if (scalar(@data) eq 2) {
 5877:             $title = $data[1];
 5878:             ($setuname,$setudom) = split(/@/,$data[0]);
 5879:         } else {
 5880:             ($setuname,$setudom,$title) = @data;
 5881:         }
 5882:         $blocks = { 'com' => 'on' };
 5883:     }
 5884:     return ($setuname,$setudom,$title,$blocks);
 5885: }
 5886: 
 5887: sub blocking_status {
 5888:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5889:     my %setters;
 5890: 
 5891: # check for active blocking
 5892:     if ($clientip eq '') {
 5893:         $clientip = &Apache::lonnet::get_requestor_ip();
 5894:     }
 5895:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5896:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5897:     my $blocked = 0;
 5898:     if (($startblock && $endblock) || ($by_ip)) {
 5899:         $blocked = 1;
 5900:     }
 5901: 
 5902: # caller just wants to know whether a block is active
 5903:     if (!wantarray) { return $blocked; }
 5904: 
 5905: # build a link to a popup window containing the details
 5906:     my $querystring  = "?activity=$activity";
 5907: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5908:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5909:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5910:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5911:     } elsif ($activity eq 'docs') {
 5912:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5913:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5914:         if ($symb) {
 5915:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5916:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5917:         }
 5918:     }
 5919: 
 5920:     my $output .= <<'END_MYBLOCK';
 5921: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5922:     var options = "width=" + w + ",height=" + h + ",";
 5923:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5924:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5925:     var newWin = window.open(url, wdwName, options);
 5926:     newWin.focus();
 5927: }
 5928: END_MYBLOCK
 5929: 
 5930:     $output = Apache::lonhtmlcommon::scripttag($output);
 5931:   
 5932:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5933:     my $text = &mt('Communication Blocked');
 5934:     my $class = 'LC_comblock';
 5935:     if ($activity eq 'docs') {
 5936:         $text = &mt('Content Access Blocked');
 5937:         $class = '';
 5938:     } elsif ($activity eq 'printout') {
 5939:         $text = &mt('Printing Blocked');
 5940:     } elsif ($activity eq 'passwd') {
 5941:         $text = &mt('Password Changing Blocked');
 5942:     } elsif ($activity eq 'grades') {
 5943:         $text = &mt('Gradebook Blocked');
 5944:     } elsif ($activity eq 'search') {
 5945:         $text = &mt('Search Blocked');
 5946:     } elsif ($activity eq 'alert') {
 5947:         $text = &mt('Checking Critical Messages Blocked');
 5948:     } elsif ($activity eq 'reinit') {
 5949:         $text = &mt('Checking Course Update Blocked');
 5950:     } elsif ($activity eq 'about') {
 5951:         $text = &mt('Access to User Information Pages Blocked');
 5952:     } elsif ($activity eq 'wishlist') {
 5953:         $text = &mt('Access to Stored Links Blocked');
 5954:     } elsif ($activity eq 'annotate') {
 5955:         $text = &mt('Access to Annotations Blocked');
 5956:     }
 5957:     $output .= <<"END_BLOCK";
 5958: <div class='$class'>
 5959:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5960:   title='$text'>
 5961:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5962:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5963:   title='$text'>$text</a>
 5964: </div>
 5965: 
 5966: END_BLOCK
 5967: 
 5968:     return ($blocked, $output);
 5969: }
 5970: 
 5971: ###############################################
 5972: 
 5973: sub check_ip_acc {
 5974:     my ($acc,$clientip)=@_;
 5975:     &Apache::lonxml::debug("acc is $acc");
 5976:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5977:         return 1;
 5978:     }
 5979:     my ($ip,$allowed);
 5980:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5981:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5982:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5983:     } else {
 5984:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5985:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5986:     }
 5987: 
 5988:     my $name;
 5989:     my %access = (
 5990:                      allowfrom => 1,
 5991:                      denyfrom  => 0,
 5992:                  );
 5993:     my @allows;
 5994:     my @denies;
 5995:     foreach my $item (split(',',$acc)) {
 5996:         $item =~ s/^\s*//;
 5997:         $item =~ s/\s*$//;
 5998:         my $pattern;
 5999:         if ($item =~ /^\!(.+)$/) {
 6000:             push(@denies,$1);
 6001:         } else {
 6002:             push(@allows,$item);
 6003:         }
 6004:    }
 6005:    my $numdenies = scalar(@denies);
 6006:    my $numallows = scalar(@allows);
 6007:    my $count = 0;
 6008:    foreach my $pattern (@denies,@allows) {
 6009:         $count ++; 
 6010:         my $acctype = 'allowfrom';
 6011:         if ($count <= $numdenies) {
 6012:             $acctype = 'denyfrom';
 6013:         }
 6014:         if ($pattern =~ /\*$/) {
 6015:             #35.8.*
 6016:             $pattern=~s/\*//;
 6017:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6018:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 6019:             #35.8.3.[34-56]
 6020:             my $low=$2;
 6021:             my $high=$3;
 6022:             $pattern=$1;
 6023:             if ($ip =~ /^\Q$pattern\E/) {
 6024:                 my $last=(split(/\./,$ip))[3];
 6025:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 6026:             }
 6027:         } elsif ($pattern =~ /^\*/) {
 6028:             #*.msu.edu
 6029:             $pattern=~s/\*//;
 6030:             if (!defined($name)) {
 6031:                 use Socket;
 6032:                 my $netaddr=inet_aton($ip);
 6033:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6034:             }
 6035:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6036:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 6037:             #127.0.0.1
 6038:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 6039:         } else {
 6040:             #some.name.com
 6041:             if (!defined($name)) {
 6042:                 use Socket;
 6043:                 my $netaddr=inet_aton($ip);
 6044:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 6045:             }
 6046:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 6047:         }
 6048:         if ($allowed =~ /^(0|1)$/) { last; }
 6049:     }
 6050:     if ($allowed eq '') {
 6051:         if ($numdenies && !$numallows) {
 6052:             $allowed = 1;
 6053:         } else {
 6054:             $allowed = 0;
 6055:         }
 6056:     }
 6057:     return $allowed;
 6058: }
 6059: 
 6060: ###############################################
 6061: 
 6062: =pod
 6063: 
 6064: =head1 Domain Template Functions
 6065: 
 6066: =over 4
 6067: 
 6068: =item * &determinedomain()
 6069: 
 6070: Inputs: $domain (usually will be undef)
 6071: 
 6072: Returns: Determines which domain should be used for designs
 6073: 
 6074: =cut
 6075: 
 6076: ###############################################
 6077: sub determinedomain {
 6078:     my $domain=shift;
 6079:     if (! $domain) {
 6080:         # Determine domain if we have not been given one
 6081:         $domain = &Apache::lonnet::default_login_domain();
 6082:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 6083:         if ($env{'request.role.domain'}) { 
 6084:             $domain=$env{'request.role.domain'}; 
 6085:         }
 6086:     }
 6087:     return $domain;
 6088: }
 6089: ###############################################
 6090: 
 6091: sub devalidate_domconfig_cache {
 6092:     my ($udom)=@_;
 6093:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 6094: }
 6095: 
 6096: # ---------------------- Get domain configuration for a domain
 6097: sub get_domainconf {
 6098:     my ($udom) = @_;
 6099:     my $cachetime=1800;
 6100:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 6101:     if (defined($cached)) { return %{$result}; }
 6102: 
 6103:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 6104: 					     ['login','rolecolors','autoenroll'],$udom);
 6105:     my (%designhash,%legacy);
 6106:     if (keys(%domconfig) > 0) {
 6107:         if (ref($domconfig{'login'}) eq 'HASH') {
 6108:             if (keys(%{$domconfig{'login'}})) {
 6109:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 6110:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6111:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 6112:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6113:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 6114:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 6115:                                         if ($key eq 'loginvia') {
 6116:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 6117:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 6118:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 6119:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 6120: 
 6121:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 6122:                                                 } else {
 6123:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 6124:                                                 }
 6125:                                             }
 6126:                                         } elsif ($key eq 'headtag') {
 6127:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 6128:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 6129:                                             }
 6130:                                         }
 6131:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 6132:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 6133:                                         }
 6134:                                     }
 6135:                                 }
 6136:                             }
 6137:                         } elsif ($key eq 'saml') {
 6138:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 6139:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 6140:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 6141:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 6142:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 6143:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 6144:                                         }
 6145:                                     }
 6146:                                 }
 6147:                             }
 6148:                         } else {
 6149:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 6150:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 6151:                                     $domconfig{'login'}{$key}{$img};
 6152:                             }
 6153:                         }
 6154:                     } else {
 6155:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 6156:                     }
 6157:                 }
 6158:             } else {
 6159:                 $legacy{'login'} = 1;
 6160:             }
 6161:         } else {
 6162:             $legacy{'login'} = 1;
 6163:         }
 6164:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 6165:             if (keys(%{$domconfig{'rolecolors'}})) {
 6166:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 6167:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 6168:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 6169:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 6170:                         }
 6171:                     }
 6172:                 }
 6173:             } else {
 6174:                 $legacy{'rolecolors'} = 1;
 6175:             }
 6176:         } else {
 6177:             $legacy{'rolecolors'} = 1;
 6178:         }
 6179:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6180:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 6181:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 6182:             }
 6183:         }
 6184:         if (keys(%legacy) > 0) {
 6185:             my %legacyhash = &get_legacy_domconf($udom);
 6186:             foreach my $item (keys(%legacyhash)) {
 6187:                 if ($item =~ /^\Q$udom\E\.login/) {
 6188:                     if ($legacy{'login'}) { 
 6189:                         $designhash{$item} = $legacyhash{$item};
 6190:                     }
 6191:                 } else {
 6192:                     if ($legacy{'rolecolors'}) {
 6193:                         $designhash{$item} = $legacyhash{$item};
 6194:                     }
 6195:                 }
 6196:             }
 6197:         }
 6198:     } else {
 6199:         %designhash = &get_legacy_domconf($udom); 
 6200:     }
 6201:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 6202: 				  $cachetime);
 6203:     return %designhash;
 6204: }
 6205: 
 6206: sub get_legacy_domconf {
 6207:     my ($udom) = @_;
 6208:     my %legacyhash;
 6209:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 6210:     my $designfile =  $designdir.'/'.$udom.'.tab';
 6211:     if (-e $designfile) {
 6212:         if ( open (my $fh,'<',$designfile) ) {
 6213:             while (my $line = <$fh>) {
 6214:                 next if ($line =~ /^\#/);
 6215:                 chomp($line);
 6216:                 my ($key,$val)=(split(/\=/,$line));
 6217:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 6218:             }
 6219:             close($fh);
 6220:         }
 6221:     }
 6222:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 6223:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 6224:     }
 6225:     return %legacyhash;
 6226: }
 6227: 
 6228: =pod
 6229: 
 6230: =item * &domainlogo()
 6231: 
 6232: Inputs: $domain (usually will be undef)
 6233: 
 6234: Returns: A link to a domain logo, if the domain logo exists.
 6235: If the domain logo does not exist, a description of the domain.
 6236: 
 6237: =cut
 6238: 
 6239: ###############################################
 6240: sub domainlogo {
 6241:     my $domain = &determinedomain(shift);
 6242:     my %designhash = &get_domainconf($domain);    
 6243:     # See if there is a logo
 6244:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 6245:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 6246:         if ($imgsrc =~ m{^/(adm|res)/}) {
 6247: 	    if ($imgsrc =~ m{^/res/}) {
 6248: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 6249: 		&Apache::lonnet::repcopy($local_name);
 6250: 	    }
 6251: 	   $imgsrc = &lonhttpdurl($imgsrc);
 6252:         }
 6253:         my $alttext = $domain;
 6254:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 6255:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 6256:         }
 6257:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 6258:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 6259:         return &Apache::lonnet::domain($domain,'description');
 6260:     } else {
 6261:         return '';
 6262:     }
 6263: }
 6264: ##############################################
 6265: 
 6266: =pod
 6267: 
 6268: =item * &designparm()
 6269: 
 6270: Inputs: $which parameter; $domain (usually will be undef)
 6271: 
 6272: Returns: value of designparamter $which
 6273: 
 6274: =cut
 6275: 
 6276: 
 6277: ##############################################
 6278: sub designparm {
 6279:     my ($which,$domain)=@_;
 6280:     if (exists($env{'environment.color.'.$which})) {
 6281:         return $env{'environment.color.'.$which};
 6282:     }
 6283:     $domain=&determinedomain($domain);
 6284:     my %domdesign;
 6285:     unless ($domain eq 'public') {
 6286:         %domdesign = &get_domainconf($domain);
 6287:     }
 6288:     my $output;
 6289:     if ($domdesign{$domain.'.'.$which} ne '') {
 6290:         $output = $domdesign{$domain.'.'.$which};
 6291:     } else {
 6292:         $output = $defaultdesign{$which};
 6293:     }
 6294:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 6295:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 6296:         if ($output =~ m{^/(adm|res)/}) {
 6297:             if ($output =~ m{^/res/}) {
 6298:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 6299:                 &Apache::lonnet::repcopy($local_name);
 6300:             }
 6301:             $output = &lonhttpdurl($output);
 6302:         }
 6303:     }
 6304:     return $output;
 6305: }
 6306: 
 6307: ##############################################
 6308: =pod
 6309: 
 6310: =item * &authorspace()
 6311: 
 6312: Inputs: $url (usually will be undef).
 6313: 
 6314: Returns: Path to Authoring Space containing the resource or 
 6315:          directory being viewed (or for which action is being taken). 
 6316:          If $url is provided, and begins /priv/<domain>/<uname>
 6317:          the path will be that portion of the $context argument.
 6318:          Otherwise the path will be for the author space of the current
 6319:          user when the current role is author, or for that of the 
 6320:          co-author/assistant co-author space when the current role 
 6321:          is co-author or assistant co-author.
 6322: 
 6323: =cut
 6324: 
 6325: sub authorspace {
 6326:     my ($url) = @_;
 6327:     if ($url ne '') {
 6328:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 6329:            return $1;
 6330:         }
 6331:     }
 6332:     my $caname = '';
 6333:     my $cadom = '';
 6334:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 6335:         ($cadom,$caname) =
 6336:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 6337:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 6338:         $caname = $env{'user.name'};
 6339:         $cadom = $env{'user.domain'};
 6340:     }
 6341:     if (($caname ne '') && ($cadom ne '')) {
 6342:         return "/priv/$cadom/$caname/";
 6343:     }
 6344:     return;
 6345: }
 6346: 
 6347: ##############################################
 6348: =pod
 6349: 
 6350: =item * &head_subbox()
 6351: 
 6352: Inputs: $content (contains HTML code with page functions, etc.)
 6353: 
 6354: Returns: HTML div with $content
 6355:          To be included in page header
 6356: 
 6357: =cut
 6358: 
 6359: sub head_subbox {
 6360:     my ($content)=@_;
 6361:     my $output =
 6362:         '<div class="LC_head_subbox">'
 6363:        .$content
 6364:        .'</div>'
 6365: }
 6366: 
 6367: ##############################################
 6368: =pod
 6369: 
 6370: =item * &CSTR_pageheader()
 6371: 
 6372: Input: (optional) filename from which breadcrumb trail is built.
 6373:        In most cases no input as needed, as $env{'request.filename'}
 6374:        is appropriate for use in building the breadcrumb trail.
 6375:        frameset flag
 6376:        If page header is being requested for use in a frameset, then
 6377:        the second (option) argument -- frameset will be true, and
 6378:        the target attribute set for links should be target="_parent".
 6379:        If $title is supplied as the thitd arg, that will be used to 
 6380:        the left of the breadcrumbs tail for the current path.
 6381: 
 6382: Returns: HTML div with CSTR path and recent box
 6383:          To be included on Authoring Space pages
 6384: 
 6385: =cut
 6386: 
 6387: sub CSTR_pageheader {
 6388:     my ($trailfile,$frameset,$title) = @_;
 6389:     if ($trailfile eq '') {
 6390:         $trailfile = $env{'request.filename'};
 6391:     }
 6392: 
 6393: # this is for resources; directories have customtitle, and crumbs
 6394: # and select recent are created in lonpubdir.pm
 6395: 
 6396:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 6397:     my ($udom,$uname,$thisdisfn)=
 6398:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 6399:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 6400:     $formaction =~ s{/+}{/}g;
 6401: 
 6402:     my $parentpath = '';
 6403:     my $lastitem = '';
 6404:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 6405:         $parentpath = $1;
 6406:         $lastitem = $2;
 6407:     } else {
 6408:         $lastitem = $thisdisfn;
 6409:     }
 6410: 
 6411:     my $crsauthor;
 6412:     if (($env{'request.course.id'}) &&
 6413:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 6414:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 6415:         $crsauthor = 1;
 6416:         if ($title eq '') {
 6417:             $title = &mt('Course Authoring Space');
 6418:         }
 6419:     } elsif ($title eq '') {
 6420:         $title = &mt('Authoring Space');
 6421:     }
 6422: 
 6423:     my ($target,$crumbtarget) = (' target="_top"','_top');
 6424:     if ($frameset) {
 6425:         $target = ' target="_parent"';
 6426:         $crumbtarget = '_parent';
 6427:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
 6428:         $target = '';
 6429:         $crumbtarget = '';
 6430:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 6431:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 6432:         $crumbtarget = $env{'request.deeplink.target'};
 6433:     }
 6434: 
 6435:     my $output =
 6436:          '<div>'
 6437:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 6438:         .'<b>'.$title.'</b> '
 6439:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 6440:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 6441: 
 6442:     if ($lastitem) {
 6443:         $output .=
 6444:              '<span class="LC_filename">'
 6445:             .$lastitem
 6446:             .'</span>';
 6447:     }
 6448: 
 6449:     if ($crsauthor) {
 6450:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
 6451:     } else {
 6452:         $output .=
 6453:              '<br />'
 6454:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 6455:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 6456:             .'</form>'
 6457:             .&Apache::lonmenu::constspaceform($frameset);
 6458:     }
 6459:     $output .= '</div>';
 6460: 
 6461:     return $output;
 6462: }
 6463: 
 6464: ###############################################
 6465: ###############################################
 6466: 
 6467: =pod
 6468: 
 6469: =back
 6470: 
 6471: =head1 HTML Helpers
 6472: 
 6473: =over 4
 6474: 
 6475: =item * &bodytag()
 6476: 
 6477: Returns a uniform header for LON-CAPA web pages.
 6478: 
 6479: Inputs: 
 6480: 
 6481: =over 4
 6482: 
 6483: =item * $title, A title to be displayed on the page.
 6484: 
 6485: =item * $function, the current role (can be undef).
 6486: 
 6487: =item * $addentries, extra parameters for the <body> tag.
 6488: 
 6489: =item * $bodyonly, if defined, only return the <body> tag.
 6490: 
 6491: =item * $domain, if defined, force a given domain.
 6492: 
 6493: =item * $forcereg, if page should register as content page (relevant for 
 6494:             text interface only)
 6495: 
 6496: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 6497:                      navigational links
 6498: 
 6499: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 6500: 
 6501: =item * $args, optional argument valid values are
 6502:             no_auto_mt_title -> prevents &mt()ing the title arg
 6503:             use_absolute     -> for external resource or syllabus, this will
 6504:                                 contain https://<hostname> if server uses
 6505:                                 https (as per hosts.tab), but request is for http
 6506:             hostname         -> hostname, from $r->hostname().
 6507: 
 6508: =item * $advtoolsref, optional argument, ref to an array containing
 6509:             inlineremote items to be added in "Functions" menu below
 6510:             breadcrumbs.
 6511: 
 6512: =item * $ltiscope, optional argument, will be one of: resource, map or
 6513:             course, if LON-CAPA is in LTI Provider context. Value is
 6514:             the scope of use, i.e., launch was for access to a single, a map
 6515:             or the entire course.
 6516: 
 6517: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 6518:             context, this will contain the URL for the landing item in
 6519:             the course, after launch from an LTI Consumer
 6520: 
 6521: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 6522:             context, this will contain a reference to hash of items
 6523:             to be included in the page header and/or inline menu.
 6524: 
 6525: =item * $menucoll, optional argument, if specific menu collection is in
 6526:             effect, either set as the default for the course, or set for
 6527:             the deeplink paramater for $env{'request.deeplink.login'}
 6528:             then $menucoll will be the number of that collection. 
 6529: 
 6530: =item * $menuref, optional argument, reference to a hash, containing the
 6531:             menu options included for the menu in effect, based on the
 6532:             configuration for the numbered menu collection in use.  
 6533: 
 6534: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 6535:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 6536:             if so, $showncrumbsref is set there to 1, and will propagate back
 6537:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 6538:             being called a second time.
 6539: 
 6540: =back
 6541: 
 6542: Returns: A uniform header for LON-CAPA web pages.  
 6543: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 6544: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 6545: other decorations will be returned.
 6546: 
 6547: =cut
 6548: 
 6549: sub bodytag {
 6550:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 6551:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
 6552:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 6553: 
 6554:     my $public;
 6555:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 6556:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 6557:         $public = 1;
 6558:     }
 6559:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6560:     my $httphost = $args->{'use_absolute'};
 6561:     my $hostname = $args->{'hostname'};
 6562: 
 6563:     $function = &get_users_function() if (!$function);
 6564:     my $img =    &designparm($function.'.img',$domain);
 6565:     my $font =   &designparm($function.'.font',$domain);
 6566:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 6567: 
 6568:     my %design = ( 'style'   => 'margin-top: 0',
 6569: 		   'bgcolor' => $pgbg,
 6570: 		   'text'    => $font,
 6571:                    'alink'   => &designparm($function.'.alink',$domain),
 6572: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 6573: 		   'link'    => &designparm($function.'.link',$domain),);
 6574:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 6575: 
 6576:  # role and realm
 6577:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 6578:     if ($realm) {
 6579:         $realm = '/'.$realm;
 6580:     }
 6581:     if ($role eq 'ca') {
 6582:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 6583:         $realm = &plainname($rname,$rdom);
 6584:     } 
 6585: # realm
 6586:     my ($cid,$sec);
 6587:     if ($env{'request.course.id'}) {
 6588:         $cid = $env{'request.course.id'};
 6589:         if ($env{'request.course.sec'}) {
 6590:             $sec = $env{'request.course.sec'};
 6591:         }
 6592:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 6593:         if (&Apache::lonnet::is_course($1,$2)) {
 6594:             $cid = $1.'_'.$2;
 6595:             $sec = $3;
 6596:         }
 6597:     }
 6598:     if ($cid) {
 6599:         if ($env{'request.role'} !~ /^cr/) {
 6600:             $role = &Apache::lonnet::plaintext($role,&course_type());
 6601:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 6602:             if ($env{'request.role.desc'}) {
 6603:                 $role = $env{'request.role.desc'};
 6604:             } else {
 6605:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 6606:             }
 6607:         } else {
 6608:             $role = (split(/\//,$role,4))[-1]; 
 6609:         }
 6610:         if ($sec) {
 6611:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 6612:         }   
 6613: 	$realm = $env{'course.'.$cid.'.description'};
 6614:     } else {
 6615:         $role = &Apache::lonnet::plaintext($role);
 6616:     }
 6617: 
 6618:     if (!$realm) { $realm='&nbsp;'; }
 6619: 
 6620:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 6621: 
 6622: # construct main body tag
 6623:     my $bodytag = "<body $extra_body_attr>".
 6624: 	&Apache::lontexconvert::init_math_support();
 6625: 
 6626:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6627: 
 6628:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6629:         return $bodytag;
 6630:     }
 6631: 
 6632:     if ($public) {
 6633: 	undef($role);
 6634:     }
 6635: 
 6636:     my $showcrstitle = 1;
 6637:     if (($cid) && ($env{'request.lti.login'})) {
 6638:         if (ref($ltimenu) eq 'HASH') {
 6639:             unless ($ltimenu->{'role'}) {
 6640:                 undef($role);
 6641:             }
 6642:             unless ($ltimenu->{'coursetitle'}) {
 6643:                 $realm='&nbsp;';
 6644:                 $showcrstitle = 0;
 6645:             }
 6646:         }
 6647:     } elsif (($cid) && ($menucoll)) {
 6648:         if (ref($menuref) eq 'HASH') {
 6649:             unless ($menuref->{'role'}) {
 6650:                 undef($role);
 6651:             }
 6652:             unless ($menuref->{'crs'}) {
 6653:                 $realm='&nbsp;';
 6654:                 $showcrstitle = 0;
 6655:             }
 6656:         }
 6657:     }
 6658: 
 6659:     my $titleinfo = '<h1>'.$title.'</h1>';
 6660:     #
 6661:     # Extra info if you are the DC
 6662:     my $dc_info = '';
 6663:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6664:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6665:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6666:         $dc_info =~ s/\s+$//;
 6667:     }
 6668: 
 6669:     my $crstype;
 6670:     if ($cid) {
 6671:         $crstype = $env{'course.'.$cid.'.type'};
 6672:     } elsif ($args->{'crstype'}) {
 6673:         $crstype = $args->{'crstype'};
 6674:     }
 6675:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 6676:         undef($role);
 6677:     } else {
 6678:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6679:     }
 6680: 
 6681:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6682: 
 6683:         #    if ($env{'request.state'} eq 'construct') {
 6684:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6685:         #    }
 6686: 
 6687:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6688:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6689: 
 6690:         unless ($args->{'no_primary_menu'}) {
 6691:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6692:                                                               $args->{'links_disabled'},
 6693:                                                               $args->{'links_target'});
 6694: 
 6695:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6696:                 if ($dc_info) {
 6697:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6698:                 }
 6699:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6700:                                <em>$realm</em> $dc_info</div>|;
 6701:                 return $bodytag;
 6702:             }
 6703: 
 6704:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6705:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6706:             }
 6707: 
 6708:             $bodytag .= $right;
 6709: 
 6710:             if ($dc_info) {
 6711:                 $dc_info = &dc_courseid_toggle($dc_info);
 6712:             }
 6713:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6714:         }
 6715: 
 6716:         #if directed to not display the secondary menu, don't.  
 6717:         if ($args->{'no_secondary_menu'}) {
 6718:             return $bodytag;
 6719:         }
 6720:         #don't show menus for public users
 6721:         if (!$public){
 6722:             unless ($args->{'no_inline_menu'}) {
 6723:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6724:                                                             $args->{'no_primary_menu'},
 6725:                                                             $menucoll,$menuref,
 6726:                                                             $args->{'links_disabled'},
 6727:                                                             $args->{'links_target'});
 6728:             }
 6729:             $bodytag .= Apache::lonmenu::serverform();
 6730:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6731:             if ($env{'request.state'} eq 'construct') {
 6732:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6733:                                 $args->{'bread_crumbs'},'','',$hostname,
 6734:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6735:             } elsif ($forcereg) {
 6736:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6737:                                 $args->{'group'},$args->{'hide_buttons'},
 6738:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6739:             } else {
 6740:                 $bodytag .= 
 6741:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6742:                                                         $forcereg,$args->{'group'},
 6743:                                                         $args->{'bread_crumbs'},
 6744:                                                         $advtoolsref,'',$hostname);
 6745:             }
 6746:         }else{
 6747:             # this is to seperate menu from content when there's no secondary
 6748:             # menu. Especially needed for public accessible ressources.
 6749:             $bodytag .= '<hr style="clear:both" />';
 6750:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6751:         }
 6752: 
 6753:         return $bodytag;
 6754: }
 6755: 
 6756: sub dc_courseid_toggle {
 6757:     my ($dc_info) = @_;
 6758:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6759:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6760:            &mt('(More ...)').'</a></span>'.
 6761:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6762: }
 6763: 
 6764: sub make_attr_string {
 6765:     my ($register,$attr_ref) = @_;
 6766: 
 6767:     if ($attr_ref && !ref($attr_ref)) {
 6768: 	die("addentries Must be a hash ref ".
 6769: 	    join(':',caller(1))." ".
 6770: 	    join(':',caller(0))." ");
 6771:     }
 6772: 
 6773:     if ($register) {
 6774: 	my ($on_load,$on_unload);
 6775: 	foreach my $key (keys(%{$attr_ref})) {
 6776: 	    if      (lc($key) eq 'onload') {
 6777: 		$on_load.=$attr_ref->{$key}.';';
 6778: 		delete($attr_ref->{$key});
 6779: 
 6780: 	    } elsif (lc($key) eq 'onunload') {
 6781: 		$on_unload.=$attr_ref->{$key}.';';
 6782: 		delete($attr_ref->{$key});
 6783: 	    }
 6784: 	}
 6785: 	$attr_ref->{'onload'}  = $on_load;
 6786: 	$attr_ref->{'onunload'}= $on_unload;
 6787:     }
 6788: 
 6789:     my $attr_string;
 6790:     foreach my $attr (sort(keys(%$attr_ref))) {
 6791: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6792:     }
 6793:     return $attr_string;
 6794: }
 6795: 
 6796: 
 6797: ###############################################
 6798: ###############################################
 6799: 
 6800: =pod
 6801: 
 6802: =item * &endbodytag()
 6803: 
 6804: Returns a uniform footer for LON-CAPA web pages.
 6805: 
 6806: Inputs: 1 - optional reference to an args hash
 6807: If in the hash, key for noredirectlink has a value which evaluates to true,
 6808: a 'Continue' link is not displayed if the page contains an
 6809: internal redirect in the <head></head> section,
 6810: i.e., $env{'internal.head.redirect'} exists   
 6811: 
 6812: =cut
 6813: 
 6814: sub endbodytag {
 6815:     my ($args) = @_;
 6816:     my $endbodytag;
 6817:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6818:         $endbodytag='</body>';
 6819:     }
 6820:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6821:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6822:             my ($endbodyjs,$idattr);
 6823:             if ($env{'internal.head.to_opener'}) {
 6824:                 my $linkid = 'LC_continue_link';
 6825:                 $idattr = ' id="'.$linkid.'"';
 6826:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6827:                 $endbodyjs=<<ENDJS;
 6828: <script type="text/javascript">
 6829: // <![CDATA[
 6830: function ebFunction(evt) {
 6831:     evt.preventDefault();
 6832:     var dest = '$redirect_for_js';
 6833:     if (window.opener != null && !window.opener.closed) {
 6834:         window.opener.location.href=dest;
 6835:         window.close();
 6836:     } else {
 6837:         window.location.href=dest;
 6838:     }
 6839:     return false;
 6840: }
 6841: 
 6842: \$(document).ready(function () {
 6843:   if (document.getElementById('$linkid')) {
 6844:     var clickelem = document.getElementById('$linkid');
 6845:     clickelem.addEventListener('click',ebFunction,false);
 6846:   }
 6847: });
 6848: // ]]>
 6849: </script>
 6850: ENDJS
 6851:             }
 6852: 	    $endbodytag=
 6853: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6854: 	        &mt('Continue').'</a>'.
 6855: 	        $endbodytag;
 6856:         }
 6857:     }
 6858:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
 6859:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
 6860:     }
 6861:     return $endbodytag;
 6862: }
 6863: 
 6864: =pod
 6865: 
 6866: =item * &standard_css()
 6867: 
 6868: Returns a style sheet
 6869: 
 6870: Inputs: (all optional)
 6871:             domain         -> force to color decorate a page for a specific
 6872:                                domain
 6873:             function       -> force usage of a specific rolish color scheme
 6874:             bgcolor        -> override the default page bgcolor
 6875: 
 6876: =cut
 6877: 
 6878: sub standard_css {
 6879:     my ($function,$domain,$bgcolor) = @_;
 6880:     $function  = &get_users_function() if (!$function);
 6881:     my $img    = &designparm($function.'.img',   $domain);
 6882:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6883:     my $font   = &designparm($function.'.font',  $domain);
 6884:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6885: #second colour for later usage
 6886:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6887:     my $pgbg_or_bgcolor =
 6888: 	         $bgcolor ||
 6889: 	         &designparm($function.'.pgbg',  $domain);
 6890:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6891:     my $alink  = &designparm($function.'.alink', $domain);
 6892:     my $vlink  = &designparm($function.'.vlink', $domain);
 6893:     my $link   = &designparm($function.'.link',  $domain);
 6894: 
 6895:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6896:     my $mono                 = 'monospace';
 6897:     my $data_table_head      = $sidebg;
 6898:     my $data_table_light     = '#FAFAFA';
 6899:     my $data_table_dark      = '#E0E0E0';
 6900:     my $data_table_darker    = '#CCCCCC';
 6901:     my $data_table_highlight = '#FFFF00';
 6902:     my $mail_new             = '#FFBB77';
 6903:     my $mail_new_hover       = '#DD9955';
 6904:     my $mail_read            = '#BBBB77';
 6905:     my $mail_read_hover      = '#999944';
 6906:     my $mail_replied         = '#AAAA88';
 6907:     my $mail_replied_hover   = '#888855';
 6908:     my $mail_other           = '#99BBBB';
 6909:     my $mail_other_hover     = '#669999';
 6910:     my $table_header         = '#DDDDDD';
 6911:     my $feedback_link_bg     = '#BBBBBB';
 6912:     my $lg_border_color      = '#C8C8C8';
 6913:     my $button_hover         = '#BF2317';
 6914: 
 6915:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6916:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6917:                                              : '0 3px 0 4px';
 6918: 
 6919: 
 6920:     return <<END;
 6921: 
 6922: /* needed for iframe to allow 100% height in FF */
 6923: body, html { 
 6924:     margin: 0;
 6925:     padding: 0 0.5%;
 6926:     height: 99%; /* to avoid scrollbars */
 6927: }
 6928: 
 6929: body {
 6930:   font-family: $sans;
 6931:   line-height:130%;
 6932:   font-size:0.83em;
 6933:   color:$font;
 6934: }
 6935: 
 6936: a:focus,
 6937: a:focus img {
 6938:   color: red;
 6939: }
 6940: 
 6941: form, .inline {
 6942:   display: inline;
 6943: }
 6944: 
 6945: .LC_right {
 6946:   text-align:right;
 6947: }
 6948: 
 6949: .LC_middle {
 6950:   vertical-align:middle;
 6951: }
 6952: 
 6953: .LC_floatleft {
 6954:   float: left;
 6955: }
 6956: 
 6957: .LC_floatright {
 6958:   float: right;
 6959: }
 6960: 
 6961: .LC_400Box {
 6962:   width:400px;
 6963: }
 6964: 
 6965: .LC_iframecontainer {
 6966:     width: 98%;
 6967:     margin: 0;
 6968:     position: fixed;
 6969:     top: 8.5em;
 6970:     bottom: 0;
 6971: }
 6972: 
 6973: .LC_iframecontainer iframe{
 6974:     border: none;
 6975:     width: 100%;
 6976:     height: 100%;
 6977: }
 6978: 
 6979: .LC_filename {
 6980:   font-family: $mono;
 6981:   white-space:pre;
 6982:   font-size: 120%;
 6983: }
 6984: 
 6985: .LC_fileicon {
 6986:   border: none;
 6987:   height: 1.3em;
 6988:   vertical-align: text-bottom;
 6989:   margin-right: 0.3em;
 6990:   text-decoration:none;
 6991: }
 6992: 
 6993: .LC_setting {
 6994:   text-decoration:underline;
 6995: }
 6996: 
 6997: .LC_error {
 6998:   color: red;
 6999: }
 7000: 
 7001: .LC_warning {
 7002:   color: darkorange;
 7003: }
 7004: 
 7005: .LC_diff_removed {
 7006:   color: red;
 7007: }
 7008: 
 7009: .LC_info,
 7010: .LC_success,
 7011: .LC_diff_added {
 7012:   color: green;
 7013: }
 7014: 
 7015: div.LC_confirm_box {
 7016:   background-color: #FAFAFA;
 7017:   border: 1px solid $lg_border_color;
 7018:   margin-right: 0;
 7019:   padding: 5px;
 7020: }
 7021: 
 7022: div.LC_confirm_box .LC_error img,
 7023: div.LC_confirm_box .LC_success img {
 7024:   vertical-align: middle;
 7025: }
 7026: 
 7027: .LC_maxwidth {
 7028:   max-width: 100%;
 7029:   height: auto;
 7030: }
 7031: 
 7032: .LC_textsize_mobile {
 7033:   \@media only screen and (max-device-width: 480px) {
 7034:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 7035:   }
 7036: }
 7037: 
 7038: .LC_icon {
 7039:   border: none;
 7040:   vertical-align: middle;
 7041: }
 7042: 
 7043: .LC_docs_spacer {
 7044:   width: 25px;
 7045:   height: 1px;
 7046:   border: none;
 7047: }
 7048: 
 7049: .LC_internal_info {
 7050:   color: #999999;
 7051: }
 7052: 
 7053: .LC_discussion {
 7054:   background: $data_table_dark;
 7055:   border: 1px solid black;
 7056:   margin: 2px;
 7057: }
 7058: 
 7059: .LC_disc_action_left {
 7060:   background: $sidebg;
 7061:   text-align: left;
 7062:   padding: 4px;
 7063:   margin: 2px;
 7064: }
 7065: 
 7066: .LC_disc_action_right {
 7067:   background: $sidebg;
 7068:   text-align: right;
 7069:   padding: 4px;
 7070:   margin: 2px;
 7071: }
 7072: 
 7073: .LC_disc_new_item {
 7074:   background: white;
 7075:   border: 2px solid red;
 7076:   margin: 4px;
 7077:   padding: 4px;
 7078: }
 7079: 
 7080: .LC_disc_old_item {
 7081:   background: white;
 7082:   margin: 4px;
 7083:   padding: 4px;
 7084: }
 7085: 
 7086: table.LC_pastsubmission {
 7087:   border: 1px solid black;
 7088:   margin: 2px;
 7089: }
 7090: 
 7091: table#LC_menubuttons {
 7092:   width: 100%;
 7093:   background: $pgbg;
 7094:   border: 2px;
 7095:   border-collapse: separate;
 7096:   padding: 0;
 7097: }
 7098: 
 7099: table#LC_title_bar a {
 7100:   color: $fontmenu;
 7101: }
 7102: 
 7103: table#LC_title_bar {
 7104:   clear: both;
 7105:   display: none;
 7106: }
 7107: 
 7108: table#LC_title_bar,
 7109: table.LC_breadcrumbs, /* obsolete? */
 7110: table#LC_title_bar.LC_with_remote {
 7111:   width: 100%;
 7112:   border-color: $pgbg;
 7113:   border-style: solid;
 7114:   border-width: $border;
 7115:   background: $pgbg;
 7116:   color: $fontmenu;
 7117:   border-collapse: collapse;
 7118:   padding: 0;
 7119:   margin: 0;
 7120: }
 7121: 
 7122: ul.LC_breadcrumb_tools_outerlist {
 7123:     margin: 0;
 7124:     padding: 0;
 7125:     position: relative;
 7126:     list-style: none;
 7127: }
 7128: ul.LC_breadcrumb_tools_outerlist li {
 7129:     display: inline;
 7130: }
 7131: 
 7132: .LC_breadcrumb_tools_navigation {
 7133:     padding: 0;
 7134:     margin: 0;
 7135:     float: left;
 7136: }
 7137: .LC_breadcrumb_tools_tools {
 7138:     padding: 0;
 7139:     margin: 0;
 7140:     float: right;
 7141: }
 7142: 
 7143: .LC_placement_prog {
 7144:     padding-right: 20px;
 7145:     font-weight: bold;
 7146:     font-size: 90%;
 7147: }
 7148: 
 7149: table#LC_title_bar td {
 7150:   background: $tabbg;
 7151: }
 7152: 
 7153: table#LC_menubuttons img {
 7154:   border: none;
 7155: }
 7156: 
 7157: .LC_breadcrumbs_component {
 7158:   float: right;
 7159:   margin: 0 1em;
 7160: }
 7161: .LC_breadcrumbs_component img {
 7162:   vertical-align: middle;
 7163: }
 7164: 
 7165: .LC_breadcrumbs_hoverable {
 7166:   background: $sidebg;
 7167: }
 7168: 
 7169: td.LC_table_cell_checkbox {
 7170:   text-align: center;
 7171: }
 7172: 
 7173: .LC_fontsize_small {
 7174:   font-size: 70%;
 7175: }
 7176: 
 7177: #LC_breadcrumbs {
 7178:   clear:both;
 7179:   background: $sidebg;
 7180:   border-bottom: 1px solid $lg_border_color;
 7181:   line-height: 2.5em;
 7182:   overflow: hidden;
 7183:   margin: 0;
 7184:   padding: 0;
 7185:   text-align: left;
 7186: }
 7187: 
 7188: .LC_head_subbox, .LC_actionbox {
 7189:   clear:both;
 7190:   background: #F8F8F8; /* $sidebg; */
 7191:   border: 1px solid $sidebg;
 7192:   margin: 0 0 10px 0;
 7193:   padding: 3px;
 7194:   text-align: left;
 7195: }
 7196: 
 7197: .LC_fontsize_medium {
 7198:   font-size: 85%;
 7199: }
 7200: 
 7201: .LC_fontsize_large {
 7202:   font-size: 120%;
 7203: }
 7204: 
 7205: .LC_menubuttons_inline_text {
 7206:   color: $font;
 7207:   font-size: 90%;
 7208:   padding-left:3px;
 7209: }
 7210: 
 7211: .LC_menubuttons_inline_text img{
 7212:   vertical-align: middle;
 7213: }
 7214: 
 7215: li.LC_menubuttons_inline_text img {
 7216:   cursor:pointer;
 7217:   text-decoration: none;
 7218: }
 7219: 
 7220: .LC_menubuttons_link {
 7221:   text-decoration: none;
 7222: }
 7223: 
 7224: .LC_menubuttons_category {
 7225:   color: $font;
 7226:   background: $pgbg;
 7227:   font-size: larger;
 7228:   font-weight: bold;
 7229: }
 7230: 
 7231: td.LC_menubuttons_text {
 7232:   color: $font;
 7233: }
 7234: 
 7235: .LC_current_location {
 7236:   background: $tabbg;
 7237: }
 7238: 
 7239: td.LC_zero_height {
 7240:   line-height: 0; 
 7241:   cellpadding: 0;
 7242: }
 7243: 
 7244: table.LC_data_table {
 7245:   border: 1px solid #000000;
 7246:   border-collapse: separate;
 7247:   border-spacing: 1px;
 7248:   background: $pgbg;
 7249: }
 7250: 
 7251: .LC_data_table_dense {
 7252:   font-size: small;
 7253: }
 7254: 
 7255: table.LC_nested_outer {
 7256:   border: 1px solid #000000;
 7257:   border-collapse: collapse;
 7258:   border-spacing: 0;
 7259:   width: 100%;
 7260: }
 7261: 
 7262: table.LC_innerpickbox,
 7263: table.LC_nested {
 7264:   border: none;
 7265:   border-collapse: collapse;
 7266:   border-spacing: 0;
 7267:   width: 100%;
 7268: }
 7269: 
 7270: table.LC_data_table tr th,
 7271: table.LC_calendar tr th,
 7272: table.LC_prior_tries tr th,
 7273: table.LC_innerpickbox tr th {
 7274:   font-weight: bold;
 7275:   background-color: $data_table_head;
 7276:   color:$fontmenu;
 7277:   font-size:90%;
 7278: }
 7279: 
 7280: table.LC_innerpickbox tr th,
 7281: table.LC_innerpickbox tr td {
 7282:   vertical-align: top;
 7283: }
 7284: 
 7285: table.LC_data_table tr.LC_info_row > td {
 7286:   background-color: #CCCCCC;
 7287:   font-weight: bold;
 7288:   text-align: left;
 7289: }
 7290: 
 7291: table.LC_data_table tr.LC_odd_row > td {
 7292:   background-color: $data_table_light;
 7293:   padding: 2px;
 7294:   vertical-align: top;
 7295: }
 7296: 
 7297: table.LC_pick_box tr > td.LC_odd_row {
 7298:   background-color: $data_table_light;
 7299:   vertical-align: top;
 7300: }
 7301: 
 7302: table.LC_data_table tr.LC_even_row > td {
 7303:   background-color: $data_table_dark;
 7304:   padding: 2px;
 7305:   vertical-align: top;
 7306: }
 7307: 
 7308: table.LC_pick_box tr > td.LC_even_row {
 7309:   background-color: $data_table_dark;
 7310:   vertical-align: top;
 7311: }
 7312: 
 7313: table.LC_data_table tr.LC_data_table_highlight td {
 7314:   background-color: $data_table_darker;
 7315: }
 7316: 
 7317: table.LC_data_table tr td.LC_leftcol_header {
 7318:   background-color: $data_table_head;
 7319:   font-weight: bold;
 7320: }
 7321: 
 7322: table.LC_data_table tr.LC_empty_row td,
 7323: table.LC_nested tr.LC_empty_row td {
 7324:   font-weight: bold;
 7325:   font-style: italic;
 7326:   text-align: center;
 7327:   padding: 8px;
 7328: }
 7329: 
 7330: table.LC_data_table tr.LC_empty_row td,
 7331: table.LC_data_table tr.LC_footer_row td {
 7332:   background-color: $sidebg;
 7333: }
 7334: 
 7335: table.LC_nested tr.LC_empty_row td {
 7336:   background-color: #FFFFFF;
 7337: }
 7338: 
 7339: table.LC_caption {
 7340: }
 7341: 
 7342: table.LC_nested tr.LC_empty_row td {
 7343:   padding: 4ex
 7344: }
 7345: 
 7346: table.LC_nested_outer tr th {
 7347:   font-weight: bold;
 7348:   color:$fontmenu;
 7349:   background-color: $data_table_head;
 7350:   font-size: small;
 7351:   border-bottom: 1px solid #000000;
 7352: }
 7353: 
 7354: table.LC_nested_outer tr td.LC_subheader {
 7355:   background-color: $data_table_head;
 7356:   font-weight: bold;
 7357:   font-size: small;
 7358:   border-bottom: 1px solid #000000;
 7359:   text-align: right;
 7360: }
 7361: 
 7362: table.LC_nested tr.LC_info_row td {
 7363:   background-color: #CCCCCC;
 7364:   font-weight: bold;
 7365:   font-size: small;
 7366:   text-align: center;
 7367: }
 7368: 
 7369: table.LC_nested tr.LC_info_row td.LC_left_item,
 7370: table.LC_nested_outer tr th.LC_left_item {
 7371:   text-align: left;
 7372: }
 7373: 
 7374: table.LC_nested td {
 7375:   background-color: #FFFFFF;
 7376:   font-size: small;
 7377: }
 7378: 
 7379: table.LC_nested_outer tr th.LC_right_item,
 7380: table.LC_nested tr.LC_info_row td.LC_right_item,
 7381: table.LC_nested tr.LC_odd_row td.LC_right_item,
 7382: table.LC_nested tr td.LC_right_item {
 7383:   text-align: right;
 7384: }
 7385: 
 7386: table.LC_nested tr.LC_odd_row td {
 7387:   background-color: #EEEEEE;
 7388: }
 7389: 
 7390: table.LC_createuser {
 7391: }
 7392: 
 7393: table.LC_createuser tr.LC_section_row td {
 7394:   font-size: small;
 7395: }
 7396: 
 7397: table.LC_createuser tr.LC_info_row td  {
 7398:   background-color: #CCCCCC;
 7399:   font-weight: bold;
 7400:   text-align: center;
 7401: }
 7402: 
 7403: table.LC_calendar {
 7404:   border: 1px solid #000000;
 7405:   border-collapse: collapse;
 7406:   width: 98%;
 7407: }
 7408: 
 7409: table.LC_calendar_pickdate {
 7410:   font-size: xx-small;
 7411: }
 7412: 
 7413: table.LC_calendar tr td {
 7414:   border: 1px solid #000000;
 7415:   vertical-align: top;
 7416:   width: 14%;
 7417: }
 7418: 
 7419: table.LC_calendar tr td.LC_calendar_day_empty {
 7420:   background-color: $data_table_dark;
 7421: }
 7422: 
 7423: table.LC_calendar tr td.LC_calendar_day_current {
 7424:   background-color: $data_table_highlight;
 7425: }
 7426: 
 7427: table.LC_data_table tr td.LC_mail_new {
 7428:   background-color: $mail_new;
 7429: }
 7430: 
 7431: table.LC_data_table tr.LC_mail_new:hover {
 7432:   background-color: $mail_new_hover;
 7433: }
 7434: 
 7435: table.LC_data_table tr td.LC_mail_read {
 7436:   background-color: $mail_read;
 7437: }
 7438: 
 7439: /*
 7440: table.LC_data_table tr.LC_mail_read:hover {
 7441:   background-color: $mail_read_hover;
 7442: }
 7443: */
 7444: 
 7445: table.LC_data_table tr td.LC_mail_replied {
 7446:   background-color: $mail_replied;
 7447: }
 7448: 
 7449: /*
 7450: table.LC_data_table tr.LC_mail_replied:hover {
 7451:   background-color: $mail_replied_hover;
 7452: }
 7453: */
 7454: 
 7455: table.LC_data_table tr td.LC_mail_other {
 7456:   background-color: $mail_other;
 7457: }
 7458: 
 7459: /*
 7460: table.LC_data_table tr.LC_mail_other:hover {
 7461:   background-color: $mail_other_hover;
 7462: }
 7463: */
 7464: 
 7465: table.LC_data_table tr > td.LC_browser_file,
 7466: table.LC_data_table tr > td.LC_browser_file_published {
 7467:   background: #AAEE77;
 7468: }
 7469: 
 7470: table.LC_data_table tr > td.LC_browser_file_locked,
 7471: table.LC_data_table tr > td.LC_browser_file_unpublished {
 7472:   background: #FFAA99;
 7473: }
 7474: 
 7475: table.LC_data_table tr > td.LC_browser_file_obsolete {
 7476:   background: #888888;
 7477: }
 7478: 
 7479: table.LC_data_table tr > td.LC_browser_file_modified,
 7480: table.LC_data_table tr > td.LC_browser_file_metamodified {
 7481:   background: #F8F866;
 7482: }
 7483: 
 7484: table.LC_data_table tr.LC_browser_folder > td {
 7485:   background: #E0E8FF;
 7486: }
 7487: 
 7488: table.LC_data_table tr > td.LC_roles_is {
 7489:   /* background: #77FF77; */
 7490: }
 7491: 
 7492: table.LC_data_table tr > td.LC_roles_future {
 7493:   border-right: 8px solid #FFFF77;
 7494: }
 7495: 
 7496: table.LC_data_table tr > td.LC_roles_will {
 7497:   border-right: 8px solid #FFAA77;
 7498: }
 7499: 
 7500: table.LC_data_table tr > td.LC_roles_expired {
 7501:   border-right: 8px solid #FF7777;
 7502: }
 7503: 
 7504: table.LC_data_table tr > td.LC_roles_will_not {
 7505:   border-right: 8px solid #AAFF77;
 7506: }
 7507: 
 7508: table.LC_data_table tr > td.LC_roles_selected {
 7509:   border-right: 8px solid #11CC55;
 7510: }
 7511: 
 7512: span.LC_current_location {
 7513:   font-size:larger;
 7514:   background: $pgbg;
 7515: }
 7516: 
 7517: span.LC_current_nav_location {
 7518:   font-weight:bold;
 7519:   background: $sidebg;
 7520: }
 7521: 
 7522: span.LC_parm_menu_item {
 7523:   font-size: larger;
 7524: }
 7525: 
 7526: span.LC_parm_scope_all {
 7527:   color: red;
 7528: }
 7529: 
 7530: span.LC_parm_scope_folder {
 7531:   color: green;
 7532: }
 7533: 
 7534: span.LC_parm_scope_resource {
 7535:   color: orange;
 7536: }
 7537: 
 7538: span.LC_parm_part {
 7539:   color: blue;
 7540: }
 7541: 
 7542: span.LC_parm_folder,
 7543: span.LC_parm_symb {
 7544:   font-size: x-small;
 7545:   font-family: $mono;
 7546:   color: #AAAAAA;
 7547: }
 7548: 
 7549: ul.LC_parm_parmlist li {
 7550:   display: inline-block;
 7551:   padding: 0.3em 0.8em;
 7552:   vertical-align: top;
 7553:   width: 150px;
 7554:   border-top:1px solid $lg_border_color;
 7555: }
 7556: 
 7557: td.LC_parm_overview_level_menu,
 7558: td.LC_parm_overview_map_menu,
 7559: td.LC_parm_overview_parm_selectors,
 7560: td.LC_parm_overview_restrictions  {
 7561:   border: 1px solid black;
 7562:   border-collapse: collapse;
 7563: }
 7564: 
 7565: span.LC_parm_recursive,
 7566: td.LC_parm_recursive {
 7567:   font-weight: bold;
 7568:   font-size: smaller;
 7569: }
 7570: 
 7571: table.LC_parm_overview_restrictions td {
 7572:   border-width: 1px 4px 1px 4px;
 7573:   border-style: solid;
 7574:   border-color: $pgbg;
 7575:   text-align: center;
 7576: }
 7577: 
 7578: table.LC_parm_overview_restrictions th {
 7579:   background: $tabbg;
 7580:   border-width: 1px 4px 1px 4px;
 7581:   border-style: solid;
 7582:   border-color: $pgbg;
 7583: }
 7584: 
 7585: table#LC_helpmenu {
 7586:   border: none;
 7587:   height: 55px;
 7588:   border-spacing: 0;
 7589: }
 7590: 
 7591: table#LC_helpmenu fieldset legend {
 7592:   font-size: larger;
 7593: }
 7594: 
 7595: table#LC_helpmenu_links {
 7596:   width: 100%;
 7597:   border: 1px solid black;
 7598:   background: $pgbg;
 7599:   padding: 0;
 7600:   border-spacing: 1px;
 7601: }
 7602: 
 7603: table#LC_helpmenu_links tr td {
 7604:   padding: 1px;
 7605:   background: $tabbg;
 7606:   text-align: center;
 7607:   font-weight: bold;
 7608: }
 7609: 
 7610: table#LC_helpmenu_links a:link,
 7611: table#LC_helpmenu_links a:visited,
 7612: table#LC_helpmenu_links a:active {
 7613:   text-decoration: none;
 7614:   color: $font;
 7615: }
 7616: 
 7617: table#LC_helpmenu_links a:hover {
 7618:   text-decoration: underline;
 7619:   color: $vlink;
 7620: }
 7621: 
 7622: .LC_chrt_popup_exists {
 7623:   border: 1px solid #339933;
 7624:   margin: -1px;
 7625: }
 7626: 
 7627: .LC_chrt_popup_up {
 7628:   border: 1px solid yellow;
 7629:   margin: -1px;
 7630: }
 7631: 
 7632: .LC_chrt_popup {
 7633:   border: 1px solid #8888FF;
 7634:   background: #CCCCFF;
 7635: }
 7636: 
 7637: table.LC_pick_box {
 7638:   border-collapse: separate;
 7639:   background: white;
 7640:   border: 1px solid black;
 7641:   border-spacing: 1px;
 7642: }
 7643: 
 7644: table.LC_pick_box td.LC_pick_box_title {
 7645:   background: $sidebg;
 7646:   font-weight: bold;
 7647:   text-align: left;
 7648:   vertical-align: top;
 7649:   width: 184px;
 7650:   padding: 8px;
 7651: }
 7652: 
 7653: table.LC_pick_box td.LC_pick_box_value {
 7654:   text-align: left;
 7655:   padding: 8px;
 7656: }
 7657: 
 7658: table.LC_pick_box td.LC_pick_box_select {
 7659:   text-align: left;
 7660:   padding: 8px;
 7661: }
 7662: 
 7663: table.LC_pick_box td.LC_pick_box_separator {
 7664:   padding: 0;
 7665:   height: 1px;
 7666:   background: black;
 7667: }
 7668: 
 7669: table.LC_pick_box td.LC_pick_box_submit {
 7670:   text-align: right;
 7671: }
 7672: 
 7673: table.LC_pick_box td.LC_evenrow_value {
 7674:   text-align: left;
 7675:   padding: 8px;
 7676:   background-color: $data_table_light;
 7677: }
 7678: 
 7679: table.LC_pick_box td.LC_oddrow_value {
 7680:   text-align: left;
 7681:   padding: 8px;
 7682:   background-color: $data_table_light;
 7683: }
 7684: 
 7685: span.LC_helpform_receipt_cat {
 7686:   font-weight: bold;
 7687: }
 7688: 
 7689: table.LC_group_priv_box {
 7690:   background: white;
 7691:   border: 1px solid black;
 7692:   border-spacing: 1px;
 7693: }
 7694: 
 7695: table.LC_group_priv_box td.LC_pick_box_title {
 7696:   background: $tabbg;
 7697:   font-weight: bold;
 7698:   text-align: right;
 7699:   width: 184px;
 7700: }
 7701: 
 7702: table.LC_group_priv_box td.LC_groups_fixed {
 7703:   background: $data_table_light;
 7704:   text-align: center;
 7705: }
 7706: 
 7707: table.LC_group_priv_box td.LC_groups_optional {
 7708:   background: $data_table_dark;
 7709:   text-align: center;
 7710: }
 7711: 
 7712: table.LC_group_priv_box td.LC_groups_functionality {
 7713:   background: $data_table_darker;
 7714:   text-align: center;
 7715:   font-weight: bold;
 7716: }
 7717: 
 7718: table.LC_group_priv td {
 7719:   text-align: left;
 7720:   padding: 0;
 7721: }
 7722: 
 7723: .LC_navbuttons {
 7724:   margin: 2ex 0ex 2ex 0ex;
 7725: }
 7726: 
 7727: .LC_topic_bar {
 7728:   font-weight: bold;
 7729:   background: $tabbg;
 7730:   margin: 1em 0em 1em 2em;
 7731:   padding: 3px;
 7732:   font-size: 1.2em;
 7733: }
 7734: 
 7735: .LC_topic_bar span {
 7736:   left: 0.5em;
 7737:   position: absolute;
 7738:   vertical-align: middle;
 7739:   font-size: 1.2em;
 7740: }
 7741: 
 7742: table.LC_course_group_status {
 7743:   margin: 20px;
 7744: }
 7745: 
 7746: table.LC_status_selector td {
 7747:   vertical-align: top;
 7748:   text-align: center;
 7749:   padding: 4px;
 7750: }
 7751: 
 7752: div.LC_feedback_link {
 7753:   clear: both;
 7754:   background: $sidebg;
 7755:   width: 100%;
 7756:   padding-bottom: 10px;
 7757:   border: 1px $tabbg solid;
 7758:   height: 22px;
 7759:   line-height: 22px;
 7760:   padding-top: 5px;
 7761: }
 7762: 
 7763: div.LC_feedback_link img {
 7764:   height: 22px;
 7765:   vertical-align:middle;
 7766: }
 7767: 
 7768: div.LC_feedback_link a {
 7769:   text-decoration: none;
 7770: }
 7771: 
 7772: div.LC_comblock {
 7773:   display:inline;
 7774:   color:$font;
 7775:   font-size:90%;
 7776: }
 7777: 
 7778: div.LC_feedback_link div.LC_comblock {
 7779:   padding-left:5px;
 7780: }
 7781: 
 7782: div.LC_feedback_link div.LC_comblock a {
 7783:   color:$font;
 7784: }
 7785: 
 7786: span.LC_feedback_link {
 7787:   /* background: $feedback_link_bg; */
 7788:   font-size: larger;
 7789: }
 7790: 
 7791: span.LC_message_link {
 7792:   /* background: $feedback_link_bg; */
 7793:   font-size: larger;
 7794:   position: absolute;
 7795:   right: 1em;
 7796: }
 7797: 
 7798: table.LC_prior_tries {
 7799:   border: 1px solid #000000;
 7800:   border-collapse: separate;
 7801:   border-spacing: 1px;
 7802: }
 7803: 
 7804: table.LC_prior_tries td {
 7805:   padding: 2px;
 7806: }
 7807: 
 7808: .LC_answer_correct {
 7809:   background: lightgreen;
 7810:   color: darkgreen;
 7811:   padding: 6px;
 7812: }
 7813: 
 7814: .LC_answer_charged_try {
 7815:   background: #FFAAAA;
 7816:   color: darkred;
 7817:   padding: 6px;
 7818: }
 7819: 
 7820: .LC_answer_not_charged_try,
 7821: .LC_answer_no_grade,
 7822: .LC_answer_late {
 7823:   background: lightyellow;
 7824:   color: black;
 7825:   padding: 6px;
 7826: }
 7827: 
 7828: .LC_answer_previous {
 7829:   background: lightblue;
 7830:   color: darkblue;
 7831:   padding: 6px;
 7832: }
 7833: 
 7834: .LC_answer_no_message {
 7835:   background: #FFFFFF;
 7836:   color: black;
 7837:   padding: 6px;
 7838: }
 7839: 
 7840: .LC_answer_unknown,
 7841: .LC_answer_warning {
 7842:   background: orange;
 7843:   color: black;
 7844:   padding: 6px;
 7845: }
 7846: 
 7847: span.LC_prior_numerical,
 7848: span.LC_prior_string,
 7849: span.LC_prior_custom,
 7850: span.LC_prior_reaction,
 7851: span.LC_prior_math {
 7852:   font-family: $mono;
 7853:   white-space: pre;
 7854: }
 7855: 
 7856: span.LC_prior_string {
 7857:   font-family: $mono;
 7858:   white-space: pre;
 7859: }
 7860: 
 7861: table.LC_prior_option {
 7862:   width: 100%;
 7863:   border-collapse: collapse;
 7864: }
 7865: 
 7866: table.LC_prior_rank,
 7867: table.LC_prior_match {
 7868:   border-collapse: collapse;
 7869: }
 7870: 
 7871: table.LC_prior_option tr td,
 7872: table.LC_prior_rank tr td,
 7873: table.LC_prior_match tr td {
 7874:   border: 1px solid #000000;
 7875: }
 7876: 
 7877: .LC_nobreak {
 7878:   white-space: nowrap;
 7879: }
 7880: 
 7881: span.LC_cusr_emph {
 7882:   font-style: italic;
 7883: }
 7884: 
 7885: span.LC_cusr_subheading {
 7886:   font-weight: normal;
 7887:   font-size: 85%;
 7888: }
 7889: 
 7890: div.LC_docs_entry_move {
 7891:   border: 1px solid #BBBBBB;
 7892:   background: #DDDDDD;
 7893:   width: 22px;
 7894:   padding: 1px;
 7895:   margin: 0;
 7896: }
 7897: 
 7898: table.LC_data_table tr > td.LC_docs_entry_commands,
 7899: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7900:   font-size: x-small;
 7901: }
 7902: 
 7903: .LC_docs_entry_parameter {
 7904:   white-space: nowrap;
 7905: }
 7906: 
 7907: .LC_docs_copy {
 7908:   color: #000099;
 7909: }
 7910: 
 7911: .LC_docs_cut {
 7912:   color: #550044;
 7913: }
 7914: 
 7915: .LC_docs_rename {
 7916:   color: #009900;
 7917: }
 7918: 
 7919: .LC_docs_remove {
 7920:   color: #990000;
 7921: }
 7922: 
 7923: .LC_docs_alias {
 7924:   color: #440055;  
 7925: }
 7926: 
 7927: .LC_domprefs_email,
 7928: .LC_docs_alias_name,
 7929: .LC_docs_reinit_warn,
 7930: .LC_docs_ext_edit {
 7931:   font-size: x-small;
 7932: }
 7933: 
 7934: table.LC_docs_adddocs td,
 7935: table.LC_docs_adddocs th {
 7936:   border: 1px solid #BBBBBB;
 7937:   padding: 4px;
 7938:   background: #DDDDDD;
 7939: }
 7940: 
 7941: table.LC_sty_begin {
 7942:   background: #BBFFBB;
 7943: }
 7944: 
 7945: table.LC_sty_end {
 7946:   background: #FFBBBB;
 7947: }
 7948: 
 7949: table.LC_double_column {
 7950:   border-width: 0;
 7951:   border-collapse: collapse;
 7952:   width: 100%;
 7953:   padding: 2px;
 7954: }
 7955: 
 7956: table.LC_double_column tr td.LC_left_col {
 7957:   top: 2px;
 7958:   left: 2px;
 7959:   width: 47%;
 7960:   vertical-align: top;
 7961: }
 7962: 
 7963: table.LC_double_column tr td.LC_right_col {
 7964:   top: 2px;
 7965:   right: 2px;
 7966:   width: 47%;
 7967:   vertical-align: top;
 7968: }
 7969: 
 7970: div.LC_left_float {
 7971:   float: left;
 7972:   padding-right: 5%;
 7973:   padding-bottom: 4px;
 7974: }
 7975: 
 7976: div.LC_clear_float_header {
 7977:   padding-bottom: 2px;
 7978: }
 7979: 
 7980: div.LC_clear_float_footer {
 7981:   padding-top: 10px;
 7982:   clear: both;
 7983: }
 7984: 
 7985: div.LC_grade_show_user {
 7986: /*  border-left: 5px solid $sidebg; */
 7987:   border-top: 5px solid #000000;
 7988:   margin: 50px 0 0 0;
 7989:   padding: 15px 0 5px 10px;
 7990: }
 7991: 
 7992: div.LC_grade_show_user_odd_row {
 7993: /*  border-left: 5px solid #000000; */
 7994: }
 7995: 
 7996: div.LC_grade_show_user div.LC_Box {
 7997:   margin-right: 50px;
 7998: }
 7999: 
 8000: div.LC_grade_submissions,
 8001: div.LC_grade_message_center,
 8002: div.LC_grade_info_links {
 8003:   margin: 5px;
 8004:   width: 99%;
 8005:   background: #FFFFFF;
 8006: }
 8007: 
 8008: div.LC_grade_submissions_header,
 8009: div.LC_grade_message_center_header {
 8010:   font-weight: bold;
 8011:   font-size: large;
 8012: }
 8013: 
 8014: div.LC_grade_submissions_body,
 8015: div.LC_grade_message_center_body {
 8016:   border: 1px solid black;
 8017:   width: 99%;
 8018:   background: #FFFFFF;
 8019: }
 8020: 
 8021: table.LC_scantron_action {
 8022:   width: 100%;
 8023: }
 8024: 
 8025: table.LC_scantron_action tr th {
 8026:   font-weight:bold;
 8027:   font-style:normal;
 8028: }
 8029: 
 8030: .LC_edit_problem_header,
 8031: div.LC_edit_problem_footer {
 8032:   font-weight: normal;
 8033:   font-size:  medium;
 8034:   margin: 2px;
 8035:   background-color: $sidebg;
 8036: }
 8037: 
 8038: div.LC_edit_problem_header,
 8039: div.LC_edit_problem_header div,
 8040: div.LC_edit_problem_footer,
 8041: div.LC_edit_problem_footer div,
 8042: div.LC_edit_problem_editxml_header,
 8043: div.LC_edit_problem_editxml_header div {
 8044:   z-index: 100;
 8045: }
 8046: 
 8047: div.LC_edit_problem_header_title {
 8048:   font-weight: bold;
 8049:   font-size: larger;
 8050:   background: $tabbg;
 8051:   padding: 3px;
 8052:   margin: 0 0 5px 0;
 8053: }
 8054: 
 8055: table.LC_edit_problem_header_title {
 8056:   width: 100%;
 8057:   background: $tabbg;
 8058: }
 8059: 
 8060: div.LC_edit_actionbar {
 8061:     background-color: $sidebg;
 8062:     margin: 0;
 8063:     padding: 0;
 8064:     line-height: 200%;
 8065: }
 8066: 
 8067: div.LC_edit_actionbar div{
 8068:     padding: 0;
 8069:     margin: 0;
 8070:     display: inline-block;
 8071: }
 8072: 
 8073: .LC_edit_opt {
 8074:   padding-left: 1em;
 8075:   white-space: nowrap;
 8076: }
 8077: 
 8078: .LC_edit_problem_latexhelper{
 8079:     text-align: right;
 8080: }
 8081: 
 8082: #LC_edit_problem_colorful div{
 8083:     margin-left: 40px;
 8084: }
 8085: 
 8086: #LC_edit_problem_codemirror div{
 8087:     margin-left: 0px;
 8088: }
 8089: 
 8090: img.stift {
 8091:   border-width: 0;
 8092:   vertical-align: middle;
 8093: }
 8094: 
 8095: table td.LC_mainmenu_col_fieldset {
 8096:   vertical-align: top;
 8097: }
 8098: 
 8099: div.LC_createcourse {
 8100:   margin: 10px 10px 10px 10px;
 8101: }
 8102: 
 8103: .LC_dccid {
 8104:   float: right;
 8105:   margin: 0.2em 0 0 0;
 8106:   padding: 0;
 8107:   font-size: 90%;
 8108:   display:none;
 8109: }
 8110: 
 8111: ol.LC_primary_menu a:hover,
 8112: ol#LC_MenuBreadcrumbs a:hover,
 8113: ol#LC_PathBreadcrumbs a:hover,
 8114: ul#LC_secondary_menu a:hover,
 8115: .LC_FormSectionClearButton input:hover
 8116: ul.LC_TabContent   li:hover a {
 8117:   color:$button_hover;
 8118:   text-decoration:none;
 8119: }
 8120: 
 8121: h1 {
 8122:   padding: 0;
 8123:   line-height:130%;
 8124: }
 8125: 
 8126: h2,
 8127: h3,
 8128: h4,
 8129: h5,
 8130: h6 {
 8131:   margin: 5px 0 5px 0;
 8132:   padding: 0;
 8133:   line-height:130%;
 8134: }
 8135: 
 8136: .LC_hcell {
 8137:   padding:3px 15px 3px 15px;
 8138:   margin: 0;
 8139:   background-color:$tabbg;
 8140:   color:$fontmenu;
 8141:   border-bottom:solid 1px $lg_border_color;
 8142: }
 8143: 
 8144: .LC_Box > .LC_hcell {
 8145:   margin: 0 -10px 10px -10px;
 8146: }
 8147: 
 8148: .LC_noBorder {
 8149:   border: 0;
 8150: }
 8151: 
 8152: .LC_FormSectionClearButton input {
 8153:   background-color:transparent;
 8154:   border: none;
 8155:   cursor:pointer;
 8156:   text-decoration:underline;
 8157: }
 8158: 
 8159: .LC_help_open_topic {
 8160:   color: #FFFFFF;
 8161:   background-color: #EEEEFF;
 8162:   margin: 1px;
 8163:   padding: 4px;
 8164:   border: 1px solid #000033;
 8165:   white-space: nowrap;
 8166:   /* vertical-align: middle; */
 8167: }
 8168: 
 8169: dl,
 8170: ul,
 8171: div,
 8172: fieldset {
 8173:   margin: 10px 10px 10px 0;
 8174:   /* overflow: hidden; */
 8175: }
 8176: 
 8177: fieldset#LC_selectuser {
 8178:     margin: 0;
 8179:     padding: 0;
 8180: }
 8181: 
 8182: article.geogebraweb div {
 8183:     margin: 0;
 8184: }
 8185: 
 8186: fieldset > legend {
 8187:   font-weight: bold;
 8188:   padding: 0 5px 0 5px;
 8189: }
 8190: 
 8191: #LC_nav_bar {
 8192:   float: left;
 8193:   background-color: $pgbg_or_bgcolor;
 8194:   margin: 0 0 2px 0;
 8195: }
 8196: 
 8197: #LC_realm {
 8198:   margin: 0.2em 0 0 0;
 8199:   padding: 0;
 8200:   font-weight: bold;
 8201:   text-align: center;
 8202:   background-color: $pgbg_or_bgcolor;
 8203: }
 8204: 
 8205: #LC_nav_bar em {
 8206:   font-weight: bold;
 8207:   font-style: normal;
 8208: }
 8209: 
 8210: ol.LC_primary_menu {
 8211:   margin: 0;
 8212:   padding: 0;
 8213: }
 8214: 
 8215: ol#LC_PathBreadcrumbs {
 8216:   margin: 0;
 8217: }
 8218: 
 8219: ol.LC_primary_menu li {
 8220:   color: RGB(80, 80, 80);
 8221:   vertical-align: middle;
 8222:   text-align: left;
 8223:   list-style: none;
 8224:   position: relative;
 8225:   float: left;
 8226:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 8227:   line-height: 1.5em;
 8228: }
 8229: 
 8230: ol.LC_primary_menu li a,
 8231: ol.LC_primary_menu li p {
 8232:   display: block;
 8233:   margin: 0;
 8234:   padding: 0 5px 0 10px;
 8235:   text-decoration: none;
 8236: }
 8237: 
 8238: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 8239:   display: inline-block;
 8240:   width: 95%;
 8241:   text-align: left;
 8242: }
 8243: 
 8244: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 8245:   display: inline-block;	
 8246:   width: 5%;
 8247:   float: right;
 8248:   text-align: right;
 8249:   font-size: 70%;
 8250: }
 8251: 
 8252: ol.LC_primary_menu ul {
 8253:   display: none;
 8254:   width: 15em;
 8255:   background-color: $data_table_light;
 8256:   position: absolute;
 8257:   top: 100%;
 8258: }
 8259: 
 8260: ol.LC_primary_menu ul ul {
 8261:   left: 100%;
 8262:   top: 0;
 8263: }
 8264: 
 8265: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 8266:   display: block;
 8267:   position: absolute;
 8268:   margin: 0;
 8269:   padding: 0;
 8270:   z-index: 2;
 8271: }
 8272: 
 8273: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 8274: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 8275:   font-size: 90%;
 8276:   vertical-align: top;
 8277:   float: none;
 8278:   border-left: 1px solid black;
 8279:   border-right: 1px solid black;
 8280: /* A dark bottom border to visualize different menu options; 
 8281: overwritten in the create_submenu routine for the last border-bottom of the menu */
 8282:   border-bottom: 1px solid $data_table_dark; 
 8283: }
 8284: 
 8285: ol.LC_primary_menu li li p:hover {
 8286:   color:$button_hover;
 8287:   text-decoration:none;
 8288:   background-color:$data_table_dark;
 8289: }
 8290: 
 8291: ol.LC_primary_menu li li a:hover {
 8292:    color:$button_hover;
 8293:    background-color:$data_table_dark;
 8294: }
 8295: 
 8296: /* Font-size equal to the size of the predecessors*/
 8297: ol.LC_primary_menu li:hover li li {
 8298:   font-size: 100%;
 8299: }
 8300: 
 8301: ol.LC_primary_menu li img {
 8302:   vertical-align: bottom;
 8303:   height: 1.1em;
 8304:   margin: 0.2em 0 0 0;
 8305: }
 8306: 
 8307: ol.LC_primary_menu a {
 8308:   color: RGB(80, 80, 80);
 8309:   text-decoration: none;
 8310: }
 8311: 
 8312: ol.LC_primary_menu a.LC_new_message {
 8313:   font-weight:bold;
 8314:   color: darkred;
 8315: }
 8316: 
 8317: ol.LC_docs_parameters {
 8318:   margin-left: 0;
 8319:   padding: 0;
 8320:   list-style: none;
 8321: }
 8322: 
 8323: ol.LC_docs_parameters li {
 8324:   margin: 0;
 8325:   padding-right: 20px;
 8326:   display: inline;
 8327: }
 8328: 
 8329: ol.LC_docs_parameters li:before {
 8330:   content: "\\002022 \\0020";
 8331: }
 8332: 
 8333: li.LC_docs_parameters_title {
 8334:   font-weight: bold;
 8335: }
 8336: 
 8337: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 8338:   content: "";
 8339: }
 8340: 
 8341: ul#LC_secondary_menu {
 8342:   clear: right;
 8343:   color: $fontmenu;
 8344:   background: $tabbg;
 8345:   list-style: none;
 8346:   padding: 0;
 8347:   margin: 0;
 8348:   width: 100%;
 8349:   text-align: left;
 8350:   float: left;
 8351: }
 8352: 
 8353: ul#LC_secondary_menu li {
 8354:   font-weight: bold;
 8355:   line-height: 1.8em;
 8356:   border-right: 1px solid black;
 8357:   float: left;
 8358: }
 8359: 
 8360: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 8361:   background-color: $data_table_light;
 8362: }
 8363: 
 8364: ul#LC_secondary_menu li a {
 8365:   padding: 0 0.8em;
 8366: }
 8367: 
 8368: ul#LC_secondary_menu li ul {
 8369:   display: none;
 8370: }
 8371: 
 8372: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 8373:   display: block;
 8374:   position: absolute;
 8375:   margin: 0;
 8376:   padding: 0;
 8377:   list-style:none;
 8378:   float: none;
 8379:   background-color: $data_table_light;
 8380:   z-index: 2;
 8381:   margin-left: -1px;
 8382: }
 8383: 
 8384: ul#LC_secondary_menu li ul li {
 8385:   font-size: 90%;
 8386:   vertical-align: top;
 8387:   border-left: 1px solid black;
 8388:   border-right: 1px solid black;
 8389:   background-color: $data_table_light;
 8390:   list-style:none;
 8391:   float: none;
 8392: }
 8393: 
 8394: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 8395:   background-color: $data_table_dark;
 8396: }
 8397: 
 8398: ul.LC_TabContent {
 8399:   display:block;
 8400:   background: $sidebg;
 8401:   border-bottom: solid 1px $lg_border_color;
 8402:   list-style:none;
 8403:   margin: -1px -10px 0 -10px;
 8404:   padding: 0;
 8405: }
 8406: 
 8407: ul.LC_TabContent li,
 8408: ul.LC_TabContentBigger li {
 8409:   float:left;
 8410: }
 8411: 
 8412: ul#LC_secondary_menu li a {
 8413:   color: $fontmenu;
 8414:   text-decoration: none;
 8415: }
 8416: 
 8417: ul.LC_TabContent {
 8418:   min-height:20px;
 8419: }
 8420: 
 8421: ul.LC_TabContent li {
 8422:   vertical-align:middle;
 8423:   padding: 0 16px 0 10px;
 8424:   background-color:$tabbg;
 8425:   border-bottom:solid 1px $lg_border_color;
 8426:   border-left: solid 1px $font;
 8427: }
 8428: 
 8429: ul.LC_TabContent .right {
 8430:   float:right;
 8431: }
 8432: 
 8433: ul.LC_TabContent li a,
 8434: ul.LC_TabContent li {
 8435:   color:rgb(47,47,47);
 8436:   text-decoration:none;
 8437:   font-size:95%;
 8438:   font-weight:bold;
 8439:   min-height:20px;
 8440: }
 8441: 
 8442: ul.LC_TabContent li a:hover,
 8443: ul.LC_TabContent li a:focus {
 8444:   color: $button_hover;
 8445:   background:none;
 8446:   outline:none;
 8447: }
 8448: 
 8449: ul.LC_TabContent li:hover {
 8450:   color: $button_hover;
 8451:   cursor:pointer;
 8452: }
 8453: 
 8454: ul.LC_TabContent li.active {
 8455:   color: $font;
 8456:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 8457:   border-bottom:solid 1px #FFFFFF;
 8458:   cursor: default;
 8459: }
 8460: 
 8461: ul.LC_TabContent li.active a {
 8462:   color:$font;
 8463:   background:#FFFFFF;
 8464:   outline: none;
 8465: }
 8466: 
 8467: ul.LC_TabContent li.goback {
 8468:   float: left;
 8469:   border-left: none;
 8470: }
 8471: 
 8472: #maincoursedoc {
 8473:   clear:both;
 8474: }
 8475: 
 8476: ul.LC_TabContentBigger {
 8477:   display:block;
 8478:   list-style:none;
 8479:   padding: 0;
 8480: }
 8481: 
 8482: ul.LC_TabContentBigger li {
 8483:   vertical-align:bottom;
 8484:   height: 30px;
 8485:   font-size:110%;
 8486:   font-weight:bold;
 8487:   color: #737373;
 8488: }
 8489: 
 8490: ul.LC_TabContentBigger li.active {
 8491:   position: relative;
 8492:   top: 1px;
 8493: }
 8494: 
 8495: ul.LC_TabContentBigger li a {
 8496:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 8497:   height: 30px;
 8498:   line-height: 30px;
 8499:   text-align: center;
 8500:   display: block;
 8501:   text-decoration: none;
 8502:   outline: none;  
 8503: }
 8504: 
 8505: ul.LC_TabContentBigger li.active a {
 8506:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 8507:   color:$font;
 8508: }
 8509: 
 8510: ul.LC_TabContentBigger li b {
 8511:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 8512:   display: block;
 8513:   float: left;
 8514:   padding: 0 30px;
 8515:   border-bottom: 1px solid $lg_border_color;
 8516: }
 8517: 
 8518: ul.LC_TabContentBigger li:hover b {
 8519:   color:$button_hover;
 8520: }
 8521: 
 8522: ul.LC_TabContentBigger li.active b {
 8523:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 8524:   color:$font;
 8525:   border: 0;
 8526: }
 8527: 
 8528: 
 8529: ul.LC_CourseBreadcrumbs {
 8530:   background: $sidebg;
 8531:   height: 2em;
 8532:   padding-left: 10px;
 8533:   margin: 0;
 8534:   list-style-position: inside;
 8535: }
 8536: 
 8537: ol#LC_MenuBreadcrumbs,
 8538: ol#LC_PathBreadcrumbs {
 8539:   padding-left: 10px;
 8540:   margin: 0;
 8541:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 8542: }
 8543: 
 8544: ol#LC_MenuBreadcrumbs li,
 8545: ol#LC_PathBreadcrumbs li,
 8546: ul.LC_CourseBreadcrumbs li {
 8547:   display: inline;
 8548:   white-space: normal;  
 8549: }
 8550: 
 8551: ol#LC_MenuBreadcrumbs li a,
 8552: ul.LC_CourseBreadcrumbs li a {
 8553:   text-decoration: none;
 8554:   font-size:90%;
 8555: }
 8556: 
 8557: ol#LC_MenuBreadcrumbs h1 {
 8558:   display: inline;
 8559:   font-size: 90%;
 8560:   line-height: 2.5em;
 8561:   margin: 0;
 8562:   padding: 0;
 8563: }
 8564: 
 8565: ol#LC_PathBreadcrumbs li a {
 8566:   text-decoration:none;
 8567:   font-size:100%;
 8568:   font-weight:bold;
 8569: }
 8570: 
 8571: .LC_Box {
 8572:   border: solid 1px $lg_border_color;
 8573:   padding: 0 10px 10px 10px;
 8574: }
 8575: 
 8576: .LC_DocsBox {
 8577:   border: solid 1px $lg_border_color;
 8578:   padding: 0 0 10px 10px;
 8579: }
 8580: 
 8581: .LC_AboutMe_Image {
 8582:   float:left;
 8583:   margin-right:10px;
 8584: }
 8585: 
 8586: .LC_Clear_AboutMe_Image {
 8587:   clear:left;
 8588: }
 8589: 
 8590: dl.LC_ListStyleClean dt {
 8591:   padding-right: 5px;
 8592:   display: table-header-group;
 8593: }
 8594: 
 8595: dl.LC_ListStyleClean dd {
 8596:   display: table-row;
 8597: }
 8598: 
 8599: .LC_ListStyleClean,
 8600: .LC_ListStyleSimple,
 8601: .LC_ListStyleNormal,
 8602: .LC_ListStyleSpecial {
 8603:   /* display:block; */
 8604:   list-style-position: inside;
 8605:   list-style-type: none;
 8606:   overflow: hidden;
 8607:   padding: 0;
 8608: }
 8609: 
 8610: .LC_ListStyleSimple li,
 8611: .LC_ListStyleSimple dd,
 8612: .LC_ListStyleNormal li,
 8613: .LC_ListStyleNormal dd,
 8614: .LC_ListStyleSpecial li,
 8615: .LC_ListStyleSpecial dd {
 8616:   margin: 0;
 8617:   padding: 5px 5px 5px 10px;
 8618:   clear: both;
 8619: }
 8620: 
 8621: .LC_ListStyleClean li,
 8622: .LC_ListStyleClean dd {
 8623:   padding-top: 0;
 8624:   padding-bottom: 0;
 8625: }
 8626: 
 8627: .LC_ListStyleSimple dd,
 8628: .LC_ListStyleSimple li {
 8629:   border-bottom: solid 1px $lg_border_color;
 8630: }
 8631: 
 8632: .LC_ListStyleSpecial li,
 8633: .LC_ListStyleSpecial dd {
 8634:   list-style-type: none;
 8635:   background-color: RGB(220, 220, 220);
 8636:   margin-bottom: 4px;
 8637: }
 8638: 
 8639: table.LC_SimpleTable {
 8640:   margin:5px;
 8641:   border:solid 1px $lg_border_color;
 8642: }
 8643: 
 8644: table.LC_SimpleTable tr {
 8645:   padding: 0;
 8646:   border:solid 1px $lg_border_color;
 8647: }
 8648: 
 8649: table.LC_SimpleTable thead {
 8650:   background:rgb(220,220,220);
 8651: }
 8652: 
 8653: div.LC_columnSection {
 8654:   display: block;
 8655:   clear: both;
 8656:   overflow: hidden;
 8657:   margin: 0;
 8658: }
 8659: 
 8660: div.LC_columnSection>* {
 8661:   float: left;
 8662:   margin: 10px 20px 10px 0;
 8663:   overflow:hidden;
 8664: }
 8665: 
 8666: table em {
 8667:   font-weight: bold;
 8668:   font-style: normal;
 8669: }
 8670: 
 8671: table.LC_tableBrowseRes,
 8672: table.LC_tableOfContent {
 8673:   border:none;
 8674:   border-spacing: 1px;
 8675:   padding: 3px;
 8676:   background-color: #FFFFFF;
 8677:   font-size: 90%;
 8678: }
 8679: 
 8680: table.LC_tableOfContent {
 8681:   border-collapse: collapse;
 8682: }
 8683: 
 8684: table.LC_tableBrowseRes a,
 8685: table.LC_tableOfContent a {
 8686:   background-color: transparent;
 8687:   text-decoration: none;
 8688: }
 8689: 
 8690: table.LC_tableOfContent img {
 8691:   border: none;
 8692:   height: 1.3em;
 8693:   vertical-align: text-bottom;
 8694:   margin-right: 0.3em;
 8695: }
 8696: 
 8697: a#LC_content_toolbar_firsthomework {
 8698:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8699: }
 8700: 
 8701: a#LC_content_toolbar_everything {
 8702:   background-image:url(/res/adm/pages/show-all.gif);
 8703: }
 8704: 
 8705: a#LC_content_toolbar_uncompleted {
 8706:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8707: }
 8708: 
 8709: #LC_content_toolbar_clearbubbles {
 8710:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8711: }
 8712: 
 8713: a#LC_content_toolbar_changefolder {
 8714:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8715: }
 8716: 
 8717: a#LC_content_toolbar_changefolder_toggled {
 8718:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8719: }
 8720: 
 8721: a#LC_content_toolbar_edittoplevel {
 8722:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8723: }
 8724: 
 8725: a#LC_content_toolbar_printout {
 8726:   background-image:url(/res/adm/pages/printout.gif);
 8727: }
 8728: 
 8729: ul#LC_toolbar li a:hover {
 8730:   background-position: bottom center;
 8731: }
 8732: 
 8733: ul#LC_toolbar {
 8734:   padding: 0;
 8735:   margin: 2px;
 8736:   list-style:none;
 8737:   position:relative;
 8738:   background-color:white;
 8739:   overflow: auto;
 8740: }
 8741: 
 8742: ul#LC_toolbar li {
 8743:   border:1px solid white;
 8744:   padding: 0;
 8745:   margin: 0;
 8746:   float: left;
 8747:   display:inline;
 8748:   vertical-align:middle;
 8749:   white-space: nowrap;
 8750: }
 8751: 
 8752: 
 8753: a.LC_toolbarItem {
 8754:   display:block;
 8755:   padding: 0;
 8756:   margin: 0;
 8757:   height: 32px;
 8758:   width: 32px;
 8759:   color:white;
 8760:   border: none;
 8761:   background-repeat:no-repeat;
 8762:   background-color:transparent;
 8763: }
 8764: 
 8765: ul.LC_funclist {
 8766:     margin: 0;
 8767:     padding: 0.5em 1em 0.5em 0;
 8768: }
 8769: 
 8770: ul.LC_funclist > li:first-child {
 8771:     font-weight:bold; 
 8772:     margin-left:0.8em;
 8773: }
 8774: 
 8775: ul.LC_funclist + ul.LC_funclist {
 8776:     /* 
 8777:        left border as a seperator if we have more than
 8778:        one list 
 8779:     */
 8780:     border-left: 1px solid $sidebg;
 8781:     /* 
 8782:        this hides the left border behind the border of the 
 8783:        outer box if element is wrapped to the next 'line' 
 8784:     */
 8785:     margin-left: -1px;
 8786: }
 8787: 
 8788: ul.LC_funclist li {
 8789:   display: inline;
 8790:   white-space: nowrap;
 8791:   margin: 0 0 0 25px;
 8792:   line-height: 150%;
 8793: }
 8794: 
 8795: .LC_hidden {
 8796:   display: none;
 8797: }
 8798: 
 8799: .LCmodal-overlay {
 8800: 		position:fixed;
 8801: 		top:0;
 8802: 		right:0;
 8803: 		bottom:0;
 8804: 		left:0;
 8805: 		height:100%;
 8806: 		width:100%;
 8807: 		margin:0;
 8808: 		padding:0;
 8809: 		background:#999;
 8810: 		opacity:.75;
 8811: 		filter: alpha(opacity=75);
 8812: 		-moz-opacity: 0.75;
 8813: 		z-index:101;
 8814: }
 8815: 
 8816: * html .LCmodal-overlay {   
 8817: 		position: absolute;
 8818: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8819: }
 8820: 
 8821: .LCmodal-window {
 8822: 		position:fixed;
 8823: 		top:50%;
 8824: 		left:50%;
 8825: 		margin:0;
 8826: 		padding:0;
 8827: 		z-index:102;
 8828: 	}
 8829: 
 8830: * html .LCmodal-window {
 8831: 		position:absolute;
 8832: }
 8833: 
 8834: .LCclose-window {
 8835: 		position:absolute;
 8836: 		width:32px;
 8837: 		height:32px;
 8838: 		right:8px;
 8839: 		top:8px;
 8840: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8841: 		text-indent:-99999px;
 8842: 		overflow:hidden;
 8843: 		cursor:pointer;
 8844: }
 8845: 
 8846: .LCisDisabled {
 8847:   cursor: not-allowed;
 8848:   opacity: 0.5;
 8849: }
 8850: 
 8851: a[aria-disabled="true"] {
 8852:   color: currentColor;
 8853:   display: inline-block;  /* For IE11/ MS Edge bug */
 8854:   pointer-events: none;
 8855:   text-decoration: none;
 8856: }
 8857: 
 8858: pre.LC_wordwrap {
 8859:   white-space: pre-wrap;
 8860:   white-space: -moz-pre-wrap;
 8861:   white-space: -pre-wrap;
 8862:   white-space: -o-pre-wrap;
 8863:   word-wrap: break-word;
 8864: }
 8865: 
 8866: /*
 8867:   styles used for response display
 8868: */
 8869: div.LC_radiofoil, div.LC_rankfoil {
 8870:   margin: .5em 0em .5em 0em;
 8871: }
 8872: table.LC_itemgroup {
 8873:   margin-top: 1em;
 8874: }
 8875: 
 8876: /*
 8877:   styles used by TTH when "Default set of options to pass to tth/m
 8878:   when converting TeX" in course settings has been set
 8879: 
 8880:   option passed: -t
 8881: 
 8882: */
 8883: 
 8884: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8885: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8886: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8887: td div.norm {line-height:normal;}
 8888: 
 8889: /*
 8890:   option passed -y3
 8891: */
 8892: 
 8893: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8894: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8895: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8896: 
 8897: /*
 8898:   sections with roles, for content only
 8899: */
 8900: section[class^="role-"] {
 8901:   padding-left: 10px;
 8902:   padding-right: 5px;
 8903:   margin-top: 8px;
 8904:   margin-bottom: 8px;
 8905:   border: 1px solid #2A4;
 8906:   border-radius: 5px;
 8907:   box-shadow: 0px 1px 1px #BBB;
 8908: }
 8909: section[class^="role-"]>h1 {
 8910:   position: relative;
 8911:   margin: 0px;
 8912:   padding-top: 10px;
 8913:   padding-left: 40px;
 8914: }
 8915: section[class^="role-"]>h1:before {
 8916:   position: absolute;
 8917:   left: -5px;
 8918:   top: 5px;
 8919: }
 8920: section.role-activity>h1:before {
 8921:   content:url('/adm/daxe/images/section_icons/activity.png');
 8922: }
 8923: section.role-advice>h1:before {
 8924:   content:url('/adm/daxe/images/section_icons/advice.png');
 8925: }
 8926: section.role-bibliography>h1:before {
 8927:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8928: }
 8929: section.role-citation>h1:before {
 8930:   content:url('/adm/daxe/images/section_icons/citation.png');
 8931: }
 8932: section.role-conclusion>h1:before {
 8933:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8934: }
 8935: section.role-definition>h1:before {
 8936:   content:url('/adm/daxe/images/section_icons/definition.png');
 8937: }
 8938: section.role-demonstration>h1:before {
 8939:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8940: }
 8941: section.role-example>h1:before {
 8942:   content:url('/adm/daxe/images/section_icons/example.png');
 8943: }
 8944: section.role-explanation>h1:before {
 8945:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8946: }
 8947: section.role-introduction>h1:before {
 8948:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8949: }
 8950: section.role-method>h1:before {
 8951:   content:url('/adm/daxe/images/section_icons/method.png');
 8952: }
 8953: section.role-more_information>h1:before {
 8954:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8955: }
 8956: section.role-objectives>h1:before {
 8957:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8958: }
 8959: section.role-prerequisites>h1:before {
 8960:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8961: }
 8962: section.role-remark>h1:before {
 8963:   content:url('/adm/daxe/images/section_icons/remark.png');
 8964: }
 8965: section.role-reminder>h1:before {
 8966:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8967: }
 8968: section.role-summary>h1:before {
 8969:   content:url('/adm/daxe/images/section_icons/summary.png');
 8970: }
 8971: section.role-syntax>h1:before {
 8972:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8973: }
 8974: section.role-warning>h1:before {
 8975:   content:url('/adm/daxe/images/section_icons/warning.png');
 8976: }
 8977: 
 8978: #LC_minitab_header {
 8979:   float:left;
 8980:   width:100%;
 8981:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8982:   font-size:93%;
 8983:   line-height:normal;
 8984:   margin: 0.5em 0 0.5em 0;
 8985: }
 8986: #LC_minitab_header ul {
 8987:   margin:0;
 8988:   padding:10px 10px 0;
 8989:   list-style:none;
 8990: }
 8991: #LC_minitab_header li {
 8992:   float:left;
 8993:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8994:   margin:0;
 8995:   padding:0 0 0 9px;
 8996: }
 8997: #LC_minitab_header a {
 8998:   display:block;
 8999:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 9000:   padding:5px 15px 4px 6px;
 9001: }
 9002: #LC_minitab_header #LC_current_minitab {
 9003:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 9004: }
 9005: #LC_minitab_header #LC_current_minitab a {
 9006:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 9007:   padding-bottom:5px;
 9008: }
 9009: 
 9010: 
 9011: END
 9012: }
 9013: 
 9014: =pod
 9015: 
 9016: =item * &headtag()
 9017: 
 9018: Returns a uniform footer for LON-CAPA web pages.
 9019: 
 9020: Inputs: $title - optional title for the head
 9021:         $head_extra - optional extra HTML to put inside the <head>
 9022:         $args - optional arguments
 9023:             force_register - if is true call registerurl so the remote is 
 9024:                              informed
 9025:             redirect       -> array ref of
 9026:                                    1- seconds before redirect occurs
 9027:                                    2- url to redirect to
 9028:                                    3- whether the side effect should occur
 9029:                            (side effect of setting 
 9030:                                $env{'internal.head.redirect'} to the url 
 9031:                                redirected to)
 9032:                                    4- whether the redirect target should be
 9033:                                       the opener of the current (pop-up)
 9034:                                       window (side effect of setting
 9035:                                       $env{'internal.head.to_opener'} to
 9036:                                       1, if true.
 9037:                                    5- whether encrypt check should be skipped
 9038:             domain         -> force to color decorate a page for a specific
 9039:                                domain
 9040:             function       -> force usage of a specific rolish color scheme
 9041:             bgcolor        -> override the default page bgcolor
 9042:             no_auto_mt_title
 9043:                            -> prevent &mt()ing the title arg
 9044: 
 9045: =cut
 9046: 
 9047: sub headtag {
 9048:     my ($title,$head_extra,$args) = @_;
 9049:     
 9050:     my $function = $args->{'function'} || &get_users_function();
 9051:     my $domain   = $args->{'domain'}   || &determinedomain();
 9052:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 9053:     my $httphost = $args->{'use_absolute'};
 9054:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 9055: 		   $Apache::lonnet::perlvar{'lonVersion'},
 9056: 		   #time(),
 9057: 		   $env{'environment.color.timestamp'},
 9058: 		   $function,$domain,$bgcolor);
 9059: 
 9060:     $url = '/adm/css/'.&escape($url).'.css';
 9061: 
 9062:     my $result =
 9063: 	'<head>'.
 9064: 	&font_settings($args);
 9065: 
 9066:     my $inhibitprint;
 9067:     if ($args->{'print_suppress'}) {
 9068:         $inhibitprint = &print_suppression();
 9069:     }
 9070: 
 9071:     if (!$args->{'frameset'}) {
 9072: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 9073:     }
 9074:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 9075:         $result .= Apache::lonxml::display_title();
 9076:     }
 9077:     if (!$args->{'no_nav_bar'} 
 9078: 	&& !$args->{'only_body'}
 9079: 	&& !$args->{'frameset'}) {
 9080: 	$result .= &help_menu_js($httphost);
 9081:         $result.=&modal_window();
 9082:         $result.=&togglebox_script();
 9083:         $result.=&wishlist_window();
 9084:         $result.=&LCprogressbarUpdate_script();
 9085:     } else {
 9086:         if ($args->{'add_modal'}) {
 9087:            $result.=&modal_window();
 9088:         }
 9089:         if ($args->{'add_wishlist'}) {
 9090:            $result.=&wishlist_window();
 9091:         }
 9092:         if ($args->{'add_togglebox'}) {
 9093:            $result.=&togglebox_script();
 9094:         }
 9095:         if ($args->{'add_progressbar'}) {
 9096:            $result.=&LCprogressbarUpdate_script();
 9097:         }
 9098:     }
 9099:     if (ref($args->{'redirect'})) {
 9100: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 9101:         if (!$skip_enc_check) {
 9102:             $url = &Apache::lonenc::check_encrypt($url);
 9103:         }
 9104: 	if (!$inhibit_continue) {
 9105: 	    $env{'internal.head.redirect'} = $url;
 9106: 	}
 9107: 	$result.=<<"ADDMETA";
 9108: <meta http-equiv="pragma" content="no-cache" />
 9109: ADDMETA
 9110:         if ($to_opener) {
 9111:             $env{'internal.head.to_opener'} = 1;
 9112:             my $dest = &js_escape($url);
 9113:             my $timeout = int($time * 1000);
 9114:             $result .=<<"ENDJS";
 9115: <script type="text/javascript">
 9116: // <![CDATA[
 9117: function LC_To_Opener() {
 9118:     var dest = '$dest';
 9119:     if (dest != '') {
 9120:         if (window.opener != null && !window.opener.closed) {
 9121:             window.opener.location.href=dest;
 9122:             window.close();
 9123:         } else {
 9124:             window.location.href=dest;
 9125:         }
 9126:     }
 9127: }
 9128: \$(document).ready(function () {
 9129:     setTimeout('LC_To_Opener()',$timeout);
 9130: });
 9131: // ]]>
 9132: </script>
 9133: ENDJS
 9134:         } else {
 9135:             $result.=<<"ADDMETA";
 9136: <meta http-equiv="Refresh" content="$time; url=$url" />
 9137: ADDMETA
 9138:         }
 9139:     } else {
 9140:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 9141:             my $requrl = $env{'request.uri'};
 9142:             if ($requrl eq '') {
 9143:                 $requrl = $ENV{'REQUEST_URI'};
 9144:                 $requrl =~ s/\?.+$//;
 9145:             }
 9146:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 9147:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 9148:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 9149:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 9150:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 9151:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 9152:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 9153:                     my ($offload,$offloadoth);
 9154:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 9155:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 9156:                             $offload = 1;
 9157:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9158:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9159:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9160:                                     $offloadoth = 1;
 9161:                                     $dom_in_use = $env{'user.domain'};
 9162:                                 }
 9163:                             }
 9164:                         }
 9165:                     }
 9166:                     unless ($offload) {
 9167:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 9168:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 9169:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 9170:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 9171:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 9172:                                         $offload = 1;
 9173:                                         $offloadoth = 1;
 9174:                                         $dom_in_use = $env{'user.domain'};
 9175:                                     }
 9176:                                 }
 9177:                             }
 9178:                         }
 9179:                     }
 9180:                     if ($offload) {
 9181:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 9182:                         if (($newserver eq '') && ($offloadoth)) {
 9183:                             my @domains = &Apache::lonnet::current_machine_domains();
 9184:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
 9185:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 9186:                             }
 9187:                         }
 9188:                         if (($newserver) && ($newserver ne $lonhost)) {
 9189:                             my $numsec = 5;
 9190:                             my $timeout = $numsec * 1000;
 9191:                             my ($newurl,$locknum,%locks,$msg);
 9192:                             if ($env{'request.role.adv'}) {
 9193:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 9194:                             }
 9195:                             my $disable_submit = 0;
 9196:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 9197:                                 $disable_submit = 1;
 9198:                             }
 9199:                             if ($locknum) {
 9200:                                 my @lockinfo = sort(values(%locks));
 9201:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 9202:                                        join(", ",sort(values(%locks)))."\n";
 9203:                                 if (&show_course()) {
 9204:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 9205:                                 } else {
 9206:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 9207:                                 }
 9208:                             } else {
 9209:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 9210:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 9211:                                 }
 9212:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 9213:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 9214:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 9215:                                     $newurl .= '&role='.$env{'request.role'};
 9216:                                 }
 9217:                                 if ($env{'request.symb'}) {
 9218:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 9219:                                     if ($shownsymb =~ m{^/enc/}) {
 9220:                                         my $reqdmajor = 2;
 9221:                                         my $reqdminor = 11;
 9222:                                         my $reqdsubminor = 3;
 9223:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 9224:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 9225:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 9226:                                         if (($major eq '' && $minor eq '') ||
 9227:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 9228:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 9229:                                              ($reqdsubminor > $subminor))))) {
 9230:                                             undef($shownsymb);
 9231:                                         }
 9232:                                     }
 9233:                                     if ($shownsymb) {
 9234:                                         &js_escape(\$shownsymb);
 9235:                                         $newurl .= '&symb='.$shownsymb;
 9236:                                     }
 9237:                                 } else {
 9238:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 9239:                                     &js_escape(\$shownurl);
 9240:                                     $newurl .= '&origurl='.$shownurl;
 9241:                                 }
 9242:                             }
 9243:                             &js_escape(\$msg);
 9244:                             $result.=<<OFFLOAD
 9245: <meta http-equiv="pragma" content="no-cache" />
 9246: <script type="text/javascript">
 9247: // <![CDATA[
 9248: function LC_Offload_Now() {
 9249:     var dest = "$newurl";
 9250:     if (dest != '') {
 9251:         window.location.href="$newurl";
 9252:     }
 9253: }
 9254: \$(document).ready(function () {
 9255:     window.alert('$msg');
 9256:     if ($disable_submit) {
 9257:         \$(".LC_hwk_submit").prop("disabled", true);
 9258:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 9259:     }
 9260:     setTimeout('LC_Offload_Now()', $timeout);
 9261: });
 9262: // ]]>
 9263: </script>
 9264: OFFLOAD
 9265:                         }
 9266:                     }
 9267:                 }
 9268:             }
 9269:         }
 9270:     }
 9271:     if (!defined($title)) {
 9272: 	$title = 'The LearningOnline Network with CAPA';
 9273:     }
 9274:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 9275:     $result .= '<title> LON-CAPA '.$title.'</title>'
 9276: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 9277:     if (!$args->{'frameset'}) {
 9278:         $result .= ' /';
 9279:     }
 9280:     $result .= '>' 
 9281:         .$inhibitprint
 9282: 	.$head_extra;
 9283:     my $clientmobile;
 9284:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 9285:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 9286:     } else {
 9287:         $clientmobile = $env{'browser.mobile'};
 9288:     }
 9289:     if ($clientmobile) {
 9290:         $result .= '
 9291: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 9292: <meta name="apple-mobile-web-app-capable" content="yes" />';
 9293:     }
 9294:     $result .= '<meta name="google" content="notranslate" />'."\n";
 9295:     return $result.'</head>';
 9296: }
 9297: 
 9298: =pod
 9299: 
 9300: =item * &font_settings()
 9301: 
 9302: Returns neccessary <meta> to set the proper encoding
 9303: 
 9304: Inputs: optional reference to HASH -- $args passed to &headtag()
 9305: 
 9306: =cut
 9307: 
 9308: sub font_settings {
 9309:     my ($args) = @_;
 9310:     my $headerstring='';
 9311:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 9312:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 9313:         $headerstring.=
 9314:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 9315:         if (!$args->{'frameset'}) {
 9316: 	    $headerstring.= ' /';
 9317:         }
 9318: 	$headerstring .= '>'."\n";
 9319:     }
 9320:     return $headerstring;
 9321: }
 9322: 
 9323: =pod
 9324: 
 9325: =item * &print_suppression()
 9326: 
 9327: In course context returns css which causes the body to be blank when media="print",
 9328: if printout generation is unavailable for the current resource.
 9329: 
 9330: This could be because:
 9331: 
 9332: (a) printstartdate is in the future
 9333: 
 9334: (b) printenddate is in the past
 9335: 
 9336: (c) there is an active exam block with "printout"
 9337: functionality blocked
 9338: 
 9339: Users with pav, pfo or evb privileges are exempt.
 9340: 
 9341: Inputs: none
 9342: 
 9343: =cut
 9344: 
 9345: 
 9346: sub print_suppression {
 9347:     my $noprint;
 9348:     if ($env{'request.course.id'}) {
 9349:         my $scope = $env{'request.course.id'};
 9350:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9351:             (&Apache::lonnet::allowed('pfo',$scope))) {
 9352:             return;
 9353:         }
 9354:         if ($env{'request.course.sec'} ne '') {
 9355:             $scope .= "/$env{'request.course.sec'}";
 9356:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 9357:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 9358:                 return;
 9359:             }
 9360:         }
 9361:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9362:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9363:         my $clientip = &Apache::lonnet::get_requestor_ip();
 9364:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 9365:         if ($blocked) {
 9366:             my $checkrole = "cm./$cdom/$cnum";
 9367:             if ($env{'request.course.sec'} ne '') {
 9368:                 $checkrole .= "/$env{'request.course.sec'}";
 9369:             }
 9370:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 9371:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 9372:                 $noprint = 1;
 9373:             }
 9374:         }
 9375:         unless ($noprint) {
 9376:             my $symb = &Apache::lonnet::symbread();
 9377:             if ($symb ne '') {
 9378:                 my $navmap = Apache::lonnavmaps::navmap->new();
 9379:                 if (ref($navmap)) {
 9380:                     my $res = $navmap->getBySymb($symb);
 9381:                     if (ref($res)) {
 9382:                         if (!$res->resprintable()) {
 9383:                             $noprint = 1;
 9384:                         }
 9385:                     }
 9386:                 }
 9387:             }
 9388:         }
 9389:         if ($noprint) {
 9390:             return <<"ENDSTYLE";
 9391: <style type="text/css" media="print">
 9392:     body { display:none }
 9393: </style>
 9394: ENDSTYLE
 9395:         }
 9396:     }
 9397:     return;
 9398: }
 9399: 
 9400: =pod
 9401: 
 9402: =item * &xml_begin()
 9403: 
 9404: Returns the needed doctype and <html>
 9405: 
 9406: Inputs: none
 9407: 
 9408: =cut
 9409: 
 9410: sub xml_begin {
 9411:     my ($is_frameset) = @_;
 9412:     my $output='';
 9413: 
 9414:     if ($env{'browser.mathml'}) {
 9415: 	$output='<?xml version="1.0"?>'
 9416:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 9417: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 9418:             
 9419: #	    .'<!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">] >'
 9420: 	    .'<!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">'
 9421:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 9422: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 9423:     } elsif ($is_frameset) {
 9424:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 9425:                 '<html>'."\n";
 9426:     } else {
 9427: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 9428:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 9429:     }
 9430:     return $output;
 9431: }
 9432: 
 9433: =pod
 9434: 
 9435: =item * &start_page()
 9436: 
 9437: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 9438: 
 9439: Inputs:
 9440: 
 9441: =over 4
 9442: 
 9443: $title - optional title for the page
 9444: 
 9445: $head_extra - optional extra HTML to incude inside the <head>
 9446: 
 9447: $args - additional optional args supported are:
 9448: 
 9449: =over 8
 9450: 
 9451:              only_body      -> is true will set &bodytag() onlybodytag
 9452:                                     arg on
 9453:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 9454:              add_entries    -> additional attributes to add to the  <body>
 9455:              domain         -> force to color decorate a page for a 
 9456:                                     specific domain
 9457:              function       -> force usage of a specific rolish color
 9458:                                     scheme
 9459:              redirect       -> see &headtag()
 9460:              bgcolor        -> override the default page bg color
 9461:              js_ready       -> return a string ready for being used in 
 9462:                                     a javascript writeln
 9463:              html_encode    -> return a string ready for being used in 
 9464:                                     a html attribute
 9465:              force_register -> if is true will turn on the &bodytag()
 9466:                                     $forcereg arg
 9467:              frameset       -> if true will start with a <frameset>
 9468:                                     rather than <body>
 9469:              skip_phases    -> hash ref of 
 9470:                                     head -> skip the <html><head> generation
 9471:                                     body -> skip all <body> generation
 9472:              no_auto_mt_title -> prevent &mt()ing the title arg
 9473:              bread_crumbs ->             Array containing breadcrumbs
 9474:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 9475:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 9476:                                     to lonhtmlcommon::breadcrumbs
 9477:              group          -> includes the current group, if page is for a 
 9478:                                specific group
 9479:              use_absolute   -> for request for external resource or syllabus, this
 9480:                                will contain https://<hostname> if server uses
 9481:                                https (as per hosts.tab), but request is for http
 9482:              hostname       -> hostname, originally from $r->hostname(), (optional).
 9483:              links_disabled -> Links in primary and secondary menus are disabled
 9484:                                (Can enable them once page has loaded - see lonroles.pm
 9485:                                for an example).
 9486:              links_target   -> Target for links, e.g., _parent (optional).
 9487: 
 9488: =back
 9489: 
 9490: =back
 9491: 
 9492: =cut
 9493: 
 9494: sub start_page {
 9495:     my ($title,$head_extra,$args) = @_;
 9496:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 9497: 
 9498:     $env{'internal.start_page'}++;
 9499:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 9500: 
 9501:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 9502:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 9503:     }
 9504: 
 9505:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 9506:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 9507:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 9508:                 $args->{'no_primary_menu'} = 1;
 9509:             }
 9510:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 9511:                 $args->{'no_inline_menu'} = 1;
 9512:             }
 9513:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 9514:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 9515:             }
 9516:         } else {
 9517:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9518:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 9519:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 9520:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 9521:                     $args->{'no_primary_menu'} = 1;
 9522:                 }
 9523:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 9524:                     $args->{'no_inline_menu'} = 1;
 9525:                 }
 9526:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 9527:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 9528:                 }
 9529:             }
 9530:         }
 9531:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 9532:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 9533:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 9534:     } elsif ($env{'request.course.id'}) {
 9535:         my $expiretime=600;
 9536:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 9537:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 9538:         }
 9539:         my ($deeplinkmenu,$menuref);
 9540:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 9541:         if ($menucoll) {
 9542:             if (ref($menuref) eq 'HASH') {
 9543:                 %menu = %{$menuref};
 9544:             }
 9545:             if ($menu{'top'} eq 'n') {
 9546:                 $args->{'no_primary_menu'} = 1;
 9547:             }
 9548:             if ($menu{'inline'} eq 'n') {
 9549:                 unless (&Apache::lonnet::allowed('opa')) {
 9550:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9551:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9552:                     my $crstype = &course_type();
 9553:                     my $now = time;
 9554:                     my $ccrole;
 9555:                     if ($crstype eq 'Community') {
 9556:                         $ccrole = 'co';
 9557:                     } else {
 9558:                         $ccrole = 'cc';
 9559:                     }
 9560:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 9561:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 9562:                         if ((($start) && ($start<0)) ||
 9563:                             (($end) && ($end<$now))  ||
 9564:                             (($start) && ($now<$start))) {
 9565:                             $args->{'no_inline_menu'} = 1;
 9566:                         }
 9567:                     } else {
 9568:                         $args->{'no_inline_menu'} = 1;
 9569:                     }
 9570:                 }
 9571:             }
 9572:         }
 9573:     }
 9574: 
 9575:     my $showncrumbs;
 9576:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 9577: 	if ($args->{'frameset'}) {
 9578: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 9579: 						$args->{'add_entries'});
 9580: 	    $result .= "\n<frameset $attr_string>\n";
 9581:         } else {
 9582:             $result .=
 9583:                 &bodytag($title, 
 9584:                          $args->{'function'},       $args->{'add_entries'},
 9585:                          $args->{'only_body'},      $args->{'domain'},
 9586:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 9587:                          $args->{'bgcolor'},        $args,
 9588:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
 9589:                          \%menu,\$showncrumbs);
 9590:         }
 9591:     }
 9592: 
 9593:     if ($args->{'js_ready'}) {
 9594: 		$result = &js_ready($result);
 9595:     }
 9596:     if ($args->{'html_encode'}) {
 9597: 		$result = &html_encode($result);
 9598:     }
 9599: 
 9600:     # Preparation for new and consistent functionlist at top of screen
 9601:     # if ($args->{'functionlist'}) {
 9602:     #            $result .= &build_functionlist();
 9603:     #}
 9604: 
 9605:     # Don't add anything more if only_body wanted or in const space
 9606:     return $result if    $args->{'only_body'} 
 9607:                       || $env{'request.state'} eq 'construct';
 9608: 
 9609:     #Breadcrumbs
 9610:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 9611:         unless ($showncrumbs) {
 9612: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 9613: 		#if any br links exists, add them to the breadcrumbs
 9614: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 9615: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 9616: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 9617: 			}
 9618: 		}
 9619:                 # if @advtools array contains items add then to the breadcrumbs
 9620:                 if (@advtools > 0) {
 9621:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 9622:                 }
 9623:                 my $menulink;
 9624:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 9625:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 9626:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
 9627:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 9628:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 9629:                      (!$env{'request.role.adv'}))) {
 9630:                     $menulink = 0;
 9631:                 } else {
 9632:                     undef($menulink);
 9633:                 }
 9634:                 my $linkprotout;
 9635:                 if ($env{'request.deeplink.login'}) {
 9636:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 9637:                     if ($linkprotout) {
 9638:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 9639:                     }
 9640:                 }
 9641: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 9642: 		if(exists($args->{'bread_crumbs_component'})){
 9643: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 9644:                 } else {
 9645: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 9646: 		}
 9647:         }
 9648:     }
 9649:     return $result;
 9650: }
 9651: 
 9652: sub end_page {
 9653:     my ($args) = @_;
 9654:     $env{'internal.end_page'}++;
 9655:     my $result;
 9656:     if ($args->{'discussion'}) {
 9657: 	my ($target,$parser);
 9658: 	if (ref($args->{'discussion'})) {
 9659: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 9660: 				$args->{'discussion'}{'parser'});
 9661: 	}
 9662: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 9663:     }
 9664:     if ($args->{'frameset'}) {
 9665: 	$result .= '</frameset>';
 9666:     } else {
 9667: 	$result .= &endbodytag($args);
 9668:     }
 9669:     unless ($args->{'notbody'}) {
 9670:         $result .= "\n</html>";
 9671:     }
 9672: 
 9673:     if ($args->{'js_ready'}) {
 9674: 	$result = &js_ready($result);
 9675:     }
 9676: 
 9677:     if ($args->{'html_encode'}) {
 9678: 	$result = &html_encode($result);
 9679:     }
 9680: 
 9681:     return $result;
 9682: }
 9683: 
 9684: sub menucoll_in_effect {
 9685:     my ($menucoll,$deeplinkmenu,%menu);
 9686:     if ($env{'request.course.id'}) {
 9687:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9688:         if ($env{'request.deeplink.login'}) {
 9689:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9690:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9691:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9692:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9693:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9694:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9695:                     if (ref($navmap)) {
 9696:                         $deeplink = $navmap->get_mapparam(undef,
 9697:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9698:                                                           '0.deeplink');
 9699:                     } else {
 9700:                         $check_login_symb = 1;
 9701:                     }
 9702:                 } else {
 9703:                     my $symb = &Apache::lonnet::symbread();
 9704:                     if ($symb) {
 9705:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9706:                     } else {
 9707:                         $check_login_symb = 1;
 9708:                     }
 9709:                 }
 9710:             } else {
 9711:                 $check_login_symb = 1;
 9712:             }
 9713:             if ($check_login_symb) {
 9714:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9715:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9716:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9717:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9718:                     if (ref($navmap)) {
 9719:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9720:                     }
 9721:                 } else {
 9722:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9723:                 }
 9724:             }
 9725:             if ($deeplink ne '') {
 9726:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9727:                 if ($display =~ /^\d+$/) {
 9728:                     $deeplinkmenu = 1;
 9729:                     $menucoll = $display;
 9730:                 }
 9731:             }
 9732:         }
 9733:         if ($menucoll) {
 9734:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9735:         }
 9736:     }
 9737:     return ($menucoll,$deeplinkmenu,\%menu);
 9738: }
 9739: 
 9740: sub deeplink_login_symb {
 9741:     my ($cnum,$cdom) = @_;
 9742:     my $login_symb;
 9743:     if ($env{'request.deeplink.login'}) {
 9744:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9745:     }
 9746:     return $login_symb;
 9747: }
 9748: 
 9749: sub symb_from_tinyurl {
 9750:     my ($url,$cnum,$cdom) = @_;
 9751:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9752:         my $key = $1;
 9753:         my ($tinyurl,$login);
 9754:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9755:         if (defined($cached)) {
 9756:             $tinyurl = $result;
 9757:         } else {
 9758:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9759:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9760:             if ($currtiny{$key} ne '') {
 9761:                 $tinyurl = $currtiny{$key};
 9762:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9763:             }
 9764:         }
 9765:         if ($tinyurl ne '') {
 9766:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9767:             if (wantarray) {
 9768:                 return ($cnumreq,$symb);
 9769:             } elsif ($cnumreq eq $cnum) {
 9770:                 return $symb;
 9771:             }
 9772:         }
 9773:     }
 9774:     if (wantarray) {
 9775:         return ();
 9776:     } else {
 9777:         return;
 9778:     }
 9779: }
 9780: 
 9781: sub usable_exttools {
 9782:     my %tooltypes;
 9783:     if ($env{'request.course.id'}) {
 9784:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
 9785:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
 9786:                %tooltypes = (
 9787:                              crs => 1,
 9788:                              dom => 1,
 9789:                             );
 9790:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
 9791:                $tooltypes{'crs'} = 1;
 9792:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
 9793:                $tooltypes{'dom'} = 1;
 9794:            }
 9795:         } else {
 9796:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9797:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9798:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
 9799:             if ($crstype eq '') {
 9800:                 $crstype = 'course';
 9801:             }
 9802:             if ($crstype eq 'course') {
 9803:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
 9804:                     $crstype = 'official';
 9805:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
 9806:                     $crstype = 'textbook';
 9807:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
 9808:                     $crstype = 'lti';
 9809:                 } else {
 9810:                     $crstype = 'unofficial';
 9811:                 }
 9812:             }
 9813:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 9814:             if ($domdefaults{$crstype.'domexttool'}) {
 9815:                 $tooltypes{'dom'} = 1;
 9816:             }
 9817:             if ($domdefaults{$crstype.'exttool'}) {
 9818:                 $tooltypes{'crs'} = 1;
 9819:             }
 9820:         }
 9821:     }
 9822:     return %tooltypes;
 9823: }
 9824: 
 9825: sub wishlist_window {
 9826:     return(<<'ENDWISHLIST');
 9827: <script type="text/javascript">
 9828: // <![CDATA[
 9829: // <!-- BEGIN LON-CAPA Internal
 9830: function set_wishlistlink(title, path) {
 9831:     if (!title) {
 9832:         title = document.title;
 9833:         title = title.replace(/^LON-CAPA /,'');
 9834:     }
 9835:     title = encodeURIComponent(title);
 9836:     title = title.replace("'","\\\'");
 9837:     if (!path) {
 9838:         path = location.pathname;
 9839:     }
 9840:     path = encodeURIComponent(path);
 9841:     path = path.replace("'","\\\'");
 9842:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9843:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9844: }
 9845: // END LON-CAPA Internal -->
 9846: // ]]>
 9847: </script>
 9848: ENDWISHLIST
 9849: }
 9850: 
 9851: sub modal_window {
 9852:     return(<<'ENDMODAL');
 9853: <script type="text/javascript">
 9854: // <![CDATA[
 9855: // <!-- BEGIN LON-CAPA Internal
 9856: var modalWindow = {
 9857: 	parent:"body",
 9858: 	windowId:null,
 9859: 	content:null,
 9860: 	width:null,
 9861: 	height:null,
 9862: 	close:function()
 9863: 	{
 9864: 	        $(".LCmodal-window").remove();
 9865: 	        $(".LCmodal-overlay").remove();
 9866: 	},
 9867: 	open:function()
 9868: 	{
 9869: 		var modal = "";
 9870: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9871: 		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;\">";
 9872: 		modal += this.content;
 9873: 		modal += "</div>";	
 9874: 
 9875: 		$(this.parent).append(modal);
 9876: 
 9877: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9878: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9879: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9880: 	}
 9881: };
 9882: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9883: 	{
 9884:                 source = source.replace(/'/g,"&#39;");
 9885: 		modalWindow.windowId = "myModal";
 9886: 		modalWindow.width = width;
 9887: 		modalWindow.height = height;
 9888: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9889: 		modalWindow.open();
 9890: 	};
 9891: // END LON-CAPA Internal -->
 9892: // ]]>
 9893: </script>
 9894: ENDMODAL
 9895: }
 9896: 
 9897: sub modal_link {
 9898:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9899:     unless ($width) { $width=480; }
 9900:     unless ($height) { $height=400; }
 9901:     unless ($scrolling) { $scrolling='yes'; }
 9902:     unless ($transparency) { $transparency='true'; }
 9903: 
 9904:     my $target_attr;
 9905:     if (defined($target)) {
 9906:         $target_attr = 'target="'.$target.'"';
 9907:     }
 9908:     return <<"ENDLINK";
 9909: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9910: ENDLINK
 9911: }
 9912: 
 9913: sub modal_adhoc_script {
 9914:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9915:     my $mathjax;
 9916:     if ($possmathjax) {
 9917:         $mathjax = <<'ENDJAX';
 9918:                if (typeof MathJax == 'object') {
 9919:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9920:                }
 9921: ENDJAX
 9922:     }
 9923:     return (<<ENDADHOC);
 9924: <script type="text/javascript">
 9925: // <![CDATA[
 9926:         var $funcname = function()
 9927:         {
 9928:                 modalWindow.windowId = "myModal";
 9929:                 modalWindow.width = $width;
 9930:                 modalWindow.height = $height;
 9931:                 modalWindow.content = '$content';
 9932:                 modalWindow.open();
 9933:                 $mathjax
 9934:         };  
 9935: // ]]>
 9936: </script>
 9937: ENDADHOC
 9938: }
 9939: 
 9940: sub modal_adhoc_inner {
 9941:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9942:     my $innerwidth=$width-20;
 9943:     $content=&js_ready(
 9944:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9945:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9946:                  $content.
 9947:                  &end_scrollbox().
 9948:                  &end_page()
 9949:              );
 9950:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9951: }
 9952: 
 9953: sub modal_adhoc_window {
 9954:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9955:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9956:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9957: }
 9958: 
 9959: sub modal_adhoc_launch {
 9960:     my ($funcname,$width,$height,$content)=@_;
 9961:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9962: <script type="text/javascript">
 9963: // <![CDATA[
 9964: $funcname();
 9965: // ]]>
 9966: </script>
 9967: ENDLAUNCH
 9968: }
 9969: 
 9970: sub modal_adhoc_close {
 9971:     return (<<ENDCLOSE);
 9972: <script type="text/javascript">
 9973: // <![CDATA[
 9974: modalWindow.close();
 9975: // ]]>
 9976: </script>
 9977: ENDCLOSE
 9978: }
 9979: 
 9980: sub togglebox_script {
 9981:    return(<<ENDTOGGLE);
 9982: <script type="text/javascript"> 
 9983: // <![CDATA[
 9984: function LCtoggleDisplay(id,hidetext,showtext) {
 9985:    link = document.getElementById(id + "link").childNodes[0];
 9986:    with (document.getElementById(id).style) {
 9987:       if (display == "none" ) {
 9988:           display = "inline";
 9989:           link.nodeValue = hidetext;
 9990:         } else {
 9991:           display = "none";
 9992:           link.nodeValue = showtext;
 9993:        }
 9994:    }
 9995: }
 9996: // ]]>
 9997: </script>
 9998: ENDTOGGLE
 9999: }
10000: 
10001: sub start_togglebox {
10002:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
10003:     unless ($heading) { $heading=''; } else { $heading.=' '; }
10004:     unless ($showtext) { $showtext=&mt('show'); }
10005:     unless ($hidetext) { $hidetext=&mt('hide'); }
10006:     unless ($headerbg) { $headerbg='#FFFFFF'; }
10007:     return &start_data_table().
10008:            &start_data_table_header_row().
10009:            '<td bgcolor="'.$headerbg.'">'.$heading.
10010:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10011:            $showtext.'\')">'.$showtext.'</a>]</td>'.
10012:            &end_data_table_header_row().
10013:            '<tr id="'.$id.'" style="display:none""><td>';
10014: }
10015: 
10016: sub end_togglebox {
10017:     return '</td></tr>'.&end_data_table();
10018: }
10019: 
10020: sub LCprogressbar_script {
10021:    my ($id,$number_to_do)=@_;
10022:    if ($number_to_do) {
10023:        return(<<ENDPROGRESS);
10024: <script type="text/javascript">
10025: // <![CDATA[
10026: \$('#progressbar$id').progressbar({
10027:   value: 0,
10028:   change: function(event, ui) {
10029:     var newVal = \$(this).progressbar('option', 'value');
10030:     \$('.pblabel', this).text(LCprogressTxt);
10031:   }
10032: });
10033: // ]]>
10034: </script>
10035: ENDPROGRESS
10036:    } else {
10037:        return(<<ENDPROGRESS);
10038: <script type="text/javascript">
10039: // <![CDATA[
10040: \$('#progressbar$id').progressbar({
10041:   value: false,
10042:   create: function(event, ui) {
10043:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10044:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10045:   }
10046: });
10047: // ]]>
10048: </script>
10049: ENDPROGRESS
10050:    }
10051: }
10052: 
10053: sub LCprogressbarUpdate_script {
10054:    return(<<ENDPROGRESSUPDATE);
10055: <style type="text/css">
10056: .ui-progressbar { position:relative; }
10057: .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%; }
10058: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10059: </style>
10060: <script type="text/javascript">
10061: // <![CDATA[
10062: var LCprogressTxt='---';
10063: 
10064: function LCupdateProgress(percent,progresstext,id,maxnum) {
10065:    LCprogressTxt=progresstext;
10066:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10067:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10068:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10069:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10070:    } else {
10071:        \$('#progressbar'+id).progressbar('value',percent);
10072:    }
10073: }
10074: // ]]>
10075: </script>
10076: ENDPROGRESSUPDATE
10077: }
10078: 
10079: my $LClastpercent;
10080: my $LCidcnt;
10081: my $LCcurrentid;
10082: 
10083: sub LCprogressbar {
10084:     my ($r,$number_to_do,$preamble)=@_;
10085:     $LClastpercent=0;
10086:     $LCidcnt++;
10087:     $LCcurrentid=$$.'_'.$LCidcnt;
10088:     my ($starting,$content);
10089:     if ($number_to_do) {
10090:         $starting=&mt('Starting');
10091:         $content=(<<ENDPROGBAR);
10092: $preamble
10093:   <div id="progressbar$LCcurrentid">
10094:     <span class="pblabel">$starting</span>
10095:   </div>
10096: ENDPROGBAR
10097:     } else {
10098:         $starting=&mt('Loading...');
10099:         $LClastpercent='false';
10100:         $content=(<<ENDPROGBAR);
10101: $preamble
10102:   <div id="progressbar$LCcurrentid">
10103:       <div class="progress-label">$starting</div>
10104:   </div>
10105: ENDPROGBAR
10106:     }
10107:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10108: }
10109: 
10110: sub LCprogressbarUpdate {
10111:     my ($r,$val,$text,$number_to_do)=@_;
10112:     if ($number_to_do) {
10113:         unless ($val) { 
10114:             if ($LClastpercent) {
10115:                 $val=$LClastpercent;
10116:             } else {
10117:                 $val=0;
10118:             }
10119:         }
10120:         if ($val<0) { $val=0; }
10121:         if ($val>100) { $val=0; }
10122:         $LClastpercent=$val;
10123:         unless ($text) { $text=$val.'%'; }
10124:     } else {
10125:         $val = 'false';
10126:     }
10127:     $text=&js_ready($text);
10128:     &r_print($r,<<ENDUPDATE);
10129: <script type="text/javascript">
10130: // <![CDATA[
10131: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10132: // ]]>
10133: </script>
10134: ENDUPDATE
10135: }
10136: 
10137: sub LCprogressbarClose {
10138:     my ($r)=@_;
10139:     $LClastpercent=0;
10140:     &r_print($r,<<ENDCLOSE);
10141: <script type="text/javascript">
10142: // <![CDATA[
10143: \$("#progressbar$LCcurrentid").hide('slow'); 
10144: // ]]>
10145: </script>
10146: ENDCLOSE
10147: }
10148: 
10149: sub r_print {
10150:     my ($r,$to_print)=@_;
10151:     if ($r) {
10152:       $r->print($to_print);
10153:       $r->rflush();
10154:     } else {
10155:       print($to_print);
10156:     }
10157: }
10158: 
10159: sub html_encode {
10160:     my ($result) = @_;
10161: 
10162:     $result = &HTML::Entities::encode($result,'<>&"');
10163:     
10164:     return $result;
10165: }
10166: 
10167: sub js_ready {
10168:     my ($result) = @_;
10169: 
10170:     $result =~ s/[\n\r]/ /xmsg;
10171:     $result =~ s/\\/\\\\/xmsg;
10172:     $result =~ s/'/\\'/xmsg;
10173:     $result =~ s{</}{<\\/}xmsg;
10174:     
10175:     return $result;
10176: }
10177: 
10178: sub validate_page {
10179:     if (  exists($env{'internal.start_page'})
10180: 	  &&     $env{'internal.start_page'} > 1) {
10181: 	&Apache::lonnet::logthis('start_page called multiple times '.
10182: 				 $env{'internal.start_page'}.' '.
10183: 				 $ENV{'request.filename'});
10184:     }
10185:     if (  exists($env{'internal.end_page'})
10186: 	  &&     $env{'internal.end_page'} > 1) {
10187: 	&Apache::lonnet::logthis('end_page called multiple times '.
10188: 				 $env{'internal.end_page'}.' '.
10189: 				 $env{'request.filename'});
10190:     }
10191:     if (     exists($env{'internal.start_page'})
10192: 	&& ! exists($env{'internal.end_page'})) {
10193: 	&Apache::lonnet::logthis('start_page called without end_page '.
10194: 				 $env{'request.filename'});
10195:     }
10196:     if (   ! exists($env{'internal.start_page'})
10197: 	&&   exists($env{'internal.end_page'})) {
10198: 	&Apache::lonnet::logthis('end_page called without start_page'.
10199: 				 $env{'request.filename'});
10200:     }
10201: }
10202: 
10203: 
10204: sub start_scrollbox {
10205:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10206:     unless ($outerwidth) { $outerwidth='520px'; }
10207:     unless ($width) { $width='500px'; }
10208:     unless ($height) { $height='200px'; }
10209:     my ($table_id,$div_id,$tdcol);
10210:     if ($id ne '') {
10211:         $table_id = ' id="table_'.$id.'"';
10212:         $div_id = ' id="div_'.$id.'"';
10213:     }
10214:     if ($bgcolor ne '') {
10215:         $tdcol = "background-color: $bgcolor;";
10216:     }
10217:     my $nicescroll_js;
10218:     if ($env{'browser.mobile'}) {
10219:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10220:     }
10221:     return <<"END";
10222: $nicescroll_js
10223: 
10224: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10225: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10226: END
10227: }
10228: 
10229: sub end_scrollbox {
10230:     return '</div></td></tr></table>';
10231: }
10232: 
10233: sub nicescroll_javascript {
10234:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10235:     my %options;
10236:     if (ref($cursor) eq 'HASH') {
10237:         %options = %{$cursor};
10238:     }
10239:     unless ($options{'railalign'} =~ /^left|right$/) {
10240:         $options{'railalign'} = 'left';
10241:     }
10242:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10243:         my $function  = &get_users_function();
10244:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10245:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10246:             $options{'cursorcolor'} = '#00F';
10247:         }
10248:     }
10249:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10250:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10251:             $options{'cursoropacity'}='1.0';
10252:         }
10253:     } else {
10254:         $options{'cursoropacity'}='1.0';
10255:     }
10256:     if ($options{'cursorfixedheight'} eq 'none') {
10257:         delete($options{'cursorfixedheight'});
10258:     } else {
10259:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10260:     }
10261:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10262:         delete($options{'railoffset'});
10263:     }
10264:     my @niceoptions;
10265:     while (my($key,$value) = each(%options)) {
10266:         if ($value =~ /^\{.+\}$/) {
10267:             push(@niceoptions,$key.':'.$value);
10268:         } else {
10269:             push(@niceoptions,$key.':"'.$value.'"');
10270:         }
10271:     }
10272:     my $nicescroll_js = '
10273: $(document).ready(
10274:       function() {
10275:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10276:       }
10277: );
10278: ';
10279:     if ($framecheck) {
10280:         $nicescroll_js .= '
10281: function expand_div(caller) {
10282:     if (top === self) {
10283:         document.getElementById("'.$id.'").style.width = "auto";
10284:         document.getElementById("'.$id.'").style.height = "auto";
10285:     } else {
10286:         try {
10287:             if (parent.frames) {
10288:                 if (parent.frames.length > 1) {
10289:                     var framesrc = parent.frames[1].location.href;
10290:                     var currsrc = framesrc.replace(/\#.*$/,"");
10291:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
10292:                         document.getElementById("'.$id.'").style.width = "auto";
10293:                         document.getElementById("'.$id.'").style.height = "auto";
10294:                     }
10295:                 }
10296:             }
10297:         } catch (e) {
10298:             return;
10299:         }
10300:     }
10301:     return;
10302: }
10303: ';
10304:     }
10305:     if ($needjsready) {
10306:         $nicescroll_js = '
10307: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10308:     } else {
10309:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10310:     }
10311:     return $nicescroll_js;
10312: }
10313: 
10314: sub simple_error_page {
10315:     my ($r,$title,$msg,$args) = @_;
10316:     my %displayargs;
10317:     if (ref($args) eq 'HASH') {
10318:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10319:         if ($args->{'only_body'}) {
10320:             $displayargs{'only_body'} = 1;
10321:         }
10322:         if ($args->{'no_nav_bar'}) {
10323:             $displayargs{'no_nav_bar'} = 1;
10324:         }
10325:     } else {
10326:         $msg = &mt($msg);
10327:     }
10328: 
10329:     my $page =
10330: 	&Apache::loncommon::start_page($title,'',\%displayargs).
10331: 	'<p class="LC_error">'.$msg.'</p>'.
10332: 	&Apache::loncommon::end_page();
10333:     if (ref($r)) {
10334: 	$r->print($page);
10335: 	return;
10336:     }
10337:     return $page;
10338: }
10339: 
10340: {
10341:     my @row_count;
10342: 
10343:     sub start_data_table_count {
10344:         unshift(@row_count, 0);
10345:         return;
10346:     }
10347: 
10348:     sub end_data_table_count {
10349:         shift(@row_count);
10350:         return;
10351:     }
10352: 
10353:     sub start_data_table {
10354: 	my ($add_class,$id) = @_;
10355: 	my $css_class = (join(' ','LC_data_table',$add_class));
10356:         my $table_id;
10357:         if (defined($id)) {
10358:             $table_id = ' id="'.$id.'"';
10359:         }
10360: 	&start_data_table_count();
10361: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10362:     }
10363: 
10364:     sub end_data_table {
10365: 	&end_data_table_count();
10366: 	return '</table>'."\n";;
10367:     }
10368: 
10369:     sub start_data_table_row {
10370: 	my ($add_class, $id) = @_;
10371: 	$row_count[0]++;
10372: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10373: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10374:         $id = (' id="'.$id.'"') unless ($id eq '');
10375:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10376:     }
10377:     
10378:     sub continue_data_table_row {
10379: 	my ($add_class, $id) = @_;
10380: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10381: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10382:         $id = (' id="'.$id.'"') unless ($id eq '');
10383:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
10384:     }
10385: 
10386:     sub end_data_table_row {
10387: 	return '</tr>'."\n";;
10388:     }
10389: 
10390:     sub start_data_table_empty_row {
10391: #	$row_count[0]++;
10392: 	return  '<tr class="LC_empty_row" >'."\n";;
10393:     }
10394: 
10395:     sub end_data_table_empty_row {
10396: 	return '</tr>'."\n";;
10397:     }
10398: 
10399:     sub start_data_table_header_row {
10400: 	return  '<tr class="LC_header_row">'."\n";;
10401:     }
10402: 
10403:     sub end_data_table_header_row {
10404: 	return '</tr>'."\n";;
10405:     }
10406: 
10407:     sub data_table_caption {
10408:         my $caption = shift;
10409:         return "<caption class=\"LC_caption\">$caption</caption>";
10410:     }
10411: }
10412: 
10413: =pod
10414: 
10415: =item * &inhibit_menu_check($arg)
10416: 
10417: Checks for a inhibitmenu state and generates output to preserve it
10418: 
10419: Inputs:         $arg - can be any of
10420:                      - undef - in which case the return value is a string 
10421:                                to add  into arguments list of a uri
10422:                      - 'input' - in which case the return value is a HTML
10423:                                  <form> <input> field of type hidden to
10424:                                  preserve the value
10425:                      - a url - in which case the return value is the url with
10426:                                the neccesary cgi args added to preserve the
10427:                                inhibitmenu state
10428:                      - a ref to a url - no return value, but the string is
10429:                                         updated to include the neccessary cgi
10430:                                         args to preserve the inhibitmenu state
10431: 
10432: =cut
10433: 
10434: sub inhibit_menu_check {
10435:     my ($arg) = @_;
10436:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10437:     if ($arg eq 'input') {
10438: 	if ($env{'form.inhibitmenu'}) {
10439: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10440: 	} else {
10441: 	    return
10442: 	}
10443:     }
10444:     if ($env{'form.inhibitmenu'}) {
10445: 	if (ref($arg)) {
10446: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10447: 	} elsif ($arg eq '') {
10448: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10449: 	} else {
10450: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10451: 	}
10452:     }
10453:     if (!ref($arg)) {
10454: 	return $arg;
10455:     }
10456: }
10457: 
10458: ###############################################
10459: 
10460: =pod
10461: 
10462: =back
10463: 
10464: =head1 User Information Routines
10465: 
10466: =over 4
10467: 
10468: =item * &get_users_function()
10469: 
10470: Used by &bodytag to determine the current users primary role.
10471: Returns either 'student','coordinator','admin', or 'author'.
10472: 
10473: =cut
10474: 
10475: ###############################################
10476: sub get_users_function {
10477:     my $function = 'norole';
10478:     if ($env{'request.role'}=~/^(st)/) {
10479:         $function='student';
10480:     }
10481:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10482:         $function='coordinator';
10483:     }
10484:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10485:         $function='admin';
10486:     }
10487:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10488:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10489:         $function='author';
10490:     }
10491:     return $function;
10492: }
10493: 
10494: ###############################################
10495: 
10496: =pod
10497: 
10498: =item * &show_course()
10499: 
10500: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10501: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10502: 
10503: Inputs:
10504: None
10505: 
10506: Outputs:
10507: Scalar: 1 if 'Course' to be used, 0 otherwise.
10508: 
10509: =cut
10510: 
10511: ###############################################
10512: sub show_course {
10513:     my ($udom,$uname) = @_;
10514:     if (($udom ne '') && ($uname ne '')) {
10515:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10516:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10517:                 return 0;
10518:             } else {
10519:                 return 1;
10520:             }
10521:         }
10522:     }
10523:     my $course = !$env{'user.adv'};
10524:     if (!$env{'user.adv'}) {
10525:         foreach my $env (keys(%env)) {
10526:             next if ($env !~ m/^user\.priv\./);
10527:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10528:                 $course = 0;
10529:                 last;
10530:             }
10531:         }
10532:     }
10533:     return $course;
10534: }
10535: 
10536: ###############################################
10537: 
10538: =pod
10539: 
10540: =item * &check_user_status()
10541: 
10542: Determines current status of supplied role for a
10543: specific user. Roles can be active, previous or future.
10544: 
10545: Inputs: 
10546: user's domain, user's username, course's domain,
10547: course's number, optional section ID.
10548: 
10549: Outputs:
10550: role status: active, previous or future. 
10551: 
10552: =cut
10553: 
10554: sub check_user_status {
10555:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10556:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10557:     my @uroles = keys(%userinfo);
10558:     my $srchstr;
10559:     my $active_chk = 'none';
10560:     my $now = time;
10561:     if (@uroles > 0) {
10562:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10563:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10564:         } else {
10565:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10566:         }
10567:         if (grep/^\Q$srchstr\E$/,@uroles) {
10568:             my $role_end = 0;
10569:             my $role_start = 0;
10570:             $active_chk = 'active';
10571:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10572:                 $role_end = $1;
10573:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10574:                     $role_start = $1;
10575:                 }
10576:             }
10577:             if ($role_start > 0) {
10578:                 if ($now < $role_start) {
10579:                     $active_chk = 'future';
10580:                 }
10581:             }
10582:             if ($role_end > 0) {
10583:                 if ($now > $role_end) {
10584:                     $active_chk = 'previous';
10585:                 }
10586:             }
10587:         }
10588:     }
10589:     return $active_chk;
10590: }
10591: 
10592: ###############################################
10593: 
10594: =pod
10595: 
10596: =item * &get_sections()
10597: 
10598: Determines all the sections for a course including
10599: sections with students and sections containing other roles.
10600: Incoming parameters: 
10601: 
10602: 1. domain
10603: 2. course number 
10604: 3. reference to array containing roles for which sections should 
10605: be gathered (optional).
10606: 4. reference to array containing status types for which sections 
10607: should be gathered (optional).
10608: 
10609: If the third argument is undefined, sections are gathered for any role. 
10610: If the fourth argument is undefined, sections are gathered for any status.
10611: Permissible values are 'active' or 'future' or 'previous'.
10612:  
10613: Returns section hash (keys are section IDs, values are
10614: number of users in each section), subject to the
10615: optional roles filter, optional status filter 
10616: 
10617: =cut
10618: 
10619: ###############################################
10620: sub get_sections {
10621:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10622:     if (!defined($cdom) || !defined($cnum)) {
10623:         my $cid =  $env{'request.course.id'};
10624: 
10625: 	return if (!defined($cid));
10626: 
10627:         $cdom = $env{'course.'.$cid.'.domain'};
10628:         $cnum = $env{'course.'.$cid.'.num'};
10629:     }
10630: 
10631:     my %sectioncount;
10632:     my $now = time;
10633: 
10634:     my $check_students = 1;
10635:     my $only_students = 0;
10636:     if (ref($possible_roles) eq 'ARRAY') {
10637:         if (grep(/^st$/,@{$possible_roles})) {
10638:             if (@{$possible_roles} == 1) {
10639:                 $only_students = 1;
10640:             }
10641:         } else {
10642:             $check_students = 0;
10643:         }
10644:     }
10645: 
10646:     if ($check_students) { 
10647: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10648: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
10649: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
10650:         my $start_index = &Apache::loncoursedata::CL_START();
10651:         my $end_index = &Apache::loncoursedata::CL_END();
10652:         my $status;
10653: 	while (my ($student,$data) = each(%$classlist)) {
10654: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10655: 				                     $data->[$status_index],
10656:                                                      $data->[$start_index],
10657:                                                      $data->[$end_index]);
10658:             if ($stu_status eq 'Active') {
10659:                 $status = 'active';
10660:             } elsif ($end < $now) {
10661:                 $status = 'previous';
10662:             } elsif ($start > $now) {
10663:                 $status = 'future';
10664:             } 
10665: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
10666:                 if ((!defined($possible_status)) || (($status ne '') && 
10667:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
10668: 		    $sectioncount{$section}++;
10669:                 }
10670: 	    }
10671: 	}
10672:     }
10673:     if ($only_students) {
10674:         return %sectioncount;
10675:     }
10676:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10677:     foreach my $user (sort(keys(%courseroles))) {
10678: 	if ($user !~ /^(\w{2})/) { next; }
10679: 	my ($role) = ($user =~ /^(\w{2})/);
10680: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10681: 	my ($section,$status);
10682: 	if ($role eq 'cr' &&
10683: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10684: 	    $section=$1;
10685: 	}
10686: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10687: 	if (!defined($section) || $section eq '-1') { next; }
10688:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10689:         if ($end == -1 && $start == -1) {
10690:             next; #deleted role
10691:         }
10692:         if (!defined($possible_status)) { 
10693:             $sectioncount{$section}++;
10694:         } else {
10695:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10696:                 $status = 'active';
10697:             } elsif ($end < $now) {
10698:                 $status = 'future';
10699:             } elsif ($start > $now) {
10700:                 $status = 'previous';
10701:             }
10702:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10703:                 $sectioncount{$section}++;
10704:             }
10705:         }
10706:     }
10707:     return %sectioncount;
10708: }
10709: 
10710: ###############################################
10711: 
10712: =pod
10713: 
10714: =item * &get_course_users()
10715: 
10716: Retrieves usernames:domains for users in the specified course
10717: with specific role(s), and access status. 
10718: 
10719: Incoming parameters:
10720: 1. course domain
10721: 2. course number
10722: 3. access status: users must have - either active, 
10723: previous, future, or all.
10724: 4. reference to array of permissible roles
10725: 5. reference to array of section restrictions (optional)
10726: 6. reference to results object (hash of hashes).
10727: 7. reference to optional userdata hash
10728: 8. reference to optional statushash
10729: 9. flag if privileged users (except those set to unhide in
10730:    course settings) should be excluded    
10731: Keys of top level results hash are roles.
10732: Keys of inner hashes are username:domain, with 
10733: values set to access type.
10734: Optional userdata hash returns an array with arguments in the 
10735: same order as loncoursedata::get_classlist() for student data.
10736: 
10737: Optional statushash returns
10738: 
10739: Entries for end, start, section and status are blank because
10740: of the possibility of multiple values for non-student roles.
10741: 
10742: =cut
10743: 
10744: ###############################################
10745: 
10746: sub get_course_users {
10747:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10748:     my %idx = ();
10749:     my %seclists;
10750: 
10751:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10752:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10753:     $idx{end} = &Apache::loncoursedata::CL_END();
10754:     $idx{start} = &Apache::loncoursedata::CL_START();
10755:     $idx{id} = &Apache::loncoursedata::CL_ID();
10756:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10757:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10758:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10759: 
10760:     if (grep(/^st$/,@{$roles})) {
10761:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10762:         my $now = time;
10763:         foreach my $student (keys(%{$classlist})) {
10764:             my $match = 0;
10765:             my $secmatch = 0;
10766:             my $section = $$classlist{$student}[$idx{section}];
10767:             my $status = $$classlist{$student}[$idx{status}];
10768:             if ($section eq '') {
10769:                 $section = 'none';
10770:             }
10771:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10772:                 if (grep(/^all$/,@{$sections})) {
10773:                     $secmatch = 1;
10774:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10775:                     if (grep(/^none$/,@{$sections})) {
10776:                         $secmatch = 1;
10777:                     }
10778:                 } else {  
10779: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10780: 		        $secmatch = 1;
10781:                     }
10782: 		}
10783:                 if (!$secmatch) {
10784:                     next;
10785:                 }
10786:             }
10787:             if (defined($$types{'active'})) {
10788:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10789:                     push(@{$$users{st}{$student}},'active');
10790:                     $match = 1;
10791:                 }
10792:             }
10793:             if (defined($$types{'previous'})) {
10794:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10795:                     push(@{$$users{st}{$student}},'previous');
10796:                     $match = 1;
10797:                 }
10798:             }
10799:             if (defined($$types{'future'})) {
10800:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10801:                     push(@{$$users{st}{$student}},'future');
10802:                     $match = 1;
10803:                 }
10804:             }
10805:             if ($match) {
10806:                 push(@{$seclists{$student}},$section);
10807:                 if (ref($userdata) eq 'HASH') {
10808:                     $$userdata{$student} = $$classlist{$student};
10809:                 }
10810:                 if (ref($statushash) eq 'HASH') {
10811:                     $statushash->{$student}{'st'}{$section} = $status;
10812:                 }
10813:             }
10814:         }
10815:     }
10816:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10817:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10818:         my $now = time;
10819:         my %displaystatus = ( previous => 'Expired',
10820:                               active   => 'Active',
10821:                               future   => 'Future',
10822:                             );
10823:         my (%nothide,@possdoms);
10824:         if ($hidepriv) {
10825:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10826:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10827:                 if ($user !~ /:/) {
10828:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10829:                 } else {
10830:                     $nothide{$user} = 1;
10831:                 }
10832:             }
10833:             my @possdoms = ($cdom);
10834:             if ($coursehash{'checkforpriv'}) {
10835:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10836:             }
10837:         }
10838:         foreach my $person (sort(keys(%coursepersonnel))) {
10839:             my $match = 0;
10840:             my $secmatch = 0;
10841:             my $status;
10842:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10843:             $user =~ s/:$//;
10844:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10845:             if ($end == -1 || $start == -1) {
10846:                 next;
10847:             }
10848:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10849:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10850:                 my ($uname,$udom) = split(/:/,$user);
10851:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10852:                     if (grep(/^all$/,@{$sections})) {
10853:                         $secmatch = 1;
10854:                     } elsif ($usec eq '') {
10855:                         if (grep(/^none$/,@{$sections})) {
10856:                             $secmatch = 1;
10857:                         }
10858:                     } else {
10859:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10860:                             $secmatch = 1;
10861:                         }
10862:                     }
10863:                     if (!$secmatch) {
10864:                         next;
10865:                     }
10866:                 }
10867:                 if ($usec eq '') {
10868:                     $usec = 'none';
10869:                 }
10870:                 if ($uname ne '' && $udom ne '') {
10871:                     if ($hidepriv) {
10872:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10873:                             (!$nothide{$uname.':'.$udom})) {
10874:                             next;
10875:                         }
10876:                     }
10877:                     if ($end > 0 && $end < $now) {
10878:                         $status = 'previous';
10879:                     } elsif ($start > $now) {
10880:                         $status = 'future';
10881:                     } else {
10882:                         $status = 'active';
10883:                     }
10884:                     foreach my $type (keys(%{$types})) { 
10885:                         if ($status eq $type) {
10886:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10887:                                 push(@{$$users{$role}{$user}},$type);
10888:                             }
10889:                             $match = 1;
10890:                         }
10891:                     }
10892:                     if (($match) && (ref($userdata) eq 'HASH')) {
10893:                         if (!exists($$userdata{$uname.':'.$udom})) {
10894: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10895:                         }
10896:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10897:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10898:                         }
10899:                         if (ref($statushash) eq 'HASH') {
10900:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10901:                         }
10902:                     }
10903:                 }
10904:             }
10905:         }
10906:         if (grep(/^ow$/,@{$roles})) {
10907:             if ((defined($cdom)) && (defined($cnum))) {
10908:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10909:                 if ( defined($csettings{'internal.courseowner'}) ) {
10910:                     my $owner = $csettings{'internal.courseowner'};
10911:                     next if ($owner eq '');
10912:                     my ($ownername,$ownerdom);
10913:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10914:                         $ownername = $1;
10915:                         $ownerdom = $2;
10916:                     } else {
10917:                         $ownername = $owner;
10918:                         $ownerdom = $cdom;
10919:                         $owner = $ownername.':'.$ownerdom;
10920:                     }
10921:                     @{$$users{'ow'}{$owner}} = 'any';
10922:                     if (defined($userdata) && 
10923: 			!exists($$userdata{$owner})) {
10924: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10925:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10926:                             push(@{$seclists{$owner}},'none');
10927:                         }
10928:                         if (ref($statushash) eq 'HASH') {
10929:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10930:                         }
10931: 		    }
10932:                 }
10933:             }
10934:         }
10935:         foreach my $user (keys(%seclists)) {
10936:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10937:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10938:         }
10939:     }
10940:     return;
10941: }
10942: 
10943: sub get_user_info {
10944:     my ($udom,$uname,$idx,$userdata) = @_;
10945:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10946: 	&plainname($uname,$udom,'lastname');
10947:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10948:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10949:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10950:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10951:     return;
10952: }
10953: 
10954: ###############################################
10955: 
10956: =pod
10957: 
10958: =item * &get_user_quota()
10959: 
10960: Retrieves quota assigned for storage of user files.
10961: Default is to report quota for portfolio files.
10962: 
10963: Incoming parameters:
10964: 1. user's username
10965: 2. user's domain
10966: 3. quota name - portfolio, author, or course
10967:    (if no quota name provided, defaults to portfolio).
10968: 4. crstype - official, unofficial, textbook, placement or community, 
10969:    if quota name is course
10970: 
10971: Returns:
10972: 1. Disk quota (in MB) assigned to student.
10973: 2. (Optional) Type of setting: custom or default
10974:    (individually assigned or default for user's 
10975:    institutional status).
10976: 3. (Optional) - User's institutional status (e.g., faculty, staff
10977:    or student - types as defined in localenroll::inst_usertypes 
10978:    for user's domain, which determines default quota for user.
10979: 4. (Optional) - Default quota which would apply to the user.
10980: 
10981: If a value has been stored in the user's environment, 
10982: it will return that, otherwise it returns the maximal default
10983: defined for the user's institutional status(es) in the domain.
10984: 
10985: =cut
10986: 
10987: ###############################################
10988: 
10989: 
10990: sub get_user_quota {
10991:     my ($uname,$udom,$quotaname,$crstype) = @_;
10992:     my ($quota,$quotatype,$settingstatus,$defquota);
10993:     if (!defined($udom)) {
10994:         $udom = $env{'user.domain'};
10995:     }
10996:     if (!defined($uname)) {
10997:         $uname = $env{'user.name'};
10998:     }
10999:     if (($udom eq '' || $uname eq '') ||
11000:         ($udom eq 'public') && ($uname eq 'public')) {
11001:         $quota = 0;
11002:         $quotatype = 'default';
11003:         $defquota = 0; 
11004:     } else {
11005:         my $inststatus;
11006:         if ($quotaname eq 'course') {
11007:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11008:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11009:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11010:             } else {
11011:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11012:                 $quota = $cenv{'internal.uploadquota'};
11013:             }
11014:         } else {
11015:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11016:                 if ($quotaname eq 'author') {
11017:                     $quota = $env{'environment.authorquota'};
11018:                 } else {
11019:                     $quota = $env{'environment.portfolioquota'};
11020:                 }
11021:                 $inststatus = $env{'environment.inststatus'};
11022:             } else {
11023:                 my %userenv = 
11024:                     &Apache::lonnet::get('environment',['portfolioquota',
11025:                                          'authorquota','inststatus'],$udom,$uname);
11026:                 my ($tmp) = keys(%userenv);
11027:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11028:                     if ($quotaname eq 'author') {
11029:                         $quota = $userenv{'authorquota'};
11030:                     } else {
11031:                         $quota = $userenv{'portfolioquota'};
11032:                     }
11033:                     $inststatus = $userenv{'inststatus'};
11034:                 } else {
11035:                     undef(%userenv);
11036:                 }
11037:             }
11038:         }
11039:         if ($quota eq '' || wantarray) {
11040:             if ($quotaname eq 'course') {
11041:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11042:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
11043:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
11044:                     ($crstype eq 'placement')) { 
11045:                     $defquota = $domdefs{$crstype.'quota'};
11046:                 }
11047:                 if ($defquota eq '') {
11048:                     $defquota = 500;
11049:                 }
11050:             } else {
11051:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11052:             }
11053:             if ($quota eq '') {
11054:                 $quota = $defquota;
11055:                 $quotatype = 'default';
11056:             } else {
11057:                 $quotatype = 'custom';
11058:             }
11059:         }
11060:     }
11061:     if (wantarray) {
11062:         return ($quota,$quotatype,$settingstatus,$defquota);
11063:     } else {
11064:         return $quota;
11065:     }
11066: }
11067: 
11068: ###############################################
11069: 
11070: =pod
11071: 
11072: =item * &default_quota()
11073: 
11074: Retrieves default quota assigned for storage of user portfolio files,
11075: given an (optional) user's institutional status.
11076: 
11077: Incoming parameters:
11078: 
11079: 1. domain
11080: 2. (Optional) institutional status(es).  This is a : separated list of 
11081:    status types (e.g., faculty, staff, student etc.)
11082:    which apply to the user for whom the default is being retrieved.
11083:    If the institutional status string in undefined, the domain
11084:    default quota will be returned.
11085: 3.  quota name - portfolio, author, or course
11086:    (if no quota name provided, defaults to portfolio).
11087: 
11088: Returns:
11089: 
11090: 1. Default disk quota (in MB) for user portfolios in the domain.
11091: 2. (Optional) institutional type which determined the value of the
11092:    default quota.
11093: 
11094: If a value has been stored in the domain's configuration db,
11095: it will return that, otherwise it returns 20 (for backwards 
11096: compatibility with domains which have not set up a configuration
11097: db file; the original statically defined portfolio quota was 20 MB). 
11098: 
11099: If the user's status includes multiple types (e.g., staff and student),
11100: the largest default quota which applies to the user determines the
11101: default quota returned.
11102: 
11103: =cut
11104: 
11105: ###############################################
11106: 
11107: 
11108: sub default_quota {
11109:     my ($udom,$inststatus,$quotaname) = @_;
11110:     my ($defquota,$settingstatus);
11111:     my %quotahash = &Apache::lonnet::get_dom('configuration',
11112:                                             ['quotas'],$udom);
11113:     my $key = 'defaultquota';
11114:     if ($quotaname eq 'author') {
11115:         $key = 'authorquota';
11116:     }
11117:     if (ref($quotahash{'quotas'}) eq 'HASH') {
11118:         if ($inststatus ne '') {
11119:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11120:             foreach my $item (@statuses) {
11121:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11122:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
11123:                         if ($defquota eq '') {
11124:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11125:                             $settingstatus = $item;
11126:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11127:                             $defquota = $quotahash{'quotas'}{$key}{$item};
11128:                             $settingstatus = $item;
11129:                         }
11130:                     }
11131:                 } elsif ($key eq 'defaultquota') {
11132:                     if ($quotahash{'quotas'}{$item} ne '') {
11133:                         if ($defquota eq '') {
11134:                             $defquota = $quotahash{'quotas'}{$item};
11135:                             $settingstatus = $item;
11136:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11137:                             $defquota = $quotahash{'quotas'}{$item};
11138:                             $settingstatus = $item;
11139:                         }
11140:                     }
11141:                 }
11142:             }
11143:         }
11144:         if ($defquota eq '') {
11145:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11146:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
11147:             } elsif ($key eq 'defaultquota') {
11148:                 $defquota = $quotahash{'quotas'}{'default'};
11149:             }
11150:             $settingstatus = 'default';
11151:             if ($defquota eq '') {
11152:                 if ($quotaname eq 'author') {
11153:                     $defquota = 500;
11154:                 }
11155:             }
11156:         }
11157:     } else {
11158:         $settingstatus = 'default';
11159:         if ($quotaname eq 'author') {
11160:             $defquota = 500;
11161:         } else {
11162:             $defquota = 20;
11163:         }
11164:     }
11165:     if (wantarray) {
11166:         return ($defquota,$settingstatus);
11167:     } else {
11168:         return $defquota;
11169:     }
11170: }
11171: 
11172: ###############################################
11173: 
11174: =pod
11175: 
11176: =item * &excess_filesize_warning()
11177: 
11178: Returns warning message if upload of file to authoring space, or copying
11179: of existing file within authoring space will cause quota for the authoring
11180: space to be exceeded.
11181: 
11182: Same, if upload of a file directly to a course/community via Course Editor
11183: will cause quota for uploaded content for the course to be exceeded.
11184: 
11185: Inputs: 7 
11186: 1. username or coursenum
11187: 2. domain
11188: 3. context ('author' or 'course')
11189: 4. filename of file for which action is being requested
11190: 5. filesize (kB) of file
11191: 6. action being taken: copy or upload.
11192: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11193: 
11194: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11195:          otherwise return null.
11196: 
11197: =back
11198: 
11199: =cut
11200: 
11201: sub excess_filesize_warning {
11202:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11203:     my $current_disk_usage = 0;
11204:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11205:     if ($context eq 'author') {
11206:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11207:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11208:     } else {
11209:         foreach my $subdir ('docs','supplemental') {
11210:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11211:         }
11212:     }
11213:     $disk_quota = int($disk_quota * 1000);
11214:     if (($current_disk_usage + $filesize) > $disk_quota) {
11215:         return '<p class="LC_warning">'.
11216:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11217:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11218:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11219:                             $disk_quota,$current_disk_usage).
11220:                '</p>';
11221:     }
11222:     return;
11223: }
11224: 
11225: ###############################################
11226: 
11227: 
11228: 
11229: 
11230: sub get_secgrprole_info {
11231:     my ($cdom,$cnum,$needroles,$type)  = @_;
11232:     my %sections_count = &get_sections($cdom,$cnum);
11233:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
11234:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11235:     my @groups = sort(keys(%curr_groups));
11236:     my $allroles = [];
11237:     my $rolehash;
11238:     my $accesshash = {
11239:                      active => 'Currently has access',
11240:                      future => 'Will have future access',
11241:                      previous => 'Previously had access',
11242:                   };
11243:     if ($needroles) {
11244:         $rolehash = {'all' => 'all'};
11245:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11246: 	if (&Apache::lonnet::error(%user_roles)) {
11247: 	    undef(%user_roles);
11248: 	}
11249:         foreach my $item (keys(%user_roles)) {
11250:             my ($role)=split(/\:/,$item,2);
11251:             if ($role eq 'cr') { next; }
11252:             if ($role =~ /^cr/) {
11253:                 $$rolehash{$role} = (split('/',$role))[3];
11254:             } else {
11255:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11256:             }
11257:         }
11258:         foreach my $key (sort(keys(%{$rolehash}))) {
11259:             push(@{$allroles},$key);
11260:         }
11261:         push (@{$allroles},'st');
11262:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11263:     }
11264:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11265: }
11266: 
11267: sub user_picker {
11268:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11269:     my $currdom = $dom;
11270:     my @alldoms = &Apache::lonnet::all_domains();
11271:     if (@alldoms == 1) {
11272:         my %domsrch = &Apache::lonnet::get_dom('configuration',
11273:                                                ['directorysrch'],$alldoms[0]);
11274:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11275:         my $showdom = $domdesc;
11276:         if ($showdom eq '') {
11277:             $showdom = $dom;
11278:         }
11279:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11280:             if ((!$domsrch{'directorysrch'}{'available'}) &&
11281:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11282:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11283:             }
11284:         }
11285:     }
11286:     my %curr_selected = (
11287:                         srchin => 'dom',
11288:                         srchby => 'lastname',
11289:                       );
11290:     my $srchterm;
11291:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11292:         if ($srch->{'srchby'} ne '') {
11293:             $curr_selected{'srchby'} = $srch->{'srchby'};
11294:         }
11295:         if ($srch->{'srchin'} ne '') {
11296:             $curr_selected{'srchin'} = $srch->{'srchin'};
11297:         }
11298:         if ($srch->{'srchtype'} ne '') {
11299:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
11300:         }
11301:         if ($srch->{'srchdomain'} ne '') {
11302:             $currdom = $srch->{'srchdomain'};
11303:         }
11304:         $srchterm = $srch->{'srchterm'};
11305:     }
11306:     my %html_lt=&Apache::lonlocal::texthash(
11307:                     'usr'       => 'Search criteria',
11308:                     'doma'      => 'Domain/institution to search',
11309:                     'uname'     => 'username',
11310:                     'lastname'  => 'last name',
11311:                     'lastfirst' => 'last name, first name',
11312:                     'crs'       => 'in this course',
11313:                     'dom'       => 'in selected LON-CAPA domain', 
11314:                     'alc'       => 'all LON-CAPA',
11315:                     'instd'     => 'in institutional directory for selected domain',
11316:                     'exact'     => 'is',
11317:                     'contains'  => 'contains',
11318:                     'begins'    => 'begins with',
11319:                                        );
11320:     my %js_lt=&Apache::lonlocal::texthash(
11321:                     'youm'      => "You must include some text to search for.",
11322:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11323:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11324:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
11325:                     'ymcd'      => "You must choose a domain when using a domain search.",
11326:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
11327:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
11328:                      'thfo'     => "The following need to be corrected before the search can be run:",
11329:                                        );
11330:     &html_escape(\%html_lt);
11331:     &js_escape(\%js_lt);
11332:     my $domform;
11333:     my $allow_blank = 1;
11334:     if ($fixeddom) {
11335:         $allow_blank = 0;
11336:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11337:     } else {
11338:         my $defdom = $env{'request.role.domain'};
11339:         my ($trusted,$untrusted);
11340:         if (($context eq 'requestcrs') || ($context eq 'course')) {
11341:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11342:         } elsif ($context eq 'author') {
11343:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11344:         } elsif ($context eq 'domain') {
11345:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11346:         }
11347:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11348:     }
11349:     my $srchinsel = ' <select name="srchin">';
11350: 
11351:     my @srchins = ('crs','dom','alc','instd');
11352: 
11353:     foreach my $option (@srchins) {
11354:         # FIXME 'alc' option unavailable until 
11355:         #       loncreateuser::print_user_query_page()
11356:         #       has been completed.
11357:         next if ($option eq 'alc');
11358:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
11359:         next if ($option eq 'crs' && !$env{'request.course.id'});
11360:         next if (($option eq 'instd') && ($noinstd));
11361:         if ($curr_selected{'srchin'} eq $option) {
11362:             $srchinsel .= ' 
11363:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11364:         } else {
11365:             $srchinsel .= '
11366:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11367:         }
11368:     }
11369:     $srchinsel .= "\n  </select>\n";
11370: 
11371:     my $srchbysel =  ' <select name="srchby">';
11372:     foreach my $option ('lastname','lastfirst','uname') {
11373:         if ($curr_selected{'srchby'} eq $option) {
11374:             $srchbysel .= '
11375:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11376:         } else {
11377:             $srchbysel .= '
11378:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11379:          }
11380:     }
11381:     $srchbysel .= "\n  </select>\n";
11382: 
11383:     my $srchtypesel = ' <select name="srchtype">';
11384:     foreach my $option ('begins','contains','exact') {
11385:         if ($curr_selected{'srchtype'} eq $option) {
11386:             $srchtypesel .= '
11387:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11388:         } else {
11389:             $srchtypesel .= '
11390:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11391:         }
11392:     }
11393:     $srchtypesel .= "\n  </select>\n";
11394: 
11395:     my ($newuserscript,$new_user_create);
11396:     my $context_dom = $env{'request.role.domain'};
11397:     if ($context eq 'requestcrs') {
11398:         if ($env{'form.coursedom'} ne '') { 
11399:             $context_dom = $env{'form.coursedom'};
11400:         }
11401:     }
11402:     if ($forcenewuser) {
11403:         if (ref($srch) eq 'HASH') {
11404:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11405:                 if ($cancreate) {
11406:                     $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>';
11407:                 } else {
11408:                     my $helplink = 'javascript:helpMenu('."'display'".')';
11409:                     my %usertypetext = (
11410:                         official   => 'institutional',
11411:                         unofficial => 'non-institutional',
11412:                     );
11413:                     $new_user_create = '<p class="LC_warning">'
11414:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11415:                                       .' '
11416:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11417:                                           ,'<a href="'.$helplink.'">','</a>')
11418:                                       .'</p><br />';
11419:                 }
11420:             }
11421:         }
11422: 
11423:         $newuserscript = <<"ENDSCRIPT";
11424: 
11425: function setSearch(createnew,callingForm) {
11426:     if (createnew == 1) {
11427:         for (var i=0; i<callingForm.srchby.length; i++) {
11428:             if (callingForm.srchby.options[i].value == 'uname') {
11429:                 callingForm.srchby.selectedIndex = i;
11430:             }
11431:         }
11432:         for (var i=0; i<callingForm.srchin.length; i++) {
11433:             if ( callingForm.srchin.options[i].value == 'dom') {
11434: 		callingForm.srchin.selectedIndex = i;
11435:             }
11436:         }
11437:         for (var i=0; i<callingForm.srchtype.length; i++) {
11438:             if (callingForm.srchtype.options[i].value == 'exact') {
11439:                 callingForm.srchtype.selectedIndex = i;
11440:             }
11441:         }
11442:         for (var i=0; i<callingForm.srchdomain.length; i++) {
11443:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
11444:                 callingForm.srchdomain.selectedIndex = i;
11445:             }
11446:         }
11447:     }
11448: }
11449: ENDSCRIPT
11450: 
11451:     }
11452: 
11453:     my $output = <<"END_BLOCK";
11454: <script type="text/javascript">
11455: // <![CDATA[
11456: function validateEntry(callingForm) {
11457: 
11458:     var checkok = 1;
11459:     var srchin;
11460:     for (var i=0; i<callingForm.srchin.length; i++) {
11461: 	if ( callingForm.srchin[i].checked ) {
11462: 	    srchin = callingForm.srchin[i].value;
11463: 	}
11464:     }
11465: 
11466:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11467:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11468:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11469:     var srchterm =  callingForm.srchterm.value;
11470:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11471:     var msg = "";
11472: 
11473:     if (srchterm == "") {
11474:         checkok = 0;
11475:         msg += "$js_lt{'youm'}\\n";
11476:     }
11477: 
11478:     if (srchtype== 'begins') {
11479:         if (srchterm.length < 2) {
11480:             checkok = 0;
11481:             msg += "$js_lt{'thte'}\\n";
11482:         }
11483:     }
11484: 
11485:     if (srchtype== 'contains') {
11486:         if (srchterm.length < 3) {
11487:             checkok = 0;
11488:             msg += "$js_lt{'thet'}\\n";
11489:         }
11490:     }
11491:     if (srchin == 'instd') {
11492:         if (srchdomain == '') {
11493:             checkok = 0;
11494:             msg += "$js_lt{'yomc'}\\n";
11495:         }
11496:     }
11497:     if (srchin == 'dom') {
11498:         if (srchdomain == '') {
11499:             checkok = 0;
11500:             msg += "$js_lt{'ymcd'}\\n";
11501:         }
11502:     }
11503:     if (srchby == 'lastfirst') {
11504:         if (srchterm.indexOf(",") == -1) {
11505:             checkok = 0;
11506:             msg += "$js_lt{'whus'}\\n";
11507:         }
11508:         if (srchterm.indexOf(",") == srchterm.length -1) {
11509:             checkok = 0;
11510:             msg += "$js_lt{'whse'}\\n";
11511:         }
11512:     }
11513:     if (checkok == 0) {
11514:         alert("$js_lt{'thfo'}\\n"+msg);
11515:         return;
11516:     }
11517:     if (checkok == 1) {
11518:         callingForm.submit();
11519:     }
11520: }
11521: 
11522: $newuserscript
11523: 
11524: // ]]>
11525: </script>
11526: 
11527: $new_user_create
11528: 
11529: END_BLOCK
11530: 
11531:     $output .= &Apache::lonhtmlcommon::start_pick_box().
11532:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11533:                $domform.
11534:                &Apache::lonhtmlcommon::row_closure().
11535:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11536:                $srchbysel.
11537:                $srchtypesel. 
11538:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11539:                $srchinsel.
11540:                &Apache::lonhtmlcommon::row_closure(1). 
11541:                &Apache::lonhtmlcommon::end_pick_box().
11542:                '<br />';
11543:     return ($output,1);
11544: }
11545: 
11546: sub user_rule_check {
11547:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11548:     my ($response,%inst_response);
11549:     if (ref($usershash) eq 'HASH') {
11550:         if (keys(%{$usershash}) > 1) {
11551:             my (%by_username,%by_id,%userdoms);
11552:             my $checkid; 
11553:             if (ref($checks) eq 'HASH') {
11554:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11555:                     $checkid = 1;
11556:                 }
11557:             }
11558:             foreach my $user (keys(%{$usershash})) {
11559:                 my ($uname,$udom) = split(/:/,$user);
11560:                 if ($checkid) {
11561:                     if (ref($usershash->{$user}) eq 'HASH') {
11562:                         if ($usershash->{$user}->{'id'} ne '') {
11563:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
11564:                             $userdoms{$udom} = 1;
11565:                             if (ref($inst_results) eq 'HASH') {
11566:                                 $inst_results->{$uname.':'.$udom} = {};
11567:                             }
11568:                         }
11569:                     }
11570:                 } else {
11571:                     $by_username{$udom}{$uname} = 1;
11572:                     $userdoms{$udom} = 1;
11573:                     if (ref($inst_results) eq 'HASH') {
11574:                         $inst_results->{$uname.':'.$udom} = {};
11575:                     }
11576:                 }
11577:             }
11578:             foreach my $udom (keys(%userdoms)) {
11579:                 if (!$got_rules->{$udom}) {
11580:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
11581:                                                              ['usercreation'],$udom);
11582:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11583:                         foreach my $item ('username','id') {
11584:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11585:                                 $$curr_rules{$udom}{$item} =
11586:                                     $domconfig{'usercreation'}{$item.'_rule'};
11587:                             }
11588:                         }
11589:                     }
11590:                     $got_rules->{$udom} = 1;
11591:                 }
11592:             }
11593:             if ($checkid) {
11594:                 foreach my $udom (keys(%by_id)) {
11595:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11596:                     if ($outcome eq 'ok') {
11597:                         foreach my $id (keys(%{$by_id{$udom}})) {
11598:                             my $uname = $by_id{$udom}{$id};
11599:                             $inst_response{$uname.':'.$udom} = $outcome;
11600:                         }
11601:                         if (ref($results) eq 'HASH') {
11602:                             foreach my $uname (keys(%{$results})) {
11603:                                 if (exists($inst_response{$uname.':'.$udom})) {
11604:                                     $inst_response{$uname.':'.$udom} = $outcome;
11605:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
11606:                                 }
11607:                             }
11608:                         }
11609:                     }
11610:                 }
11611:             } else {
11612:                 foreach my $udom (keys(%by_username)) {
11613:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11614:                     if ($outcome eq 'ok') {
11615:                         foreach my $uname (keys(%{$by_username{$udom}})) {
11616:                             $inst_response{$uname.':'.$udom} = $outcome;
11617:                         }
11618:                         if (ref($results) eq 'HASH') {
11619:                             foreach my $uname (keys(%{$results})) {
11620:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
11621:                             }
11622:                         }
11623:                     }
11624:                 }
11625:             }
11626:         } elsif (keys(%{$usershash}) == 1) {
11627:             my $user = (keys(%{$usershash}))[0];
11628:             my ($uname,$udom) = split(/:/,$user);
11629:             if (($udom ne '') && ($uname ne '')) {
11630:                 if (ref($usershash->{$user}) eq 'HASH') {
11631:                     if (ref($checks) eq 'HASH') {
11632:                         if (defined($checks->{'username'})) {
11633:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
11634:                                 &Apache::lonnet::get_instuser($udom,$uname);
11635:                         } elsif (defined($checks->{'id'})) {
11636:                             if ($usershash->{$user}->{'id'} ne '') {
11637:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11638:                                     &Apache::lonnet::get_instuser($udom,undef,
11639:                                                                   $usershash->{$user}->{'id'});
11640:                             } else {
11641:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
11642:                                     &Apache::lonnet::get_instuser($udom,$uname);
11643:                             }
11644:                         }
11645:                     } else {
11646:                        ($inst_response{$user},%{$inst_results->{$user}}) =
11647:                             &Apache::lonnet::get_instuser($udom,$uname);
11648:                        return;
11649:                     }
11650:                     if (!$got_rules->{$udom}) {
11651:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
11652:                                                                  ['usercreation'],$udom);
11653:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
11654:                             foreach my $item ('username','id') {
11655:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11656:                                    $$curr_rules{$udom}{$item} = 
11657:                                        $domconfig{'usercreation'}{$item.'_rule'};
11658:                                 }
11659:                             }
11660:                         }
11661:                         $got_rules->{$udom} = 1;
11662:                     }
11663:                 }
11664:             } else {
11665:                 return;
11666:             }
11667:         } else {
11668:             return;
11669:         }
11670:         foreach my $user (keys(%{$usershash})) {
11671:             my ($uname,$udom) = split(/:/,$user);
11672:             next if (($udom eq '') || ($uname eq ''));
11673:             my $id;
11674:             if (ref($inst_results) eq 'HASH') {
11675:                 if (ref($inst_results->{$user}) eq 'HASH') {
11676:                     $id = $inst_results->{$user}->{'id'};
11677:                 }
11678:             }
11679:             if ($id eq '') { 
11680:                 if (ref($usershash->{$user})) {
11681:                     $id = $usershash->{$user}->{'id'};
11682:                 }
11683:             }
11684:             foreach my $item (keys(%{$checks})) {
11685:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
11686:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11687:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
11688:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11689:                                                                              $$curr_rules{$udom}{$item});
11690:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11691:                                 if ($rule_check{$rule}) {
11692:                                     $$rulematch{$user}{$item} = $rule;
11693:                                     if ($inst_response{$user} eq 'ok') {
11694:                                         if (ref($inst_results) eq 'HASH') {
11695:                                             if (ref($inst_results->{$user}) eq 'HASH') {
11696:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
11697:                                                     $$alerts{$item}{$udom}{$uname} = 1;
11698:                                                 } elsif ($item eq 'id') {
11699:                                                     if ($inst_results->{$user}->{'id'} eq '') {
11700:                                                         $$alerts{$item}{$udom}{$uname} = 1;
11701:                                                     }
11702:                                                 }
11703:                                             }
11704:                                         }
11705:                                     }
11706:                                     last;
11707:                                 }
11708:                             }
11709:                         }
11710:                     }
11711:                 }
11712:             }
11713:         }
11714:     }
11715:     return;
11716: }
11717: 
11718: sub user_rule_formats {
11719:     my ($domain,$domdesc,$curr_rules,$check) = @_;
11720:     my %text = ( 
11721:                  'username' => 'Usernames',
11722:                  'id'       => 'IDs',
11723:                );
11724:     my $output;
11725:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11726:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11727:         if (@{$ruleorder} > 0) {
11728:             $output = '<br />'.
11729:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11730:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
11731:                       ' <ul>';
11732:             foreach my $rule (@{$ruleorder}) {
11733:                 if (ref($curr_rules) eq 'ARRAY') {
11734:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11735:                         if (ref($rules->{$rule}) eq 'HASH') {
11736:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11737:                                         $rules->{$rule}{'desc'}.'</li>';
11738:                         }
11739:                     }
11740:                 }
11741:             }
11742:             $output .= '</ul>';
11743:         }
11744:     }
11745:     return $output;
11746: }
11747: 
11748: sub instrule_disallow_msg {
11749:     my ($checkitem,$domdesc,$count,$mode) = @_;
11750:     my $response;
11751:     my %text = (
11752:                   item   => 'username',
11753:                   items  => 'usernames',
11754:                   match  => 'matches',
11755:                   do     => 'does',
11756:                   action => 'a username',
11757:                   one    => 'one',
11758:                );
11759:     if ($count > 1) {
11760:         $text{'item'} = 'usernames';
11761:         $text{'match'} ='match';
11762:         $text{'do'} = 'do';
11763:         $text{'action'} = 'usernames',
11764:         $text{'one'} = 'ones';
11765:     }
11766:     if ($checkitem eq 'id') {
11767:         $text{'items'} = 'IDs';
11768:         $text{'item'} = 'ID';
11769:         $text{'action'} = 'an ID';
11770:         if ($count > 1) {
11771:             $text{'item'} = 'IDs';
11772:             $text{'action'} = 'IDs';
11773:         }
11774:     }
11775:     $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 />';
11776:     if ($mode eq 'upload') {
11777:         if ($checkitem eq 'username') {
11778:             $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'}.");
11779:         } elsif ($checkitem eq 'id') {
11780:             $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.");
11781:         }
11782:     } elsif ($mode eq 'selfcreate') {
11783:         if ($checkitem eq 'id') {
11784:             $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.");
11785:         }
11786:     } else {
11787:         if ($checkitem eq 'username') {
11788:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11789:         } elsif ($checkitem eq 'id') {
11790:             $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.");
11791:         }
11792:     }
11793:     return $response;
11794: }
11795: 
11796: sub personal_data_fieldtitles {
11797:     my %fieldtitles = &Apache::lonlocal::texthash (
11798:                         id => 'Student/Employee ID',
11799:                         permanentemail => 'E-mail address',
11800:                         lastname => 'Last Name',
11801:                         firstname => 'First Name',
11802:                         middlename => 'Middle Name',
11803:                         generation => 'Generation',
11804:                         gen => 'Generation',
11805:                         inststatus => 'Affiliation',
11806:                    );
11807:     return %fieldtitles;
11808: }
11809: 
11810: sub sorted_inst_types {
11811:     my ($dom) = @_;
11812:     my ($usertypes,$order);
11813:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11814:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11815:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11816:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11817:     } else {
11818:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11819:     }
11820:     my $othertitle = &mt('All users');
11821:     if ($env{'request.course.id'}) {
11822:         $othertitle  = &mt('Any users');
11823:     }
11824:     my @types;
11825:     if (ref($order) eq 'ARRAY') {
11826:         @types = @{$order};
11827:     }
11828:     if (@types == 0) {
11829:         if (ref($usertypes) eq 'HASH') {
11830:             @types = sort(keys(%{$usertypes}));
11831:         }
11832:     }
11833:     if (keys(%{$usertypes}) > 0) {
11834:         $othertitle = &mt('Other users');
11835:     }
11836:     return ($othertitle,$usertypes,\@types);
11837: }
11838: 
11839: sub get_institutional_codes {
11840:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11841: # Get complete list of course sections to update
11842:     my @currsections = ();
11843:     my @currxlists = ();
11844:     my (%unclutteredsec,%unclutteredlcsec);
11845:     my $coursecode = $$settings{'internal.coursecode'};
11846:     my $crskey = $crs.':'.$coursecode;
11847:     @{$unclutteredsec{$crskey}} = ();
11848:     @{$unclutteredlcsec{$crskey}} = ();
11849: 
11850:     if ($$settings{'internal.sectionnums'} ne '') {
11851:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11852:     }
11853: 
11854:     if ($$settings{'internal.crosslistings'} ne '') {
11855:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11856:     }
11857: 
11858:     if (@currxlists > 0) {
11859:         foreach my $xl (@currxlists) {
11860:             if ($xl =~ /^([^:]+):(\w*)$/) {
11861:                 unless (grep/^$1$/,@{$allcourses}) {
11862:                     push(@{$allcourses},$1);
11863:                     $$LC_code{$1} = $2;
11864:                 }
11865:             }
11866:         }
11867:     }
11868: 
11869:     if (@currsections > 0) {
11870:         foreach my $sec (@currsections) {
11871:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11872:                 my $instsec = $1;
11873:                 my $lc_sec = $2;
11874:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11875:                     push(@{$unclutteredsec{$crskey}},$instsec);
11876:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11877:                 }
11878:             }
11879:         }
11880:     }
11881: 
11882:     if (@{$unclutteredsec{$crskey}} > 0) {
11883:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11884:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11885:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11886:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11887:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11888:                     push(@{$allcourses},$sec);
11889:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11890:                 }
11891:             }
11892:         }
11893:     }
11894:     return;
11895: }
11896: 
11897: sub get_standard_codeitems {
11898:     return ('Year','Semester','Department','Number','Section');
11899: }
11900: 
11901: =pod
11902: 
11903: =head1 Slot Helpers
11904: 
11905: =over 4
11906: 
11907: =item * sorted_slots()
11908: 
11909: Sorts an array of slot names in order of an optional sort key,
11910: default sort is by slot start time (earliest first). 
11911: 
11912: Inputs:
11913: 
11914: =over 4
11915: 
11916: slotsarr  - Reference to array of unsorted slot names.
11917: 
11918: slots     - Reference to hash of hash, where outer hash keys are slot names.
11919: 
11920: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11921: 
11922: =back
11923: 
11924: Returns:
11925: 
11926: =over 4
11927: 
11928: sorted   - An array of slot names sorted by a specified sort key 
11929:            (default sort key is start time of the slot).
11930: 
11931: =back
11932: 
11933: =cut
11934: 
11935: 
11936: sub sorted_slots {
11937:     my ($slotsarr,$slots,$sortkey) = @_;
11938:     if ($sortkey eq '') {
11939:         $sortkey = 'starttime';
11940:     }
11941:     my @sorted;
11942:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11943:         @sorted =
11944:             sort {
11945:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11946:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11947:                      }
11948:                      if (ref($slots->{$a})) { return -1;}
11949:                      if (ref($slots->{$b})) { return 1;}
11950:                      return 0;
11951:                  } @{$slotsarr};
11952:     }
11953:     return @sorted;
11954: }
11955: 
11956: =pod
11957: 
11958: =item * get_future_slots()
11959: 
11960: Inputs:
11961: 
11962: =over 4
11963: 
11964: cnum - course number
11965: 
11966: cdom - course domain
11967: 
11968: now - current UNIX time
11969: 
11970: symb - optional symb
11971: 
11972: =back
11973: 
11974: Returns:
11975: 
11976: =over 4
11977: 
11978: sorted_reservable - ref to array of student_schedulable slots currently 
11979:                     reservable, ordered by end date of reservation period.
11980: 
11981: reservable_now - ref to hash of student_schedulable slots currently
11982:                  reservable.
11983: 
11984:     Keys in inner hash are:
11985:     (a) symb: either blank or symb to which slot use is restricted.
11986:     (b) endreserve: end date of reservation period.
11987:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11988:         selected.
11989: 
11990: sorted_future - ref to array of student_schedulable slots reservable in
11991:                 the future, ordered by start date of reservation period.
11992: 
11993: future_reservable - ref to hash of student_schedulable slots reservable
11994:                     in the future.
11995: 
11996:     Keys in inner hash are:
11997:     (a) symb: either blank or symb to which slot use is restricted.
11998:     (b) startreserve: start date of reservation period.
11999:     (c) uniqueperiod: start,end dates when slot is to be uniquely
12000:         selected.
12001: 
12002: =back
12003: 
12004: =cut
12005: 
12006: sub get_future_slots {
12007:     my ($cnum,$cdom,$now,$symb) = @_;
12008:     my $map;
12009:     if ($symb) {
12010:         ($map) = &Apache::lonnet::decode_symb($symb);
12011:     }
12012:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12013:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12014:     foreach my $slot (keys(%slots)) {
12015:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12016:         if ($symb) {
12017:             if ($slots{$slot}->{'symb'} ne '') {
12018:                 my $canuse;
12019:                 my %oksymbs;
12020:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12021:                 map { $oksymbs{$_} = 1; } @slotsymbs;
12022:                 if ($oksymbs{$symb}) {
12023:                     $canuse = 1;
12024:                 } else {
12025:                     foreach my $item (@slotsymbs) {
12026:                         if ($item =~ /\.(page|sequence)$/) {
12027:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12028:                             if (($map ne '') && ($map eq $sloturl)) {
12029:                                 $canuse = 1;
12030:                                 last;
12031:                             }
12032:                         }
12033:                     }
12034:                 }
12035:                 next unless ($canuse);
12036:             }
12037:         }
12038:         if (($slots{$slot}->{'starttime'} > $now) &&
12039:             ($slots{$slot}->{'endtime'} > $now)) {
12040:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12041:                 my $userallowed = 0;
12042:                 if ($slots{$slot}->{'allowedsections'}) {
12043:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12044:                     if (!defined($env{'request.role.sec'})
12045:                         && grep(/^No section assigned$/,@allowed_sec)) {
12046:                         $userallowed=1;
12047:                     } else {
12048:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12049:                             $userallowed=1;
12050:                         }
12051:                     }
12052:                     unless ($userallowed) {
12053:                         if (defined($env{'request.course.groups'})) {
12054:                             my @groups = split(/:/,$env{'request.course.groups'});
12055:                             foreach my $group (@groups) {
12056:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
12057:                                     $userallowed=1;
12058:                                     last;
12059:                                 }
12060:                             }
12061:                         }
12062:                     }
12063:                 }
12064:                 if ($slots{$slot}->{'allowedusers'}) {
12065:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12066:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
12067:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
12068:                         $userallowed = 1;
12069:                     }
12070:                 }
12071:                 next unless($userallowed);
12072:             }
12073:             my $startreserve = $slots{$slot}->{'startreserve'};
12074:             my $endreserve = $slots{$slot}->{'endreserve'};
12075:             my $symb = $slots{$slot}->{'symb'};
12076:             my $uniqueperiod;
12077:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12078:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12079:             }
12080:             if (($startreserve < $now) &&
12081:                 (!$endreserve || $endreserve > $now)) {
12082:                 my $lastres = $endreserve;
12083:                 if (!$lastres) {
12084:                     $lastres = $slots{$slot}->{'starttime'};
12085:                 }
12086:                 $reservable_now{$slot} = {
12087:                                            symb       => $symb,
12088:                                            endreserve => $lastres,
12089:                                            uniqueperiod => $uniqueperiod,
12090:                                          };
12091:             } elsif (($startreserve > $now) &&
12092:                      (!$endreserve || $endreserve > $startreserve)) {
12093:                 $future_reservable{$slot} = {
12094:                                               symb         => $symb,
12095:                                               startreserve => $startreserve,
12096:                                               uniqueperiod => $uniqueperiod,
12097:                                             };
12098:             }
12099:         }
12100:     }
12101:     my @unsorted_reservable = keys(%reservable_now);
12102:     if (@unsorted_reservable > 0) {
12103:         @sorted_reservable = 
12104:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12105:     }
12106:     my @unsorted_future = keys(%future_reservable);
12107:     if (@unsorted_future > 0) {
12108:         @sorted_future =
12109:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12110:     }
12111:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12112: }
12113: 
12114: =pod
12115: 
12116: =back
12117: 
12118: =head1 HTTP Helpers
12119: 
12120: =over 4
12121: 
12122: =item * &get_unprocessed_cgi($query,$possible_names)
12123: 
12124: Modify the %env hash to contain unprocessed CGI form parameters held in
12125: $query.  The parameters listed in $possible_names (an array reference),
12126: will be set in $env{'form.name'} if they do not already exist.
12127: 
12128: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
12129: $possible_names is an ref to an array of form element names.  As an example:
12130: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12131: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12132: 
12133: =cut
12134: 
12135: sub get_unprocessed_cgi {
12136:   my ($query,$possible_names)= @_;
12137:   # $Apache::lonxml::debug=1;
12138:   foreach my $pair (split(/&/,$query)) {
12139:     my ($name, $value) = split(/=/,$pair);
12140:     $name = &unescape($name);
12141:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12142:       $value =~ tr/+/ /;
12143:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12144:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12145:     }
12146:   }
12147: }
12148: 
12149: =pod
12150: 
12151: =item * &cacheheader() 
12152: 
12153: returns cache-controlling header code
12154: 
12155: =cut
12156: 
12157: sub cacheheader {
12158:     unless ($env{'request.method'} eq 'GET') { return ''; }
12159:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12160:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12161:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12162:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12163:     return $output;
12164: }
12165: 
12166: =pod
12167: 
12168: =item * &no_cache($r) 
12169: 
12170: specifies header code to not have cache
12171: 
12172: =cut
12173: 
12174: sub no_cache {
12175:     my ($r) = @_;
12176:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12177: 	$env{'request.method'} ne 'GET') { return ''; }
12178:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12179:     $r->no_cache(1);
12180:     $r->header_out("Expires" => $date);
12181:     $r->header_out("Pragma" => "no-cache");
12182: }
12183: 
12184: sub content_type {
12185:     my ($r,$type,$charset) = @_;
12186:     if ($r) {
12187: 	#  Note that printout.pl calls this with undef for $r.
12188: 	&no_cache($r);
12189:     }
12190:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12191:     unless ($charset) {
12192: 	$charset=&Apache::lonlocal::current_encoding;
12193:     }
12194:     if ($charset) { $type.='; charset='.$charset; }
12195:     if ($r) {
12196: 	$r->content_type($type);
12197:     } else {
12198: 	print("Content-type: $type\n\n");
12199:     }
12200: }
12201: 
12202: =pod
12203: 
12204: =item * &add_to_env($name,$value) 
12205: 
12206: adds $name to the %env hash with value
12207: $value, if $name already exists, the entry is converted to an array
12208: reference and $value is added to the array.
12209: 
12210: =cut
12211: 
12212: sub add_to_env {
12213:   my ($name,$value)=@_;
12214:   if (defined($env{$name})) {
12215:     if (ref($env{$name})) {
12216:       #already have multiple values
12217:       push(@{ $env{$name} },$value);
12218:     } else {
12219:       #first time seeing multiple values, convert hash entry to an arrayref
12220:       my $first=$env{$name};
12221:       undef($env{$name});
12222:       push(@{ $env{$name} },$first,$value);
12223:     }
12224:   } else {
12225:     $env{$name}=$value;
12226:   }
12227: }
12228: 
12229: =pod
12230: 
12231: =item * &get_env_multiple($name) 
12232: 
12233: gets $name from the %env hash, it seemlessly handles the cases where multiple
12234: values may be defined and end up as an array ref.
12235: 
12236: returns an array of values
12237: 
12238: =cut
12239: 
12240: sub get_env_multiple {
12241:     my ($name) = @_;
12242:     my @values;
12243:     if (defined($env{$name})) {
12244:         # exists is it an array
12245:         if (ref($env{$name})) {
12246:             @values=@{ $env{$name} };
12247:         } else {
12248:             $values[0]=$env{$name};
12249:         }
12250:     }
12251:     return(@values);
12252: }
12253: 
12254: # Looks at given dependencies, and returns something depending on the context.
12255: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12256: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12257: # For all other contexts, returns ($output, $counter, $numpathchg).
12258: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12259: # $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.
12260: # $numpathchg: integer with the number of cleaned up dependency paths.
12261: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12262: # \%mapping: hash reference clean path -> original path for all dependencies.
12263: # @param {string} actionurl - The path to the handler, indicative of the context.
12264: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12265: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12266: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12267: # @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)
12268: # @return {Array} - array depending on the context (not a reference)
12269: sub ask_for_embedded_content {
12270:     # NOTE: documentation was added afterwards, it could be wrong
12271:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12272:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12273:         %currsubfile,%unused,$rem);
12274:     my $counter = 0;
12275:     my $numnew = 0;
12276:     my $numremref = 0;
12277:     my $numinvalid = 0;
12278:     my $numpathchg = 0;
12279:     my $numexisting = 0;
12280:     my $numunused = 0;
12281:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12282:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12283:     my $heading = &mt('Upload embedded files');
12284:     my $buttontext = &mt('Upload');
12285: 
12286:     # fills these variables based on the context:
12287:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12288:     # $path, $fileloc, $title, $rem, $filename
12289:     if ($env{'request.course.id'}) {
12290:         if ($actionurl eq '/adm/dependencies') {
12291:             $navmap = Apache::lonnavmaps::navmap->new();
12292:         }
12293:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12294:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12295:     }
12296:     if (($actionurl eq '/adm/portfolio') || 
12297:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12298:         my $current_path='/';
12299:         if ($env{'form.currentpath'}) {
12300:             $current_path = $env{'form.currentpath'};
12301:         }
12302:         if ($actionurl eq '/adm/coursegrp_portfolio') {
12303:             $udom = $cdom;
12304:             $uname = $cnum;
12305:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12306:         } else {
12307:             $udom = $env{'user.domain'};
12308:             $uname = $env{'user.name'};
12309:             $url = '/userfiles/portfolio';
12310:         }
12311:         $toplevel = $url.'/';
12312:         $url .= $current_path;
12313:         $getpropath = 1;
12314:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12315:              ($actionurl eq '/adm/imsimport')) { 
12316:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12317:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12318:         $toplevel = $url;
12319:         if ($rest ne '') {
12320:             $url .= $rest;
12321:         }
12322:     } elsif ($actionurl eq '/adm/coursedocs') {
12323:         if (ref($args) eq 'HASH') {
12324:             $url = $args->{'docs_url'};
12325:             $toplevel = $url;
12326:             if ($args->{'context'} eq 'paste') {
12327:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12328:                 ($path) = 
12329:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12330:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12331:                 $fileloc =~ s{^/}{};
12332:             }
12333:         }
12334:     } elsif ($actionurl eq '/adm/dependencies')  {
12335:         if ($env{'request.course.id'} ne '') {
12336:             if (ref($args) eq 'HASH') {
12337:                 $url = $args->{'docs_url'};
12338:                 $title = $args->{'docs_title'};
12339:                 $toplevel = $url; 
12340:                 unless ($toplevel =~ m{^/}) {
12341:                     $toplevel = "/$url";
12342:                 }
12343:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12344:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12345:                     $path = $1;
12346:                 } else {
12347:                     ($path) =
12348:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12349:                 }
12350:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
12351:                     $fileloc = $toplevel;
12352:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12353:                     my ($udom,$uname,$fname) =
12354:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12355:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12356:                 } else {
12357:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12358:                 }
12359:                 $fileloc =~ s{^/}{};
12360:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12361:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12362:             }
12363:         }
12364:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12365:         $udom = $cdom;
12366:         $uname = $cnum;
12367:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12368:         $toplevel = $url;
12369:         $path = $url;
12370:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12371:         $fileloc =~ s{^/}{};
12372:     }
12373:     
12374:     # parses the dependency paths to get some info
12375:     # fills $newfiles, $mapping, $subdependencies, $dependencies
12376:     # $newfiles: hash URL -> 1 for new files or external URLs
12377:     # (will be completed later)
12378:     # $mapping:
12379:     #   for external URLs: external URL -> external URL
12380:     #   for relative paths: clean path -> original path
12381:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12382:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12383:     foreach my $file (keys(%{$allfiles})) {
12384:         my $embed_file;
12385:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12386:             $embed_file = $1;
12387:         } else {
12388:             $embed_file = $file;
12389:         }
12390:         my ($absolutepath,$cleaned_file);
12391:         if ($embed_file =~ m{^\w+://}) {
12392:             $cleaned_file = $embed_file;
12393:             $newfiles{$cleaned_file} = 1;
12394:             $mapping{$cleaned_file} = $embed_file;
12395:         } else {
12396:             $cleaned_file = &clean_path($embed_file);
12397:             if ($embed_file =~ m{^/}) {
12398:                 $absolutepath = $embed_file;
12399:             }
12400:             if ($cleaned_file =~ m{/}) {
12401:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12402:                 $path = &check_for_traversal($path,$url,$toplevel);
12403:                 my $item = $fname;
12404:                 if ($path ne '') {
12405:                     $item = $path.'/'.$fname;
12406:                     $subdependencies{$path}{$fname} = 1;
12407:                 } else {
12408:                     $dependencies{$item} = 1;
12409:                 }
12410:                 if ($absolutepath) {
12411:                     $mapping{$item} = $absolutepath;
12412:                 } else {
12413:                     $mapping{$item} = $embed_file;
12414:                 }
12415:             } else {
12416:                 $dependencies{$embed_file} = 1;
12417:                 if ($absolutepath) {
12418:                     $mapping{$cleaned_file} = $absolutepath;
12419:                 } else {
12420:                     $mapping{$cleaned_file} = $embed_file;
12421:                 }
12422:             }
12423:         }
12424:     }
12425:     
12426:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12427:     # and lists
12428:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12429:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12430:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12431:     #                                    the path had to be cleaned up
12432:     # $existing: hash clean path -> 1 if the file exists
12433:     # $numexisting: number of keys in $existing
12434:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12435:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12436:     #                                      dependency subdirectories that are
12437:     #                                      not listed as dependencies, with some exceptions using $rem
12438:     my $dirptr = 16384;
12439:     foreach my $path (keys(%subdependencies)) {
12440:         $currsubfile{$path} = {};
12441:         if (($actionurl eq '/adm/portfolio') || 
12442:             ($actionurl eq '/adm/coursegrp_portfolio')) {
12443:             my ($sublistref,$listerror) =
12444:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12445:             if (ref($sublistref) eq 'ARRAY') {
12446:                 foreach my $line (@{$sublistref}) {
12447:                     my ($file_name,$rest) = split(/\&/,$line,2);
12448:                     $currsubfile{$path}{$file_name} = 1;
12449:                 }
12450:             }
12451:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12452:             if (opendir(my $dir,$url.'/'.$path)) {
12453:                 my @subdir_list = grep(!/^\./,readdir($dir));
12454:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12455:             }
12456:         } elsif (($actionurl eq '/adm/dependencies') ||
12457:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12458:                   ($args->{'context'} eq 'paste')) ||
12459:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12460:             if ($env{'request.course.id'} ne '') {
12461:                 my $dir;
12462:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12463:                     $dir = $fileloc;
12464:                 } else {
12465:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12466:                 }
12467:                 if ($dir ne '') {
12468:                     my ($sublistref,$listerror) =
12469:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12470:                     if (ref($sublistref) eq 'ARRAY') {
12471:                         foreach my $line (@{$sublistref}) {
12472:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12473:                                 undef,$mtime)=split(/\&/,$line,12);
12474:                             unless (($testdir&$dirptr) ||
12475:                                     ($file_name =~ /^\.\.?$/)) {
12476:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
12477:                             }
12478:                         }
12479:                     }
12480:                 }
12481:             }
12482:         }
12483:         foreach my $file (keys(%{$subdependencies{$path}})) {
12484:             if (exists($currsubfile{$path}{$file})) {
12485:                 my $item = $path.'/'.$file;
12486:                 unless ($mapping{$item} eq $item) {
12487:                     $pathchanges{$item} = 1;
12488:                 }
12489:                 $existing{$item} = 1;
12490:                 $numexisting ++;
12491:             } else {
12492:                 $newfiles{$path.'/'.$file} = 1;
12493:             }
12494:         }
12495:         if ($actionurl eq '/adm/dependencies') {
12496:             foreach my $path (keys(%currsubfile)) {
12497:                 if (ref($currsubfile{$path}) eq 'HASH') {
12498:                     foreach my $file (keys(%{$currsubfile{$path}})) {
12499:                          unless ($subdependencies{$path}{$file}) {
12500:                              next if (($rem ne '') &&
12501:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
12502:                                        (ref($navmap) &&
12503:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12504:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12505:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
12506:                              $unused{$path.'/'.$file} = 1; 
12507:                          }
12508:                     }
12509:                 }
12510:             }
12511:         }
12512:     }
12513:     
12514:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
12515:     # for files in $url or $fileloc (target directory) in some contexts
12516:     my %currfile;
12517:     if (($actionurl eq '/adm/portfolio') ||
12518:         ($actionurl eq '/adm/coursegrp_portfolio')) {
12519:         my ($dirlistref,$listerror) =
12520:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12521:         if (ref($dirlistref) eq 'ARRAY') {
12522:             foreach my $line (@{$dirlistref}) {
12523:                 my ($file_name,$rest) = split(/\&/,$line,2);
12524:                 $currfile{$file_name} = 1;
12525:             }
12526:         }
12527:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12528:         if (opendir(my $dir,$url)) {
12529:             my @dir_list = grep(!/^\./,readdir($dir));
12530:             map {$currfile{$_} = 1;} @dir_list;
12531:         }
12532:     } elsif (($actionurl eq '/adm/dependencies') ||
12533:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12534:               ($args->{'context'} eq 'paste')) ||
12535:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12536:         if ($env{'request.course.id'} ne '') {
12537:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12538:             if ($dir ne '') {
12539:                 my ($dirlistref,$listerror) =
12540:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12541:                 if (ref($dirlistref) eq 'ARRAY') {
12542:                     foreach my $line (@{$dirlistref}) {
12543:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12544:                             $size,undef,$mtime)=split(/\&/,$line,12);
12545:                         unless (($testdir&$dirptr) ||
12546:                                 ($file_name =~ /^\.\.?$/)) {
12547:                             $currfile{$file_name} = [$size,$mtime];
12548:                         }
12549:                     }
12550:                 }
12551:             }
12552:         }
12553:     }
12554:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12555:     # are not in subdirectories, using $currfile
12556:     foreach my $file (keys(%dependencies)) {
12557:         if (exists($currfile{$file})) {
12558:             unless ($mapping{$file} eq $file) {
12559:                 $pathchanges{$file} = 1;
12560:             }
12561:             $existing{$file} = 1;
12562:             $numexisting ++;
12563:         } else {
12564:             $newfiles{$file} = 1;
12565:         }
12566:     }
12567:     foreach my $file (keys(%currfile)) {
12568:         unless (($file eq $filename) ||
12569:                 ($file eq $filename.'.bak') ||
12570:                 ($dependencies{$file})) {
12571:             if ($actionurl eq '/adm/dependencies') {
12572:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12573:                     next if (($rem ne '') &&
12574:                              (($env{"httpref.$rem".$file} ne '') ||
12575:                               (ref($navmap) &&
12576:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
12577:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12578:                                 ($navmap->getResourceByUrl($rem.$1)))))));
12579:                 }
12580:             }
12581:             $unused{$file} = 1;
12582:         }
12583:     }
12584:     
12585:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12586:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12587:         ($args->{'context'} eq 'paste')) {
12588:         $counter = scalar(keys(%existing));
12589:         $numpathchg = scalar(keys(%pathchanges));
12590:         return ($output,$counter,$numpathchg,\%existing);
12591:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
12592:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12593:         $counter = scalar(keys(%existing));
12594:         $numpathchg = scalar(keys(%pathchanges));
12595:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
12596:     }
12597:     
12598:     # returns HTML otherwise, with dependency results and to ask for more uploads
12599:     
12600:     # $upload_output: missing dependencies (with upload form)
12601:     # $modify_output: uploaded dependencies (in use)
12602:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12603:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12604:         if ($actionurl eq '/adm/dependencies') {
12605:             next if ($embed_file =~ m{^\w+://});
12606:         }
12607:         $upload_output .= &start_data_table_row().
12608:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12609:                           '<span class="LC_filename">'.$embed_file.'</span>';
12610:         unless ($mapping{$embed_file} eq $embed_file) {
12611:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12612:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12613:         }
12614:         $upload_output .= '</td>';
12615:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
12616:             $upload_output.='<td align="right">'.
12617:                             '<span class="LC_info LC_fontsize_medium">'.
12618:                             &mt("URL points to web address").'</span>';
12619:             $numremref++;
12620:         } elsif ($args->{'error_on_invalid_names'}
12621:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12622:             $upload_output.='<td align="right"><span class="LC_warning">'.
12623:                             &mt('Invalid characters').'</span>';
12624:             $numinvalid++;
12625:         } else {
12626:             $upload_output .= '<td>'.
12627:                               &embedded_file_element('upload_embedded',$counter,
12628:                                                      $embed_file,\%mapping,
12629:                                                      $allfiles,$codebase,'upload');
12630:             $counter ++;
12631:             $numnew ++;
12632:         }
12633:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12634:     }
12635:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12636:         if ($actionurl eq '/adm/dependencies') {
12637:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12638:             $modify_output .= &start_data_table_row().
12639:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12640:                               '<img src="'.&icon($embed_file).'" border="0" />'.
12641:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
12642:                               '<td>'.$size.'</td>'.
12643:                               '<td>'.$mtime.'</td>'.
12644:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
12645:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12646:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12647:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12648:                               &embedded_file_element('upload_embedded',$counter,
12649:                                                      $embed_file,\%mapping,
12650:                                                      $allfiles,$codebase,'modify').
12651:                               '</div></td>'.
12652:                               &end_data_table_row()."\n";
12653:             $counter ++;
12654:         } else {
12655:             $upload_output .= &start_data_table_row().
12656:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
12657:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
12658:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12659:                               &Apache::loncommon::end_data_table_row()."\n";
12660:         }
12661:     }
12662:     my $delidx = $counter;
12663:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12664:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12665:         $delete_output .= &start_data_table_row().
12666:                           '<td><img src="'.&icon($oldfile).'" />'.
12667:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
12668:                           '<td>'.$size.'</td>'.
12669:                           '<td>'.$mtime.'</td>'.
12670:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
12671:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12672:                           &embedded_file_element('upload_embedded',$delidx,
12673:                                                  $oldfile,\%mapping,$allfiles,
12674:                                                  $codebase,'delete').'</td>'.
12675:                           &end_data_table_row()."\n"; 
12676:         $numunused ++;
12677:         $delidx ++;
12678:     }
12679:     if ($upload_output) {
12680:         $upload_output = &start_data_table().
12681:                          $upload_output.
12682:                          &end_data_table()."\n";
12683:     }
12684:     if ($modify_output) {
12685:         $modify_output = &start_data_table().
12686:                          &start_data_table_header_row().
12687:                          '<th>'.&mt('File').'</th>'.
12688:                          '<th>'.&mt('Size (KB)').'</th>'.
12689:                          '<th>'.&mt('Modified').'</th>'.
12690:                          '<th>'.&mt('Upload replacement?').'</th>'.
12691:                          &end_data_table_header_row().
12692:                          $modify_output.
12693:                          &end_data_table()."\n";
12694:     }
12695:     if ($delete_output) {
12696:         $delete_output = &start_data_table().
12697:                          &start_data_table_header_row().
12698:                          '<th>'.&mt('File').'</th>'.
12699:                          '<th>'.&mt('Size (KB)').'</th>'.
12700:                          '<th>'.&mt('Modified').'</th>'.
12701:                          '<th>'.&mt('Delete?').'</th>'.
12702:                          &end_data_table_header_row().
12703:                          $delete_output.
12704:                          &end_data_table()."\n";
12705:     }
12706:     my $applies = 0;
12707:     if ($numremref) {
12708:         $applies ++;
12709:     }
12710:     if ($numinvalid) {
12711:         $applies ++;
12712:     }
12713:     if ($numexisting) {
12714:         $applies ++;
12715:     }
12716:     if ($counter || $numunused) {
12717:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12718:                   ' method="post" enctype="multipart/form-data">'."\n".
12719:                   $state.'<h3>'.$heading.'</h3>'; 
12720:         if ($actionurl eq '/adm/dependencies') {
12721:             if ($numnew) {
12722:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12723:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12724:                            $upload_output.'<br />'."\n";
12725:             }
12726:             if ($numexisting) {
12727:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12728:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12729:                            $modify_output.'<br />'."\n";
12730:                            $buttontext = &mt('Save changes');
12731:             }
12732:             if ($numunused) {
12733:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
12734:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12735:                            $delete_output.'<br />'."\n";
12736:                            $buttontext = &mt('Save changes');
12737:             }
12738:         } else {
12739:             $output .= $upload_output.'<br />'."\n";
12740:         }
12741:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12742:                    $counter.'" />'."\n";
12743:         if ($actionurl eq '/adm/dependencies') { 
12744:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12745:                        $numnew.'" />'."\n";
12746:         } elsif ($actionurl eq '') {
12747:             $output .=  '<input type="hidden" name="phase" value="three" />';
12748:         }
12749:     } elsif ($applies) {
12750:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12751:         if ($applies > 1) {
12752:             $output .=  
12753:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12754:             if ($numremref) {
12755:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12756:             }
12757:             if ($numinvalid) {
12758:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12759:             }
12760:             if ($numexisting) {
12761:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12762:             }
12763:             $output .= '</ul><br />';
12764:         } elsif ($numremref) {
12765:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12766:         } elsif ($numinvalid) {
12767:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12768:         } elsif ($numexisting) {
12769:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12770:         }
12771:         $output .= $upload_output.'<br />';
12772:     }
12773:     my ($pathchange_output,$chgcount);
12774:     $chgcount = $counter;
12775:     if (keys(%pathchanges) > 0) {
12776:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12777:             if ($counter) {
12778:                 $output .= &embedded_file_element('pathchange',$chgcount,
12779:                                                   $embed_file,\%mapping,
12780:                                                   $allfiles,$codebase,'change');
12781:             } else {
12782:                 $pathchange_output .= 
12783:                     &start_data_table_row().
12784:                     '<td><input type ="checkbox" name="namechange" value="'.
12785:                     $chgcount.'" checked="checked" /></td>'.
12786:                     '<td>'.$mapping{$embed_file}.'</td>'.
12787:                     '<td>'.$embed_file.
12788:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
12789:                                            \%mapping,$allfiles,$codebase,'change').
12790:                     '</td>'.&end_data_table_row();
12791:             }
12792:             $numpathchg ++;
12793:             $chgcount ++;
12794:         }
12795:     }
12796:     if (($counter) || ($numunused)) {
12797:         if ($numpathchg) {
12798:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12799:                        $numpathchg.'" />'."\n";
12800:         }
12801:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
12802:             ($actionurl eq '/adm/imsimport')) {
12803:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12804:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12805:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12806:         } elsif ($actionurl eq '/adm/dependencies') {
12807:             $output .= '<input type="hidden" name="action" value="process_changes" />';
12808:         }
12809:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12810:     } elsif ($numpathchg) {
12811:         my %pathchange = ();
12812:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12813:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12814:             $output .= '<p>'.&mt('or').'</p>'; 
12815:         }
12816:     }
12817:     return ($output,$counter,$numpathchg);
12818: }
12819: 
12820: =pod
12821: 
12822: =item * clean_path($name)
12823: 
12824: Performs clean-up of directories, subdirectories and filename in an
12825: embedded object, referenced in an HTML file which is being uploaded
12826: to a course or portfolio, where 
12827: "Upload embedded images/multimedia files if HTML file" checkbox was
12828: checked.
12829: 
12830: Clean-up is similar to replacements in lonnet::clean_filename()
12831: except each / between sub-directory and next level is preserved.
12832: 
12833: =cut
12834: 
12835: sub clean_path {
12836:     my ($embed_file) = @_;
12837:     $embed_file =~s{^/+}{};
12838:     my @contents;
12839:     if ($embed_file =~ m{/}) {
12840:         @contents = split(/\//,$embed_file);
12841:     } else {
12842:         @contents = ($embed_file);
12843:     }
12844:     my $lastidx = scalar(@contents)-1;
12845:     for (my $i=0; $i<=$lastidx; $i++) { 
12846:         $contents[$i]=~s{\\}{/}g;
12847:         $contents[$i]=~s/\s+/\_/g;
12848:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12849:         if ($i == $lastidx) {
12850:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12851:         }
12852:     }
12853:     if ($lastidx > 0) {
12854:         return join('/',@contents);
12855:     } else {
12856:         return $contents[0];
12857:     }
12858: }
12859: 
12860: sub embedded_file_element {
12861:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12862:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12863:                    (ref($codebase) eq 'HASH'));
12864:     my $output;
12865:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12866:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12867:     }
12868:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12869:                &escape($embed_file).'" />';
12870:     unless (($context eq 'upload_embedded') && 
12871:             ($mapping->{$embed_file} eq $embed_file)) {
12872:         $output .='
12873:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12874:     }
12875:     my $attrib;
12876:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12877:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12878:     }
12879:     $output .=
12880:         "\n\t\t".
12881:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12882:         $attrib.'" />';
12883:     if (exists($codebase->{$mapping->{$embed_file}})) {
12884:         $output .=
12885:             "\n\t\t".
12886:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12887:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12888:     }
12889:     return $output;
12890: }
12891: 
12892: sub get_dependency_details {
12893:     my ($currfile,$currsubfile,$embed_file) = @_;
12894:     my ($size,$mtime,$showsize,$showmtime);
12895:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12896:         if ($embed_file =~ m{/}) {
12897:             my ($path,$fname) = split(/\//,$embed_file);
12898:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12899:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12900:             }
12901:         } else {
12902:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12903:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12904:             }
12905:         }
12906:         $showsize = $size/1024.0;
12907:         $showsize = sprintf("%.1f",$showsize);
12908:         if ($mtime > 0) {
12909:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12910:         }
12911:     }
12912:     return ($showsize,$showmtime);
12913: }
12914: 
12915: sub ask_embedded_js {
12916:     return <<"END";
12917: <script type="text/javascript"">
12918: // <![CDATA[
12919: function toggleBrowse(counter) {
12920:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12921:     var fileid = document.getElementById('embedded_item_'+counter);
12922:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12923:     if (chkboxid.checked == true) {
12924:         uploaddivid.style.display='block';
12925:     } else {
12926:         uploaddivid.style.display='none';
12927:         fileid.value = '';
12928:     }
12929: }
12930: // ]]>
12931: </script>
12932: 
12933: END
12934: }
12935: 
12936: sub upload_embedded {
12937:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12938:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12939:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12940:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12941:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12942:         my $orig_uploaded_filename =
12943:             $env{'form.embedded_item_'.$i.'.filename'};
12944:         foreach my $type ('orig','ref','attrib','codebase') {
12945:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12946:                 $env{'form.embedded_'.$type.'_'.$i} =
12947:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12948:             }
12949:         }
12950:         my ($path,$fname) =
12951:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12952:         # no path, whole string is fname
12953:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12954:         $fname = &Apache::lonnet::clean_filename($fname);
12955:         # See if there is anything left
12956:         next if ($fname eq '');
12957: 
12958:         # Check if file already exists as a file or directory.
12959:         my ($state,$msg);
12960:         if ($context eq 'portfolio') {
12961:             my $port_path = $dirpath;
12962:             if ($group ne '') {
12963:                 $port_path = "groups/$group/$port_path";
12964:             }
12965:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12966:                                               $fname,$group,'embedded_item_'.$i,
12967:                                               $dir_root,$port_path,$disk_quota,
12968:                                               $current_disk_usage,$uname,$udom);
12969:             if ($state eq 'will_exceed_quota'
12970:                 || $state eq 'file_locked') {
12971:                 $output .= $msg;
12972:                 next;
12973:             }
12974:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12975:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12976:             if ($state eq 'exists') {
12977:                 $output .= $msg;
12978:                 next;
12979:             }
12980:         }
12981:         # Check if extension is valid
12982:         if (($fname =~ /\.(\w+)$/) &&
12983:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12984:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12985:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12986:             next;
12987:         } elsif (($fname =~ /\.(\w+)$/) &&
12988:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12989:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12990:             next;
12991:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12992:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12993:             next;
12994:         }
12995:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12996:         my $subdir = $path;
12997:         $subdir =~ s{/+$}{};
12998:         if ($context eq 'portfolio') {
12999:             my $result;
13000:             if ($state eq 'existingfile') {
13001:                 $result=
13002:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
13003:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
13004:             } else {
13005:                 $result=
13006:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13007:                                                     $dirpath.
13008:                                                     $env{'form.currentpath'}.$subdir);
13009:                 if ($result !~ m|^/uploaded/|) {
13010:                     $output .= '<span class="LC_error">'
13011:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13012:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13013:                                .'</span><br />';
13014:                     next;
13015:                 } else {
13016:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13017:                                $path.$fname.'</span>').'<br />';     
13018:                 }
13019:             }
13020:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13021:             my $extendedsubdir = $dirpath.'/'.$subdir;
13022:             $extendedsubdir =~ s{/+$}{};
13023:             my $result =
13024:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13025:             if ($result !~ m|^/uploaded/|) {
13026:                 $output .= '<span class="LC_error">'
13027:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13028:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13029:                            .'</span><br />';
13030:                     next;
13031:             } else {
13032:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13033:                            $path.$fname.'</span>').'<br />';
13034:                 if ($context eq 'syllabus') {
13035:                     &Apache::lonnet::make_public_indefinitely($result);
13036:                 }
13037:             }
13038:         } else {
13039: # Save the file
13040:             my $target = $env{'form.embedded_item_'.$i};
13041:             my $fullpath = $dir_root.$dirpath.'/'.$path;
13042:             my $dest = $fullpath.$fname;
13043:             my $url = $url_root.$dirpath.'/'.$path.$fname;
13044:             my @parts=split(/\//,"$dirpath/$path");
13045:             my $count;
13046:             my $filepath = $dir_root;
13047:             foreach my $subdir (@parts) {
13048:                 $filepath .= "/$subdir";
13049:                 if (!-e $filepath) {
13050:                     mkdir($filepath,0770);
13051:                 }
13052:             }
13053:             my $fh;
13054:             if (!open($fh,'>'.$dest)) {
13055:                 &Apache::lonnet::logthis('Failed to create '.$dest);
13056:                 $output .= '<span class="LC_error">'.
13057:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13058:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13059:                            '</span><br />';
13060:             } else {
13061:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
13062:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
13063:                     $output .= '<span class="LC_error">'.
13064:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13065:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13066:                               '</span><br />';
13067:                 } else {
13068:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13069:                                $url.'</span>').'<br />';
13070:                     unless ($context eq 'testbank') {
13071:                         $footer .= &mt('View embedded file: [_1]',
13072:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13073:                     }
13074:                 }
13075:                 close($fh);
13076:             }
13077:         }
13078:         if ($env{'form.embedded_ref_'.$i}) {
13079:             $pathchange{$i} = 1;
13080:         }
13081:     }
13082:     if ($output) {
13083:         $output = '<p>'.$output.'</p>';
13084:     }
13085:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13086:     $returnflag = 'ok';
13087:     my $numpathchgs = scalar(keys(%pathchange));
13088:     if ($numpathchgs > 0) {
13089:         if ($context eq 'portfolio') {
13090:             $output .= '<p>'.&mt('or').'</p>';
13091:         } elsif ($context eq 'testbank') {
13092:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13093:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13094:             $returnflag = 'modify_orightml';
13095:         }
13096:     }
13097:     return ($output.$footer,$returnflag,$numpathchgs);
13098: }
13099: 
13100: sub modify_html_form {
13101:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13102:     my $end = 0;
13103:     my $modifyform;
13104:     if ($context eq 'upload_embedded') {
13105:         return unless (ref($pathchange) eq 'HASH');
13106:         if ($env{'form.number_embedded_items'}) {
13107:             $end += $env{'form.number_embedded_items'};
13108:         }
13109:         if ($env{'form.number_pathchange_items'}) {
13110:             $end += $env{'form.number_pathchange_items'};
13111:         }
13112:         if ($end) {
13113:             for (my $i=0; $i<$end; $i++) {
13114:                 if ($i < $env{'form.number_embedded_items'}) {
13115:                     next unless($pathchange->{$i});
13116:                 }
13117:                 $modifyform .=
13118:                     &start_data_table_row().
13119:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13120:                     'checked="checked" /></td>'.
13121:                     '<td>'.$env{'form.embedded_ref_'.$i}.
13122:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13123:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
13124:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13125:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13126:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13127:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13128:                     '<td>'.$env{'form.embedded_orig_'.$i}.
13129:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13130:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13131:                     &end_data_table_row();
13132:             }
13133:         }
13134:     } else {
13135:         $modifyform = $pathchgtable;
13136:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13137:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13138:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13139:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13140:         }
13141:     }
13142:     if ($modifyform) {
13143:         if ($actionurl eq '/adm/dependencies') {
13144:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13145:         }
13146:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13147:                '<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".
13148:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13149:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13150:                '</ol></p>'."\n".'<p>'.
13151:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13152:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13153:                &start_data_table()."\n".
13154:                &start_data_table_header_row().
13155:                '<th>'.&mt('Change?').'</th>'.
13156:                '<th>'.&mt('Current reference').'</th>'.
13157:                '<th>'.&mt('Required reference').'</th>'.
13158:                &end_data_table_header_row()."\n".
13159:                $modifyform.
13160:                &end_data_table().'<br />'."\n".$hiddenstate.
13161:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13162:                '</form>'."\n";
13163:     }
13164:     return;
13165: }
13166: 
13167: sub modify_html_refs {
13168:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13169:     my $container;
13170:     if ($context eq 'portfolio') {
13171:         $container = $env{'form.container'};
13172:     } elsif ($context eq 'coursedoc') {
13173:         $container = $env{'form.primaryurl'};
13174:     } elsif ($context eq 'manage_dependencies') {
13175:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13176:         $container = "/$container";
13177:     } elsif ($context eq 'syllabus') {
13178:         $container = $url;
13179:     } else {
13180:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13181:     }
13182:     my (%allfiles,%codebase,$output,$content);
13183:     my @changes = &get_env_multiple('form.namechange');
13184:     unless ((@changes > 0) || ($context eq 'syllabus')) {
13185:         if (wantarray) {
13186:             return ('',0,0); 
13187:         } else {
13188:             return;
13189:         }
13190:     }
13191:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13192:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13193:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13194:             if (wantarray) {
13195:                 return ('',0,0);
13196:             } else {
13197:                 return;
13198:             }
13199:         } 
13200:         $content = &Apache::lonnet::getfile($container);
13201:         if ($content eq '-1') {
13202:             if (wantarray) {
13203:                 return ('',0,0);
13204:             } else {
13205:                 return;
13206:             }
13207:         }
13208:     } else {
13209:         unless ($container =~ /^\Q$dir_root\E/) {
13210:             if (wantarray) {
13211:                 return ('',0,0);
13212:             } else {
13213:                 return;
13214:             }
13215:         } 
13216:         if (open(my $fh,'<',$container)) {
13217:             $content = join('', <$fh>);
13218:             close($fh);
13219:         } else {
13220:             if (wantarray) {
13221:                 return ('',0,0);
13222:             } else {
13223:                 return;
13224:             }
13225:         }
13226:     }
13227:     my ($count,$codebasecount) = (0,0);
13228:     my $mm = new File::MMagic;
13229:     my $mime_type = $mm->checktype_contents($content);
13230:     if ($mime_type eq 'text/html') {
13231:         my $parse_result = 
13232:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13233:                                                     \%codebase,\$content);
13234:         if ($parse_result eq 'ok') {
13235:             foreach my $i (@changes) {
13236:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
13237:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
13238:                 if ($allfiles{$ref}) {
13239:                     my $newname =  $orig;
13240:                     my ($attrib_regexp,$codebase);
13241:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13242:                     if ($attrib_regexp =~ /:/) {
13243:                         $attrib_regexp =~ s/\:/|/g;
13244:                     }
13245:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13246:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13247:                         $count += $numchg;
13248:                         $allfiles{$newname} = $allfiles{$ref};
13249:                         delete($allfiles{$ref});
13250:                     }
13251:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
13252:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13253:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13254:                         $codebasecount ++;
13255:                     }
13256:                 }
13257:             }
13258:             my $skiprewrites;
13259:             if ($count || $codebasecount) {
13260:                 my $saveresult;
13261:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
13262:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13263:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13264:                     if ($url eq $container) {
13265:                         my ($fname) = ($container =~ m{/([^/]+)$});
13266:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13267:                                             $count,'<span class="LC_filename">'.
13268:                                             $fname.'</span>').'</p>';
13269:                     } else {
13270:                          $output = '<p class="LC_error">'.
13271:                                    &mt('Error: update failed for: [_1].',
13272:                                    '<span class="LC_filename">'.
13273:                                    $container.'</span>').'</p>';
13274:                     }
13275:                     if ($context eq 'syllabus') {
13276:                         unless ($saveresult eq 'ok') {
13277:                             $skiprewrites = 1;
13278:                         }
13279:                     }
13280:                 } else {
13281:                     if (open(my $fh,'>',$container)) {
13282:                         print $fh $content;
13283:                         close($fh);
13284:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13285:                                   $count,'<span class="LC_filename">'.
13286:                                   $container.'</span>').'</p>';
13287:                     } else {
13288:                          $output = '<p class="LC_error">'.
13289:                                    &mt('Error: could not update [_1].',
13290:                                    '<span class="LC_filename">'.
13291:                                    $container.'</span>').'</p>';
13292:                     }
13293:                 }
13294:             }
13295:             if (($context eq 'syllabus') && (!$skiprewrites)) {
13296:                 my ($actionurl,$state);
13297:                 $actionurl = "/public/$udom/$uname/syllabus";
13298:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13299:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
13300:                                               \%codebase,
13301:                                               {'context' => 'rewrites',
13302:                                                'ignore_remote_references' => 1,});
13303:                 if (ref($mapping) eq 'HASH') {
13304:                     my $rewrites = 0;
13305:                     foreach my $key (keys(%{$mapping})) {
13306:                         next if ($key =~ m{^https?://});
13307:                         my $ref = $mapping->{$key};
13308:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13309:                         my $attrib;
13310:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13311:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13312:                         }
13313:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13314:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13315:                             $rewrites += $numchg;
13316:                         }
13317:                     }
13318:                     if ($rewrites) {
13319:                         my $saveresult; 
13320:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13321:                         if ($url eq $container) {
13322:                             my ($fname) = ($container =~ m{/([^/]+)$});
13323:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13324:                                             $count,'<span class="LC_filename">'.
13325:                                             $fname.'</span>').'</p>';
13326:                         } else {
13327:                             $output .= '<p class="LC_error">'.
13328:                                        &mt('Error: could not update links in [_1].',
13329:                                        '<span class="LC_filename">'.
13330:                                        $container.'</span>').'</p>';
13331: 
13332:                         }
13333:                     }
13334:                 }
13335:             }
13336:         } else {
13337:             &logthis('Failed to parse '.$container.
13338:                      ' to modify references: '.$parse_result);
13339:         }
13340:     }
13341:     if (wantarray) {
13342:         return ($output,$count,$codebasecount);
13343:     } else {
13344:         return $output;
13345:     }
13346: }
13347: 
13348: sub check_for_existing {
13349:     my ($path,$fname,$element) = @_;
13350:     my ($state,$msg);
13351:     if (-d $path.'/'.$fname) {
13352:         $state = 'exists';
13353:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13354:     } elsif (-e $path.'/'.$fname) {
13355:         $state = 'exists';
13356:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13357:     }
13358:     if ($state eq 'exists') {
13359:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
13360:     }
13361:     return ($state,$msg);
13362: }
13363: 
13364: sub check_for_upload {
13365:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13366:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13367:     my $filesize = length($env{'form.'.$element});
13368:     if (!$filesize) {
13369:         my $msg = '<span class="LC_error">'.
13370:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
13371:                       '<span class="LC_filename">'.$fname.'</span>',
13372:                       $filesize).'<br />'.
13373:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13374:                   '</span>';
13375:         return ('zero_bytes',$msg);
13376:     }
13377:     $filesize =  $filesize/1000; #express in k (1024?)
13378:     my $getpropath = 1;
13379:     my ($dirlistref,$listerror) =
13380:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13381:     my $found_file = 0;
13382:     my $locked_file = 0;
13383:     my @lockers;
13384:     my $navmap;
13385:     if ($env{'request.course.id'}) {
13386:         $navmap = Apache::lonnavmaps::navmap->new();
13387:     }
13388:     if (ref($dirlistref) eq 'ARRAY') {
13389:         foreach my $line (@{$dirlistref}) {
13390:             my ($file_name,$rest)=split(/\&/,$line,2);
13391:             if ($file_name eq $fname){
13392:                 $file_name = $path.$file_name;
13393:                 if ($group ne '') {
13394:                     $file_name = $group.$file_name;
13395:                 }
13396:                 $found_file = 1;
13397:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13398:                     foreach my $lock (@lockers) {
13399:                         if (ref($lock) eq 'ARRAY') {
13400:                             my ($symb,$crsid) = @{$lock};
13401:                             if ($crsid eq $env{'request.course.id'}) {
13402:                                 if (ref($navmap)) {
13403:                                     my $res = $navmap->getBySymb($symb);
13404:                                     foreach my $part (@{$res->parts()}) { 
13405:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13406:                                         unless (($slot_status == $res->RESERVED) ||
13407:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
13408:                                             $locked_file = 1;
13409:                                         }
13410:                                     }
13411:                                 } else {
13412:                                     $locked_file = 1;
13413:                                 }
13414:                             } else {
13415:                                 $locked_file = 1;
13416:                             }
13417:                         }
13418:                    }
13419:                 } else {
13420:                     my @info = split(/\&/,$rest);
13421:                     my $currsize = $info[6]/1000;
13422:                     if ($currsize < $filesize) {
13423:                         my $extra = $filesize - $currsize;
13424:                         if (($current_disk_usage + $extra) > $disk_quota) {
13425:                             my $msg = '<p class="LC_warning">'.
13426:                                       &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.',
13427:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13428:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13429:                                                    $disk_quota,$current_disk_usage).'</p>';
13430:                             return ('will_exceed_quota',$msg);
13431:                         }
13432:                     }
13433:                 }
13434:             }
13435:         }
13436:     }
13437:     if (($current_disk_usage + $filesize) > $disk_quota){
13438:         my $msg = '<p class="LC_warning">'.
13439:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13440:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13441:         return ('will_exceed_quota',$msg);
13442:     } elsif ($found_file) {
13443:         if ($locked_file) {
13444:             my $msg = '<p class="LC_warning">';
13445:             $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>');
13446:             $msg .= '</p>';
13447:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13448:             return ('file_locked',$msg);
13449:         } else {
13450:             my $msg = '<p class="LC_error">';
13451:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13452:             $msg .= '</p>';
13453:             return ('existingfile',$msg);
13454:         }
13455:     }
13456: }
13457: 
13458: sub check_for_traversal {
13459:     my ($path,$url,$toplevel) = @_;
13460:     my @parts=split(/\//,$path);
13461:     my $cleanpath;
13462:     my $fullpath = $url;
13463:     for (my $i=0;$i<@parts;$i++) {
13464:         next if ($parts[$i] eq '.');
13465:         if ($parts[$i] eq '..') {
13466:             $fullpath =~ s{([^/]+/)$}{};
13467:         } else {
13468:             $fullpath .= $parts[$i].'/';
13469:         }
13470:     }
13471:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
13472:         $cleanpath = $1;
13473:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13474:         my $curr_toprel = $1;
13475:         my @parts = split(/\//,$curr_toprel);
13476:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13477:         my @urlparts = split(/\//,$url_toprel);
13478:         my $doubledots;
13479:         my $startdiff = -1;
13480:         for (my $i=0; $i<@urlparts; $i++) {
13481:             if ($startdiff == -1) {
13482:                 unless ($urlparts[$i] eq $parts[$i]) {
13483:                     $startdiff = $i;
13484:                     $doubledots .= '../';
13485:                 }
13486:             } else {
13487:                 $doubledots .= '../';
13488:             }
13489:         }
13490:         if ($startdiff > -1) {
13491:             $cleanpath = $doubledots;
13492:             for (my $i=$startdiff; $i<@parts; $i++) {
13493:                 $cleanpath .= $parts[$i].'/';
13494:             }
13495:         }
13496:     }
13497:     $cleanpath =~ s{(/)$}{};
13498:     return $cleanpath;
13499: }
13500: 
13501: sub is_archive_file {
13502:     my ($mimetype) = @_;
13503:     if (($mimetype eq 'application/octet-stream') ||
13504:         ($mimetype eq 'application/x-stuffit') ||
13505:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13506:         return 1;
13507:     }
13508:     return;
13509: }
13510: 
13511: sub decompress_form {
13512:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13513:     my %lt = &Apache::lonlocal::texthash (
13514:         this => 'This file is an archive file.',
13515:         camt => 'This file is a Camtasia archive file.',
13516:         itsc => 'Its contents are as follows:',
13517:         youm => 'You may wish to extract its contents.',
13518:         extr => 'Extract contents',
13519:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13520:         proa => 'Process automatically?',
13521:         yes  => 'Yes',
13522:         no   => 'No',
13523:         fold => 'Title for folder containing movie',
13524:         movi => 'Title for page containing embedded movie', 
13525:     );
13526:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13527:     my ($is_camtasia,$topdir,%toplevel,@paths);
13528:     my $info = &list_archive_contents($fileloc,\@paths);
13529:     if (@paths) {
13530:         foreach my $path (@paths) {
13531:             $path =~ s{^/}{};
13532:             if ($path =~ m{^([^/]+)/$}) {
13533:                 $topdir = $1;
13534:             }
13535:             if ($path =~ m{^([^/]+)/}) {
13536:                 $toplevel{$1} = $path;
13537:             } else {
13538:                 $toplevel{$path} = $path;
13539:             }
13540:         }
13541:     }
13542:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13543:         my @camtasia6 = ("$topdir/","$topdir/index.html",
13544:                         "$topdir/media/",
13545:                         "$topdir/media/$topdir.mp4",
13546:                         "$topdir/media/FirstFrame.png",
13547:                         "$topdir/media/player.swf",
13548:                         "$topdir/media/swfobject.js",
13549:                         "$topdir/media/expressInstall.swf");
13550:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13551:                          "$topdir/$topdir.mp4",
13552:                          "$topdir/$topdir\_config.xml",
13553:                          "$topdir/$topdir\_controller.swf",
13554:                          "$topdir/$topdir\_embed.css",
13555:                          "$topdir/$topdir\_First_Frame.png",
13556:                          "$topdir/$topdir\_player.html",
13557:                          "$topdir/$topdir\_Thumbnails.png",
13558:                          "$topdir/playerProductInstall.swf",
13559:                          "$topdir/scripts/",
13560:                          "$topdir/scripts/config_xml.js",
13561:                          "$topdir/scripts/handlebars.js",
13562:                          "$topdir/scripts/jquery-1.7.1.min.js",
13563:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13564:                          "$topdir/scripts/modernizr.js",
13565:                          "$topdir/scripts/player-min.js",
13566:                          "$topdir/scripts/swfobject.js",
13567:                          "$topdir/skins/",
13568:                          "$topdir/skins/configuration_express.xml",
13569:                          "$topdir/skins/express_show/",
13570:                          "$topdir/skins/express_show/player-min.css",
13571:                          "$topdir/skins/express_show/spritesheet.png");
13572:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13573:                          "$topdir/$topdir.mp4",
13574:                          "$topdir/$topdir\_config.xml",
13575:                          "$topdir/$topdir\_controller.swf",
13576:                          "$topdir/$topdir\_embed.css",
13577:                          "$topdir/$topdir\_First_Frame.png",
13578:                          "$topdir/$topdir\_player.html",
13579:                          "$topdir/$topdir\_Thumbnails.png",
13580:                          "$topdir/playerProductInstall.swf",
13581:                          "$topdir/scripts/",
13582:                          "$topdir/scripts/config_xml.js",
13583:                          "$topdir/scripts/techsmith-smart-player.min.js",
13584:                          "$topdir/skins/",
13585:                          "$topdir/skins/configuration_express.xml",
13586:                          "$topdir/skins/express_show/",
13587:                          "$topdir/skins/express_show/spritesheet.min.css",
13588:                          "$topdir/skins/express_show/spritesheet.png",
13589:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
13590:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
13591:         if (@diffs == 0) {
13592:             $is_camtasia = 6;
13593:         } else {
13594:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13595:             if (@diffs == 0) {
13596:                 $is_camtasia = 8;
13597:             } else {
13598:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13599:                 if (@diffs == 0) {
13600:                     $is_camtasia = 8;
13601:                 }
13602:             }
13603:         }
13604:     }
13605:     my $output;
13606:     if ($is_camtasia) {
13607:         $output = <<"ENDCAM";
13608: <script type="text/javascript" language="Javascript">
13609: // <![CDATA[
13610: 
13611: function camtasiaToggle() {
13612:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13613:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13614:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13615:                 document.getElementById('camtasia_titles').style.display='block';
13616:             } else {
13617:                 document.getElementById('camtasia_titles').style.display='none';
13618:             }
13619:         }
13620:     }
13621:     return;
13622: }
13623: 
13624: // ]]>
13625: </script>
13626: <p>$lt{'camt'}</p>
13627: ENDCAM
13628:     } else {
13629:         $output = '<p>'.$lt{'this'};
13630:         if ($info eq '') {
13631:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
13632:         } else {
13633:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13634:                        '<div><pre>'.$info.'</pre></div>';
13635:         }
13636:     }
13637:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13638:     my $duplicates;
13639:     my $num = 0;
13640:     if (ref($dirlist) eq 'ARRAY') {
13641:         foreach my $item (@{$dirlist}) {
13642:             if (ref($item) eq 'ARRAY') {
13643:                 if (exists($toplevel{$item->[0]})) {
13644:                     $duplicates .= 
13645:                         &start_data_table_row().
13646:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13647:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
13648:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
13649:                         'value="1" />'.&mt('Yes').'</label>'.
13650:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13651:                         '<td>'.$item->[0].'</td>';
13652:                     if ($item->[2]) {
13653:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
13654:                     } else {
13655:                         $duplicates .= '<td>'.&mt('File').'</td>';
13656:                     }
13657:                     $duplicates .= '<td>'.$item->[3].'</td>'.
13658:                                    '<td>'.
13659:                                    &Apache::lonlocal::locallocaltime($item->[4]).
13660:                                    '</td>'.
13661:                                    &end_data_table_row();
13662:                     $num ++;
13663:                 }
13664:             }
13665:         }
13666:     }
13667:     my $itemcount;
13668:     if (@paths > 0) {
13669:         $itemcount = scalar(@paths);
13670:     } else {
13671:         $itemcount = 1;
13672:     }
13673:     if ($is_camtasia) {
13674:         $output .= $lt{'auto'}.'<br />'.
13675:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13676:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13677:                    $lt{'yes'}.'</label>&nbsp;<label>'.
13678:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13679:                    $lt{'no'}.'</label></span><br />'.
13680:                    '<div id="camtasia_titles" style="display:block">'.
13681:                    &Apache::lonhtmlcommon::start_pick_box().
13682:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13683:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13684:                    &Apache::lonhtmlcommon::row_closure().
13685:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13686:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13687:                    &Apache::lonhtmlcommon::row_closure(1).
13688:                    &Apache::lonhtmlcommon::end_pick_box().
13689:                    '</div>';
13690:     }
13691:     $output .= 
13692:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13693:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13694:         "\n";
13695:     if ($duplicates ne '') {
13696:         $output .= '<p><span class="LC_warning">'.
13697:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
13698:                    &start_data_table().
13699:                    &start_data_table_header_row().
13700:                    '<th>'.&mt('Overwrite?').'</th>'.
13701:                    '<th>'.&mt('Name').'</th>'.
13702:                    '<th>'.&mt('Type').'</th>'.
13703:                    '<th>'.&mt('Size').'</th>'.
13704:                    '<th>'.&mt('Last modified').'</th>'.
13705:                    &end_data_table_header_row().
13706:                    $duplicates.
13707:                    &end_data_table().
13708:                    '</p>';
13709:     }
13710:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13711:     if (ref($hiddenelements) eq 'HASH') {
13712:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13713:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13714:         }
13715:     }
13716:     $output .= <<"END";
13717: <br />
13718: <input type="submit" name="decompress" value="$lt{'extr'}" />
13719: </form>
13720: $noextract
13721: END
13722:     return $output;
13723: }
13724: 
13725: sub decompression_utility {
13726:     my ($program) = @_;
13727:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
13728:     my $location;
13729:     if (grep(/^\Q$program\E$/,@utilities)) { 
13730:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13731:                          '/usr/sbin/') {
13732:             if (-x $dir.$program) {
13733:                 $location = $dir.$program;
13734:                 last;
13735:             }
13736:         }
13737:     }
13738:     return $location;
13739: }
13740: 
13741: sub list_archive_contents {
13742:     my ($file,$pathsref) = @_;
13743:     my (@cmd,$output);
13744:     my $needsregexp;
13745:     if ($file =~ /\.zip$/) {
13746:         @cmd = (&decompression_utility('unzip'),"-l");
13747:         $needsregexp = 1;
13748:     } elsif (($file =~ m/\.tar\.gz$/) ||
13749:              ($file =~ /\.tgz$/)) {
13750:         @cmd = (&decompression_utility('tar'),"-ztf");
13751:     } elsif ($file =~ /\.tar\.bz2$/) {
13752:         @cmd = (&decompression_utility('tar'),"-jtf");
13753:     } elsif ($file =~ m|\.tar$|) {
13754:         @cmd = (&decompression_utility('tar'),"-tf");
13755:     }
13756:     if (@cmd) {
13757:         undef($!);
13758:         undef($@);
13759:         if (open(my $fh,"-|", @cmd, $file)) {
13760:             while (my $line = <$fh>) {
13761:                 $output .= $line;
13762:                 chomp($line);
13763:                 my $item;
13764:                 if ($needsregexp) {
13765:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
13766:                 } else {
13767:                     $item = $line;
13768:                 }
13769:                 if ($item ne '') {
13770:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13771:                         push(@{$pathsref},$item);
13772:                     } 
13773:                 }
13774:             }
13775:             close($fh);
13776:         }
13777:     }
13778:     return $output;
13779: }
13780: 
13781: sub decompress_uploaded_file {
13782:     my ($file,$dir) = @_;
13783:     &Apache::lonnet::appenv({'cgi.file' => $file});
13784:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
13785:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13786:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13787:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13788:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13789:     my $decompressed = $env{'cgi.decompressed'};
13790:     &Apache::lonnet::delenv('cgi.file');
13791:     &Apache::lonnet::delenv('cgi.dir');
13792:     &Apache::lonnet::delenv('cgi.decompressed');
13793:     return ($decompressed,$result);
13794: }
13795: 
13796: sub process_decompression {
13797:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13798:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13799:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13800:                &mt('Unexpected file path.').'</p>'."\n";
13801:     }
13802:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13803:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13804:                &mt('Unexpected course context.').'</p>'."\n";
13805:     }
13806:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
13807:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13808:                &mt('Filename contained unexpected characters.').'</p>'."\n";
13809:     }
13810:     my ($dir,$error,$warning,$output);
13811:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13812:         $error = &mt('Filename not a supported archive file type.').
13813:                  '<br />'.&mt('Filename should end with one of: [_1].',
13814:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13815:     } else {
13816:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13817:         if ($docuhome eq 'no_host') {
13818:             $error = &mt('Could not determine home server for course.');
13819:         } else {
13820:             my @ids=&Apache::lonnet::current_machine_ids();
13821:             my $currdir = "$dir_root/$destination";
13822:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13823:                 $dir = &LONCAPA::propath($docudom,$docuname).
13824:                        "$dir_root/$destination";
13825:             } else {
13826:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13827:                        "$dir_root/$docudom/$docuname/$destination";
13828:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13829:                     $error = &mt('Archive file not found.');
13830:                 }
13831:             }
13832:             my (@to_overwrite,@to_skip);
13833:             if ($env{'form.archive_overwrite_total'} > 0) {
13834:                 my $total = $env{'form.archive_overwrite_total'};
13835:                 for (my $i=0; $i<$total; $i++) {
13836:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13837:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13838:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13839:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13840:                     }
13841:                 }
13842:             }
13843:             my $numskip = scalar(@to_skip);
13844:             my $numoverwrite = scalar(@to_overwrite);
13845:             if (($numskip) && (!$numoverwrite)) { 
13846:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13847:             } elsif ($dir eq '') {
13848:                 $error = &mt('Directory containing archive file unavailable.');
13849:             } elsif (!$error) {
13850:                 my ($decompressed,$display);
13851:                 if (($numskip) || ($numoverwrite)) {
13852:                     my $tempdir = time.'_'.$$.int(rand(10000));
13853:                     mkdir("$dir/$tempdir",0755);
13854:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13855:                         ($decompressed,$display) = 
13856:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13857:                         foreach my $item (@to_skip) {
13858:                             if (($item ne '') && ($item !~ /\.\./)) {
13859:                                 if (-f "$dir/$tempdir/$item") { 
13860:                                     unlink("$dir/$tempdir/$item");
13861:                                 } elsif (-d "$dir/$tempdir/$item") {
13862:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13863:                                 }
13864:                             }
13865:                         }
13866:                         foreach my $item (@to_overwrite) {
13867:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13868:                                 if (($item ne '') && ($item !~ /\.\./)) {
13869:                                     if (-f "$dir/$item") {
13870:                                         unlink("$dir/$item");
13871:                                     } elsif (-d "$dir/$item") {
13872:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13873:                                     }
13874:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13875:                                 }
13876:                             }
13877:                         }
13878:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13879:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13880:                         }
13881:                     }
13882:                 } else {
13883:                     ($decompressed,$display) = 
13884:                         &decompress_uploaded_file($file,$dir);
13885:                 }
13886:                 if ($decompressed eq 'ok') {
13887:                     $output = '<p class="LC_info">'.
13888:                               &mt('Files extracted successfully from archive.').
13889:                               '</p>'."\n";
13890:                     my ($warning,$result,@contents);
13891:                     my ($newdirlistref,$newlisterror) =
13892:                         &Apache::lonnet::dirlist($currdir,$docudom,
13893:                                                  $docuname,1);
13894:                     my (%is_dir,%changes,@newitems);
13895:                     my $dirptr = 16384;
13896:                     if (ref($newdirlistref) eq 'ARRAY') {
13897:                         foreach my $dir_line (@{$newdirlistref}) {
13898:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13899:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
13900:                                 push(@newitems,$item);
13901:                                 if ($dirptr&$testdir) {
13902:                                     $is_dir{$item} = 1;
13903:                                 }
13904:                                 $changes{$item} = 1;
13905:                             }
13906:                         }
13907:                     }
13908:                     if (keys(%changes) > 0) {
13909:                         foreach my $item (sort(@newitems)) {
13910:                             if ($changes{$item}) {
13911:                                 push(@contents,$item);
13912:                             }
13913:                         }
13914:                     }
13915:                     if (@contents > 0) {
13916:                         my $wantform;
13917:                         unless ($env{'form.autoextract_camtasia'}) {
13918:                             $wantform = 1;
13919:                         }
13920:                         my (%children,%parent,%dirorder,%titles);
13921:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13922:                                                                 $currdir,\%is_dir,
13923:                                                                 \%children,\%parent,
13924:                                                                 \@contents,\%dirorder,
13925:                                                                 \%titles,$wantform);
13926:                         if ($datatable ne '') {
13927:                             $output .= &archive_options_form('decompressed',$datatable,
13928:                                                              $count,$hiddenelem);
13929:                             my $startcount = 6;
13930:                             $output .= &archive_javascript($startcount,$count,
13931:                                                            \%titles,\%children);
13932:                         }
13933:                         if ($env{'form.autoextract_camtasia'}) {
13934:                             my $version = $env{'form.autoextract_camtasia'};
13935:                             my %displayed;
13936:                             my $total = 1;
13937:                             $env{'form.archive_directory'} = [];
13938:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13939:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13940:                                 $path =~ s{/$}{};
13941:                                 my $item;
13942:                                 if ($path ne '') {
13943:                                     $item = "$path/$titles{$i}";
13944:                                 } else {
13945:                                     $item = $titles{$i};
13946:                                 }
13947:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13948:                                 if ($item eq $contents[0]) {
13949:                                     push(@{$env{'form.archive_directory'}},$i);
13950:                                     $env{'form.archive_'.$i} = 'display';
13951:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13952:                                     $displayed{'folder'} = $i;
13953:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13954:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
13955:                                     $env{'form.archive_'.$i} = 'display';
13956:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13957:                                     $displayed{'web'} = $i;
13958:                                 } else {
13959:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13960:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13961:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13962:                                         push(@{$env{'form.archive_directory'}},$i);
13963:                                     }
13964:                                     $env{'form.archive_'.$i} = 'dependency';
13965:                                 }
13966:                                 $total ++;
13967:                             }
13968:                             for (my $i=1; $i<$total; $i++) {
13969:                                 next if ($i == $displayed{'web'});
13970:                                 next if ($i == $displayed{'folder'});
13971:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13972:                             }
13973:                             $env{'form.phase'} = 'decompress_cleanup';
13974:                             $env{'form.archivedelete'} = 1;
13975:                             $env{'form.archive_count'} = $total-1;
13976:                             $output .=
13977:                                 &process_extracted_files('coursedocs',$docudom,
13978:                                                          $docuname,$destination,
13979:                                                          $dir_root,$hiddenelem);
13980:                         }
13981:                     } else {
13982:                         $warning = &mt('No new items extracted from archive file.');
13983:                     }
13984:                 } else {
13985:                     $output = $display;
13986:                     $error = &mt('An error occurred during extraction from the archive file.');
13987:                 }
13988:             }
13989:         }
13990:     }
13991:     if ($error) {
13992:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13993:                    $error.'</p>'."\n";
13994:     }
13995:     if ($warning) {
13996:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13997:     }
13998:     return $output;
13999: }
14000: 
14001: sub get_extracted {
14002:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
14003:         $titles,$wantform) = @_;
14004:     my $count = 0;
14005:     my $depth = 0;
14006:     my $datatable;
14007:     my @hierarchy;
14008:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14009:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14010:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14011:     foreach my $item (@{$contents}) {
14012:         $count ++;
14013:         @{$dirorder->{$count}} = @hierarchy;
14014:         $titles->{$count} = $item;
14015:         &archive_hierarchy($depth,$count,$parent,$children);
14016:         if ($wantform) {
14017:             $datatable .= &archive_row($is_dir->{$item},$item,
14018:                                        $currdir,$depth,$count);
14019:         }
14020:         if ($is_dir->{$item}) {
14021:             $depth ++;
14022:             push(@hierarchy,$count);
14023:             $parent->{$depth} = $count;
14024:             $datatable .=
14025:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14026:                                            \$depth,\$count,\@hierarchy,$dirorder,
14027:                                            $children,$parent,$titles,$wantform);
14028:             $depth --;
14029:             pop(@hierarchy);
14030:         }
14031:     }
14032:     return ($count,$datatable);
14033: }
14034: 
14035: sub recurse_extracted_archive {
14036:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14037:         $children,$parent,$titles,$wantform) = @_;
14038:     my $result='';
14039:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14040:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14041:             (ref($dirorder) eq 'HASH')) {
14042:         return $result;
14043:     }
14044:     my $dirptr = 16384;
14045:     my ($newdirlistref,$newlisterror) =
14046:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14047:     if (ref($newdirlistref) eq 'ARRAY') {
14048:         foreach my $dir_line (@{$newdirlistref}) {
14049:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14050:             unless ($item =~ /^\.+$/) {
14051:                 $$count ++;
14052:                 @{$dirorder->{$$count}} = @{$hierarchy};
14053:                 $titles->{$$count} = $item;
14054:                 &archive_hierarchy($$depth,$$count,$parent,$children);
14055: 
14056:                 my $is_dir;
14057:                 if ($dirptr&$testdir) {
14058:                     $is_dir = 1;
14059:                 }
14060:                 if ($wantform) {
14061:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14062:                 }
14063:                 if ($is_dir) {
14064:                     $$depth ++;
14065:                     push(@{$hierarchy},$$count);
14066:                     $parent->{$$depth} = $$count;
14067:                     $result .=
14068:                         &recurse_extracted_archive("$currdir/$item",$docudom,
14069:                                                    $docuname,$depth,$count,
14070:                                                    $hierarchy,$dirorder,$children,
14071:                                                    $parent,$titles,$wantform);
14072:                     $$depth --;
14073:                     pop(@{$hierarchy});
14074:                 }
14075:             }
14076:         }
14077:     }
14078:     return $result;
14079: }
14080: 
14081: sub archive_hierarchy {
14082:     my ($depth,$count,$parent,$children) =@_;
14083:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14084:         if (exists($parent->{$depth})) {
14085:              $children->{$parent->{$depth}} .= $count.':';
14086:         }
14087:     }
14088:     return;
14089: }
14090: 
14091: sub archive_row {
14092:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
14093:     my ($name) = ($item =~ m{([^/]+)$});
14094:     my %choices = &Apache::lonlocal::texthash (
14095:                                        'display'    => 'Add as file',
14096:                                        'dependency' => 'Include as dependency',
14097:                                        'discard'    => 'Discard',
14098:                                       );
14099:     if ($is_dir) {
14100:         $choices{'display'} = &mt('Add as folder'); 
14101:     }
14102:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14103:     my $offset = 0;
14104:     foreach my $action ('display','dependency','discard') {
14105:         $offset ++;
14106:         if ($action ne 'display') {
14107:             $offset ++;
14108:         }  
14109:         $output .= '<td><span class="LC_nobreak">'.
14110:                    '<label><input type="radio" name="archive_'.$count.
14111:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14112:         my $text = $choices{$action};
14113:         if ($is_dir) {
14114:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14115:             if ($action eq 'display') {
14116:                 $text = &mt('Add as folder');
14117:             }
14118:         } else {
14119:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14120: 
14121:         }
14122:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
14123:         if ($action eq 'dependency') {
14124:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14125:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
14126:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14127:                        '<option value=""></option>'."\n".
14128:                        '</select>'."\n".
14129:                        '</div>';
14130:         } elsif ($action eq 'display') {
14131:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14132:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14133:                        '</div>';
14134:         }
14135:         $output .= '</td>';
14136:     }
14137:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14138:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
14139:     for (my $i=0; $i<$depth; $i++) {
14140:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14141:     }
14142:     if ($is_dir) {
14143:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
14144:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14145:     } else {
14146:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14147:     }
14148:     $output .= '&nbsp;'.$name.'</td>'."\n".
14149:                &end_data_table_row();
14150:     return $output;
14151: }
14152: 
14153: sub archive_options_form {
14154:     my ($form,$display,$count,$hiddenelem) = @_;
14155:     my %lt = &Apache::lonlocal::texthash(
14156:                perm => 'Permanently remove archive file?',
14157:                hows => 'How should each extracted item be incorporated in the course?',
14158:                cont => 'Content actions for all',
14159:                addf => 'Add as folder/file',
14160:                incd => 'Include as dependency for a displayed file',
14161:                disc => 'Discard',
14162:                no   => 'No',
14163:                yes  => 'Yes',
14164:                save => 'Save',
14165:     );
14166:     my $output = <<"END";
14167: <form name="$form" method="post" action="">
14168: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
14169: <label>
14170:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14171: </label>
14172: &nbsp;
14173: <label>
14174:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14175: </span>
14176: </p>
14177: <input type="hidden" name="phase" value="decompress_cleanup" />
14178: <br />$lt{'hows'}
14179: <div class="LC_columnSection">
14180:   <fieldset>
14181:     <legend>$lt{'cont'}</legend>
14182:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
14183:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14184:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14185:   </fieldset>
14186: </div>
14187: END
14188:     return $output.
14189:            &start_data_table()."\n".
14190:            $display."\n".
14191:            &end_data_table()."\n".
14192:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14193:            $hiddenelem.
14194:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14195:            '</form>';
14196: }
14197: 
14198: sub archive_javascript {
14199:     my ($startcount,$numitems,$titles,$children) = @_;
14200:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14201:     my $maintitle = $env{'form.comment'};
14202:     my $scripttag = <<START;
14203: <script type="text/javascript">
14204: // <![CDATA[
14205: 
14206: function checkAll(form,prefix) {
14207:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
14208:     for (var i=0; i < form.elements.length; i++) {
14209:         var id = form.elements[i].id;
14210:         if ((id != '') && (id != undefined)) {
14211:             if (idstr.test(id)) {
14212:                 if (form.elements[i].type == 'radio') {
14213:                     form.elements[i].checked = true;
14214:                     var nostart = i-$startcount;
14215:                     var offset = nostart%7;
14216:                     var count = (nostart-offset)/7;    
14217:                     dependencyCheck(form,count,offset);
14218:                 }
14219:             }
14220:         }
14221:     }
14222: }
14223: 
14224: function propagateCheck(form,count) {
14225:     if (count > 0) {
14226:         var startelement = $startcount + ((count-1) * 7);
14227:         for (var j=1; j<6; j++) {
14228:             if ((j != 2) && (j != 4)) {
14229:                 var item = startelement + j; 
14230:                 if (form.elements[item].type == 'radio') {
14231:                     if (form.elements[item].checked) {
14232:                         containerCheck(form,count,j);
14233:                         break;
14234:                     }
14235:                 }
14236:             }
14237:         }
14238:     }
14239: }
14240: 
14241: numitems = $numitems
14242: var titles = new Array(numitems);
14243: var parents = new Array(numitems);
14244: for (var i=0; i<numitems; i++) {
14245:     parents[i] = new Array;
14246: }
14247: var maintitle = '$maintitle';
14248: 
14249: START
14250: 
14251:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14252:         my @contents = split(/:/,$children->{$container});
14253:         for (my $i=0; $i<@contents; $i ++) {
14254:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14255:         }
14256:     }
14257: 
14258:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14259:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14260:     }
14261: 
14262:     $scripttag .= <<END;
14263: 
14264: function containerCheck(form,count,offset) {
14265:     if (count > 0) {
14266:         dependencyCheck(form,count,offset);
14267:         var item = (offset+$startcount)+7*(count-1);
14268:         form.elements[item].checked = true;
14269:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14270:             if (parents[count].length > 0) {
14271:                 for (var j=0; j<parents[count].length; j++) {
14272:                     containerCheck(form,parents[count][j],offset);
14273:                 }
14274:             }
14275:         }
14276:     }
14277: }
14278: 
14279: function dependencyCheck(form,count,offset) {
14280:     if (count > 0) {
14281:         var chosen = (offset+$startcount)+7*(count-1);
14282:         var depitem = $startcount + ((count-1) * 7) + 4;
14283:         var currtype = form.elements[depitem].type;
14284:         if (form.elements[chosen].value == 'dependency') {
14285:             document.getElementById('arc_depon_'+count).style.display='block'; 
14286:             form.elements[depitem].options.length = 0;
14287:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14288:             for (var i=1; i<=numitems; i++) {
14289:                 if (i == count) {
14290:                     continue;
14291:                 }
14292:                 var startelement = $startcount + (i-1) * 7;
14293:                 for (var j=1; j<6; j++) {
14294:                     if ((j != 2) && (j!= 4)) {
14295:                         var item = startelement + j;
14296:                         if (form.elements[item].type == 'radio') {
14297:                             if (form.elements[item].checked) {
14298:                                 if (form.elements[item].value == 'display') {
14299:                                     var n = form.elements[depitem].options.length;
14300:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14301:                                 }
14302:                             }
14303:                         }
14304:                     }
14305:                 }
14306:             }
14307:         } else {
14308:             document.getElementById('arc_depon_'+count).style.display='none';
14309:             form.elements[depitem].options.length = 0;
14310:             form.elements[depitem].options[0] = new Option('Select','',true,true);
14311:         }
14312:         titleCheck(form,count,offset);
14313:     }
14314: }
14315: 
14316: function propagateSelect(form,count,offset) {
14317:     if (count > 0) {
14318:         var item = (1+offset+$startcount)+7*(count-1);
14319:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
14320:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14321:             if (parents[count].length > 0) {
14322:                 for (var j=0; j<parents[count].length; j++) {
14323:                     containerSelect(form,parents[count][j],offset,picked);
14324:                 }
14325:             }
14326:         }
14327:     }
14328: }
14329: 
14330: function containerSelect(form,count,offset,picked) {
14331:     if (count > 0) {
14332:         var item = (offset+$startcount)+7*(count-1);
14333:         if (form.elements[item].type == 'radio') {
14334:             if (form.elements[item].value == 'dependency') {
14335:                 if (form.elements[item+1].type == 'select-one') {
14336:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
14337:                         if (form.elements[item+1].options[i].value == picked) {
14338:                             form.elements[item+1].selectedIndex = i;
14339:                             break;
14340:                         }
14341:                     }
14342:                 }
14343:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14344:                     if (parents[count].length > 0) {
14345:                         for (var j=0; j<parents[count].length; j++) {
14346:                             containerSelect(form,parents[count][j],offset,picked);
14347:                         }
14348:                     }
14349:                 }
14350:             }
14351:         }
14352:     }
14353: }
14354: 
14355: function titleCheck(form,count,offset) {
14356:     if (count > 0) {
14357:         var chosen = (offset+$startcount)+7*(count-1);
14358:         var depitem = $startcount + ((count-1) * 7) + 2;
14359:         var currtype = form.elements[depitem].type;
14360:         if (form.elements[chosen].value == 'display') {
14361:             document.getElementById('arc_title_'+count).style.display='block';
14362:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14363:                 document.getElementById('archive_title_'+count).value=maintitle;
14364:             }
14365:         } else {
14366:             document.getElementById('arc_title_'+count).style.display='none';
14367:             if (currtype == 'text') { 
14368:                 document.getElementById('archive_title_'+count).value='';
14369:             }
14370:         }
14371:     }
14372:     return;
14373: }
14374: 
14375: // ]]>
14376: </script>
14377: END
14378:     return $scripttag;
14379: }
14380: 
14381: sub process_extracted_files {
14382:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14383:     my $numitems = $env{'form.archive_count'};
14384:     return if ((!$numitems) || ($numitems =~ /\D/));
14385:     my @ids=&Apache::lonnet::current_machine_ids();
14386:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14387:         %folders,%containers,%mapinner,%prompttofetch);
14388:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14389:     if (grep(/^\Q$docuhome\E$/,@ids)) {
14390:         $prefix = &LONCAPA::propath($docudom,$docuname);
14391:         $pathtocheck = "$dir_root/$destination";
14392:         $dir = $dir_root;
14393:         $ishome = 1;
14394:     } else {
14395:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14396:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14397:         $dir = "$dir_root/$docudom/$docuname";
14398:     }
14399:     my $currdir = "$dir_root/$destination";
14400:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14401:     if ($env{'form.folderpath'}) {
14402:         my @items = split('&',$env{'form.folderpath'});
14403:         $folders{'0'} = $items[-2];
14404:         if ($env{'form.folderpath'} =~ /\:1$/) {
14405:             $containers{'0'}='page';
14406:         } else {  
14407:             $containers{'0'}='sequence';
14408:         }
14409:     }
14410:     my @archdirs = &get_env_multiple('form.archive_directory');
14411:     if ($numitems) {
14412:         for (my $i=1; $i<=$numitems; $i++) {
14413:             my $path = $env{'form.archive_content_'.$i};
14414:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14415:                 my $item = $1;
14416:                 $toplevelitems{$item} = $i;
14417:                 if (grep(/^\Q$i\E$/,@archdirs)) {
14418:                     $is_dir{$item} = 1;
14419:                 }
14420:             }
14421:         }
14422:     }
14423:     my ($output,%children,%parent,%titles,%dirorder,$result);
14424:     if (keys(%toplevelitems) > 0) {
14425:         my @contents = sort(keys(%toplevelitems));
14426:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14427:                                            \%parent,\@contents,\%dirorder,\%titles);
14428:     }
14429:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14430:     if ($numitems) {
14431:         for (my $i=1; $i<=$numitems; $i++) {
14432:             next if ($env{'form.archive_'.$i} eq 'dependency');
14433:             my $path = $env{'form.archive_content_'.$i};
14434:             if ($path =~ /^\Q$pathtocheck\E/) {
14435:                 if ($env{'form.archive_'.$i} eq 'discard') {
14436:                     if ($prefix ne '' && $path ne '') {
14437:                         if (-e $prefix.$path) {
14438:                             if ((@archdirs > 0) && 
14439:                                 (grep(/^\Q$i\E$/,@archdirs))) {
14440:                                 $todeletedir{$prefix.$path} = 1;
14441:                             } else {
14442:                                 $todelete{$prefix.$path} = 1;
14443:                             }
14444:                         }
14445:                     }
14446:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
14447:                     my ($docstitle,$title,$url,$outer);
14448:                     ($title) = ($path =~ m{/([^/]+)$});
14449:                     $docstitle = $env{'form.archive_title_'.$i};
14450:                     if ($docstitle eq '') {
14451:                         $docstitle = $title;
14452:                     }
14453:                     $outer = 0;
14454:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14455:                         if (@{$dirorder{$i}} > 0) {
14456:                             foreach my $item (reverse(@{$dirorder{$i}})) {
14457:                                 if ($env{'form.archive_'.$item} eq 'display') {
14458:                                     $outer = $item;
14459:                                     last;
14460:                                 }
14461:                             }
14462:                         }
14463:                     }
14464:                     my ($errtext,$fatal) = 
14465:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14466:                                                '/'.$folders{$outer}.'.'.
14467:                                                $containers{$outer});
14468:                     next if ($fatal);
14469:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14470:                         if ($context eq 'coursedocs') {
14471:                             $mapinner{$i} = time;
14472:                             $folders{$i} = 'default_'.$mapinner{$i};
14473:                             $containers{$i} = 'sequence';
14474:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14475:                                       $folders{$i}.'.'.$containers{$i};
14476:                             my $newidx = &LONCAPA::map::getresidx();
14477:                             $LONCAPA::map::resources[$newidx]=
14478:                                 $docstitle.':'.$url.':false:normal:res';
14479:                             push(@LONCAPA::map::order,$newidx);
14480:                             my ($outtext,$errtext) =
14481:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14482:                                                         $docuname.'/'.$folders{$outer}.
14483:                                                         '.'.$containers{$outer},1,1);
14484:                             $newseqid{$i} = $newidx;
14485:                             unless ($errtext) {
14486:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
14487:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
14488:                                             '</li>'."\n";
14489:                             }
14490:                         }
14491:                     } else {
14492:                         if ($context eq 'coursedocs') {
14493:                             my $newidx=&LONCAPA::map::getresidx();
14494:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14495:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14496:                                       $title;
14497:                             if (($outer !~ /\D/) &&
14498:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14499:                                 ($newidx !~ /\D/)) {
14500:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14501:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14502:                                 }
14503:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14504:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14505:                                 }
14506:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14507:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14508:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14509:                                         unless ($ishome) {
14510:                                             my $fetch = "$newdest{$i}/$title";
14511:                                             $fetch =~ s/^\Q$prefix$dir\E//;
14512:                                             $prompttofetch{$fetch} = 1;
14513:                                         }
14514:                                     }
14515:                                 }
14516:                                 $LONCAPA::map::resources[$newidx]=
14517:                                     $docstitle.':'.$url.':false:normal:res';
14518:                                 push(@LONCAPA::map::order, $newidx);
14519:                                 my ($outtext,$errtext)=
14520:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14521:                                                             $docuname.'/'.$folders{$outer}.
14522:                                                             '.'.$containers{$outer},1,1);
14523:                                 unless ($errtext) {
14524:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14525:                                         $result .= '<li>'.&mt('File: [_1] added to course',
14526:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
14527:                                                    '</li>'."\n";
14528:                                     }
14529:                                 }
14530:                             } else {
14531:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14532:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
14533:                             }
14534:                         }
14535:                     }
14536:                 }
14537:             } else {
14538:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14539:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
14540:             }
14541:         }
14542:         for (my $i=1; $i<=$numitems; $i++) {
14543:             next unless ($env{'form.archive_'.$i} eq 'dependency');
14544:             my $path = $env{'form.archive_content_'.$i};
14545:             if ($path =~ /^\Q$pathtocheck\E/) {
14546:                 my ($title) = ($path =~ m{/([^/]+)$});
14547:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14548:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14549:                     if (ref($dirorder{$i}) eq 'ARRAY') {
14550:                         my ($itemidx,$fullpath,$relpath);
14551:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14552:                             my $container = $dirorder{$referrer{$i}}->[-1];
14553:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14554:                                 if ($dirorder{$i}->[$j] eq $container) {
14555:                                     $itemidx = $j;
14556:                                 }
14557:                             }
14558:                         }
14559:                         if ($itemidx eq '') {
14560:                             $itemidx =  0;
14561:                         } 
14562:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14563:                             if ($mapinner{$referrer{$i}}) {
14564:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14565:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14566:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14567:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14568:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14569:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14570:                                             if (!-e $fullpath) {
14571:                                                 mkdir($fullpath,0755);
14572:                                             }
14573:                                         }
14574:                                     } else {
14575:                                         last;
14576:                                     }
14577:                                 }
14578:                             }
14579:                         } elsif ($newdest{$referrer{$i}}) {
14580:                             $fullpath = $newdest{$referrer{$i}};
14581:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14582:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14583:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14584:                                     last;
14585:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14586:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14587:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14588:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14589:                                         if (!-e $fullpath) {
14590:                                             mkdir($fullpath,0755);
14591:                                         }
14592:                                     }
14593:                                 } else {
14594:                                     last;
14595:                                 }
14596:                             }
14597:                         }
14598:                         if ($fullpath ne '') {
14599:                             if (-e "$prefix$path") {
14600:                                 unless (rename("$prefix$path","$fullpath/$title")) {
14601:                                      $warning .= &mt('Failed to rename dependency').'<br />';
14602:                                 }
14603:                             }
14604:                             if (-e "$fullpath/$title") {
14605:                                 my $showpath;
14606:                                 if ($relpath ne '') {
14607:                                     $showpath = "$relpath/$title";
14608:                                 } else {
14609:                                     $showpath = "/$title";
14610:                                 } 
14611:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
14612:                                                       &HTML::Entities::encode($showpath,'<>&"')).
14613:                                            '</li>'."\n";
14614:                                 unless ($ishome) {
14615:                                     my $fetch = "$fullpath/$title";
14616:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
14617:                                     $prompttofetch{$fetch} = 1;
14618:                                 }
14619:                             }
14620:                         }
14621:                     }
14622:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14623:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14624:                                     &HTML::Entities::encode($path,'<>&"'),
14625:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14626:                                 '<br />';
14627:                 }
14628:             } else {
14629:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14630:                                 &HTML::Entities::encode($path)).'<br />';
14631:             }
14632:         }
14633:         if (keys(%todelete)) {
14634:             foreach my $key (keys(%todelete)) {
14635:                 unlink($key);
14636:             }
14637:         }
14638:         if (keys(%todeletedir)) {
14639:             foreach my $key (keys(%todeletedir)) {
14640:                 rmdir($key);
14641:             }
14642:         }
14643:         foreach my $dir (sort(keys(%is_dir))) {
14644:             if (($pathtocheck ne '') && ($dir ne ''))  {
14645:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14646:             }
14647:         }
14648:         if ($result ne '') {
14649:             $output .= '<ul>'."\n".
14650:                        $result."\n".
14651:                        '</ul>';
14652:         }
14653:         unless ($ishome) {
14654:             my $replicationfail;
14655:             foreach my $item (keys(%prompttofetch)) {
14656:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14657:                 unless ($fetchresult eq 'ok') {
14658:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
14659:                 }
14660:             }
14661:             if ($replicationfail) {
14662:                 $output .= '<p class="LC_error">'.
14663:                            &mt('Course home server failed to retrieve:').'<ul>'.
14664:                            $replicationfail.
14665:                            '</ul></p>';
14666:             }
14667:         }
14668:     } else {
14669:         $warning = &mt('No items found in archive.');
14670:     }
14671:     if ($error) {
14672:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14673:                    $error.'</p>'."\n";
14674:     }
14675:     if ($warning) {
14676:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14677:     }
14678:     return $output;
14679: }
14680: 
14681: sub cleanup_empty_dirs {
14682:     my ($path) = @_;
14683:     if (($path ne '') && (-d $path)) {
14684:         if (opendir(my $dirh,$path)) {
14685:             my @dircontents = grep(!/^\./,readdir($dirh));
14686:             my $numitems = 0;
14687:             foreach my $item (@dircontents) {
14688:                 if (-d "$path/$item") {
14689:                     &cleanup_empty_dirs("$path/$item");
14690:                     if (-e "$path/$item") {
14691:                         $numitems ++;
14692:                     }
14693:                 } else {
14694:                     $numitems ++;
14695:                 }
14696:             }
14697:             if ($numitems == 0) {
14698:                 rmdir($path);
14699:             }
14700:             closedir($dirh);
14701:         }
14702:     }
14703:     return;
14704: }
14705: 
14706: =pod
14707: 
14708: =item * &get_folder_hierarchy()
14709: 
14710: Provides hierarchy of names of folders/sub-folders containing the current
14711: item,
14712: 
14713: Inputs: 3
14714:      - $navmap - navmaps object
14715: 
14716:      - $map - url for map (either the trigger itself, or map containing
14717:                            the resource, which is the trigger).
14718: 
14719:      - $showitem - 1 => show title for map itself; 0 => do not show.
14720: 
14721: Outputs: 1 @pathitems - array of folder/subfolder names.
14722: 
14723: =cut
14724: 
14725: sub get_folder_hierarchy {
14726:     my ($navmap,$map,$showitem) = @_;
14727:     my @pathitems;
14728:     if (ref($navmap)) {
14729:         my $mapres = $navmap->getResourceByUrl($map);
14730:         if (ref($mapres)) {
14731:             my $pcslist = $mapres->map_hierarchy();
14732:             if ($pcslist ne '') {
14733:                 my @pcs = split(/,/,$pcslist);
14734:                 foreach my $pc (@pcs) {
14735:                     if ($pc == 1) {
14736:                         push(@pathitems,&mt('Main Content'));
14737:                     } else {
14738:                         my $res = $navmap->getByMapPc($pc);
14739:                         if (ref($res)) {
14740:                             my $title = $res->compTitle();
14741:                             $title =~ s/\W+/_/g;
14742:                             if ($title ne '') {
14743:                                 push(@pathitems,$title);
14744:                             }
14745:                         }
14746:                     }
14747:                 }
14748:             }
14749:             if ($showitem) {
14750:                 if ($mapres->{ID} eq '0.0') {
14751:                     push(@pathitems,&mt('Main Content'));
14752:                 } else {
14753:                     my $maptitle = $mapres->compTitle();
14754:                     $maptitle =~ s/\W+/_/g;
14755:                     if ($maptitle ne '') {
14756:                         push(@pathitems,$maptitle);
14757:                     }
14758:                 }
14759:             }
14760:         }
14761:     }
14762:     return @pathitems;
14763: }
14764: 
14765: =pod
14766: 
14767: =item * &get_turnedin_filepath()
14768: 
14769: Determines path in a user's portfolio file for storage of files uploaded
14770: to a specific essayresponse or dropbox item.
14771: 
14772: Inputs: 3 required + 1 optional.
14773: $symb is symb for resource, $uname and $udom are for current user (required).
14774: $caller is optional (can be "submission", if routine is called when storing
14775: an upoaded file when "Submit Answer" button was pressed).
14776: 
14777: Returns array containing $path and $multiresp. 
14778: $path is path in portfolio.  $multiresp is 1 if this resource contains more
14779: than one file upload item.  Callers of routine should append partid as a 
14780: subdirectory to $path in cases where $multiresp is 1.
14781: 
14782: Called by: homework/essayresponse.pm and homework/structuretags.pm
14783: 
14784: =cut
14785: 
14786: sub get_turnedin_filepath {
14787:     my ($symb,$uname,$udom,$caller) = @_;
14788:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14789:     my $turnindir;
14790:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14791:     $turnindir = $userhash{'turnindir'};
14792:     my ($path,$multiresp);
14793:     if ($turnindir eq '') {
14794:         if ($caller eq 'submission') {
14795:             $turnindir = &mt('turned in');
14796:             $turnindir =~ s/\W+/_/g;
14797:             my %newhash = (
14798:                             'turnindir' => $turnindir,
14799:                           );
14800:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14801:         }
14802:     }
14803:     if ($turnindir ne '') {
14804:         $path = '/'.$turnindir.'/';
14805:         my ($multipart,$turnin,@pathitems);
14806:         my $navmap = Apache::lonnavmaps::navmap->new();
14807:         if (defined($navmap)) {
14808:             my $mapres = $navmap->getResourceByUrl($map);
14809:             if (ref($mapres)) {
14810:                 my $pcslist = $mapres->map_hierarchy();
14811:                 if ($pcslist ne '') {
14812:                     foreach my $pc (split(/,/,$pcslist)) {
14813:                         my $res = $navmap->getByMapPc($pc);
14814:                         if (ref($res)) {
14815:                             my $title = $res->compTitle();
14816:                             $title =~ s/\W+/_/g;
14817:                             if ($title ne '') {
14818:                                 if (($pc > 1) && (length($title) > 12)) {
14819:                                     $title = substr($title,0,12);
14820:                                 }
14821:                                 push(@pathitems,$title);
14822:                             }
14823:                         }
14824:                     }
14825:                 }
14826:                 my $maptitle = $mapres->compTitle();
14827:                 $maptitle =~ s/\W+/_/g;
14828:                 if ($maptitle ne '') {
14829:                     if (length($maptitle) > 12) {
14830:                         $maptitle = substr($maptitle,0,12);
14831:                     }
14832:                     push(@pathitems,$maptitle);
14833:                 }
14834:                 unless ($env{'request.state'} eq 'construct') {
14835:                     my $res = $navmap->getBySymb($symb);
14836:                     if (ref($res)) {
14837:                         my $partlist = $res->parts();
14838:                         my $totaluploads = 0;
14839:                         if (ref($partlist) eq 'ARRAY') {
14840:                             foreach my $part (@{$partlist}) {
14841:                                 my @types = $res->responseType($part);
14842:                                 my @ids = $res->responseIds($part);
14843:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14844:                                     if ($types[$i] eq 'essay') {
14845:                                         my $partid = $part.'_'.$ids[$i];
14846:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14847:                                             $totaluploads ++;
14848:                                         }
14849:                                     }
14850:                                 }
14851:                             }
14852:                             if ($totaluploads > 1) {
14853:                                 $multiresp = 1;
14854:                             }
14855:                         }
14856:                     }
14857:                 }
14858:             } else {
14859:                 return;
14860:             }
14861:         } else {
14862:             return;
14863:         }
14864:         my $restitle=&Apache::lonnet::gettitle($symb);
14865:         $restitle =~ s/\W+/_/g;
14866:         if ($restitle eq '') {
14867:             $restitle = ($resurl =~ m{/[^/]+$});
14868:             if ($restitle eq '') {
14869:                 $restitle = time;
14870:             }
14871:         }
14872:         if (length($restitle) > 12) {
14873:             $restitle = substr($restitle,0,12);
14874:         }
14875:         push(@pathitems,$restitle);
14876:         $path .= join('/',@pathitems);
14877:     }
14878:     return ($path,$multiresp);
14879: }
14880: 
14881: =pod
14882: 
14883: =back
14884: 
14885: =head1 CSV Upload/Handling functions
14886: 
14887: =over 4
14888: 
14889: =item * &upfile_store($r)
14890: 
14891: Store uploaded file, $r should be the HTTP Request object,
14892: needs $env{'form.upfile'}
14893: returns $datatoken to be put into hidden field
14894: 
14895: =cut
14896: 
14897: sub upfile_store {
14898:     my $r=shift;
14899:     $env{'form.upfile'}=~s/\r/\n/gs;
14900:     $env{'form.upfile'}=~s/\f/\n/gs;
14901:     $env{'form.upfile'}=~s/\n+/\n/gs;
14902:     $env{'form.upfile'}=~s/\n+$//gs;
14903: 
14904:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14905:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14906:                                      time.'_'.$$);
14907:     return if ($datatoken eq '');
14908: 
14909:     {
14910:         my $datafile = $r->dir_config('lonDaemons').
14911:                            '/tmp/'.$datatoken.'.tmp';
14912:         if ( open(my $fh,'>',$datafile) ) {
14913:             print $fh $env{'form.upfile'};
14914:             close($fh);
14915:         }
14916:     }
14917:     return $datatoken;
14918: }
14919: 
14920: =pod
14921: 
14922: =item * &load_tmp_file($r,$datatoken)
14923: 
14924: Load uploaded file from tmp, $r should be the HTTP Request object,
14925: $datatoken is the name to assign to the temporary file.
14926: sets $env{'form.upfile'} to the contents of the file
14927: 
14928: =cut
14929: 
14930: sub load_tmp_file {
14931:     my ($r,$datatoken) = @_;
14932:     return if ($datatoken eq '');
14933:     my @studentdata=();
14934:     {
14935:         my $studentfile = $r->dir_config('lonDaemons').
14936:                               '/tmp/'.$datatoken.'.tmp';
14937:         if ( open(my $fh,'<',$studentfile) ) {
14938:             @studentdata=<$fh>;
14939:             close($fh);
14940:         }
14941:     }
14942:     $env{'form.upfile'}=join('',@studentdata);
14943: }
14944: 
14945: sub valid_datatoken {
14946:     my ($datatoken) = @_;
14947:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14948:         return $datatoken;
14949:     }
14950:     return;
14951: }
14952: 
14953: =pod
14954: 
14955: =item * &upfile_record_sep()
14956: 
14957: Separate uploaded file into records
14958: returns array of records,
14959: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14960: 
14961: =cut
14962: 
14963: sub upfile_record_sep {
14964:     if ($env{'form.upfiletype'} eq 'xml') {
14965:     } else {
14966: 	my @records;
14967: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14968: 	    if ($line=~/^\s*$/) { next; }
14969: 	    push(@records,$line);
14970: 	}
14971: 	return @records;
14972:     }
14973: }
14974: 
14975: =pod
14976: 
14977: =item * &record_sep($record)
14978: 
14979: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14980: 
14981: =cut
14982: 
14983: sub takeleft {
14984:     my $index=shift;
14985:     return substr('0000'.$index,-4,4);
14986: }
14987: 
14988: sub record_sep {
14989:     my $record=shift;
14990:     my %components=();
14991:     if ($env{'form.upfiletype'} eq 'xml') {
14992:     } elsif ($env{'form.upfiletype'} eq 'space') {
14993:         my $i=0;
14994:         foreach my $field (split(/\s+/,$record)) {
14995:             $field=~s/^(\"|\')//;
14996:             $field=~s/(\"|\')$//;
14997:             $components{&takeleft($i)}=$field;
14998:             $i++;
14999:         }
15000:     } elsif ($env{'form.upfiletype'} eq 'tab') {
15001:         my $i=0;
15002:         foreach my $field (split(/\t/,$record)) {
15003:             $field=~s/^(\"|\')//;
15004:             $field=~s/(\"|\')$//;
15005:             $components{&takeleft($i)}=$field;
15006:             $i++;
15007:         }
15008:     } else {
15009:         my $separator=',';
15010:         if ($env{'form.upfiletype'} eq 'semisv') {
15011:             $separator=';';
15012:         }
15013:         my $i=0;
15014: # the character we are looking for to indicate the end of a quote or a record 
15015:         my $looking_for=$separator;
15016: # do not add the characters to the fields
15017:         my $ignore=0;
15018: # we just encountered a separator (or the beginning of the record)
15019:         my $just_found_separator=1;
15020: # store the field we are working on here
15021:         my $field='';
15022: # work our way through all characters in record
15023:         foreach my $character ($record=~/(.)/g) {
15024:             if ($character eq $looking_for) {
15025:                if ($character ne $separator) {
15026: # Found the end of a quote, again looking for separator
15027:                   $looking_for=$separator;
15028:                   $ignore=1;
15029:                } else {
15030: # Found a separator, store away what we got
15031:                   $components{&takeleft($i)}=$field;
15032: 	          $i++;
15033:                   $just_found_separator=1;
15034:                   $ignore=0;
15035:                   $field='';
15036:                }
15037:                next;
15038:             }
15039: # single or double quotation marks after a separator indicate beginning of a quote
15040: # we are now looking for the end of the quote and need to ignore separators
15041:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
15042:                $looking_for=$character;
15043:                next;
15044:             }
15045: # ignore would be true after we reached the end of a quote
15046:             if ($ignore) { next; }
15047:             if (($just_found_separator) && ($character=~/\s/)) { next; }
15048:             $field.=$character;
15049:             $just_found_separator=0; 
15050:         }
15051: # catch the very last entry, since we never encountered the separator
15052:         $components{&takeleft($i)}=$field;
15053:     }
15054:     return %components;
15055: }
15056: 
15057: ######################################################
15058: ######################################################
15059: 
15060: =pod
15061: 
15062: =item * &upfile_select_html()
15063: 
15064: Return HTML code to select a file from the users machine and specify 
15065: the file type.
15066: 
15067: =cut
15068: 
15069: ######################################################
15070: ######################################################
15071: sub upfile_select_html {
15072:     my %Types = (
15073:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
15074:                  semisv => &mt('Semicolon separated values'),
15075:                  space => &mt('Space separated'),
15076:                  tab   => &mt('Tabulator separated'),
15077: #                 xml   => &mt('HTML/XML'),
15078:                  );
15079:     my $Str = '<input type="file" name="upfile" size="50" />'.
15080:         '<br />'.&mt('Type').': <select name="upfiletype">';
15081:     foreach my $type (sort(keys(%Types))) {
15082:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15083:     }
15084:     $Str .= "</select>\n";
15085:     return $Str;
15086: }
15087: 
15088: sub get_samples {
15089:     my ($records,$toget) = @_;
15090:     my @samples=({});
15091:     my $got=0;
15092:     foreach my $rec (@$records) {
15093: 	my %temp = &record_sep($rec);
15094: 	if (! grep(/\S/, values(%temp))) { next; }
15095: 	if (%temp) {
15096: 	    $samples[$got]=\%temp;
15097: 	    $got++;
15098: 	    if ($got == $toget) { last; }
15099: 	}
15100:     }
15101:     return \@samples;
15102: }
15103: 
15104: ######################################################
15105: ######################################################
15106: 
15107: =pod
15108: 
15109: =item * &csv_print_samples($r,$records)
15110: 
15111: Prints a table of sample values from each column uploaded $r is an
15112: Apache Request ref, $records is an arrayref from
15113: &Apache::loncommon::upfile_record_sep
15114: 
15115: =cut
15116: 
15117: ######################################################
15118: ######################################################
15119: sub csv_print_samples {
15120:     my ($r,$records) = @_;
15121:     my $samples = &get_samples($records,5);
15122: 
15123:     $r->print(&mt('Samples').'<br />'.&start_data_table().
15124:               &start_data_table_header_row());
15125:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
15126:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15127:     $r->print(&end_data_table_header_row());
15128:     foreach my $hash (@$samples) {
15129: 	$r->print(&start_data_table_row());
15130: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15131: 	    $r->print('<td>');
15132: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15133: 	    $r->print('</td>');
15134: 	}
15135: 	$r->print(&end_data_table_row());
15136:     }
15137:     $r->print(&end_data_table().'<br />'."\n");
15138: }
15139: 
15140: ######################################################
15141: ######################################################
15142: 
15143: =pod
15144: 
15145: =item * &csv_print_select_table($r,$records,$d)
15146: 
15147: Prints a table to create associations between values and table columns.
15148: 
15149: $r is an Apache Request ref,
15150: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15151: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15152: 
15153: =cut
15154: 
15155: ######################################################
15156: ######################################################
15157: sub csv_print_select_table {
15158:     my ($r,$records,$d) = @_;
15159:     my $i=0;
15160:     my $samples = &get_samples($records,1);
15161:     $r->print(&mt('Associate columns with student attributes.')."\n".
15162: 	      &start_data_table().&start_data_table_header_row().
15163:               '<th>'.&mt('Attribute').'</th>'.
15164:               '<th>'.&mt('Column').'</th>'.
15165:               &end_data_table_header_row()."\n");
15166:     foreach my $array_ref (@$d) {
15167: 	my ($value,$display,$defaultcol)=@{ $array_ref };
15168: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
15169: 
15170: 	$r->print('<td><select name="f'.$i.'"'.
15171: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15172: 	$r->print('<option value="none"></option>');
15173: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15174: 	    $r->print('<option value="'.$sample.'"'.
15175:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
15176:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
15177: 	}
15178: 	$r->print('</select></td>'.&end_data_table_row()."\n");
15179: 	$i++;
15180:     }
15181:     $r->print(&end_data_table());
15182:     $i--;
15183:     return $i;
15184: }
15185: 
15186: ######################################################
15187: ######################################################
15188: 
15189: =pod
15190: 
15191: =item * &csv_samples_select_table($r,$records,$d)
15192: 
15193: Prints a table of sample values from the upload and can make associate samples to internal names.
15194: 
15195: $r is an Apache Request ref,
15196: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15197: $d is an array of 2 element arrays (internal name, displayed name)
15198: 
15199: =cut
15200: 
15201: ######################################################
15202: ######################################################
15203: sub csv_samples_select_table {
15204:     my ($r,$records,$d) = @_;
15205:     my $i=0;
15206:     #
15207:     my $max_samples = 5;
15208:     my $samples = &get_samples($records,$max_samples);
15209:     $r->print(&start_data_table().
15210:               &start_data_table_header_row().'<th>'.
15211:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15212:               &end_data_table_header_row());
15213: 
15214:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
15215: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15216: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
15217: 	foreach my $option (@$d) {
15218: 	    my ($value,$display,$defaultcol)=@{ $option };
15219: 	    $r->print('<option value="'.$value.'"'.
15220:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15221:                       $display.'</option>');
15222: 	}
15223: 	$r->print('</select></td><td>');
15224: 	foreach my $line (0..($max_samples-1)) {
15225: 	    if (defined($samples->[$line]{$key})) { 
15226: 		$r->print($samples->[$line]{$key}."<br />\n"); 
15227: 	    }
15228: 	}
15229: 	$r->print('</td>'.&end_data_table_row());
15230: 	$i++;
15231:     }
15232:     $r->print(&end_data_table());
15233:     $i--;
15234:     return($i);
15235: }
15236: 
15237: ######################################################
15238: ######################################################
15239: 
15240: =pod
15241: 
15242: =item * &clean_excel_name($name)
15243: 
15244: Returns a replacement for $name which does not contain any illegal characters.
15245: 
15246: =cut
15247: 
15248: ######################################################
15249: ######################################################
15250: sub clean_excel_name {
15251:     my ($name) = @_;
15252:     $name =~ s/[:\*\?\/\\]//g;
15253:     if (length($name) > 31) {
15254:         $name = substr($name,0,31);
15255:     }
15256:     return $name;
15257: }
15258: 
15259: =pod
15260: 
15261: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15262: 
15263: Returns either 1 or undef
15264: 
15265: 1 if the part is to be hidden, undef if it is to be shown
15266: 
15267: Arguments are:
15268: 
15269: $id the id of the part to be checked
15270: $symb, optional the symb of the resource to check
15271: $udom, optional the domain of the user to check for
15272: $uname, optional the username of the user to check for
15273: 
15274: =cut
15275: 
15276: sub check_if_partid_hidden {
15277:     my ($id,$symb,$udom,$uname) = @_;
15278:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15279: 					 $symb,$udom,$uname);
15280:     my $truth=1;
15281:     #if the string starts with !, then the list is the list to show not hide
15282:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15283:     my @hiddenlist=split(/,/,$hiddenparts);
15284:     foreach my $checkid (@hiddenlist) {
15285: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15286:     }
15287:     return !$truth;
15288: }
15289: 
15290: 
15291: ############################################################
15292: ############################################################
15293: 
15294: =pod
15295: 
15296: =back 
15297: 
15298: =head1 cgi-bin script and graphing routines
15299: 
15300: =over 4
15301: 
15302: =item * &get_cgi_id()
15303: 
15304: Inputs: none
15305: 
15306: Returns an id which can be used to pass environment variables
15307: to various cgi-bin scripts.  These environment variables will
15308: be removed from the users environment after a given time by
15309: the routine &Apache::lonnet::transfer_profile_to_env.
15310: 
15311: =cut
15312: 
15313: ############################################################
15314: ############################################################
15315: my $uniq=0;
15316: sub get_cgi_id {
15317:     $uniq=($uniq+1)%100000;
15318:     return (time.'_'.$$.'_'.$uniq);
15319: }
15320: 
15321: ############################################################
15322: ############################################################
15323: 
15324: =pod
15325: 
15326: =item * &DrawBarGraph()
15327: 
15328: Facilitates the plotting of data in a (stacked) bar graph.
15329: Puts plot definition data into the users environment in order for 
15330: graph.png to plot it.  Returns an <img> tag for the plot.
15331: The bars on the plot are labeled '1','2',...,'n'.
15332: 
15333: Inputs:
15334: 
15335: =over 4
15336: 
15337: =item $Title: string, the title of the plot
15338: 
15339: =item $xlabel: string, text describing the X-axis of the plot
15340: 
15341: =item $ylabel: string, text describing the Y-axis of the plot
15342: 
15343: =item $Max: scalar, the maximum Y value to use in the plot
15344: If $Max is < any data point, the graph will not be rendered.
15345: 
15346: =item $colors: array ref holding the colors to be used for the data sets when
15347: they are plotted.  If undefined, default values will be used.
15348: 
15349: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15350: 
15351: =item @Values: An array of array references.  Each array reference holds data
15352: to be plotted in a stacked bar chart.
15353: 
15354: =item If the final element of @Values is a hash reference the key/value
15355: pairs will be added to the graph definition.
15356: 
15357: =back
15358: 
15359: Returns:
15360: 
15361: An <img> tag which references graph.png and the appropriate identifying
15362: information for the plot.
15363: 
15364: =cut
15365: 
15366: ############################################################
15367: ############################################################
15368: sub DrawBarGraph {
15369:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15370:     #
15371:     if (! defined($colors)) {
15372:         $colors = ['#33ff00', 
15373:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15374:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15375:                   ]; 
15376:     }
15377:     my $extra_settings = {};
15378:     if (ref($Values[-1]) eq 'HASH') {
15379:         $extra_settings = pop(@Values);
15380:     }
15381:     #
15382:     my $identifier = &get_cgi_id();
15383:     my $id = 'cgi.'.$identifier;        
15384:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
15385:         return '';
15386:     }
15387:     #
15388:     my @Labels;
15389:     if (defined($labels)) {
15390:         @Labels = @$labels;
15391:     } else {
15392:         for (my $i=0;$i<@{$Values[0]};$i++) {
15393:             push(@Labels,$i+1);
15394:         }
15395:     }
15396:     #
15397:     my $NumBars = scalar(@{$Values[0]});
15398:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15399:     my %ValuesHash;
15400:     my $NumSets=1;
15401:     foreach my $array (@Values) {
15402:         next if (! ref($array));
15403:         $ValuesHash{$id.'.data.'.$NumSets++} = 
15404:             join(',',@$array);
15405:     }
15406:     #
15407:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15408:     if ($NumBars < 3) {
15409:         $width = 120+$NumBars*32;
15410:         $xskip = 1;
15411:         $bar_width = 30;
15412:     } elsif ($NumBars < 5) {
15413:         $width = 120+$NumBars*20;
15414:         $xskip = 1;
15415:         $bar_width = 20;
15416:     } elsif ($NumBars < 10) {
15417:         $width = 120+$NumBars*15;
15418:         $xskip = 1;
15419:         $bar_width = 15;
15420:     } elsif ($NumBars <= 25) {
15421:         $width = 120+$NumBars*11;
15422:         $xskip = 5;
15423:         $bar_width = 8;
15424:     } elsif ($NumBars <= 50) {
15425:         $width = 120+$NumBars*8;
15426:         $xskip = 5;
15427:         $bar_width = 4;
15428:     } else {
15429:         $width = 120+$NumBars*8;
15430:         $xskip = 5;
15431:         $bar_width = 4;
15432:     }
15433:     #
15434:     $Max = 1 if ($Max < 1);
15435:     if ( int($Max) < $Max ) {
15436:         $Max++;
15437:         $Max = int($Max);
15438:     }
15439:     $Title  = '' if (! defined($Title));
15440:     $xlabel = '' if (! defined($xlabel));
15441:     $ylabel = '' if (! defined($ylabel));
15442:     $ValuesHash{$id.'.title'}    = &escape($Title);
15443:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
15444:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
15445:     $ValuesHash{$id.'.y_max_value'} = $Max;
15446:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
15447:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
15448:     $ValuesHash{$id.'.PlotType'} = 'bar';
15449:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15450:     $ValuesHash{$id.'.height'}   = $height;
15451:     $ValuesHash{$id.'.width'}    = $width;
15452:     $ValuesHash{$id.'.xskip'}    = $xskip;
15453:     $ValuesHash{$id.'.bar_width'} = $bar_width;
15454:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
15455:     #
15456:     # Deal with other parameters
15457:     while (my ($key,$value) = each(%$extra_settings)) {
15458:         $ValuesHash{$id.'.'.$key} = $value;
15459:     }
15460:     #
15461:     &Apache::lonnet::appenv(\%ValuesHash);
15462:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15463: }
15464: 
15465: ############################################################
15466: ############################################################
15467: 
15468: =pod
15469: 
15470: =item * &DrawXYGraph()
15471: 
15472: Facilitates the plotting of data in an XY graph.
15473: Puts plot definition data into the users environment in order for 
15474: graph.png to plot it.  Returns an <img> tag for the plot.
15475: 
15476: Inputs:
15477: 
15478: =over 4
15479: 
15480: =item $Title: string, the title of the plot
15481: 
15482: =item $xlabel: string, text describing the X-axis of the plot
15483: 
15484: =item $ylabel: string, text describing the Y-axis of the plot
15485: 
15486: =item $Max: scalar, the maximum Y value to use in the plot
15487: If $Max is < any data point, the graph will not be rendered.
15488: 
15489: =item $colors: Array ref containing the hex color codes for the data to be 
15490: plotted in.  If undefined, default values will be used.
15491: 
15492: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15493: 
15494: =item $Ydata: Array ref containing Array refs.  
15495: Each of the contained arrays will be plotted as a separate curve.
15496: 
15497: =item %Values: hash indicating or overriding any default values which are 
15498: passed to graph.png.  
15499: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15500: 
15501: =back
15502: 
15503: Returns:
15504: 
15505: An <img> tag which references graph.png and the appropriate identifying
15506: information for the plot.
15507: 
15508: =cut
15509: 
15510: ############################################################
15511: ############################################################
15512: sub DrawXYGraph {
15513:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15514:     #
15515:     # Create the identifier for the graph
15516:     my $identifier = &get_cgi_id();
15517:     my $id = 'cgi.'.$identifier;
15518:     #
15519:     $Title  = '' if (! defined($Title));
15520:     $xlabel = '' if (! defined($xlabel));
15521:     $ylabel = '' if (! defined($ylabel));
15522:     my %ValuesHash = 
15523:         (
15524:          $id.'.title'  => &escape($Title),
15525:          $id.'.xlabel' => &escape($xlabel),
15526:          $id.'.ylabel' => &escape($ylabel),
15527:          $id.'.y_max_value'=> $Max,
15528:          $id.'.labels'     => join(',',@$Xlabels),
15529:          $id.'.PlotType'   => 'XY',
15530:          );
15531:     #
15532:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15533:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15534:     }
15535:     #
15536:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15537:         return '';
15538:     }
15539:     my $NumSets=1;
15540:     foreach my $array (@{$Ydata}){
15541:         next if (! ref($array));
15542:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15543:     }
15544:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15545:     #
15546:     # Deal with other parameters
15547:     while (my ($key,$value) = each(%Values)) {
15548:         $ValuesHash{$id.'.'.$key} = $value;
15549:     }
15550:     #
15551:     &Apache::lonnet::appenv(\%ValuesHash);
15552:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15553: }
15554: 
15555: ############################################################
15556: ############################################################
15557: 
15558: =pod
15559: 
15560: =item * &DrawXYYGraph()
15561: 
15562: Facilitates the plotting of data in an XY graph with two Y axes.
15563: Puts plot definition data into the users environment in order for 
15564: graph.png to plot it.  Returns an <img> tag for the plot.
15565: 
15566: Inputs:
15567: 
15568: =over 4
15569: 
15570: =item $Title: string, the title of the plot
15571: 
15572: =item $xlabel: string, text describing the X-axis of the plot
15573: 
15574: =item $ylabel: string, text describing the Y-axis of the plot
15575: 
15576: =item $colors: Array ref containing the hex color codes for the data to be 
15577: plotted in.  If undefined, default values will be used.
15578: 
15579: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15580: 
15581: =item $Ydata1: The first data set
15582: 
15583: =item $Min1: The minimum value of the left Y-axis
15584: 
15585: =item $Max1: The maximum value of the left Y-axis
15586: 
15587: =item $Ydata2: The second data set
15588: 
15589: =item $Min2: The minimum value of the right Y-axis
15590: 
15591: =item $Max2: The maximum value of the left Y-axis
15592: 
15593: =item %Values: hash indicating or overriding any default values which are 
15594: passed to graph.png.  
15595: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15596: 
15597: =back
15598: 
15599: Returns:
15600: 
15601: An <img> tag which references graph.png and the appropriate identifying
15602: information for the plot.
15603: 
15604: =cut
15605: 
15606: ############################################################
15607: ############################################################
15608: sub DrawXYYGraph {
15609:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15610:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
15611:     #
15612:     # Create the identifier for the graph
15613:     my $identifier = &get_cgi_id();
15614:     my $id = 'cgi.'.$identifier;
15615:     #
15616:     $Title  = '' if (! defined($Title));
15617:     $xlabel = '' if (! defined($xlabel));
15618:     $ylabel = '' if (! defined($ylabel));
15619:     my %ValuesHash = 
15620:         (
15621:          $id.'.title'  => &escape($Title),
15622:          $id.'.xlabel' => &escape($xlabel),
15623:          $id.'.ylabel' => &escape($ylabel),
15624:          $id.'.labels' => join(',',@$Xlabels),
15625:          $id.'.PlotType' => 'XY',
15626:          $id.'.NumSets' => 2,
15627:          $id.'.two_axes' => 1,
15628:          $id.'.y1_max_value' => $Max1,
15629:          $id.'.y1_min_value' => $Min1,
15630:          $id.'.y2_max_value' => $Max2,
15631:          $id.'.y2_min_value' => $Min2,
15632:          );
15633:     #
15634:     if (defined($colors) && ref($colors) eq 'ARRAY') {
15635:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
15636:     }
15637:     #
15638:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15639:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15640:         return '';
15641:     }
15642:     my $NumSets=1;
15643:     foreach my $array ($Ydata1,$Ydata2){
15644:         next if (! ref($array));
15645:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15646:     }
15647:     #
15648:     # Deal with other parameters
15649:     while (my ($key,$value) = each(%Values)) {
15650:         $ValuesHash{$id.'.'.$key} = $value;
15651:     }
15652:     #
15653:     &Apache::lonnet::appenv(\%ValuesHash);
15654:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15655: }
15656: 
15657: ############################################################
15658: ############################################################
15659: 
15660: =pod
15661: 
15662: =back 
15663: 
15664: =head1 Statistics helper routines?  
15665: 
15666: Bad place for them but what the hell.
15667: 
15668: =over 4
15669: 
15670: =item * &chartlink()
15671: 
15672: Returns a link to the chart for a specific student.  
15673: 
15674: Inputs:
15675: 
15676: =over 4
15677: 
15678: =item $linktext: The text of the link
15679: 
15680: =item $sname: The students username
15681: 
15682: =item $sdomain: The students domain
15683: 
15684: =back
15685: 
15686: =back
15687: 
15688: =cut
15689: 
15690: ############################################################
15691: ############################################################
15692: sub chartlink {
15693:     my ($linktext, $sname, $sdomain) = @_;
15694:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15695:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
15696:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
15697:        '">'.$linktext.'</a>';
15698: }
15699: 
15700: #######################################################
15701: #######################################################
15702: 
15703: =pod
15704: 
15705: =head1 Course Environment Routines
15706: 
15707: =over 4
15708: 
15709: =item * &restore_course_settings()
15710: 
15711: =item * &store_course_settings()
15712: 
15713: Restores/Store indicated form parameters from the course environment.
15714: Will not overwrite existing values of the form parameters.
15715: 
15716: Inputs: 
15717: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15718: 
15719: a hash ref describing the data to be stored.  For example:
15720:    
15721: %Save_Parameters = ('Status' => 'scalar',
15722:     'chartoutputmode' => 'scalar',
15723:     'chartoutputdata' => 'scalar',
15724:     'Section' => 'array',
15725:     'Group' => 'array',
15726:     'StudentData' => 'array',
15727:     'Maps' => 'array');
15728: 
15729: Returns: both routines return nothing
15730: 
15731: =back
15732: 
15733: =cut
15734: 
15735: #######################################################
15736: #######################################################
15737: sub store_course_settings {
15738:     return &store_settings($env{'request.course.id'},@_);
15739: }
15740: 
15741: sub store_settings {
15742:     # save to the environment
15743:     # appenv the same items, just to be safe
15744:     my $udom  = $env{'user.domain'};
15745:     my $uname = $env{'user.name'};
15746:     my ($context,$prefix,$Settings) = @_;
15747:     my %SaveHash;
15748:     my %AppHash;
15749:     while (my ($setting,$type) = each(%$Settings)) {
15750:         my $basename = join('.','internal',$context,$prefix,$setting);
15751:         my $envname = 'environment.'.$basename;
15752:         if (exists($env{'form.'.$setting})) {
15753:             # Save this value away
15754:             if ($type eq 'scalar' &&
15755:                 (! exists($env{$envname}) || 
15756:                  $env{$envname} ne $env{'form.'.$setting})) {
15757:                 $SaveHash{$basename} = $env{'form.'.$setting};
15758:                 $AppHash{$envname}   = $env{'form.'.$setting};
15759:             } elsif ($type eq 'array') {
15760:                 my $stored_form;
15761:                 if (ref($env{'form.'.$setting})) {
15762:                     $stored_form = join(',',
15763:                                         map {
15764:                                             &escape($_);
15765:                                         } sort(@{$env{'form.'.$setting}}));
15766:                 } else {
15767:                     $stored_form = 
15768:                         &escape($env{'form.'.$setting});
15769:                 }
15770:                 # Determine if the array contents are the same.
15771:                 if ($stored_form ne $env{$envname}) {
15772:                     $SaveHash{$basename} = $stored_form;
15773:                     $AppHash{$envname}   = $stored_form;
15774:                 }
15775:             }
15776:         }
15777:     }
15778:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15779:                                           $udom,$uname);
15780:     if ($put_result !~ /^(ok|delayed)/) {
15781:         &Apache::lonnet::logthis('unable to save form parameters, '.
15782:                                  'got error:'.$put_result);
15783:     }
15784:     # Make sure these settings stick around in this session, too
15785:     &Apache::lonnet::appenv(\%AppHash);
15786:     return;
15787: }
15788: 
15789: sub restore_course_settings {
15790:     return &restore_settings($env{'request.course.id'},@_);
15791: }
15792: 
15793: sub restore_settings {
15794:     my ($context,$prefix,$Settings) = @_;
15795:     while (my ($setting,$type) = each(%$Settings)) {
15796:         next if (exists($env{'form.'.$setting}));
15797:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
15798:             '.'.$setting;
15799:         if (exists($env{$envname})) {
15800:             if ($type eq 'scalar') {
15801:                 $env{'form.'.$setting} = $env{$envname};
15802:             } elsif ($type eq 'array') {
15803:                 $env{'form.'.$setting} = [ 
15804:                                            map { 
15805:                                                &unescape($_); 
15806:                                            } split(',',$env{$envname})
15807:                                            ];
15808:             }
15809:         }
15810:     }
15811: }
15812: 
15813: #######################################################
15814: #######################################################
15815: 
15816: =pod
15817: 
15818: =head1 Domain E-mail Routines  
15819: 
15820: =over 4
15821: 
15822: =item * &build_recipient_list()
15823: 
15824: Build recipient lists for following types of e-mail:
15825: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15826: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15827: module change checking, student/employee ID conflict checks, as
15828: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15829: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15830: 
15831: Inputs:
15832: defmail (scalar - email address of default recipient), 
15833: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15834: requestsmail, updatesmail, or idconflictsmail).
15835: 
15836: defdom (domain for which to retrieve configuration settings),
15837: 
15838: origmail (scalar - email address of recipient from loncapa.conf, 
15839: i.e., predates configuration by DC via domainprefs.pm
15840: 
15841: $requname username of requester (if mailing type is helpdeskmail)
15842: 
15843: $requdom domain of requester (if mailing type is helpdeskmail)
15844: 
15845: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15846: 
15847: 
15848: Returns: comma separated list of addresses to which to send e-mail.
15849: 
15850: =back
15851: 
15852: =cut
15853: 
15854: ############################################################
15855: ############################################################
15856: sub build_recipient_list {
15857:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15858:     my @recipients;
15859:     my ($otheremails,$lastresort,$allbcc,$addtext);
15860:     my %domconfig =
15861:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15862:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15863:         if (exists($domconfig{'contacts'}{$mailing})) {
15864:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15865:                 my @contacts = ('adminemail','supportemail');
15866:                 foreach my $item (@contacts) {
15867:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15868:                         my $addr = $domconfig{'contacts'}{$item}; 
15869:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15870:                             push(@recipients,$addr);
15871:                         }
15872:                     }
15873:                 }
15874:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15875:                 if ($mailing eq 'helpdeskmail') {
15876:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15877:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15878:                         my @ok_bccs;
15879:                         foreach my $bcc (@bccs) {
15880:                             $bcc =~ s/^\s+//g;
15881:                             $bcc =~ s/\s+$//g;
15882:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15883:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15884:                                     push(@ok_bccs,$bcc);
15885:                                 }
15886:                             }
15887:                         }
15888:                         if (@ok_bccs > 0) {
15889:                             $allbcc = join(', ',@ok_bccs);
15890:                         }
15891:                     }
15892:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15893:                 }
15894:             }
15895:         } elsif ($origmail ne '') {
15896:             $lastresort = $origmail;
15897:         }
15898:         if ($mailing eq 'helpdeskmail') {
15899:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15900:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15901:                 my ($inststatus,$inststatus_checked);
15902:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15903:                     ($env{'user.domain'} ne 'public')) {
15904:                     $inststatus_checked = 1;
15905:                     $inststatus = $env{'environment.inststatus'};
15906:                 }
15907:                 unless ($inststatus_checked) {
15908:                     if (($requname ne '') && ($requdom ne '')) {
15909:                         if (($requname =~ /^$match_username$/) &&
15910:                             ($requdom =~ /^$match_domain$/) &&
15911:                             (&Apache::lonnet::domain($requdom))) {
15912:                             my $requhome = &Apache::lonnet::homeserver($requname,
15913:                                                                       $requdom);
15914:                             unless ($requhome eq 'no_host') {
15915:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15916:                                 $inststatus = $userenv{'inststatus'};
15917:                                 $inststatus_checked = 1;
15918:                             }
15919:                         }
15920:                     }
15921:                 }
15922:                 unless ($inststatus_checked) {
15923:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15924:                         my %srch = (srchby     => 'email',
15925:                                     srchdomain => $defdom,
15926:                                     srchterm   => $reqemail,
15927:                                     srchtype   => 'exact');
15928:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15929:                         foreach my $uname (keys(%srch_results)) {
15930:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15931:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15932:                                 $inststatus_checked = 1;
15933:                                 last;
15934:                             }
15935:                         }
15936:                         unless ($inststatus_checked) {
15937:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15938:                             if ($dirsrchres eq 'ok') {
15939:                                 foreach my $uname (keys(%srch_results)) {
15940:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15941:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15942:                                         $inststatus_checked = 1;
15943:                                         last;
15944:                                     }
15945:                                 }
15946:                             }
15947:                         }
15948:                     }
15949:                 }
15950:                 if ($inststatus ne '') {
15951:                     foreach my $status (split(/\:/,$inststatus)) {
15952:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15953:                             my @contacts = ('adminemail','supportemail');
15954:                             foreach my $item (@contacts) {
15955:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15956:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15957:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15958:                                         push(@recipients,$addr);
15959:                                     }
15960:                                 }
15961:                             }
15962:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15963:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15964:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15965:                                 my @ok_bccs;
15966:                                 foreach my $bcc (@bccs) {
15967:                                     $bcc =~ s/^\s+//g;
15968:                                     $bcc =~ s/\s+$//g;
15969:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15970:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15971:                                             push(@ok_bccs,$bcc);
15972:                                         }
15973:                                     }
15974:                                 }
15975:                                 if (@ok_bccs > 0) {
15976:                                     $allbcc = join(', ',@ok_bccs);
15977:                                 }
15978:                             }
15979:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15980:                             last;
15981:                         }
15982:                     }
15983:                 }
15984:             }
15985:         }
15986:     } elsif ($origmail ne '') {
15987:         $lastresort = $origmail;
15988:     }
15989:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15990:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15991:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15992:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15993:             my %what = (
15994:                           perlvar => 1,
15995:                        );
15996:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15997:             if ($primary) {
15998:                 my $gotaddr;
15999:                 my ($result,$returnhash) =
16000:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
16001:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
16002:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
16003:                         $lastresort = $returnhash->{'lonSupportEMail'};
16004:                         $gotaddr = 1;
16005:                     }
16006:                 }
16007:                 unless ($gotaddr) {
16008:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
16009:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
16010:                     unless ($uintdom eq $intdom) {
16011:                         my %domconfig =
16012:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16013:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
16014:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16015:                                 my @contacts = ('adminemail','supportemail');
16016:                                 foreach my $item (@contacts) {
16017:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16018:                                         my $addr = $domconfig{'contacts'}{$item};
16019:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
16020:                                             push(@recipients,$addr);
16021:                                         }
16022:                                     }
16023:                                 }
16024:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16025:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16026:                                 }
16027:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16028:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16029:                                     my @ok_bccs;
16030:                                     foreach my $bcc (@bccs) {
16031:                                         $bcc =~ s/^\s+//g;
16032:                                         $bcc =~ s/\s+$//g;
16033:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16034:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16035:                                                 push(@ok_bccs,$bcc);
16036:                                             }
16037:                                         }
16038:                                     }
16039:                                     if (@ok_bccs > 0) {
16040:                                         $allbcc = join(', ',@ok_bccs);
16041:                                     }
16042:                                 }
16043:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16044:                             }
16045:                         }
16046:                     }
16047:                 }
16048:             }
16049:         }
16050:     }
16051:     if (defined($defmail)) {
16052:         if ($defmail ne '') {
16053:             push(@recipients,$defmail);
16054:         }
16055:     }
16056:     if ($otheremails) {
16057:         my @others;
16058:         if ($otheremails =~ /,/) {
16059:             @others = split(/,/,$otheremails);
16060:         } else {
16061:             push(@others,$otheremails);
16062:         }
16063:         foreach my $addr (@others) {
16064:             if (!grep(/^\Q$addr\E$/,@recipients)) {
16065:                 push(@recipients,$addr);
16066:             }
16067:         }
16068:     }
16069:     if ($mailing eq 'helpdeskmail') {
16070:         if ((!@recipients) && ($lastresort ne '')) {
16071:             push(@recipients,$lastresort);
16072:         }
16073:     } elsif ($lastresort ne '') {
16074:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16075:             push(@recipients,$lastresort);
16076:         }
16077:     }
16078:     my $recipientlist = join(',',@recipients);
16079:     if (wantarray) {
16080:         return ($recipientlist,$allbcc,$addtext);
16081:     } else {
16082:         return $recipientlist;
16083:     }
16084: }
16085: 
16086: ############################################################
16087: ############################################################
16088: 
16089: =pod
16090: 
16091: =over 4
16092: 
16093: =item * &mime_email()
16094: 
16095: Sends an email with a possible attachment
16096: 
16097: Inputs:
16098: 
16099: =over 4
16100: 
16101: from -              Sender's email address
16102: 
16103: replyto -           Reply-To email address
16104: 
16105: to -                Email address of recipient
16106: 
16107: subject -           Subject of email
16108: 
16109: body -              Body of email
16110: 
16111: cc_string -         Carbon copy email address
16112: 
16113: bcc -               Blind carbon copy email address
16114: 
16115: attachment_path -   Path of file to be attached
16116: 
16117: file_name -         Name of file to be attached
16118: 
16119: attachment_text -   The body of an attachment of type "TEXT"
16120: 
16121: =back
16122: 
16123: =back
16124: 
16125: =cut
16126: 
16127: ############################################################
16128: ############################################################
16129: 
16130: sub mime_email {
16131:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
16132:         $file_name,$attachment_text) = @_;
16133:  
16134:     my $msg = MIME::Lite->new(
16135:              From    => $from,
16136:              To      => $to,
16137:              Subject => $subject,
16138:              Type    =>'TEXT',
16139:              Data    => $body,
16140:              );
16141:     if ($replyto ne '') {
16142:         $msg->add("Reply-To" => $replyto);
16143:     }
16144:     if ($cc_string ne '') {
16145:         $msg->add("Cc" => $cc_string);
16146:     }
16147:     if ($bcc ne '') {
16148:         $msg->add("Bcc" => $bcc);
16149:     }
16150:     $msg->attr("content-type"         => "text/plain");
16151:     $msg->attr("content-type.charset" => "UTF-8");
16152:     # Attach file if given
16153:     if ($attachment_path) {
16154:         unless ($file_name) {
16155:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16156:         }
16157:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16158:         $msg->attach(Type     => $type,
16159:                      Path     => $attachment_path,
16160:                      Filename => $file_name
16161:                      );
16162:     # Otherwise attach text if given
16163:     } elsif ($attachment_text) {
16164:         $msg->attach(Type => 'TEXT',
16165:                      Data => $attachment_text);
16166:     }
16167:     # Send it
16168:     $msg->send('sendmail');
16169: }
16170: 
16171: ############################################################
16172: ############################################################
16173: 
16174: =pod
16175: 
16176: =head1 Course Catalog Routines
16177: 
16178: =over 4
16179: 
16180: =item * &gather_categories()
16181: 
16182: Converts category definitions - keys of categories hash stored in  
16183: coursecategories in configuration.db on the primary library server in a 
16184: domain - to an array.  Also generates javascript and idx hash used to 
16185: generate Domain Coordinator interface for editing Course Categories.
16186: 
16187: Inputs:
16188: 
16189: categories (reference to hash of category definitions).
16190: 
16191: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16192:       categories and subcategories).
16193: 
16194: idx (reference to hash of counters used in Domain Coordinator interface for 
16195:       editing Course Categories).
16196: 
16197: jsarray (reference to array of categories used to create Javascript arrays for
16198:          Domain Coordinator interface for editing Course Categories).
16199: 
16200: Returns: nothing
16201: 
16202: Side effects: populates cats, idx and jsarray. 
16203: 
16204: =cut
16205: 
16206: sub gather_categories {
16207:     my ($categories,$cats,$idx,$jsarray) = @_;
16208:     my %counters;
16209:     my $num = 0;
16210:     foreach my $item (keys(%{$categories})) {
16211:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16212:         if ($container eq '' && $depth == 0) {
16213:             $cats->[$depth][$categories->{$item}] = $cat;
16214:         } else {
16215:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16216:         }
16217:         my ($escitem,$tail) = split(/:/,$item,2);
16218:         if ($counters{$tail} eq '') {
16219:             $counters{$tail} = $num;
16220:             $num ++;
16221:         }
16222:         if (ref($idx) eq 'HASH') {
16223:             $idx->{$item} = $counters{$tail};
16224:         }
16225:         if (ref($jsarray) eq 'ARRAY') {
16226:             push(@{$jsarray->[$counters{$tail}]},$item);
16227:         }
16228:     }
16229:     return;
16230: }
16231: 
16232: =pod
16233: 
16234: =item * &extract_categories()
16235: 
16236: Used to generate breadcrumb trails for course categories.
16237: 
16238: Inputs:
16239: 
16240: categories (reference to hash of category definitions).
16241: 
16242: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16243:       categories and subcategories).
16244: 
16245: trails (reference to array of breacrumb trails for each category).
16246: 
16247: allitems (reference to hash - key is category key 
16248:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16249: 
16250: idx (reference to hash of counters used in Domain Coordinator interface for
16251:       editing Course Categories).
16252: 
16253: jsarray (reference to array of categories used to create Javascript arrays for
16254:          Domain Coordinator interface for editing Course Categories).
16255: 
16256: subcats (reference to hash of arrays containing all subcategories within each 
16257:          category, -recursive)
16258: 
16259: maxd (reference to hash used to hold max depth for all top-level categories).
16260: 
16261: Returns: nothing
16262: 
16263: Side effects: populates trails and allitems hash references.
16264: 
16265: =cut
16266: 
16267: sub extract_categories {
16268:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16269:     if (ref($categories) eq 'HASH') {
16270:         &gather_categories($categories,$cats,$idx,$jsarray);
16271:         if (ref($cats->[0]) eq 'ARRAY') {
16272:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
16273:                 my $name = $cats->[0][$i];
16274:                 my $item = &escape($name).'::0';
16275:                 my $trailstr;
16276:                 if ($name eq 'instcode') {
16277:                     $trailstr = &mt('Official courses (with institutional codes)');
16278:                 } elsif ($name eq 'communities') {
16279:                     $trailstr = &mt('Communities');
16280:                 } elsif ($name eq 'placement') {
16281:                     $trailstr = &mt('Placement Tests');
16282:                 } else {
16283:                     $trailstr = $name;
16284:                 }
16285:                 if ($allitems->{$item} eq '') {
16286:                     push(@{$trails},$trailstr);
16287:                     $allitems->{$item} = scalar(@{$trails})-1;
16288:                 }
16289:                 my @parents = ($name);
16290:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
16291:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16292:                         my $category = $cats->[1]{$name}[$j];
16293:                         if (ref($subcats) eq 'HASH') {
16294:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16295:                         }
16296:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16297:                     }
16298:                 } else {
16299:                     if (ref($subcats) eq 'HASH') {
16300:                         $subcats->{$item} = [];
16301:                     }
16302:                     if (ref($maxd) eq 'HASH') {
16303:                         $maxd->{$name} = 1;
16304:                     }
16305:                 }
16306:             }
16307:         }
16308:     }
16309:     return;
16310: }
16311: 
16312: =pod
16313: 
16314: =item * &recurse_categories()
16315: 
16316: Recursively used to generate breadcrumb trails for course categories.
16317: 
16318: Inputs:
16319: 
16320: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16321:       categories and subcategories).
16322: 
16323: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16324: 
16325: category (current course category, for which breadcrumb trail is being generated).
16326: 
16327: trails (reference to array of breadcrumb trails for each category).
16328: 
16329: allitems (reference to hash - key is category key
16330:          (format: escaped(name):escaped(parent category):depth in hierarchy).
16331: 
16332: parents (array containing containers directories for current category, 
16333:          back to top level). 
16334: 
16335: Returns: nothing
16336: 
16337: Side effects: populates trails and allitems hash references
16338: 
16339: =cut
16340: 
16341: sub recurse_categories {
16342:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16343:     my $shallower = $depth - 1;
16344:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16345:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16346:             my $name = $cats->[$depth]{$category}[$k];
16347:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16348:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
16349:             if ($allitems->{$item} eq '') {
16350:                 push(@{$trails},$trailstr);
16351:                 $allitems->{$item} = scalar(@{$trails})-1;
16352:             }
16353:             my $deeper = $depth+1;
16354:             push(@{$parents},$category);
16355:             if (ref($subcats) eq 'HASH') {
16356:                 my $subcat = &escape($name).':'.$category.':'.$depth;
16357:                 for (my $j=@{$parents}; $j>=0; $j--) {
16358:                     my $higher;
16359:                     if ($j > 0) {
16360:                         $higher = &escape($parents->[$j]).':'.
16361:                                   &escape($parents->[$j-1]).':'.$j;
16362:                     } else {
16363:                         $higher = &escape($parents->[$j]).'::'.$j;
16364:                     }
16365:                     push(@{$subcats->{$higher}},$subcat);
16366:                 }
16367:             }
16368:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16369:                                 $subcats,$maxd);
16370:             pop(@{$parents});
16371:         }
16372:     } else {
16373:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16374:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
16375:         if ($allitems->{$item} eq '') {
16376:             push(@{$trails},$trailstr);
16377:             $allitems->{$item} = scalar(@{$trails})-1;
16378:         }
16379:         if (ref($maxd) eq 'HASH') {
16380:             if ($depth > $maxd->{$parents->[0]}) {
16381:                 $maxd->{$parents->[0]} = $depth;
16382:             }
16383:         }
16384:     }
16385:     return;
16386: }
16387: 
16388: =pod
16389: 
16390: =item * &assign_categories_table()
16391: 
16392: Create a datatable for display of hierarchical categories in a domain,
16393: with checkboxes to allow a course to be categorized. 
16394: 
16395: Inputs:
16396: 
16397: cathash - reference to hash of categories defined for the domain (from
16398:           configuration.db)
16399: 
16400: currcat - scalar with an & separated list of categories assigned to a course. 
16401: 
16402: type    - scalar contains course type (Course or Community).
16403: 
16404: disabled - scalar (optional) contains disabled="disabled" if input elements are
16405:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16406: 
16407: Returns: $output (markup to be displayed) 
16408: 
16409: =cut
16410: 
16411: sub assign_categories_table {
16412:     my ($cathash,$currcat,$type,$disabled) = @_;
16413:     my $output;
16414:     if (ref($cathash) eq 'HASH') {
16415:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16416:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16417:         $maxdepth = scalar(@cats);
16418:         if (@cats > 0) {
16419:             my $itemcount = 0;
16420:             if (ref($cats[0]) eq 'ARRAY') {
16421:                 my @currcategories;
16422:                 if ($currcat ne '') {
16423:                     @currcategories = split('&',$currcat);
16424:                 }
16425:                 my $table;
16426:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
16427:                     my $parent = $cats[0][$i];
16428:                     next if ($parent eq 'instcode');
16429:                     if ($type eq 'Community') {
16430:                         next unless ($parent eq 'communities');
16431:                     } elsif ($type eq 'Placement') {
16432:                         next unless ($parent eq 'placement');
16433:                     } else {
16434:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
16435:                     }
16436:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16437:                     my $item = &escape($parent).'::0';
16438:                     my $checked = '';
16439:                     if (@currcategories > 0) {
16440:                         if (grep(/^\Q$item\E$/,@currcategories)) {
16441:                             $checked = ' checked="checked"';
16442:                         }
16443:                     }
16444:                     my $parent_title = $parent;
16445:                     if ($parent eq 'communities') {
16446:                         $parent_title = &mt('Communities');
16447:                     } elsif ($parent eq 'placement') {
16448:                         $parent_title = &mt('Placement Tests');
16449:                     }
16450:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16451:                               '<input type="checkbox" name="usecategory" value="'.
16452:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16453:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16454:                     my $depth = 1;
16455:                     push(@path,$parent);
16456:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16457:                     pop(@path);
16458:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16459:                     $itemcount ++;
16460:                 }
16461:                 if ($itemcount) {
16462:                     $output = &Apache::loncommon::start_data_table().
16463:                               $table.
16464:                               &Apache::loncommon::end_data_table();
16465:                 }
16466:             }
16467:         }
16468:     }
16469:     return $output;
16470: }
16471: 
16472: =pod
16473: 
16474: =item * &assign_category_rows()
16475: 
16476: Create a datatable row for display of nested categories in a domain,
16477: with checkboxes to allow a course to be categorized,called recursively.
16478: 
16479: Inputs:
16480: 
16481: itemcount - track row number for alternating colors
16482: 
16483: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16484:       categories and subcategories.
16485: 
16486: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16487: 
16488: parent - parent of current category item
16489: 
16490: path - Array containing all categories back up through the hierarchy from the
16491:        current category to the top level.
16492: 
16493: currcategories - reference to array of current categories assigned to the course
16494: 
16495: disabled - scalar (optional) contains disabled="disabled" if input elements are
16496:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
16497: 
16498: Returns: $output (markup to be displayed).
16499: 
16500: =cut
16501: 
16502: sub assign_category_rows {
16503:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16504:     my ($text,$name,$item,$chgstr);
16505:     if (ref($cats) eq 'ARRAY') {
16506:         my $maxdepth = scalar(@{$cats});
16507:         if (ref($cats->[$depth]) eq 'HASH') {
16508:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16509:                 my $numchildren = @{$cats->[$depth]{$parent}};
16510:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16511:                 $text .= '<td><table class="LC_data_table">';
16512:                 for (my $j=0; $j<$numchildren; $j++) {
16513:                     $name = $cats->[$depth]{$parent}[$j];
16514:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
16515:                     my $deeper = $depth+1;
16516:                     my $checked = '';
16517:                     if (ref($currcategories) eq 'ARRAY') {
16518:                         if (@{$currcategories} > 0) {
16519:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
16520:                                 $checked = ' checked="checked"';
16521:                             }
16522:                         }
16523:                     }
16524:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
16525:                              '<input type="checkbox" name="usecategory" value="'.
16526:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16527:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
16528:                              '</td><td>';
16529:                     if (ref($path) eq 'ARRAY') {
16530:                         push(@{$path},$name);
16531:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16532:                         pop(@{$path});
16533:                     }
16534:                     $text .= '</td></tr>';
16535:                 }
16536:                 $text .= '</table></td>';
16537:             }
16538:         }
16539:     }
16540:     return $text;
16541: }
16542: 
16543: =pod
16544: 
16545: =back
16546: 
16547: =cut
16548: 
16549: ############################################################
16550: ############################################################
16551: 
16552: 
16553: sub commit_customrole {
16554:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16555:     my $result = &Apache::lonnet::assigncustomrole(
16556:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16557:                      $context,$othdomby,$requester);
16558:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16559:                          ($start?', '.&mt('starting').' '.localtime($start):'').
16560:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16561:     if (wantarray) {
16562:         return ($output,$result);
16563:     } else {
16564:         return $output;
16565:     }
16566: }
16567: 
16568: sub commit_standardrole {
16569:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16570:         $othdomby,$requester) = @_;
16571:     my ($output,$logmsg,$linefeed,$result);
16572:     if ($context eq 'auto') {
16573:         $linefeed = "\n";
16574:     } else {
16575:         $linefeed = "<br />\n";
16576:     }  
16577:     if ($three eq 'st') {
16578:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16579:                                       $one,$two,$sec,$context,$credits,$othdomby,
16580:                                       $requester);
16581:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
16582:             ($result eq 'unknown_course') || ($result eq 'refused')) {
16583:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
16584:         } else {
16585:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16586:                ($start?', '.&mt('starting').' '.localtime($start):'').
16587:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16588:             if ($context eq 'auto') {
16589:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16590:             } else {
16591:                $output .= '<b>'.$result.'</b>'.$linefeed.
16592:                &mt('Add to classlist').': <b>ok</b>';
16593:             }
16594:             $output .= $linefeed;
16595:         }
16596:     } else {
16597:         $output = &mt('Assigning').' '.$three.' in '.$url.
16598:                ($start?', '.&mt('starting').' '.localtime($start):'').
16599:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16600:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16601:                                               '','',$context,$othdomby,$requester);
16602:         if ($context eq 'auto') {
16603:             $output .= $result.$linefeed;
16604:         } else {
16605:             $output .= '<b>'.$result.'</b>'.$linefeed;
16606:         }
16607:     }
16608:     if (wantarray) {
16609:         return ($output,$result);
16610:     } else {
16611:         return $output;
16612:     }
16613: }
16614: 
16615: sub commit_studentrole {
16616:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16617:         $credits,$othdomby,$requester) = @_;
16618:     my ($result,$linefeed,$oldsecurl,$newsecurl);
16619:     if ($context eq 'auto') {
16620:         $linefeed = "\n";
16621:     } else {
16622:         $linefeed = '<br />'."\n";
16623:     }
16624:     if (defined($one) && defined($two)) {
16625:         my $cid=$one.'_'.$two;
16626:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16627:         my $secchange = 0;
16628:         my $expire_role_result;
16629:         my $modify_section_result;
16630:         if ($oldsec ne '-1') { 
16631:             if ($oldsec ne $sec) {
16632:                 $secchange = 1;
16633:                 my $now = time;
16634:                 my $uurl='/'.$cid;
16635:                 $uurl=~s/\_/\//g;
16636:                 if ($oldsec) {
16637:                     $uurl.='/'.$oldsec;
16638:                 }
16639:                 $oldsecurl = $uurl;
16640:                 $expire_role_result = 
16641:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16642:                                                 '','','',$context,$othdomby,$requester);
16643:                 if ($env{'request.course.sec'} ne '') {
16644:                     if ($expire_role_result eq 'refused') {
16645:                         my @roles = ('st');
16646:                         my @statuses = ('previous');
16647:                         my @roledoms = ($one);
16648:                         my $withsec = 1;
16649:                         my %roleshash = 
16650:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16651:                                               \@statuses,\@roles,\@roledoms,$withsec);
16652:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16653:                             my ($oldstart,$oldend) = 
16654:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16655:                             if ($oldend > 0 && $oldend <= $now) {
16656:                                 $expire_role_result = 'ok';
16657:                             }
16658:                         }
16659:                     }
16660:                 }
16661:                 $result = $expire_role_result;
16662:             }
16663:         }
16664:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16665:             $modify_section_result = 
16666:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16667:                                                            undef,undef,undef,$sec,
16668:                                                            $end,$start,'','',$cid,
16669:                                                            '',$context,$credits,'',
16670:                                                            $othdomby,$requester);
16671:             if ($modify_section_result =~ /^ok/) {
16672:                 if ($secchange == 1) {
16673:                     if ($sec eq '') {
16674:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16675:                     } else {
16676:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16677:                     }
16678:                 } elsif ($oldsec eq '-1') {
16679:                     if ($sec eq '') {
16680:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16681:                     } else {
16682:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16683:                     }
16684:                 } else {
16685:                     if ($sec eq '') {
16686:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16687:                     } else {
16688:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16689:                     }
16690:                 }
16691:             } else {
16692:                 if ($secchange) { 
16693:                     $$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;
16694:                 } else {
16695:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16696:                 }
16697:             }
16698:             $result = $modify_section_result;
16699:         } elsif ($secchange == 1) {
16700:             if ($oldsec eq '') {
16701:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16702:             } else {
16703:                 $$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;
16704:             }
16705:             if ($expire_role_result eq 'refused') {
16706:                 my $newsecurl = '/'.$cid;
16707:                 $newsecurl =~ s/\_/\//g;
16708:                 if ($sec ne '') {
16709:                     $newsecurl.='/'.$sec;
16710:                 }
16711:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16712:                     if ($sec eq '') {
16713:                         $$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;
16714:                     } else {
16715:                         $$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;
16716:                     }
16717:                 }
16718:             }
16719:         }
16720:     } else {
16721:         $$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;
16722:         $result = "error: incomplete course id\n";
16723:     }
16724:     return $result;
16725: }
16726: 
16727: sub show_role_extent {
16728:     my ($scope,$context,$role) = @_;
16729:     $scope =~ s{^/}{};
16730:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16731:     push(@courseroles,'co');
16732:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16733:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16734:         $scope =~ s{/}{_};
16735:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16736:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16737:         my ($audom,$auname) = split(/\//,$scope);
16738:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16739:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
16740:     } else {
16741:         $scope =~ s{/$}{};
16742:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16743:                    &Apache::lonnet::domain($scope,'description').'</span>');
16744:     }
16745: }
16746: 
16747: ############################################################
16748: ############################################################
16749: 
16750: sub check_clone {
16751:     my ($args,$linefeed) = @_;
16752:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16753:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16754:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16755:     my $clonetitle;
16756:     my @clonemsg;
16757:     my $can_clone = 0;
16758:     my $lctype = lc($args->{'crstype'});
16759:     if ($lctype ne 'community') {
16760:         $lctype = 'course';
16761:     }
16762:     if ($clonehome eq 'no_host') {
16763:         if ($args->{'crstype'} eq 'Community') {
16764:             push(@clonemsg,({
16765:                               mt => 'No new community created.',
16766:                               args => [],
16767:                             },
16768:                             {
16769:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16770:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16771:                             }));
16772:         } else {
16773:             push(@clonemsg,({
16774:                               mt => 'No new course created.',
16775:                               args => [],
16776:                             },
16777:                             {
16778:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16779:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16780:                             }));
16781:         }
16782:     } else {
16783: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16784:         $clonetitle = $clonedesc{'description'};
16785:         if ($args->{'crstype'} eq 'Community') {
16786:             if ($clonedesc{'type'} ne 'Community') {
16787:                 push(@clonemsg,({
16788:                                   mt => 'No new community created.',
16789:                                   args => [],
16790:                                 },
16791:                                 {
16792:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16793:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16794:                                 }));
16795:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16796:             }
16797:         }
16798: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16799:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16800: 	    $can_clone = 1;
16801: 	} else {
16802: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16803: 						 $args->{'clonedomain'},$args->{'clonecourse'});
16804:             if ($clonehash{'cloners'} eq '') {
16805:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16806:                 if ($domdefs{'canclone'}) {
16807:                     unless ($domdefs{'canclone'} eq 'none') {
16808:                         if ($domdefs{'canclone'} eq 'domain') {
16809:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16810:                                 $can_clone = 1;
16811:                             }
16812:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16813:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16814:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16815:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16816:                                 $can_clone = 1;
16817:                             }
16818:                         }
16819:                     }
16820:                 }
16821:             } else {
16822: 	        my @cloners = split(/,/,$clonehash{'cloners'});
16823:                 if (grep(/^\*$/,@cloners)) {
16824:                     $can_clone = 1;
16825:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16826:                     $can_clone = 1;
16827:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16828:                     $can_clone = 1;
16829:                 }
16830:                 unless ($can_clone) {
16831:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
16832:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
16833:                         my (%gotdomdefaults,%gotcodedefaults);
16834:                         foreach my $cloner (@cloners) {
16835:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16836:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16837:                                 my (%codedefaults,@code_order);
16838:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16839:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16840:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16841:                                     }
16842:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16843:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16844:                                     }
16845:                                 } else {
16846:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16847:                                                                             \%codedefaults,
16848:                                                                             \@code_order);
16849:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16850:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16851:                                 }
16852:                                 if (@code_order > 0) {
16853:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16854:                                                                                 $cloner,$clonehash{'internal.coursecode'},
16855:                                                                                 $args->{'crscode'})) {
16856:                                         $can_clone = 1;
16857:                                         last;
16858:                                     }
16859:                                 }
16860:                             }
16861:                         }
16862:                     }
16863:                 }
16864:             }
16865:             unless ($can_clone) {
16866:                 my $ccrole = 'cc';
16867:                 if ($args->{'crstype'} eq 'Community') {
16868:                     $ccrole = 'co';
16869:                 }
16870: 	        my %roleshash =
16871: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
16872: 					          $args->{'ccdomain'},
16873:                                                   'userroles',['active'],[$ccrole],
16874: 					          [$args->{'clonedomain'}]);
16875: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16876:                     $can_clone = 1;
16877:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16878:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
16879:                     $can_clone = 1;
16880:                 }
16881:             }
16882:             unless ($can_clone) {
16883:                 if ($args->{'crstype'} eq 'Community') {
16884:                     push(@clonemsg,({
16885:                                       mt => 'No new community created.',
16886:                                       args => [],
16887:                                     },
16888:                                     {
16889:                                       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]).',
16890:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16891:                                     }));
16892:                 } else {
16893:                     push(@clonemsg,({
16894:                                       mt => 'No new course created.',
16895:                                       args => [],
16896:                                     },
16897:                                     {
16898:                                       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]).',
16899:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16900:                                     }));
16901:                 }
16902: 	    }
16903:         }
16904:     }
16905:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16906: }
16907: 
16908: sub construct_course {
16909:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16910:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16911:     my ($outcome,$msgref,$clonemsgref);
16912:     my $linefeed =  '<br />'."\n";
16913:     if ($context eq 'auto') {
16914:         $linefeed = "\n";
16915:     }
16916: 
16917: #
16918: # Are we cloning?
16919: #
16920:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16921:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16922: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16923:         if (!$can_clone) {
16924: 	    return (0,$outcome,$clonemsgref);
16925: 	}
16926:     }
16927: 
16928: #
16929: # Open course
16930: #
16931:     my $showncrstype;
16932:     if ($args->{'crstype'} eq 'Placement') {
16933:         $showncrstype = 'placement test'; 
16934:     } else {  
16935:         $showncrstype = lc($args->{'crstype'});
16936:     }
16937:     my %cenv=();
16938:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16939:                                              $args->{'cdescr'},
16940:                                              $args->{'curl'},
16941:                                              $args->{'course_home'},
16942:                                              $args->{'nonstandard'},
16943:                                              $args->{'crscode'},
16944:                                              $args->{'ccuname'}.':'.
16945:                                              $args->{'ccdomain'},
16946:                                              $args->{'crstype'},
16947:                                              $cnum,$context,$category,
16948:                                              $callercontext);
16949: 
16950:     # Note: The testing routines depend on this being output; see 
16951:     # Utils::Course. This needs to at least be output as a comment
16952:     # if anyone ever decides to not show this, and Utils::Course::new
16953:     # will need to be suitably modified.
16954:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16955:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16956:     } else {
16957:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16958:     }
16959:     if ($$courseid =~ /^error:/) {
16960:         return (0,$outcome,$clonemsgref);
16961:     }
16962: 
16963: #
16964: # Check if created correctly
16965: #
16966:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16967:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16968:     if ($crsuhome eq 'no_host') {
16969:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16970:             $outcome .= &mt_user($user_lh,
16971:                             'Course creation failed, unrecognized course home server.');
16972:         } else {
16973:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16974:         }
16975:         $outcome .= $linefeed;
16976:         return (0,$outcome,$clonemsgref);
16977:     }
16978:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16979: 
16980: #
16981: # Do the cloning
16982: #   
16983:     my @clonemsg;
16984:     if ($can_clone && $cloneid) {
16985:         push(@clonemsg,
16986:                       {
16987:                           mt => 'Created [_1] by cloning from [_2]',
16988:                           args => [$showncrstype,$clonetitle],
16989:                       });
16990: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16991: # Copy all files
16992:         my @info =
16993: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16994: 	                                             $args->{'dateshift'},$args->{'crscode'},
16995:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16996:                                                      $args->{'tinyurls'});
16997:         if (@info) {
16998:             push(@clonemsg,@info);
16999:         }
17000: # Restore URL
17001: 	$cenv{'url'}=$oldcenv{'url'};
17002: # Restore title
17003: 	$cenv{'description'}=$oldcenv{'description'};
17004: # Restore creation date, creator and creation context.
17005:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
17006:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17007:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17008: # Mark as cloned
17009: 	$cenv{'clonedfrom'}=$cloneid;
17010: # Need to clone grading mode
17011:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17012:         $cenv{'grading'}=$newenv{'grading'};
17013: # Do not clone these environment entries
17014:         &Apache::lonnet::del('environment',
17015:                   ['default_enrollment_start_date',
17016:                    'default_enrollment_end_date',
17017:                    'question.email',
17018:                    'policy.email',
17019:                    'comment.email',
17020:                    'pch.users.denied',
17021:                    'plc.users.denied',
17022:                    'hidefromcat',
17023:                    'checkforpriv',
17024:                    'categories'],
17025:                    $$crsudom,$$crsunum);
17026:         if ($args->{'textbook'}) {
17027:             $cenv{'internal.textbook'} = $args->{'textbook'};
17028:         }
17029:     }
17030: 
17031: #
17032: # Set environment (will override cloned, if existing)
17033: #
17034:     my @sections = ();
17035:     my @xlists = ();
17036:     if ($args->{'crstype'}) {
17037:         $cenv{'type'}=$args->{'crstype'};
17038:     }
17039:     if ($args->{'lti'}) {
17040:         $cenv{'internal.lti'}=$args->{'lti'};
17041:     }
17042:     if ($args->{'crsid'}) {
17043:         $cenv{'courseid'}=$args->{'crsid'};
17044:     }
17045:     if ($args->{'crscode'}) {
17046:         $cenv{'internal.coursecode'}=$args->{'crscode'};
17047:     }
17048:     if ($args->{'crsquota'} ne '') {
17049:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
17050:     } else {
17051:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17052:     }
17053:     if ($args->{'ccuname'}) {
17054:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17055:                                         ':'.$args->{'ccdomain'};
17056:     } else {
17057:         $cenv{'internal.courseowner'} = $args->{'curruser'};
17058:     }
17059:     if ($args->{'defaultcredits'}) {
17060:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17061:     }
17062:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17063:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17064:     if ($args->{'crssections'}) {
17065:         $cenv{'internal.sectionnums'} = '';
17066:         if ($args->{'crssections'} =~ m/,/) {
17067:             @sections = split/,/,$args->{'crssections'};
17068:         } else {
17069:             $sections[0] = $args->{'crssections'};
17070:         }
17071:         if (@sections > 0) {
17072:             foreach my $item (@sections) {
17073:                 my ($sec,$gp) = split/:/,$item;
17074:                 my $class = $args->{'crscode'}.$sec;
17075:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17076:                 $cenv{'internal.sectionnums'} .= $item.',';
17077:                 if ($addcheck eq 'ok') {
17078:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17079:                         push(@oklcsecs,$gp);
17080:                     }
17081:                 } else {
17082:                     push(@badclasses,$class);
17083:                 }
17084:             }
17085:             $cenv{'internal.sectionnums'} =~ s/,$//;
17086:         }
17087:     }
17088: # do not hide course coordinator from staff listing, 
17089: # even if privileged
17090:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17091: # add course coordinator's domain to domains to check for privileged users
17092: # if different to course domain
17093:     if ($$crsudom ne $args->{'ccdomain'}) {
17094:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
17095:     }
17096: # add crosslistings
17097:     if ($args->{'crsxlist'}) {
17098:         $cenv{'internal.crosslistings'}='';
17099:         if ($args->{'crsxlist'} =~ m/,/) {
17100:             @xlists = split/,/,$args->{'crsxlist'};
17101:         } else {
17102:             $xlists[0] = $args->{'crsxlist'};
17103:         }
17104:         if (@xlists > 0) {
17105:             foreach my $item (@xlists) {
17106:                 my ($xl,$gp) = split/:/,$item;
17107:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17108:                 $cenv{'internal.crosslistings'} .= $item.',';
17109:                 if ($addcheck eq 'ok') {
17110:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17111:                         push(@oklcsecs,$gp);
17112:                     }
17113:                 } else {
17114:                     push(@badclasses,$xl);
17115:                 }
17116:             }
17117:             $cenv{'internal.crosslistings'} =~ s/,$//;
17118:         }
17119:     }
17120:     if ($args->{'autoadds'}) {
17121:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
17122:     }
17123:     if ($args->{'autodrops'}) {
17124:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
17125:     }
17126: # check for notification of enrollment changes
17127:     my @notified = ();
17128:     if ($args->{'notify_owner'}) {
17129:         if ($args->{'ccuname'} ne '') {
17130:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17131:         }
17132:     }
17133:     if ($args->{'notify_dc'}) {
17134:         if ($uname ne '') { 
17135:             push(@notified,$uname.':'.$udom);
17136:         }
17137:     }
17138:     if (@notified > 0) {
17139:         my $notifylist;
17140:         if (@notified > 1) {
17141:             $notifylist = join(',',@notified);
17142:         } else {
17143:             $notifylist = $notified[0];
17144:         }
17145:         $cenv{'internal.notifylist'} = $notifylist;
17146:     }
17147:     if (@badclasses > 0) {
17148:         my %lt=&Apache::lonlocal::texthash(
17149:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17150:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17151:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17152:         );
17153:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17154:                            &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'};
17155:         if ($context eq 'auto') {
17156:             $outcome .= $badclass_msg.$linefeed;
17157:         } else {
17158:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17159:         }
17160:         foreach my $item (@badclasses) {
17161:             if ($context eq 'auto') {
17162:                 $outcome .= " - $item\n";
17163:             } else {
17164:                 $outcome .= "<li>$item</li>\n";
17165:             }
17166:         }
17167:         if ($context eq 'auto') {
17168:             $outcome .= $linefeed;
17169:         } else {
17170:             $outcome .= "</ul><br /><br /></div>\n";
17171:         } 
17172:     }
17173:     if ($args->{'no_end_date'}) {
17174:         $args->{'endaccess'} = 0;
17175:     }
17176: #  If an official course with institutional sections is created by cloning 
17177: #  an existing course, section-specific hiding of course totals in student's
17178: #  view of grades as copied from cloned course, will be checked for valid 
17179: #  sections.
17180:     if (($can_clone && $cloneid) &&
17181:         ($cenv{'internal.coursecode'} ne '') &&
17182:         ($cenv{'grading'} eq 'standard') &&
17183:         ($cenv{'hidetotals'} ne '') &&
17184:         ($cenv{'hidetotals'} ne 'all')) {
17185:         my @hidesecs;
17186:         my $deletehidetotals;
17187:         if (@oklcsecs) {
17188:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17189:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
17190:                     push(@hidesecs,$sec);
17191:                 }
17192:             }
17193:             if (@hidesecs) {
17194:                 $cenv{'hidetotals'} = join(',',@hidesecs);
17195:             } else {
17196:                 $deletehidetotals = 1;
17197:             }
17198:         } else {
17199:             $deletehidetotals = 1;
17200:         }
17201:         if ($deletehidetotals) {
17202:             delete($cenv{'hidetotals'});
17203:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17204:         }
17205:     }
17206:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
17207:     $cenv{'internal.autoend'}=$args->{'enrollend'};
17208:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17209:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17210:     if ($args->{'showphotos'}) {
17211:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
17212:     }
17213:     $cenv{'internal.authtype'} = $args->{'authtype'};
17214:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
17215:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17216:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
17217:             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'); 
17218:             if ($context eq 'auto') {
17219:                 $outcome .= $krb_msg;
17220:             } else {
17221:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17222:             }
17223:             $outcome .= $linefeed;
17224:         }
17225:     }
17226:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17227:        if ($args->{'setpolicy'}) {
17228:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17229:        }
17230:        if ($args->{'setcontent'}) {
17231:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17232:        }
17233:        if ($args->{'setcomment'}) {
17234:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17235:        }
17236:     }
17237:     if ($args->{'reshome'}) {
17238: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
17239: 	$cenv{'reshome'}=~s/\/+$/\//;
17240:     }
17241: #
17242: # course has keyed access
17243: #
17244:     if ($args->{'setkeys'}) {
17245:        $cenv{'keyaccess'}='yes';
17246:     }
17247: # if specified, key authority is not course, but user
17248: # only active if keyaccess is yes
17249:     if ($args->{'keyauth'}) {
17250: 	my ($user,$domain) = split(':',$args->{'keyauth'});
17251: 	$user = &LONCAPA::clean_username($user);
17252: 	$domain = &LONCAPA::clean_username($domain);
17253: 	if ($user ne '' && $domain ne '') {
17254: 	    $cenv{'keyauth'}=$user.':'.$domain;
17255: 	}
17256:     }
17257: 
17258: #
17259: #  generate and store uniquecode (available to course requester), if course should have one.
17260: #
17261:     if ($args->{'uniquecode'}) {
17262:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17263:         if ($code) {
17264:             $cenv{'internal.uniquecode'} = $code;
17265:             my %crsinfo =
17266:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17267:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17268:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17269:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17270:             } 
17271:             if (ref($coderef)) {
17272:                 $$coderef = $code;
17273:             }
17274:         }
17275:     }
17276: 
17277:     if ($args->{'disresdis'}) {
17278:         $cenv{'pch.roles.denied'}='st';
17279:     }
17280:     if ($args->{'disablechat'}) {
17281:         $cenv{'plc.roles.denied'}='st';
17282:     }
17283: 
17284:     # Record we've not yet viewed the Course Initialization Helper for this 
17285:     # course
17286:     $cenv{'course.helper.not.run'} = 1;
17287:     #
17288:     # Use new Randomseed
17289:     #
17290:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17291:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17292:     #
17293:     # The encryption code and receipt prefix for this course
17294:     #
17295:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17296:     $cenv{'internal.encpref'}=100+int(9*rand(99));
17297:     #
17298:     # By default, use standard grading
17299:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17300: 
17301:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
17302:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17303: #
17304: # Open all assignments
17305: #
17306:     if ($args->{'openall'}) {
17307:        my $opendate = time;
17308:        if ($args->{'openallfrom'} =~ /^\d+$/) {
17309:            $opendate = $args->{'openallfrom'};
17310:        }
17311:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17312:        my %storecontent = ($storeunder         => $opendate,
17313:                            $storeunder.'.type' => 'date_start');
17314:        $outcome .= &mt('All assignments open starting [_1]',
17315:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
17316:                    &Apache::lonnet::cput
17317:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17318:    }
17319: #
17320: # Set first page
17321: #
17322:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17323: 	    || ($cloneid)) {
17324: 	$outcome .= &mt('Setting first resource').': ';
17325: 
17326: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17327:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17328: 
17329:         $outcome .= ($fatal?$errtext:'read ok').' - ';
17330:         my $title; my $url;
17331:         if ($args->{'firstres'} eq 'syl') {
17332: 	    $title=&mt('Syllabus');
17333:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17334:         } else {
17335:             $title=&mt('Table of Contents');
17336:             $url='/adm/navmaps';
17337:         }
17338: 
17339:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17340: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17341: 
17342: 	if ($errtext) { $fatal=2; }
17343:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17344:     }
17345: 
17346: # 
17347: # Set params for Placement Tests
17348: #
17349:     if ($args->{'crstype'} eq 'Placement') {
17350:        my %storecontent; 
17351:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17352:        my %defaults = (
17353:                         buttonshide   => { value => 'yes',
17354:                                            type => 'string_yesno',},
17355:                         type          => { value => 'randomizetry',
17356:                                            type  => 'string_questiontype',},
17357:                         maxtries      => { value => 1,
17358:                                            type => 'int_pos',},
17359:                         problemstatus => { value => 'no',
17360:                                            type  => 'string_problemstatus',},
17361:                       );
17362:        foreach my $key (keys(%defaults)) {
17363:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17364:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17365:        }
17366:        &Apache::lonnet::cput
17367:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
17368:     }
17369: 
17370:     return (1,$outcome,\@clonemsg);
17371: }
17372: 
17373: sub make_unique_code {
17374:     my ($cdom,$cnum) = @_;
17375:     # get lock on uniquecodes db
17376:     my $lockhash = {
17377:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
17378:                                                   ':'.$env{'user.domain'},
17379:                    };
17380:     my $tries = 0;
17381:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17382:     my ($code,$error);
17383:   
17384:     while (($gotlock ne 'ok') && ($tries<3)) {
17385:         $tries ++;
17386:         sleep 1;
17387:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17388:     }
17389:     if ($gotlock eq 'ok') {
17390:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17391:         my $gotcode;
17392:         my $attempts = 0;
17393:         while ((!$gotcode) && ($attempts < 100)) {
17394:             $code = &generate_code();
17395:             if (!exists($currcodes{$code})) {
17396:                 $gotcode = 1;
17397:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17398:                     $error = 'nostore';
17399:                 }
17400:             }
17401:             $attempts ++;
17402:         }
17403:         my @del_lock = ($cnum."\0".'uniquecodes');
17404:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17405:     } else {
17406:         $error = 'nolock';
17407:     }
17408:     return ($code,$error);
17409: }
17410: 
17411: sub generate_code {
17412:     my $code;
17413:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17414:     for (my $i=0; $i<6; $i++) {
17415:         my $lettnum = int (rand 2);
17416:         my $item = '';
17417:         if ($lettnum) {
17418:             $item = $letts[int( rand(18) )];
17419:         } else {
17420:             $item = 1+int( rand(8) );
17421:         }
17422:         $code .= $item;
17423:     }
17424:     return $code;
17425: }
17426: 
17427: ############################################################
17428: ############################################################
17429: 
17430: # Community, Course and Placement Test
17431: sub course_type {
17432:     my ($cid) = @_;
17433:     if (!defined($cid)) {
17434:         $cid = $env{'request.course.id'};
17435:     }
17436:     if (defined($env{'course.'.$cid.'.type'})) {
17437:         return $env{'course.'.$cid.'.type'};
17438:     } else {
17439:         return 'Course';
17440:     }
17441: }
17442: 
17443: sub group_term {
17444:     my $crstype = &course_type();
17445:     my %names = (
17446:                   'Course' => 'group',
17447:                   'Community' => 'group',
17448:                   'Placement' => 'group',
17449:                 );
17450:     return $names{$crstype};
17451: }
17452: 
17453: sub course_types {
17454:     my @types = ('official','unofficial','community','textbook','placement','lti');
17455:     my %typename = (
17456:                          official   => 'Official course',
17457:                          unofficial => 'Unofficial course',
17458:                          community  => 'Community',
17459:                          textbook   => 'Textbook course',
17460:                          placement  => 'Placement test',
17461:                          lti        => 'LTI provider',
17462:                    );
17463:     return (\@types,\%typename);
17464: }
17465: 
17466: sub icon {
17467:     my ($file)=@_;
17468:     my $curfext = lc((split(/\./,$file))[-1]);
17469:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17470:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17471:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17472: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17473: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17474: 	            $curfext.".gif") {
17475: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17476: 		$curfext.".gif";
17477: 	}
17478:     }
17479:     return &lonhttpdurl($iconname);
17480: } 
17481: 
17482: sub lonhttpdurl {
17483: #
17484: # Had been used for "small fry" static images on separate port 8080.
17485: # Modify here if lightweight http functionality desired again.
17486: # Currently eliminated due to increasing firewall issues.
17487: #
17488:     my ($url)=@_;
17489:     return $url;
17490: }
17491: 
17492: sub connection_aborted {
17493:     my ($r)=@_;
17494:     $r->print(" ");$r->rflush();
17495:     my $c = $r->connection;
17496:     return $c->aborted();
17497: }
17498: 
17499: #    Escapes strings that may have embedded 's that will be put into
17500: #    strings as 'strings'.
17501: sub escape_single {
17502:     my ($input) = @_;
17503:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
17504:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
17505:     return $input;
17506: }
17507: 
17508: #  Same as escape_single, but escape's "'s  This 
17509: #  can be used for  "strings"
17510: sub escape_double {
17511:     my ($input) = @_;
17512:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
17513:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
17514:     return $input;
17515: }
17516:  
17517: #   Escapes the last element of a full URL.
17518: sub escape_url {
17519:     my ($url)   = @_;
17520:     my @urlslices = split(/\//, $url,-1);
17521:     my $lastitem = &escape(pop(@urlslices));
17522:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17523: }
17524: 
17525: sub compare_arrays {
17526:     my ($arrayref1,$arrayref2) = @_;
17527:     my (@difference,%count);
17528:     @difference = ();
17529:     %count = ();
17530:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17531:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17532:         foreach my $element (keys(%count)) {
17533:             if ($count{$element} == 1) {
17534:                 push(@difference,$element);
17535:             }
17536:         }
17537:     }
17538:     return @difference;
17539: }
17540: 
17541: sub lon_status_items {
17542:     my %defaults = (
17543:                      E         => 100,
17544:                      W         => 4,
17545:                      N         => 1,
17546:                      U         => 5,
17547:                      threshold => 200,
17548:                      sysmail   => 2500,
17549:                    );
17550:     my %names = (
17551:                    E => 'Errors',
17552:                    W => 'Warnings',
17553:                    N => 'Notices',
17554:                    U => 'Unsent',
17555:                 );
17556:     return (\%defaults,\%names);
17557: }
17558: 
17559: # -------------------------------------------------------- Initialize user login
17560: sub init_user_environment {
17561:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
17562:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17563: 
17564:     my $public=($username eq 'public' && $domain eq 'public');
17565: 
17566:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17567:     my $now=time;
17568: 
17569:     if ($public) {
17570: 	my $max_public=100;
17571: 	my $oldest;
17572: 	my $oldest_time=0;
17573: 	for(my $next=1;$next<=$max_public;$next++) {
17574: 	    if (-e $lonids."/publicuser_$next.id") {
17575: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17576: 		if ($mtime<$oldest_time || !$oldest_time) {
17577: 		    $oldest_time=$mtime;
17578: 		    $oldest=$next;
17579: 		}
17580: 	    } else {
17581: 		$cookie="publicuser_$next";
17582: 		last;
17583: 	    }
17584: 	}
17585: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
17586:     } else {
17587: 	# See if old ID present, if so, remove if this isn't a robot,
17588: 	# killing any existing non-robot sessions
17589: 	if (!$args->{'robot'}) {
17590: 	    opendir(DIR,$lonids);
17591: 	    while ($filename=readdir(DIR)) {
17592: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17593:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17594:                             &GDBM_READER(),0640)) {
17595:                         my $linkedfile;
17596:                         if (exists($oldenv{'user.linkedenv'})) {
17597:                             $linkedfile = $oldenv{'user.linkedenv'};
17598:                         }
17599:                         untie(%oldenv);
17600:                         if (unlink("$lonids/$filename")) {
17601:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17602:                                 if (-l "$lonids/$linkedfile.id") {
17603:                                     unlink("$lonids/$linkedfile.id");
17604:                                 }
17605:                             }
17606:                         }
17607:                     } else {
17608:                         unlink($lonids.'/'.$filename);
17609:                     }
17610: 		}
17611: 	    }
17612: 	    closedir(DIR);
17613: # If there is a undeleted lockfile for the user's paste buffer remove it.
17614:             my $namespace = 'nohist_courseeditor';
17615:             my $lockingkey = 'paste'."\0".'locked_num';
17616:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17617:                                                 $domain,$username);
17618:             if (exists($lockhash{$lockingkey})) {
17619:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17620:                 unless ($delresult eq 'ok') {
17621:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17622:                 }
17623:             }
17624: 	}
17625: # Give them a new cookie
17626: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17627: 		                   : $now.$$.int(rand(10000)));
17628: 	$cookie="$username\_$id\_$domain\_$authhost";
17629:     
17630: # Initialize roles
17631: 
17632: 	($userroles,$firstaccenv,$timerintenv) = 
17633:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
17634:     }
17635: # ------------------------------------ Check browser type and MathML capability
17636: 
17637:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17638:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17639: 
17640: # ------------------------------------------------------------- Get environment
17641: 
17642:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17643:     my ($tmp) = keys(%userenv);
17644:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17645: 	undef(%userenv);
17646:     }
17647:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
17648: 	$form->{'interface'}=$userenv{'interface'};
17649:     }
17650:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17651: 
17652: # --------------- Do not trust query string to be put directly into environment
17653:     foreach my $option ('interface','localpath','localres') {
17654:         $form->{$option}=~s/[\n\r\=]//gs;
17655:     }
17656: # --------------------------------------------------------- Write first profile
17657: 
17658:     {
17659:         my $ip = &Apache::lonnet::get_requestor_ip($r);
17660: 	my %initial_env = 
17661: 	    ("user.name"          => $username,
17662: 	     "user.domain"        => $domain,
17663: 	     "user.home"          => $authhost,
17664: 	     "browser.type"       => $clientbrowser,
17665: 	     "browser.version"    => $clientversion,
17666: 	     "browser.mathml"     => $clientmathml,
17667: 	     "browser.unicode"    => $clientunicode,
17668: 	     "browser.os"         => $clientos,
17669:              "browser.mobile"     => $clientmobile,
17670:              "browser.info"       => $clientinfo,
17671:              "browser.osversion"  => $clientosversion,
17672: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
17673: 	     "request.course.fn"  => '',
17674: 	     "request.course.uri" => '',
17675: 	     "request.course.sec" => '',
17676: 	     "request.role"       => 'cm',
17677: 	     "request.role.adv"   => $env{'user.adv'},
17678: 	     "request.host"       => $ip,);
17679: 
17680:         if ($form->{'localpath'}) {
17681: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
17682: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
17683:         }
17684: 	
17685: 	if ($form->{'interface'}) {
17686: 	    $form->{'interface'}=~s/\W//gs;
17687: 	    $initial_env{"browser.interface"} = $form->{'interface'};
17688: 	    $env{'browser.interface'}=$form->{'interface'};
17689: 	}
17690: 
17691:         if ($form->{'iptoken'}) {
17692:             my $lonhost = $r->dir_config('lonHostID');
17693:             $initial_env{"user.noloadbalance"} = $lonhost;
17694:             $env{'user.noloadbalance'} = $lonhost;
17695:         }
17696: 
17697:         if ($form->{'noloadbalance'}) {
17698:             my @hosts = &Apache::lonnet::current_machine_ids();
17699:             my $hosthere = $form->{'noloadbalance'};
17700:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
17701:                 $initial_env{"user.noloadbalance"} = $hosthere;
17702:                 $env{'user.noloadbalance'} = $hosthere;
17703:             }
17704:         }
17705: 
17706:         unless ($domain eq 'public') {
17707:             my %is_adv = ( is_adv => $env{'user.adv'} );
17708:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17709: 
17710:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17711:                 $userenv{'availabletools.'.$tool} = 
17712:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17713:                                                       undef,\%userenv,\%domdef,\%is_adv);
17714:             }
17715: 
17716:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17717:                 $userenv{'canrequest.'.$crstype} =
17718:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
17719:                                                       'reload','requestcourses',
17720:                                                       \%userenv,\%domdef,\%is_adv);
17721:             }
17722: 
17723:             $userenv{'canrequest.author'} =
17724:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17725:                                                   'reload','requestauthor',
17726:                                                   \%userenv,\%domdef,\%is_adv);
17727:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17728:                                                  $domain,$username);
17729:             my $reqstatus = $reqauthor{'author_status'};
17730:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
17731:                 if (ref($reqauthor{'author'}) eq 'HASH') {
17732:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
17733:                                                       $reqauthor{'author'}{'timestamp'};
17734:                 }
17735:             }
17736:             my ($types,$typename) = &course_types();
17737:             if (ref($types) eq 'ARRAY') {
17738:                 my @options = ('approval','validate','autolimit');
17739:                 my $optregex = join('|',@options);
17740:                 my (%willtrust,%trustchecked);
17741:                 foreach my $type (@{$types}) {
17742:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17743:                     if ($dom_str ne '') {
17744:                         my $updatedstr = '';
17745:                         my @possdomains = split(',',$dom_str);
17746:                         foreach my $entry (@possdomains) {
17747:                             my ($extdom,$extopt) = split(':',$entry);
17748:                             unless ($trustchecked{$extdom}) {
17749:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17750:                                 $trustchecked{$extdom} = 1;
17751:                             }
17752:                             if ($willtrust{$extdom}) {
17753:                                 $updatedstr .= $entry.',';
17754:                             }
17755:                         }
17756:                         $updatedstr =~ s/,$//;
17757:                         if ($updatedstr) {
17758:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17759:                         } else {
17760:                             delete($userenv{'reqcrsotherdom.'.$type});
17761:                         }
17762:                     }
17763:                 }
17764:             }
17765:         }
17766: 	$env{'user.environment'} = "$lonids/$cookie.id";
17767: 
17768: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17769: 		 &GDBM_WRCREAT(),0640)) {
17770: 	    &_add_to_env(\%disk_env,\%initial_env);
17771: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
17772: 	    &_add_to_env(\%disk_env,$userroles);
17773:             if (ref($firstaccenv) eq 'HASH') {
17774:                 &_add_to_env(\%disk_env,$firstaccenv);
17775:             }
17776:             if (ref($timerintenv) eq 'HASH') {
17777:                 &_add_to_env(\%disk_env,$timerintenv);
17778:             }
17779: 	    if (ref($args->{'extra_env'})) {
17780: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
17781: 	    }
17782: 	    untie(%disk_env);
17783: 	} else {
17784: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17785: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
17786: 	    return 'error: '.$!;
17787: 	}
17788:     }
17789:     $env{'request.role'}='cm';
17790:     $env{'request.role.adv'}=$env{'user.adv'};
17791:     $env{'browser.type'}=$clientbrowser;
17792: 
17793:     return $cookie;
17794: 
17795: }
17796: 
17797: sub _add_to_env {
17798:     my ($idf,$env_data,$prefix) = @_;
17799:     if (ref($env_data) eq 'HASH') {
17800:         while (my ($key,$value) = each(%$env_data)) {
17801: 	    $idf->{$prefix.$key} = $value;
17802: 	    $env{$prefix.$key}   = $value;
17803:         }
17804:     }
17805: }
17806: 
17807: # --- Get the symbolic name of a problem and the url
17808: sub get_symb {
17809:     my ($request,$silent) = @_;
17810:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17811:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17812:     if ($symb eq '') {
17813:         if (!$silent) {
17814:             if (ref($request)) { 
17815:                 $request->print("Unable to handle ambiguous references:$url:.");
17816:             }
17817:             return ();
17818:         }
17819:     }
17820:     &Apache::lonenc::check_decrypt(\$symb);
17821:     return ($symb);
17822: }
17823: 
17824: # --------------------------------------------------------------Get annotation
17825: 
17826: sub get_annotation {
17827:     my ($symb,$enc) = @_;
17828: 
17829:     my $key = $symb;
17830:     if (!$enc) {
17831:         $key =
17832:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17833:     }
17834:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17835:     return $annotation{$key};
17836: }
17837: 
17838: sub clean_symb {
17839:     my ($symb,$delete_enc) = @_;
17840: 
17841:     &Apache::lonenc::check_decrypt(\$symb);
17842:     my $enc = $env{'request.enc'};
17843:     if ($delete_enc) {
17844:         delete($env{'request.enc'});
17845:     }
17846: 
17847:     return ($symb,$enc);
17848: }
17849: 
17850: ############################################################
17851: ############################################################
17852: 
17853: =pod
17854: 
17855: =head1 Routines for building display used to search for courses
17856: 
17857: 
17858: =over 4
17859: 
17860: =item * &build_filters()
17861: 
17862: Create markup for a table used to set filters to use when selecting
17863: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
17864: and quotacheck.pl
17865: 
17866: 
17867: Inputs:
17868: 
17869: filterlist - anonymous array of fields to include as potential filters 
17870: 
17871: crstype - course type
17872: 
17873: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17874:               to pop-open a course selector (will contain "extra element"). 
17875: 
17876: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17877: 
17878: filter - anonymous hash of criteria and their values
17879: 
17880: action - form action
17881: 
17882: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17883: 
17884: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17885: 
17886: cloneruname - username of owner of new course who wants to clone
17887: 
17888: clonerudom - domain of owner of new course who wants to clone
17889: 
17890: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
17891: 
17892: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17893: 
17894: codedom - domain
17895: 
17896: formname - value of form element named "form". 
17897: 
17898: fixeddom - domain, if fixed.
17899: 
17900: prevphase - value to assign to form element named "phase" when going back to the previous screen  
17901: 
17902: cnameelement - name of form element in form on opener page which will receive title of selected course 
17903: 
17904: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
17905: 
17906: cdomelement - name of form element in form on opener page which will receive domain of selected course
17907: 
17908: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17909: 
17910: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17911: 
17912: clonewarning - warning message about missing information for intended course owner when DC creates a course
17913: 
17914: 
17915: Returns: $output - HTML for display of search criteria, and hidden form elements.
17916: 
17917: 
17918: Side Effects: None
17919: 
17920: =cut
17921: 
17922: # ---------------------------------------------- search for courses based on last activity etc.
17923: 
17924: sub build_filters {
17925:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17926:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17927:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17928:         $cnameelement,$cnumelement,$cdomelement,$setroles,
17929:         $clonetext,$clonewarning) = @_;
17930:     my ($list,$jscript);
17931:     my $onchange = 'javascript:updateFilters(this)';
17932:     my ($domainselectform,$sincefilterform,$createdfilterform,
17933:         $ownerdomselectform,$persondomselectform,$instcodeform,
17934:         $typeselectform,$instcodetitle);
17935:     if ($formname eq '') {
17936:         $formname = $caller;
17937:     }
17938:     foreach my $item (@{$filterlist}) {
17939:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17940:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17941:             if ($item eq 'domainfilter') {
17942:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17943:             } elsif ($item eq 'coursefilter') {
17944:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17945:             } elsif ($item eq 'ownerfilter') {
17946:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17947:             } elsif ($item eq 'ownerdomfilter') {
17948:                 $filter->{'ownerdomfilter'} =
17949:                     &LONCAPA::clean_domain($filter->{$item});
17950:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17951:                                                        'ownerdomfilter',1);
17952:             } elsif ($item eq 'personfilter') {
17953:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17954:             } elsif ($item eq 'persondomfilter') {
17955:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17956:                                                         'persondomfilter',1);
17957:             } else {
17958:                 $filter->{$item} =~ s/\W//g;
17959:             }
17960:             if (!$filter->{$item}) {
17961:                 $filter->{$item} = '';
17962:             }
17963:         }
17964:         if ($item eq 'domainfilter') {
17965:             my $allow_blank = 1;
17966:             if ($formname eq 'portform') {
17967:                 $allow_blank=0;
17968:             } elsif ($formname eq 'studentform') {
17969:                 $allow_blank=0;
17970:             }
17971:             if ($fixeddom) {
17972:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
17973:                                     ' value="'.$codedom.'" />'.
17974:                                     &Apache::lonnet::domain($codedom,'description');
17975:             } else {
17976:                 $domainselectform = &select_dom_form($filter->{$item},
17977:                                                      'domainfilter',
17978:                                                       $allow_blank,'',$onchange);
17979:             }
17980:         } else {
17981:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17982:         }
17983:     }
17984: 
17985:     # last course activity filter and selection
17986:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
17987: 
17988:     # course created filter and selection
17989:     if (exists($filter->{'createdfilter'})) {
17990:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
17991:     }
17992: 
17993:     my $prefix = $crstype;
17994:     if ($crstype eq 'Placement') {
17995:         $prefix = 'Placement Test'
17996:     }
17997:     my %lt = &Apache::lonlocal::texthash(
17998:                 'cac' => "$prefix Activity",
17999:                 'ccr' => "$prefix Created",
18000:                 'cde' => "$prefix Title",
18001:                 'cdo' => "$prefix Domain",
18002:                 'ins' => 'Institutional Code',
18003:                 'inc' => 'Institutional Categorization',
18004:                 'cow' => "$prefix Owner/Co-owner",
18005:                 'cop' => "$prefix Personnel Includes",
18006:                 'cog' => 'Type',
18007:              );
18008: 
18009:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18010:         my $typeval = 'Course';
18011:         if ($crstype eq 'Community') {
18012:             $typeval = 'Community';
18013:         } elsif ($crstype eq 'Placement') {
18014:             $typeval = 'Placement';
18015:         }
18016:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18017:     } else {
18018:         $typeselectform =  '<select name="type" size="1"';
18019:         if ($onchange) {
18020:             $typeselectform .= ' onchange="'.$onchange.'"';
18021:         }
18022:         $typeselectform .= '>'."\n";
18023:         foreach my $posstype ('Course','Community','Placement') {
18024:             my $shown;
18025:             if ($posstype eq 'Placement') {
18026:                 $shown = &mt('Placement Test');
18027:             } else {
18028:                 $shown = &mt($posstype);
18029:             }
18030:             $typeselectform.='<option value="'.$posstype.'"'.
18031:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18032:         }
18033:         $typeselectform.="</select>";
18034:     }
18035: 
18036:     my ($cloneableonlyform,$cloneabletitle);
18037:     if (exists($filter->{'cloneableonly'})) {
18038:         my $cloneableon = '';
18039:         my $cloneableoff = ' checked="checked"';
18040:         if ($filter->{'cloneableonly'}) {
18041:             $cloneableon = $cloneableoff;
18042:             $cloneableoff = '';
18043:         }
18044:         $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>';
18045:         if ($formname eq 'ccrs') {
18046:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18047:         } else {
18048:             $cloneabletitle = &mt('Cloneable by you');
18049:         }
18050:     }
18051:     my $officialjs;
18052:     if ($crstype eq 'Course') {
18053:         if (exists($filter->{'instcodefilter'})) {
18054: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
18055: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18056:             if ($codedom) { 
18057:                 $officialjs = 1;
18058:                 ($instcodeform,$jscript,$$numtitlesref) =
18059:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18060:                                                                   $officialjs,$codetitlesref);
18061:                 if ($jscript) {
18062:                     $jscript = '<script type="text/javascript">'."\n".
18063:                                '// <![CDATA['."\n".
18064:                                $jscript."\n".
18065:                                '// ]]>'."\n".
18066:                                '</script>'."\n";
18067:                 }
18068:             }
18069:             if ($instcodeform eq '') {
18070:                 $instcodeform =
18071:                     '<input type="text" name="instcodefilter" size="10" value="'.
18072:                     $list->{'instcodefilter'}.'" />';
18073:                 $instcodetitle = $lt{'ins'};
18074:             } else {
18075:                 $instcodetitle = $lt{'inc'};
18076:             }
18077:             if ($fixeddom) {
18078:                 $instcodetitle .= '<br />('.$codedom.')';
18079:             }
18080:         }
18081:     }
18082:     my $output = qq|
18083: <form method="post" name="filterpicker" action="$action">
18084: <input type="hidden" name="form" value="$formname" />
18085: |;
18086:     if ($formname eq 'modifycourse') {
18087:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18088:                    '<input type="hidden" name="prevphase" value="'.
18089:                    $prevphase.'" />'."\n";
18090:     } elsif ($formname eq 'quotacheck') {
18091:         $output .= qq|
18092: <input type="hidden" name="sortby" value="" />
18093: <input type="hidden" name="sortorder" value="" />
18094: |;
18095:     } else {
18096:         my $name_input;
18097:         if ($cnameelement ne '') {
18098:             $name_input = '<input type="hidden" name="cnameelement" value="'.
18099:                           $cnameelement.'" />';
18100:         }
18101:         $output .= qq|
18102: <input type="hidden" name="cnumelement" value="$cnumelement" />
18103: <input type="hidden" name="cdomelement" value="$cdomelement" />
18104: $name_input
18105: $roleelement
18106: $multelement
18107: $typeelement
18108: |;
18109:         if ($formname eq 'portform') {
18110:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18111:         }
18112:     }
18113:     if ($fixeddom) {
18114:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18115:     }
18116:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18117:     if ($sincefilterform) {
18118:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18119:                   .$sincefilterform
18120:                   .&Apache::lonhtmlcommon::row_closure();
18121:     }
18122:     if ($createdfilterform) {
18123:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18124:                   .$createdfilterform
18125:                   .&Apache::lonhtmlcommon::row_closure();
18126:     }
18127:     if ($domainselectform) {
18128:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18129:                   .$domainselectform
18130:                   .&Apache::lonhtmlcommon::row_closure();
18131:     }
18132:     if ($typeselectform) {
18133:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18134:             $output .= $typeselectform;
18135:         } else {
18136:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18137:                       .$typeselectform
18138:                       .&Apache::lonhtmlcommon::row_closure();
18139:         }
18140:     }
18141:     if ($instcodeform) {
18142:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18143:                   .$instcodeform
18144:                   .&Apache::lonhtmlcommon::row_closure();
18145:     }
18146:     if (exists($filter->{'ownerfilter'})) {
18147:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18148:                    '<table><tr><td>'.&mt('Username').'<br />'.
18149:                    '<input type="text" name="ownerfilter" size="20" value="'.
18150:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18151:                    $ownerdomselectform.'</td></tr></table>'.
18152:                    &Apache::lonhtmlcommon::row_closure();
18153:     }
18154:     if (exists($filter->{'personfilter'})) {
18155:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18156:                    '<table><tr><td>'.&mt('Username').'<br />'.
18157:                    '<input type="text" name="personfilter" size="20" value="'.
18158:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18159:                    $persondomselectform.'</td></tr></table>'.
18160:                    &Apache::lonhtmlcommon::row_closure();
18161:     }
18162:     if (exists($filter->{'coursefilter'})) {
18163:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18164:                   .'<input type="text" name="coursefilter" size="25" value="'
18165:                   .$list->{'coursefilter'}.'" />'
18166:                   .&Apache::lonhtmlcommon::row_closure();
18167:     }
18168:     if ($cloneableonlyform) {
18169:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18170:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18171:     }
18172:     if (exists($filter->{'descriptfilter'})) {
18173:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18174:                   .'<input type="text" name="descriptfilter" size="40" value="'
18175:                   .$list->{'descriptfilter'}.'" />'
18176:                   .&Apache::lonhtmlcommon::row_closure(1);
18177:     }
18178:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18179:                '<input type="hidden" name="updater" value="" />'."\n".
18180:                '<input type="submit" name="gosearch" value="'.
18181:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18182:     return $jscript.$clonewarning.$output;
18183: }
18184: 
18185: =pod 
18186: 
18187: =item * &timebased_select_form()
18188: 
18189: Create markup for a dropdown list used to select a time-based
18190: filter e.g., Course Activity, Course Created, when searching for courses
18191: or communities
18192: 
18193: Inputs:
18194: 
18195: item - name of form element (sincefilter or createdfilter)
18196: 
18197: filter - anonymous hash of criteria and their values
18198: 
18199: Returns: HTML for a select box contained a blank, then six time selections,
18200:          with value set in incoming form variables currently selected. 
18201: 
18202: Side Effects: None
18203: 
18204: =cut
18205: 
18206: sub timebased_select_form {
18207:     my ($item,$filter) = @_;
18208:     if (ref($filter) eq 'HASH') {
18209:         $filter->{$item} =~ s/[^\d-]//g;
18210:         if (!$filter->{$item}) { $filter->{$item}=-1; }
18211:         return &select_form(
18212:                             $filter->{$item},
18213:                             $item,
18214:                             {      '-1' => '',
18215:                                 '86400' => &mt('today'),
18216:                                '604800' => &mt('last week'),
18217:                               '2592000' => &mt('last month'),
18218:                               '7776000' => &mt('last three months'),
18219:                              '15552000' => &mt('last six months'),
18220:                              '31104000' => &mt('last year'),
18221:                     'select_form_order' =>
18222:                            ['-1','86400','604800','2592000','7776000',
18223:                             '15552000','31104000']});
18224:     }
18225: }
18226: 
18227: =pod
18228: 
18229: =item * &js_changer()
18230: 
18231: Create script tag containing Javascript used to submit course search form
18232: when course type or domain is changed, and also to hide 'Searching ...' on
18233: page load completion for page showing search result.
18234: 
18235: Inputs: None
18236: 
18237: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
18238: 
18239: Side Effects: None
18240: 
18241: =cut
18242: 
18243: sub js_changer {
18244:     return <<ENDJS;
18245: <script type="text/javascript">
18246: // <![CDATA[
18247: function updateFilters(caller) {
18248:     if (typeof(caller) != "undefined") {
18249:         document.filterpicker.updater.value = caller.name;
18250:     }
18251:     document.filterpicker.submit();
18252: }
18253: 
18254: function hideSearching() {
18255:     if (document.getElementById('searching')) {
18256:         document.getElementById('searching').style.display = 'none';
18257:     }
18258:     return;
18259: }
18260: 
18261: // ]]>
18262: </script>
18263: 
18264: ENDJS
18265: }
18266: 
18267: =pod
18268: 
18269: =item * &search_courses()
18270: 
18271: Process selected filters form course search form and pass to lonnet::courseiddump
18272: to retrieve a hash for which keys are courseIDs which match the selected filters.
18273: 
18274: Inputs:
18275: 
18276: dom - domain being searched 
18277: 
18278: type - course type ('Course' or 'Community' or '.' if any).
18279: 
18280: filter - anonymous hash of criteria and their values
18281: 
18282: numtitles - for institutional codes - number of categories
18283: 
18284: cloneruname - optional username of new course owner
18285: 
18286: clonerudom - optional domain of new course owner
18287: 
18288: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
18289:             (used when DC is using course creation form)
18290: 
18291: codetitles - reference to array of titles of components in institutional codes (official courses).
18292: 
18293: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18294:            (and so can clone automatically)
18295: 
18296: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18297: 
18298: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
18299:               courses to clone 
18300: 
18301: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18302: 
18303: 
18304: Side Effects: None
18305: 
18306: =cut
18307: 
18308: 
18309: sub search_courses {
18310:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18311:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18312:     my (%courses,%showcourses,$cloner);
18313:     if (($filter->{'ownerfilter'} ne '') ||
18314:         ($filter->{'ownerdomfilter'} ne '')) {
18315:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18316:                                        $filter->{'ownerdomfilter'};
18317:     }
18318:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18319:         if (!$filter->{$item}) {
18320:             $filter->{$item}='.';
18321:         }
18322:     }
18323:     my $now = time;
18324:     my $timefilter =
18325:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18326:     my ($createdbefore,$createdafter);
18327:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18328:         $createdbefore = $now;
18329:         $createdafter = $now-$filter->{'createdfilter'};
18330:     }
18331:     my ($instcodefilter,$regexpok);
18332:     if ($numtitles) {
18333:         if ($env{'form.official'} eq 'on') {
18334:             $instcodefilter =
18335:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18336:             $regexpok = 1;
18337:         } elsif ($env{'form.official'} eq 'off') {
18338:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18339:             unless ($instcodefilter eq '') {
18340:                 $regexpok = -1;
18341:             }
18342:         }
18343:     } else {
18344:         $instcodefilter = $filter->{'instcodefilter'};
18345:     }
18346:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
18347:     if ($type eq '') { $type = '.'; }
18348: 
18349:     if (($clonerudom ne '') && ($cloneruname ne '')) {
18350:         $cloner = $cloneruname.':'.$clonerudom;
18351:     }
18352:     %courses = &Apache::lonnet::courseiddump($dom,
18353:                                              $filter->{'descriptfilter'},
18354:                                              $timefilter,
18355:                                              $instcodefilter,
18356:                                              $filter->{'combownerfilter'},
18357:                                              $filter->{'coursefilter'},
18358:                                              undef,undef,$type,$regexpok,undef,undef,
18359:                                              undef,undef,$cloner,$cc_clone,
18360:                                              $filter->{'cloneableonly'},
18361:                                              $createdbefore,$createdafter,undef,
18362:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
18363:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18364:         my $ccrole;
18365:         if ($type eq 'Community') {
18366:             $ccrole = 'co';
18367:         } else {
18368:             $ccrole = 'cc';
18369:         }
18370:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18371:                                                      $filter->{'persondomfilter'},
18372:                                                      'userroles',undef,
18373:                                                      [$ccrole,'in','ad','ep','ta','cr'],
18374:                                                      $dom);
18375:         foreach my $role (keys(%rolehash)) {
18376:             my ($cnum,$cdom,$courserole) = split(':',$role);
18377:             my $cid = $cdom.'_'.$cnum;
18378:             if (exists($courses{$cid})) {
18379:                 if (ref($courses{$cid}) eq 'HASH') {
18380:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18381:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18382:                             push(@{$courses{$cid}{roles}},$courserole);
18383:                         }
18384:                     } else {
18385:                         $courses{$cid}{roles} = [$courserole];
18386:                     }
18387:                     $showcourses{$cid} = $courses{$cid};
18388:                 }
18389:             }
18390:         }
18391:         %courses = %showcourses;
18392:     }
18393:     return %courses;
18394: }
18395: 
18396: =pod
18397: 
18398: =back
18399: 
18400: =head1 Routines for version requirements for current course.
18401: 
18402: =over 4
18403: 
18404: =item * &check_release_required()
18405: 
18406: Compares required LON-CAPA version with version on server, and
18407: if required version is newer looks for a server with the required version.
18408: 
18409: Looks first at servers in user's owen domain; if none suitable, looks at
18410: servers in course's domain are permitted to host sessions for user's domain.
18411: 
18412: Inputs:
18413: 
18414: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18415: 
18416: $courseid - Course ID of current course
18417: 
18418: $rolecode - User's current role in course (for switchserver query string).
18419: 
18420: $required - LON-CAPA version needed by course (format: Major.Minor).
18421: 
18422: 
18423: Returns:
18424: 
18425: $switchserver - query string tp append to /adm/switchserver call (if 
18426:                 current server's LON-CAPA version is too old. 
18427: 
18428: $warning - Message is displayed if no suitable server could be found.
18429: 
18430: =cut
18431: 
18432: sub check_release_required {
18433:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
18434:     my ($switchserver,$warning);
18435:     if ($required ne '') {
18436:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18437:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18438:         if ($reqdmajor ne '' && $reqdminor ne '') {
18439:             my $otherserver;
18440:             if (($major eq '' && $minor eq '') ||
18441:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18442:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18443:                 my $switchlcrev =
18444:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18445:                                                            $userdomserver);
18446:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18447:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18448:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18449:                     my $cdom = $env{'course.'.$courseid.'.domain'};
18450:                     if ($cdom ne $env{'user.domain'}) {
18451:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18452:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18453:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18454:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18455:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18456:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18457:                         my $canhost =
18458:                             &Apache::lonnet::can_host_session($env{'user.domain'},
18459:                                                               $coursedomserver,
18460:                                                               $remoterev,
18461:                                                               $udomdefaults{'remotesessions'},
18462:                                                               $defdomdefaults{'hostedsessions'});
18463: 
18464:                         if ($canhost) {
18465:                             $otherserver = $coursedomserver;
18466:                         } else {
18467:                             $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.");
18468:                         }
18469:                     } else {
18470:                         $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).");
18471:                     }
18472:                 } else {
18473:                     $otherserver = $userdomserver;
18474:                 }
18475:             }
18476:             if ($otherserver ne '') {
18477:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
18478:             }
18479:         }
18480:     }
18481:     return ($switchserver,$warning);
18482: }
18483: 
18484: =pod
18485: 
18486: =item * &check_release_result()
18487: 
18488: Inputs:
18489: 
18490: $switchwarning - Warning message if no suitable server found to host session.
18491: 
18492: $switchserver - query string to append to /adm/switchserver containing lonHostID
18493:                 and current role.
18494: 
18495: Returns: HTML to display with information about requirement to switch server.
18496:          Either displaying warning with link to Roles/Courses screen or
18497:          display link to switchserver.
18498: 
18499: =cut
18500: 
18501: sub check_release_result {
18502:     my ($switchwarning,$switchserver) = @_;
18503:     my $output = &start_page('Selected course unavailable on this server').
18504:                  '<p class="LC_warning">';
18505:     if ($switchwarning) {
18506:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
18507:         if (&show_course()) {
18508:             $output .= &mt('Display courses');
18509:         } else {
18510:             $output .= &mt('Display roles');
18511:         }
18512:         $output .= '</a>';
18513:     } elsif ($switchserver) {
18514:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18515:                    '<br />'.
18516:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
18517:                    &mt('Switch Server').
18518:                    '</a>';
18519:     }
18520:     $output .= '</p>'.&end_page();
18521:     return $output;
18522: }
18523: 
18524: =pod
18525: 
18526: =item * &needs_coursereinit()
18527: 
18528: Determine if course contents stored for user's session needs to be
18529: refreshed, because content has changed since "Big Hash" last tied.
18530: 
18531: Check for change is made if time last checked is more than 10 minutes ago
18532: (by default).
18533: 
18534: Inputs:
18535: 
18536: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18537: 
18538: $interval (optional) - Time which may elapse (in s) between last check for content
18539:                        change in current course. (default: 600 s).  
18540: 
18541: Returns: an array; first element is:
18542: 
18543: =over 4
18544: 
18545: 'switch' - if content updates mean user's session
18546:            needs to be switched to a server running a newer LON-CAPA version
18547:  
18548: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18549:            on current server hosting user's session                
18550: 
18551: ''       - if no action required.
18552: 
18553: =back
18554: 
18555: If first item element is 'switch':
18556: 
18557: second item is $switchwarning - Warning message if no suitable server found to host session. 
18558: 
18559: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18560:                               and current role. 
18561: 
18562: otherwise: no other elements returned.
18563: 
18564: =back
18565: 
18566: =cut
18567: 
18568: sub needs_coursereinit {
18569:     my ($loncaparev,$interval) = @_;
18570:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18571:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18572:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18573:     my $now = time;
18574:     if ($interval eq '') {
18575:         $interval = 600;
18576:     }
18577:     if (($now-$env{'request.course.timechecked'})>$interval) {
18578:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18579:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18580:         if ($blocked) {
18581:             return ();
18582:         }
18583:         my $update;
18584:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18585:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18586:         if ($lastmainchange > $env{'request.course.tied'}) {
18587:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18588:             if ($needswitch) {
18589:                 return ('switch',$switchwarning,$switchserver);
18590:             }
18591:             $update = 'main';
18592:         }
18593:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18594:             if ($update) {
18595:                 $update = 'both';
18596:             } else {
18597:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18598:                 if ($needswitch) {
18599:                     return ('switch',$switchwarning,$switchserver);
18600:                 } else {
18601:                     $update = 'supp';
18602:                 }
18603:             }
18604:             return ($update);
18605:         }
18606:     }
18607:     return ();
18608: }
18609: 
18610: sub switch_for_update {
18611:     my ($loncaparev,$cdom,$cnum) = @_;
18612:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18613:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18614:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18615:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18616:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18617:                                     $curr_reqd_hash{'internal.releaserequired'}});
18618:             my ($switchserver,$switchwarning) =
18619:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18620:                                         $curr_reqd_hash{'internal.releaserequired'});
18621:             if ($switchwarning ne '' || $switchserver ne '') {
18622:                 return ('switch',$switchwarning,$switchserver);
18623:             }
18624:         }
18625:     }
18626:     return ();
18627: }
18628: 
18629: sub update_content_constraints {
18630:     my ($cdom,$cnum,$chome,$cid) = @_;
18631:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18632:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18633:     my (%checkresponsetypes,%checkcrsrestypes);
18634:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18635:         my ($item,$name,$value) = split(/:/,$key);
18636:         if ($item eq 'resourcetag') {
18637:             if ($name eq 'responsetype') {
18638:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18639:             }
18640:         } elsif ($item eq 'course') {
18641:             if ($name eq 'courserestype') {
18642:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18643:             }
18644:         }
18645:     }
18646:     my $navmap = Apache::lonnavmaps::navmap->new();
18647:     if (defined($navmap)) {
18648:         my (%allresponses,%allcrsrestypes);
18649:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18650:             if ($res->is_tool()) {
18651:                 if ($allcrsrestypes{'exttool'}) {
18652:                     $allcrsrestypes{'exttool'} ++;
18653:                 } else {
18654:                     $allcrsrestypes{'exttool'} = 1;
18655:                 }
18656:                 next;
18657:             }
18658:             my %responses = $res->responseTypes();
18659:             foreach my $key (keys(%responses)) {
18660:                 next unless(exists($checkresponsetypes{$key}));
18661:                 $allresponses{$key} += $responses{$key};
18662:             }
18663:         }
18664:         foreach my $key (keys(%allresponses)) {
18665:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18666:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18667:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18668:             }
18669:         }
18670:         foreach my $key (keys(%allcrsrestypes)) {
18671:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18672:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18673:                 ($reqdmajor,$reqdminor) = ($major,$minor);
18674:             }
18675:         }
18676:         undef($navmap);
18677:     }
18678:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18679:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18680:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18681:             ($reqdmajor,$reqdminor) = ($major,$minor);
18682:         }
18683:     }
18684:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18685:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18686:     }
18687:     return;
18688: }
18689: 
18690: sub allmaps_incourse {
18691:     my ($cdom,$cnum,$chome,$cid) = @_;
18692:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18693:         $cid = $env{'request.course.id'};
18694:         $cdom = $env{'course.'.$cid.'.domain'};
18695:         $cnum = $env{'course.'.$cid.'.num'};
18696:         $chome = $env{'course.'.$cid.'.home'};
18697:     }
18698:     my %allmaps = ();
18699:     my $lastchange =
18700:         &Apache::lonnet::get_coursechange($cdom,$cnum);
18701:     if ($lastchange > $env{'request.course.tied'}) {
18702:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18703:         unless ($ferr) {
18704:             &update_content_constraints($cdom,$cnum,$chome,$cid);
18705:         }
18706:     }
18707:     my $navmap = Apache::lonnavmaps::navmap->new();
18708:     if (defined($navmap)) {
18709:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18710:             $allmaps{$res->src()} = 1;
18711:         }
18712:     }
18713:     return \%allmaps;
18714: }
18715: 
18716: sub parse_supplemental_title {
18717:     my ($title) = @_;
18718: 
18719:     my ($foldertitle,$renametitle);
18720:     if ($title =~ /&amp;&amp;&amp;/) {
18721:         $title = &HTML::Entites::decode($title);
18722:     }
18723:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18724:         $renametitle=$4;
18725:         my ($time,$uname,$udom) = ($1,$2,$3);
18726:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18727:         my $name =  &plainname($uname,$udom);
18728:         $name = &HTML::Entities::encode($name,'"<>&\'');
18729:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18730:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18731:         if ($foldertitle ne '') {
18732:             $title .= ': <br />'.$foldertitle;
18733:         }
18734:     }
18735:     if (wantarray) {
18736:         return ($title,$foldertitle,$renametitle);
18737:     }
18738:     return $title;
18739: }
18740: 
18741: sub get_supplemental {
18742:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18743:     my $hashid=$cnum.':'.$cdom;
18744:     my ($supplemental,$cached,$set_httprefs);
18745:     unless ($ignorecache) {
18746:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18747:     }
18748:     unless (defined($cached)) {
18749:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18750:         unless ($chome eq 'no_host') {
18751:             my @order = @LONCAPA::map::order;
18752:             my @resources = @LONCAPA::map::resources;
18753:             my @resparms = @LONCAPA::map::resparms;
18754:             my @zombies = @LONCAPA::map::zombies;
18755:             my ($errors,%ids,%hidden);
18756:             $errors =
18757:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18758:                                       $errors,$possdel,\%ids,\%hidden);
18759:             @LONCAPA::map::order = @order;
18760:             @LONCAPA::map::resources = @resources;
18761:             @LONCAPA::map::resparms = @resparms;
18762:             @LONCAPA::map::zombies = @zombies;
18763:             $set_httprefs = 1;
18764:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18765:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18766:             }
18767:             $supplemental = {
18768:                                ids => \%ids,
18769:                                hidden => \%hidden,
18770:                             };
18771:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18772:         }
18773:     }
18774:     return ($supplemental,$set_httprefs);
18775: }
18776: 
18777: sub recurse_supplemental {
18778:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18779:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18780:         my $mapnum;
18781:         if ($suppmap eq 'supplemental.sequence') {
18782:             $mapnum = 0;
18783:         } else {
18784:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18785:         }
18786:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18787:         if ($fatal) {
18788:             $errors ++;
18789:         } else {
18790:             my @order = @LONCAPA::map::order;
18791:             if (@order > 0) {
18792:                 my @resources = @LONCAPA::map::resources;
18793:                 my @resparms = @LONCAPA::map::resparms;
18794:                 foreach my $idx (@order) {
18795:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18796:                     if (($src ne '') && ($status eq 'res')) {
18797:                         my $id = $mapnum.':'.$idx;
18798:                         push(@{$suppids->{$src}},$id);
18799:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18800:                             $hiddensupp->{$id} = 1;
18801:                         }
18802:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18803:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18804:                                                             $hiddensupp,$hiddensupp->{$id});
18805:                         } else {
18806:                             my $allowed;
18807:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18808:                                 $allowed = 1;
18809:                             } elsif ($possdel) {
18810:                                 foreach my $item (@{$suppids->{$src}}) {
18811:                                     next if ($item eq $id);
18812:                                     unless ($hiddensupp->{$item}) {
18813:                                        $allowed = 1;
18814:                                        last;
18815:                                     }
18816:                                 }
18817:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18818:                                     &Apache::lonnet::delenv('httpref.'.$src);
18819:                                 }
18820:                             }
18821:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
18822:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18823:                             }
18824:                         }
18825:                     }
18826:                 }
18827:             }
18828:         }
18829:     }
18830:     return $errors;
18831: }
18832: 
18833: sub set_supp_httprefs {
18834:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
18835:     if (ref($supplemental) eq 'HASH') {
18836:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18837:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
18838:                 next if ($src =~ /\.sequence$/);
18839:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18840:                     my $allowed;
18841:                     if ($env{'request.role.adv'}) {
18842:                         $allowed = 1;
18843:                     } else {
18844:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18845:                             unless ($supplemental->{'hidden'}->{$id}) {
18846:                                 $allowed = 1;
18847:                                 last;
18848:                             }
18849:                         }
18850:                     }
18851:                     if (exists($env{'httpref.'.$src})) {
18852:                         if ($possdel) {
18853:                             unless ($allowed) {
18854:                                 &Apache::lonnet::delenv('httpref.'.$src);
18855:                             }
18856:                         }
18857:                     } elsif ($allowed) {
18858:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18859:                     }
18860:                 }
18861:             }
18862:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18863:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18864:             }
18865:         }
18866:     }
18867: }
18868: 
18869: sub get_supp_parameter {
18870:     my ($resparm,$name)=@_;
18871:     return if ($resparm eq '');
18872:     my $value=undef;
18873:     my $ptype=undef;
18874:     foreach (split('&&&',$resparm)) {
18875:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
18876:         if ($thisname eq $name) {
18877:             $value=$thisvalue;
18878:             $ptype=$thistype;
18879:         }
18880:     }
18881:     return $value;
18882: }
18883: 
18884: sub symb_to_docspath {
18885:     my ($symb,$navmapref) = @_;
18886:     return unless ($symb && ref($navmapref));
18887:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18888:     if ($resurl=~/\.(sequence|page)$/) {
18889:         $mapurl=$resurl;
18890:     } elsif ($resurl eq 'adm/navmaps') {
18891:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18892:     }
18893:     my $mapresobj;
18894:     unless (ref($$navmapref)) {
18895:         $$navmapref = Apache::lonnavmaps::navmap->new();
18896:     }
18897:     if (ref($$navmapref)) {
18898:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18899:     }
18900:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18901:     my $type=$2;
18902:     my $path;
18903:     if (ref($mapresobj)) {
18904:         my $pcslist = $mapresobj->map_hierarchy();
18905:         if ($pcslist ne '') {
18906:             foreach my $pc (split(/,/,$pcslist)) {
18907:                 next if ($pc <= 1);
18908:                 my $res = $$navmapref->getByMapPc($pc);
18909:                 if (ref($res)) {
18910:                     my $thisurl = $res->src();
18911:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18912:                     my $thistitle = $res->title();
18913:                     $path .= '&'.
18914:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18915:                              &escape($thistitle).
18916:                              ':'.$res->randompick().
18917:                              ':'.$res->randomout().
18918:                              ':'.$res->encrypted().
18919:                              ':'.$res->randomorder().
18920:                              ':'.$res->is_page();
18921:                 }
18922:             }
18923:         }
18924:         $path =~ s/^\&//;
18925:         my $maptitle = $mapresobj->title();
18926:         if ($mapurl eq 'default') {
18927:             $maptitle = 'Main Content';
18928:         }
18929:         $path .= (($path ne '')? '&' : '').
18930:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18931:                  &escape($maptitle).
18932:                  ':'.$mapresobj->randompick().
18933:                  ':'.$mapresobj->randomout().
18934:                  ':'.$mapresobj->encrypted().
18935:                  ':'.$mapresobj->randomorder().
18936:                  ':'.$mapresobj->is_page();
18937:     } else {
18938:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
18939:         my $ispage = (($type eq 'page')? 1 : '');
18940:         if ($mapurl eq 'default') {
18941:             $maptitle = 'Main Content';
18942:         }
18943:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18944:                 &escape($maptitle).':::::'.$ispage;
18945:     }
18946:     unless ($mapurl eq 'default') {
18947:         $path = 'default&'.
18948:                 &escape('Main Content').
18949:                 ':::::&'.$path;
18950:     }
18951:     return $path;
18952: }
18953: 
18954: sub validate_folderpath {
18955:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18956:     if ($env{'form.folderpath'} ne '') {
18957:         my @items = split(/\&/,$env{'form.folderpath'});
18958:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18959:         for (my $i=0; $i<@items; $i++) {
18960:             my $odd = $i%2;
18961:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18962:                 $badpath = 1;
18963:             } elsif ($odd && $supplementalflag) {
18964:                 my $idx = $i-1;
18965:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18966:                     my $esc_name = $1;
18967:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18968:                         $supppath .= '&'.$esc_name;
18969:                         $changed = 1;
18970:                     } else {
18971:                         $supppath .= '&'.$items[$i];
18972:                     }
18973:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18974:                     $changed = 1;
18975:                     my $is_hidden;
18976:                     unless ($got_supp) {
18977:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18978:                         if (ref($supplemental) eq 'HASH') {
18979:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
18980:                                 %supphidden = %{$supplemental->{'hidden'}};
18981:                             }
18982:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
18983:                                 %suppids = %{$supplemental->{'ids'}};
18984:                             }
18985:                         }
18986:                         $got_supp = 1;
18987:                     }
18988:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18989:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18990:                         if ($supphidden{$mapid}) {
18991:                             $is_hidden = 1;
18992:                         }
18993:                     }
18994:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18995:                 } else {
18996:                     $supppath .= '&'.$items[$i];
18997:                 }
18998:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18999:                 $badpath = 1;
19000:             } elsif ($supplementalflag) {
19001:                 $supppath .= '&'.$items[$i];
19002:             }
19003:             last if ($badpath);
19004:         }
19005:         if ($badpath) {
19006:             delete($env{'form.folderpath'});
19007:         } elsif ($changed && $supplementalflag) {
19008:             $supppath =~ s/^\&//;
19009:             $env{'form.folderpath'} = $supppath;
19010:         }
19011:     }
19012:     return;
19013: }
19014: 
19015: sub captcha_display {
19016:     my ($context,$lonhost,$defdom) = @_;
19017:     my ($output,$error);
19018:     my ($captcha,$pubkey,$privkey,$version) = 
19019:         &get_captcha_config($context,$lonhost,$defdom);
19020:     if ($captcha eq 'original') {
19021:         $output = &create_captcha();
19022:         unless ($output) {
19023:             $error = 'captcha';
19024:         }
19025:     } elsif ($captcha eq 'recaptcha') {
19026:         $output = &create_recaptcha($pubkey,$version);
19027:         unless ($output) {
19028:             $error = 'recaptcha';
19029:         }
19030:     }
19031:     return ($output,$error,$captcha,$version);
19032: }
19033: 
19034: sub captcha_response {
19035:     my ($context,$lonhost,$defdom) = @_;
19036:     my ($captcha_chk,$captcha_error);
19037:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19038:     if ($captcha eq 'original') {
19039:         ($captcha_chk,$captcha_error) = &check_captcha();
19040:     } elsif ($captcha eq 'recaptcha') {
19041:         $captcha_chk = &check_recaptcha($privkey,$version);
19042:     } else {
19043:         $captcha_chk = 1;
19044:     }
19045:     return ($captcha_chk,$captcha_error);
19046: }
19047: 
19048: sub get_captcha_config {
19049:     my ($context,$lonhost,$dom_in_effect) = @_;
19050:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19051:     my $hostname = &Apache::lonnet::hostname($lonhost);
19052:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19053:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19054:     if ($context eq 'usercreation') {
19055:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19056:         if (ref($domconfig{$context}) eq 'HASH') {
19057:             $hashtocheck = $domconfig{$context}{'cancreate'};
19058:             if (ref($hashtocheck) eq 'HASH') {
19059:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19060:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19061:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19062:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19063:                     }
19064:                     if ($privkey && $pubkey) {
19065:                         $captcha = 'recaptcha';
19066:                         $version = $hashtocheck->{'recaptchaversion'};
19067:                         if ($version ne '2') {
19068:                             $version = 1;
19069:                         }
19070:                     } else {
19071:                         $captcha = 'original';
19072:                     }
19073:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19074:                     $captcha = 'original';
19075:                 }
19076:             }
19077:         } else {
19078:             $captcha = 'captcha';
19079:         }
19080:     } elsif ($context eq 'login') {
19081:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19082:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19083:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19084:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19085:             if ($privkey && $pubkey) {
19086:                 $captcha = 'recaptcha';
19087:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19088:                 if ($version ne '2') {
19089:                     $version = 1; 
19090:                 }
19091:             } else {
19092:                 $captcha = 'original';
19093:             }
19094:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19095:             $captcha = 'original';
19096:         }
19097:     } elsif ($context eq 'passwords') {
19098:         if ($dom_in_effect) {
19099:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19100:             if ($passwdconf{'captcha'} eq 'recaptcha') {
19101:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19102:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19103:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
19104:                 }
19105:                 if ($privkey && $pubkey) {
19106:                     $captcha = 'recaptcha';
19107:                     $version = $passwdconf{'recaptchaversion'};
19108:                     if ($version ne '2') {
19109:                         $version = 1;
19110:                     }
19111:                 } else {
19112:                     $captcha = 'original';
19113:                 }
19114:             } elsif ($passwdconf{'captcha'} ne 'notused') {
19115:                 $captcha = 'original';
19116:             }
19117:         }
19118:     } 
19119:     return ($captcha,$pubkey,$privkey,$version);
19120: }
19121: 
19122: sub create_captcha {
19123:     my %captcha_params = &captcha_settings();
19124:     my ($output,$maxtries,$tries) = ('',10,0);
19125:     while ($tries < $maxtries) {
19126:         $tries ++;
19127:         my $captcha = Authen::Captcha->new (
19128:                                            output_folder => $captcha_params{'output_dir'},
19129:                                            data_folder   => $captcha_params{'db_dir'},
19130:                                           );
19131:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19132: 
19133:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19134:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19135:                       '<span class="LC_nobreak">'.
19136:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
19137:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19138:                       '</span><br />'.
19139:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19140:             last;
19141:         }
19142:     }
19143:     if ($output eq '') {
19144:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19145:     }
19146:     return $output;
19147: }
19148: 
19149: sub captcha_settings {
19150:     my %captcha_params = (
19151:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19152:                            www_output_dir => "/captchaspool",
19153:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19154:                            numchars       => '5',
19155:                          );
19156:     return %captcha_params;
19157: }
19158: 
19159: sub check_captcha {
19160:     my ($captcha_chk,$captcha_error);
19161:     my $code = $env{'form.code'};
19162:     my $md5sum = $env{'form.crypt'};
19163:     my %captcha_params = &captcha_settings();
19164:     my $captcha = Authen::Captcha->new(
19165:                       output_folder => $captcha_params{'output_dir'},
19166:                       data_folder   => $captcha_params{'db_dir'},
19167:                   );
19168:     $captcha_chk = $captcha->check_code($code,$md5sum);
19169:     my %captcha_hash = (
19170:                         0       => 'Code not checked (file error)',
19171:                        -1      => 'Failed: code expired',
19172:                        -2      => 'Failed: invalid code (not in database)',
19173:                        -3      => 'Failed: invalid code (code does not match crypt)',
19174:     );
19175:     if ($captcha_chk != 1) {
19176:         $captcha_error = $captcha_hash{$captcha_chk}
19177:     }
19178:     return ($captcha_chk,$captcha_error);
19179: }
19180: 
19181: sub create_recaptcha {
19182:     my ($pubkey,$version) = @_;
19183:     if ($version >= 2) {
19184:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19185:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19186:     } else {
19187:         my $use_ssl;
19188:         if ($ENV{'SERVER_PORT'} == 443) {
19189:             $use_ssl = 1;
19190:         }
19191:         my $captcha = Captcha::reCAPTCHA->new;
19192:         return $captcha->get_options_setter({theme => 'white'})."\n".
19193:                $captcha->get_html($pubkey,undef,$use_ssl).
19194:                &mt('If the text is hard to read, [_1] will replace them.',
19195:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19196:                '<br /><br />';
19197:     }
19198: }
19199: 
19200: sub check_recaptcha {
19201:     my ($privkey,$version) = @_;
19202:     my $captcha_chk;
19203:     my $ip = &Apache::lonnet::get_requestor_ip();
19204:     if ($version >= 2) {
19205:         my %info = (
19206:                      secret   => $privkey, 
19207:                      response => $env{'form.g-recaptcha-response'},
19208:                      remoteip => $ip,
19209:                    );
19210:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19211:         $request->content(join('&',map {
19212:                          my $name = escape($_);
19213:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
19214:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
19215:                          : &escape($info{$_}) );
19216:         } keys(%info)));
19217:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19218:         if ($response->is_success)  {
19219:             my $data = JSON::DWIW->from_json($response->decoded_content);
19220:             if (ref($data) eq 'HASH') {
19221:                 if ($data->{'success'}) {
19222:                     $captcha_chk = 1;
19223:                 }
19224:             }
19225:         }
19226:     } else {
19227:         my $captcha = Captcha::reCAPTCHA->new;
19228:         my $captcha_result =
19229:             $captcha->check_answer(
19230:                                     $privkey,
19231:                                     $ip,
19232:                                     $env{'form.recaptcha_challenge_field'},
19233:                                     $env{'form.recaptcha_response_field'},
19234:                                   );
19235:         if ($captcha_result->{is_valid}) {
19236:             $captcha_chk = 1;
19237:         }
19238:     }
19239:     return $captcha_chk;
19240: }
19241: 
19242: sub emailusername_info {
19243:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19244:     my %titles = &Apache::lonlocal::texthash (
19245:                      lastname      => 'Last Name',
19246:                      firstname     => 'First Name',
19247:                      institution   => 'School/college/university',
19248:                      location      => "School's city, state/province, country",
19249:                      web           => "School's web address",
19250:                      officialemail => 'E-mail address at institution (if different)',
19251:                      id            => 'Student/Employee ID',
19252:                  );
19253:     return (\@fields,\%titles);
19254: }
19255: 
19256: sub cleanup_html {
19257:     my ($incoming) = @_;
19258:     my $outgoing;
19259:     if ($incoming ne '') {
19260:         $outgoing = $incoming;
19261:         $outgoing =~ s/;/&#059;/g;
19262:         $outgoing =~ s/\#/&#035;/g;
19263:         $outgoing =~ s/\&/&#038;/g;
19264:         $outgoing =~ s/</&#060;/g;
19265:         $outgoing =~ s/>/&#062;/g;
19266:         $outgoing =~ s/\(/&#040/g;
19267:         $outgoing =~ s/\)/&#041;/g;
19268:         $outgoing =~ s/"/&#034;/g;
19269:         $outgoing =~ s/'/&#039;/g;
19270:         $outgoing =~ s/\$/&#036;/g;
19271:         $outgoing =~ s{/}{&#047;}g;
19272:         $outgoing =~ s/=/&#061;/g;
19273:         $outgoing =~ s/\\/&#092;/g
19274:     }
19275:     return $outgoing;
19276: }
19277: 
19278: # Checks for critical messages and returns a redirect url if one exists.
19279: # $interval indicates how often to check for messages.
19280: # $context is the calling context -- roles, grades, contents, menu or flip. 
19281: sub critical_redirect {
19282:     my ($interval,$context) = @_;
19283:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19284:         return ();
19285:     }
19286:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
19287:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19288:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19289:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19290:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19291:             if ($blocked) {
19292:                 my $checkrole = "cm./$cdom/$cnum";
19293:                 if ($env{'request.course.sec'} ne '') {
19294:                     $checkrole .= "/$env{'request.course.sec'}";
19295:                 }
19296:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19297:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19298:                     return;
19299:                 }
19300:             }
19301:         }
19302:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
19303:                                         $env{'user.name'});
19304:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19305:         my $redirecturl;
19306:         if ($what[0]) {
19307: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19308: 	        $redirecturl='/adm/email?critical=display';
19309: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
19310:                 return (1, $url);
19311:             }
19312:         }
19313:     } 
19314:     return ();
19315: }
19316: 
19317: # Use:
19318: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19319: #
19320: ##################################################
19321: #          password associated functions         #
19322: ##################################################
19323: sub des_keys {
19324:     # Make a new key for DES encryption.
19325:     # Each key has two parts which are returned separately.
19326:     # Please note:  Each key must be passed through the &hex function
19327:     # before it is output to the web browser.  The hex versions cannot
19328:     # be used to decrypt.
19329:     my @hexstr=('0','1','2','3','4','5','6','7',
19330:                 '8','9','a','b','c','d','e','f');
19331:     my $lkey='';
19332:     for (0..7) {
19333:         $lkey.=$hexstr[rand(15)];
19334:     }
19335:     my $ukey='';
19336:     for (0..7) {
19337:         $ukey.=$hexstr[rand(15)];
19338:     }
19339:     return ($lkey,$ukey);
19340: }
19341: 
19342: sub des_decrypt {
19343:     my ($key,$cyphertext) = @_;
19344:     my $keybin=pack("H16",$key);
19345:     my $cypher;
19346:     if ($Crypt::DES::VERSION>=2.03) {
19347:         $cypher=new Crypt::DES $keybin;
19348:     } else {
19349:         $cypher=new DES $keybin;
19350:     }
19351:     my $plaintext='';
19352:     my $cypherlength = length($cyphertext);
19353:     my $numchunks = int($cypherlength/32);
19354:     for (my $j=0; $j<$numchunks; $j++) {
19355:         my $start = $j*32;
19356:         my $cypherblock = substr($cyphertext,$start,32);
19357:         my $chunk =
19358:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19359:         $chunk .=
19360:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19361:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19362:         $plaintext .= $chunk;
19363:     }
19364:     return $plaintext;
19365: }
19366: 
19367: sub get_requested_shorturls {
19368:     my ($cdom,$cnum,$navmap) = @_;
19369:     return unless (ref($navmap));
19370:     my ($numnew,$errors);
19371:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19372:     if (@toshorten) {
19373:         my (%maps,%resources,%titles);
19374:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19375:                                                                'shorturls',$cdom,$cnum);
19376:         if (keys(%resources)) {
19377:             my %tocreate;
19378:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
19379:                 my $symb = $resources{$item};
19380:                 if ($symb) {
19381:                     $tocreate{$cnum.'&'.$symb} = 1;
19382:                 }
19383:             }
19384:             if (keys(%tocreate)) {
19385:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19386:                                                       \%tocreate);
19387:             }
19388:         }
19389:     }
19390:     return ($numnew,$errors);
19391: }
19392: 
19393: sub make_short_symbs {
19394:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19395:     my ($numnew,@errors);
19396:     if (ref($tocreateref) eq 'HASH') {
19397:         my %tocreate = %{$tocreateref};
19398:         if (keys(%tocreate)) {
19399:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19400:             my $su = Short::URL->new(no_vowels => 1);
19401:             my $init = '';
19402:             my (%newunique,%addcourse,%courseonly,%failed);
19403:             # get lock on tiny db
19404:             my $now = time;
19405:             if ($lockuser eq '') {
19406:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19407:             }
19408:             my $lockhash = {
19409:                                 "lock\0$now" => $lockuser,
19410:                             };
19411:             my $tries = 0;
19412:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19413:             my ($code,$error);
19414:             while (($gotlock ne 'ok') && ($tries<3)) {
19415:                 $tries ++;
19416:                 sleep 1;
19417:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19418:             }
19419:             if ($gotlock eq 'ok') {
19420:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19421:                                        \%addcourse,\%courseonly,\%failed);
19422:                 if (keys(%failed)) {
19423:                     my $numfailed = scalar(keys(%failed));
19424:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19425:                 }
19426:                 if (keys(%newunique)) {
19427:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19428:                     if ($putres eq 'ok') {
19429:                         $numnew = scalar(keys(%newunique));
19430:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19431:                         unless ($newputres eq 'ok') {
19432:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
19433:                         }
19434:                     } else {
19435:                         push(@errors,&mt('error: could not store unique six character URLs'));
19436:                     }
19437:                 }
19438:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19439:                 unless ($dellockres eq 'ok') {
19440:                     push(@errors,&mt('error: could not release lockfile'));
19441:                 }
19442:             } else {
19443:                 push(@errors,&mt('error: could not obtain lockfile'));
19444:             }
19445:             if (keys(%courseonly)) {
19446:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19447:                 if ($result ne 'ok') {
19448:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
19449:                 }
19450:             }
19451:         }
19452:     }
19453:     return ($numnew,\@errors);
19454: }
19455: 
19456: sub shorten_symbs {
19457:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19458:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19459:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19460:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19461:     my (%possibles,%collisions);
19462:     foreach my $key (keys(%{$tocreate})) {
19463:         my $num = String::CRC32::crc32($key);
19464:         my $tiny = $su->encode($num,$init);
19465:         if ($tiny) {
19466:             $possibles{$tiny} = $key;
19467:         }
19468:     }
19469:     if (!$init) {
19470:         $init = 1;
19471:     } else {
19472:         $init ++;
19473:     }
19474:     if (keys(%possibles)) {
19475:         my @posstiny = keys(%possibles);
19476:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19477:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19478:         if (keys(%currtiny)) {
19479:             foreach my $key (keys(%currtiny)) {
19480:                 next if ($currtiny{$key} eq '');
19481:                 if ($currtiny{$key} eq $possibles{$key}) {
19482:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19483:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19484:                         $courseonly->{$tsymb} = $key;
19485:                     }
19486:                 } else {
19487:                     $collisions{$possibles{$key}} = 1;
19488:                 }
19489:                 delete($possibles{$key});
19490:             }
19491:         }
19492:         foreach my $key (keys(%possibles)) {
19493:             $newunique->{$key} = $possibles{$key};
19494:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19495:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19496:                 $addcourse->{$tsymb} = $key;
19497:             }
19498:         }
19499:     }
19500:     if (keys(%collisions)) {
19501:         if ($init <5) {
19502:             if (!$init) {
19503:                 $init = 1;
19504:             } else {
19505:                 $init ++;
19506:             }
19507:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19508:                                    $newunique,$addcourse,$courseonly,$failed);
19509:         } else {
19510:             foreach my $key (keys(%collisions)) {
19511:                 $failed->{$key} = 1;
19512:             }
19513:         }
19514:     }
19515:     return $init;
19516: }
19517: 
19518: sub is_nonframeable {
19519:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19520:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19521:     return if (($remprotocol eq '') || ($remhost eq ''));
19522: 
19523:     $remprotocol = lc($remprotocol);
19524:     $remhost = lc($remhost);
19525:     my $remport = 80;
19526:     if ($remprotocol eq 'https') {
19527:         $remport = 443;
19528:     }
19529:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19530:     if ($cached) {
19531:         unless ($nocache) {
19532:             if ($result) {
19533:                 return 1;
19534:             } else {
19535:                 return 0;
19536:             }
19537:         }
19538:     }
19539:     my $uselink;
19540:     my $request = new HTTP::Request('HEAD',$url);
19541:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19542:     if ($response->is_success()) {
19543:         my $secpolicy = lc($response->header('content-security-policy'));
19544:         my $xframeop = lc($response->header('x-frame-options'));
19545:         $secpolicy =~ s/^\s+|\s+$//g;
19546:         $xframeop =~ s/^\s+|\s+$//g;
19547:         if (($secpolicy ne '') || ($xframeop ne '')) {
19548:             my $remotehost = $remprotocol.'://'.$remhost;
19549:             my ($origin,$protocol,$port);
19550:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19551:                 $port = $ENV{'SERVER_PORT'};
19552:             } else {
19553:                 $port = 80;
19554:             }
19555:             if ($absolute eq '') {
19556:                 $protocol = 'http:';
19557:                 if ($port == 443) {
19558:                     $protocol = 'https:';
19559:                 }
19560:                 $origin = $protocol.'//'.lc($hostname);
19561:             } else {
19562:                 $origin = lc($absolute);
19563:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19564:             }
19565:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19566:                 my $framepolicy = $1;
19567:                 $framepolicy =~ s/^\s+|\s+$//g;
19568:                 my @policies = split(/\s+/,$framepolicy);
19569:                 if (@policies) {
19570:                     if (grep(/^\Q'none'\E$/,@policies)) {
19571:                         $uselink = 1;
19572:                     } else {
19573:                         $uselink = 1;
19574:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19575:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19576:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19577:                             undef($uselink);
19578:                         }
19579:                         if ($uselink) {
19580:                             if (grep(/^\Q'self'\E$/,@policies)) {
19581:                                 if (($origin ne '') && ($remotehost eq $origin)) {
19582:                                     undef($uselink);
19583:                                 }
19584:                             }
19585:                         }
19586:                         if ($uselink) {
19587:                             my @possok;
19588:                             if ($ip ne '') {
19589:                                 push(@possok,$ip);
19590:                             }
19591:                             my $hoststr = '';
19592:                             foreach my $part (reverse(split(/\./,$hostname))) {
19593:                                 if ($hoststr eq '') {
19594:                                     $hoststr = $part;
19595:                                 } else {
19596:                                     $hoststr = "$part.$hoststr";
19597:                                 }
19598:                                 if ($hoststr eq $hostname) {
19599:                                     push(@possok,$hostname);
19600:                                 } else {
19601:                                     push(@possok,"*.$hoststr");
19602:                                 }
19603:                             }
19604:                             if (@possok) {
19605:                                 foreach my $poss (@possok) {
19606:                                     last if (!$uselink);
19607:                                     foreach my $policy (@policies) {
19608:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19609:                                             undef($uselink);
19610:                                             last;
19611:                                         }
19612:                                     }
19613:                                 }
19614:                             }
19615:                         }
19616:                     }
19617:                 }
19618:             } elsif ($xframeop ne '') {
19619:                 $uselink = 1;
19620:                 my @policies = split(/\s*,\s*/,$xframeop);
19621:                 if (@policies) {
19622:                     unless (grep(/^deny$/,@policies)) {
19623:                         if ($origin ne '') {
19624:                             if (grep(/^sameorigin$/,@policies)) {
19625:                                 if ($remotehost eq $origin) {
19626:                                     undef($uselink);
19627:                                 }
19628:                             }
19629:                             if ($uselink) {
19630:                                 foreach my $policy (@policies) {
19631:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
19632:                                         my $allowfrom = $1;
19633:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19634:                                             undef($uselink);
19635:                                             last;
19636:                                         }
19637:                                     }
19638:                                 }
19639:                             }
19640:                         }
19641:                     }
19642:                 }
19643:             }
19644:         }
19645:     }
19646:     if ($nocache) {
19647:         if ($cached) {
19648:             my $devalidate;
19649:             if ($uselink && !$result) {
19650:                 $devalidate = 1;
19651:             } elsif (!$uselink && $result) {
19652:                 $devalidate = 1;
19653:             }
19654:             if ($devalidate) {
19655:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19656:             }
19657:         }
19658:     } else {
19659:         if ($uselink) {
19660:             $result = 1;
19661:         } else {
19662:             $result = 0;
19663:         }
19664:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19665:     }
19666:     return $uselink;
19667: }
19668: 
19669: sub page_menu {
19670:     my ($menucolls,$menunum) = @_;
19671:     my %menu;
19672:     foreach my $item (split(/;/,$menucolls)) {
19673:         my ($num,$value) = split(/\%/,$item);
19674:         if ($num eq $menunum) {
19675:             my @entries = split(/\&/,$value);
19676:             foreach my $entry (@entries) {
19677:                 my ($name,$fields) = split(/=/,$entry);
19678:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19679:                     $menu{$name} = $fields;
19680:                 } else {
19681:                     my @shown;
19682:                     if ($fields =~ /,/) {
19683:                         @shown = split(/,/,$fields);
19684:                     } else {
19685:                         @shown = ($fields);
19686:                     }
19687:                     if (@shown) {
19688:                         foreach my $field (@shown) {
19689:                             next if ($field eq '');
19690:                             $menu{$field} = 1;
19691:                         }
19692:                     }
19693:                 }
19694:             }
19695:         }
19696:     }
19697:     return %menu;
19698: }
19699: 
19700: 1;
19701: __END__;
19702: 

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