File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1073: download - view: text, annotated - select for diffs
Wed Apr 25 21:22:01 2012 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- lond uses client's LON-CAPA version to determine whether checking a user's
  course roles for version requirements needs to occur -- will be skipped
  on 2.10 and later, as it occurs client-side in rolesinit when building
  roles/courses display.
- No longer require sixth arg for lonnet::dump
    (frozen hash containing skipcheck => 1).
  - Reverse changes in loncommon.pm 1.982, longroup.pm rev 1.26, 1.27
    loncreateuser.pm rev 1.350, lonuserutils.pm 1.127, 1.137,
    lonnet.pm rev 1.1086, 1.1078 which used the "$extra" sixth arg.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1073 2012/04/25 21:22:01 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %latex_language;		# For choosing hyphenation in <transl..>
  158: my %latex_language_bykey;	# for choosing hyphenation from metadata
  159: my %cprtag;
  160: my %scprtag;
  161: my %fe; my %fd; my %fm;
  162: my %category_extensions;
  163: 
  164: # ---------------------------------------------- Thesaurus variables
  165: #
  166: # %Keywords:
  167: #      A hash used by &keyword to determine if a word is considered a keyword.
  168: # $thesaurus_db_file 
  169: #      Scalar containing the full path to the thesaurus database.
  170: 
  171: my %Keywords;
  172: my $thesaurus_db_file;
  173: 
  174: #
  175: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  176: # thesaurus.tab, and filecategories.tab.
  177: #
  178: BEGIN {
  179:     # Variable initialization
  180:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  181:     #
  182:     unless ($readit) {
  183: # ------------------------------------------------------------------- languages
  184:     {
  185:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  186:                                    '/language.tab';
  187:         if ( open(my $fh,"<$langtabfile") ) {
  188:             while (my $line = <$fh>) {
  189:                 next if ($line=~/^\#/);
  190:                 chomp($line);
  191:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  192:                 $language{$key}=$val.' - '.$enc;
  193:                 if ($sup) {
  194:                     $supported_language{$key}=$sup;
  195:                 }
  196: 		if ($latex) {
  197: 		    $latex_language_bykey{$key} = $latex;
  198: 		    $latex_language{$two} = $latex;
  199: 		}
  200:             }
  201:             close($fh);
  202:         }
  203:     }
  204: # ------------------------------------------------------------------ copyrights
  205:     {
  206:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  207:                                   '/copyright.tab';
  208:         if ( open (my $fh,"<$copyrightfile") ) {
  209:             while (my $line = <$fh>) {
  210:                 next if ($line=~/^\#/);
  211:                 chomp($line);
  212:                 my ($key,$val)=(split(/\s+/,$line,2));
  213:                 $cprtag{$key}=$val;
  214:             }
  215:             close($fh);
  216:         }
  217:     }
  218: # ----------------------------------------------------------- source copyrights
  219:     {
  220:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  221:                                   '/source_copyright.tab';
  222:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  223:             while (my $line = <$fh>) {
  224:                 next if ($line =~ /^\#/);
  225:                 chomp($line);
  226:                 my ($key,$val)=(split(/\s+/,$line,2));
  227:                 $scprtag{$key}=$val;
  228:             }
  229:             close($fh);
  230:         }
  231:     }
  232: 
  233: # -------------------------------------------------------------- default domain designs
  234:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  235:     my $designfile = $designdir.'/default.tab';
  236:     if ( open (my $fh,"<$designfile") ) {
  237:         while (my $line = <$fh>) {
  238:             next if ($line =~ /^\#/);
  239:             chomp($line);
  240:             my ($key,$val)=(split(/\=/,$line));
  241:             if ($val) { $defaultdesign{$key}=$val; }
  242:         }
  243:         close($fh);
  244:     }
  245: 
  246: # ------------------------------------------------------------- file categories
  247:     {
  248:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  249:                                   '/filecategories.tab';
  250:         if ( open (my $fh,"<$categoryfile") ) {
  251: 	    while (my $line = <$fh>) {
  252: 		next if ($line =~ /^\#/);
  253: 		chomp($line);
  254:                 my ($extension,$category)=(split(/\s+/,$line,2));
  255:                 push @{$category_extensions{lc($category)}},$extension;
  256:             }
  257:             close($fh);
  258:         }
  259: 
  260:     }
  261: # ------------------------------------------------------------------ file types
  262:     {
  263:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                '/filetypes.tab';
  265:         if ( open (my $fh,"<$typesfile") ) {
  266:             while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  270:                 if ($descr ne '') {
  271:                     $fe{$ending}=lc($emb);
  272:                     $fd{$ending}=$descr;
  273:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  274:                 }
  275:             }
  276:             close($fh);
  277:         }
  278:     }
  279:     &Apache::lonnet::logthis(
  280:              "<span style='color:yellow;'>INFO: Read file types</span>");
  281:     $readit=1;
  282:     }  # end of unless($readit) 
  283:     
  284: }
  285: 
  286: ###############################################################
  287: ##           HTML and Javascript Helper Functions            ##
  288: ###############################################################
  289: 
  290: =pod 
  291: 
  292: =head1 HTML and Javascript Functions
  293: 
  294: =over 4
  295: 
  296: =item * &browser_and_searcher_javascript()
  297: 
  298: X<browsing, javascript>X<searching, javascript>Returns a string
  299: containing javascript with two functions, C<openbrowser> and
  300: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  301: tags.
  302: 
  303: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  304: 
  305: inputs: formname, elementname, only, omit
  306: 
  307: formname and elementname indicate the name of the html form and name of
  308: the element that the results of the browsing selection are to be placed in. 
  309: 
  310: Specifying 'only' will restrict the browser to displaying only files
  311: with the given extension.  Can be a comma separated list.
  312: 
  313: Specifying 'omit' will restrict the browser to NOT displaying files
  314: with the given extension.  Can be a comma separated list.
  315: 
  316: =item * &opensearcher(formname,elementname) [javascript]
  317: 
  318: Inputs: formname, elementname
  319: 
  320: formname and elementname specify the name of the html form and the name
  321: of the element the selection from the search results will be placed in.
  322: 
  323: =cut
  324: 
  325: sub browser_and_searcher_javascript {
  326:     my ($mode)=@_;
  327:     if (!defined($mode)) { $mode='edit'; }
  328:     my $resurl=&escape_single(&lastresurl());
  329:     return <<END;
  330: // <!-- BEGIN LON-CAPA Internal
  331:     var editbrowser = null;
  332:     function openbrowser(formname,elementname,only,omit,titleelement) {
  333:         var url = '$resurl/?';
  334:         if (editbrowser == null) {
  335:             url += 'launch=1&';
  336:         }
  337:         url += 'catalogmode=interactive&';
  338:         url += 'mode=$mode&';
  339:         url += 'inhibitmenu=yes&';
  340:         url += 'form=' + formname + '&';
  341:         if (only != null) {
  342:             url += 'only=' + only + '&';
  343:         } else {
  344:             url += 'only=&';
  345: 	}
  346:         if (omit != null) {
  347:             url += 'omit=' + omit + '&';
  348:         } else {
  349:             url += 'omit=&';
  350: 	}
  351:         if (titleelement != null) {
  352:             url += 'titleelement=' + titleelement + '&';
  353:         } else {
  354: 	    url += 'titleelement=&';
  355: 	}
  356:         url += 'element=' + elementname + '';
  357:         var title = 'Browser';
  358:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  359:         options += ',width=700,height=600';
  360:         editbrowser = open(url,title,options,'1');
  361:         editbrowser.focus();
  362:     }
  363:     var editsearcher;
  364:     function opensearcher(formname,elementname,titleelement) {
  365:         var url = '/adm/searchcat?';
  366:         if (editsearcher == null) {
  367:             url += 'launch=1&';
  368:         }
  369:         url += 'catalogmode=interactive&';
  370:         url += 'mode=$mode&';
  371:         url += 'form=' + formname + '&';
  372:         if (titleelement != null) {
  373:             url += 'titleelement=' + titleelement + '&';
  374:         } else {
  375: 	    url += 'titleelement=&';
  376: 	}
  377:         url += 'element=' + elementname + '';
  378:         var title = 'Search';
  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  380:         options += ',width=700,height=600';
  381:         editsearcher = open(url,title,options,'1');
  382:         editsearcher.focus();
  383:     }
  384: // END LON-CAPA Internal -->
  385: END
  386: }
  387: 
  388: sub lastresurl {
  389:     if ($env{'environment.lastresurl'}) {
  390: 	return $env{'environment.lastresurl'}
  391:     } else {
  392: 	return '/res';
  393:     }
  394: }
  395: 
  396: sub storeresurl {
  397:     my $resurl=&Apache::lonnet::clutter(shift);
  398:     unless ($resurl=~/^\/res/) { return 0; }
  399:     $resurl=~s/\/$//;
  400:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  401:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  402:     return 1;
  403: }
  404: 
  405: sub studentbrowser_javascript {
  406:    unless (
  407:             (($env{'request.course.id'}) && 
  408:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  409: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  410: 					  '/'.$env{'request.course.sec'})
  411: 	      ))
  412:          || ($env{'request.role'}=~/^(au|dc|su)/)
  413:           ) { return ''; }  
  414:    return (<<'ENDSTDBRW');
  415: <script type="text/javascript" language="Javascript">
  416: // <![CDATA[
  417:     var stdeditbrowser;
  418:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  419:         var url = '/adm/pickstudent?';
  420:         var filter;
  421: 	if (!ignorefilter) {
  422: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  423: 	}
  424:         if (filter != null) {
  425:            if (filter != '') {
  426:                url += 'filter='+filter+'&';
  427: 	   }
  428:         }
  429:         url += 'form=' + formname + '&unameelement='+uname+
  430:                                     '&udomelement='+udom+
  431:                                     '&clicker='+clicker;
  432: 	if (roleflag) { url+="&roles=1"; }
  433:         if (courseadvonly) { url+="&courseadvonly=1"; }
  434:         var title = 'Student_Browser';
  435:         var options = 'scrollbars=1,resizable=1,menubar=0';
  436:         options += ',width=700,height=600';
  437:         stdeditbrowser = open(url,title,options,'1');
  438:         stdeditbrowser.focus();
  439:     }
  440: // ]]>
  441: </script>
  442: ENDSTDBRW
  443: }
  444: 
  445: sub resourcebrowser_javascript {
  446:    unless ($env{'request.course.id'}) { return ''; }
  447:    return (<<'ENDRESBRW');
  448: <script type="text/javascript" language="Javascript">
  449: // <![CDATA[
  450:     var reseditbrowser;
  451:     function openresbrowser(formname,reslink) {
  452:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  453:         var title = 'Resource_Browser';
  454:         var options = 'scrollbars=1,resizable=1,menubar=0';
  455:         options += ',width=700,height=500';
  456:         reseditbrowser = open(url,title,options,'1');
  457:         reseditbrowser.focus();
  458:     }
  459: // ]]>
  460: </script>
  461: ENDRESBRW
  462: }
  463: 
  464: sub selectstudent_link {
  465:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  466:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  467:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  468:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  469:    if ($env{'request.course.id'}) {  
  470:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  471: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  472: 					'/'.$env{'request.course.sec'})) {
  473: 	   return '';
  474:        }
  475:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  476:        if ($courseadvonly)  {
  477:            $callargs .= ",'',1,1";
  478:        }
  479:        return '<span class="LC_nobreak">'.
  480:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  481:               &mt('Select User').'</a></span>';
  482:    }
  483:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  484:        $callargs .= ",'',1"; 
  485:        return '<span class="LC_nobreak">'.
  486:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  487:               &mt('Select User').'</a></span>';
  488:    }
  489:    return '';
  490: }
  491: 
  492: sub selectresource_link {
  493:    my ($form,$reslink,$arg)=@_;
  494:    
  495:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  496:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  497:    unless ($env{'request.course.id'}) { return $arg; }
  498:    return '<span class="LC_nobreak">'.
  499:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  500:               $arg.'</a></span>';
  501: }
  502: 
  503: 
  504: 
  505: sub authorbrowser_javascript {
  506:     return <<"ENDAUTHORBRW";
  507: <script type="text/javascript" language="JavaScript">
  508: // <![CDATA[
  509: var stdeditbrowser;
  510: 
  511: function openauthorbrowser(formname,udom) {
  512:     var url = '/adm/pickauthor?';
  513:     url += 'form='+formname+'&roledom='+udom;
  514:     var title = 'Author_Browser';
  515:     var options = 'scrollbars=1,resizable=1,menubar=0';
  516:     options += ',width=700,height=600';
  517:     stdeditbrowser = open(url,title,options,'1');
  518:     stdeditbrowser.focus();
  519: }
  520: 
  521: // ]]>
  522: </script>
  523: ENDAUTHORBRW
  524: }
  525: 
  526: sub coursebrowser_javascript {
  527:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  528:     my $wintitle = 'Course_Browser';
  529:     if ($crstype eq 'Community') {
  530:         $wintitle = 'Community_Browser';
  531:     }
  532:     my $id_functions = &javascript_index_functions();
  533:     my $output = '
  534: <script type="text/javascript" language="JavaScript">
  535: // <![CDATA[
  536:     var stdeditbrowser;'."\n";
  537: 
  538:     $output .= <<"ENDSTDBRW";
  539:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  540:         var url = '/adm/pickcourse?';
  541:         var formid = getFormIdByName(formname);
  542:         var domainfilter = getDomainFromSelectbox(formname,udom);
  543:         if (domainfilter != null) {
  544:            if (domainfilter != '') {
  545:                url += 'domainfilter='+domainfilter+'&';
  546: 	   }
  547:         }
  548:         url += 'form=' + formname + '&cnumelement='+uname+
  549: 	                            '&cdomelement='+udom+
  550:                                     '&cnameelement='+desc;
  551:         if (extra_element !=null && extra_element != '') {
  552:             if (formname == 'rolechoice' || formname == 'studentform') {
  553:                 url += '&roleelement='+extra_element;
  554:                 if (domainfilter == null || domainfilter == '') {
  555:                     url += '&domainfilter='+extra_element;
  556:                 }
  557:             }
  558:             else {
  559:                 if (formname == 'portform') {
  560:                     url += '&setroles='+extra_element;
  561:                 } else {
  562:                     if (formname == 'rules') {
  563:                         url += '&fixeddom='+extra_element; 
  564:                     }
  565:                 }
  566:             }     
  567:         }
  568:         if (type != null && type != '') {
  569:             url += '&type='+type;
  570:         }
  571:         if (type_elem != null && type_elem != '') {
  572:             url += '&typeelement='+type_elem;
  573:         }
  574:         if (formname == 'ccrs') {
  575:             var ownername = document.forms[formid].ccuname.value;
  576:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  577:             url += '&cloner='+ownername+':'+ownerdom;
  578:         }
  579:         if (multflag !=null && multflag != '') {
  580:             url += '&multiple='+multflag;
  581:         }
  582:         var title = '$wintitle';
  583:         var options = 'scrollbars=1,resizable=1,menubar=0';
  584:         options += ',width=700,height=600';
  585:         stdeditbrowser = open(url,title,options,'1');
  586:         stdeditbrowser.focus();
  587:     }
  588: $id_functions
  589: ENDSTDBRW
  590:     if (($sec_element ne '') || ($role_element ne '')) {
  591:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  592:     }
  593:     $output .= '
  594: // ]]>
  595: </script>';
  596:     return $output;
  597: }
  598: 
  599: sub javascript_index_functions {
  600:     return <<"ENDJS";
  601: 
  602: function getFormIdByName(formname) {
  603:     for (var i=0;i<document.forms.length;i++) {
  604:         if (document.forms[i].name == formname) {
  605:             return i;
  606:         }
  607:     }
  608:     return -1;
  609: }
  610: 
  611: function getIndexByName(formid,item) {
  612:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  613:         if (document.forms[formid].elements[i].name == item) {
  614:             return i;
  615:         }
  616:     }
  617:     return -1;
  618: }
  619: 
  620: function getDomainFromSelectbox(formname,udom) {
  621:     var userdom;
  622:     var formid = getFormIdByName(formname);
  623:     if (formid > -1) {
  624:         var domid = getIndexByName(formid,udom);
  625:         if (domid > -1) {
  626:             if (document.forms[formid].elements[domid].type == 'select-one') {
  627:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  628:             }
  629:             if (document.forms[formid].elements[domid].type == 'hidden') {
  630:                 userdom=document.forms[formid].elements[domid].value;
  631:             }
  632:         }
  633:     }
  634:     return userdom;
  635: }
  636: 
  637: ENDJS
  638: 
  639: }
  640: 
  641: sub javascript_array_indexof {
  642:     return <<ENDJS;
  643: <script type="text/javascript" language="JavaScript">
  644: // <![CDATA[
  645: 
  646: if (!Array.prototype.indexOf) {
  647:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  648:         "use strict";
  649:         if (this === void 0 || this === null) {
  650:             throw new TypeError();
  651:         }
  652:         var t = Object(this);
  653:         var len = t.length >>> 0;
  654:         if (len === 0) {
  655:             return -1;
  656:         }
  657:         var n = 0;
  658:         if (arguments.length > 0) {
  659:             n = Number(arguments[1]);
  660:             if (n !== n) { // shortcut for verifying if it's NaN
  661:                 n = 0;
  662:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  663:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  664:             }
  665:         }
  666:         if (n >= len) {
  667:             return -1;
  668:         }
  669:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  670:         for (; k < len; k++) {
  671:             if (k in t && t[k] === searchElement) {
  672:                 return k;
  673:             }
  674:         }
  675:         return -1;
  676:     }
  677: }
  678: 
  679: // ]]>
  680: </script>
  681: 
  682: ENDJS
  683: 
  684: }
  685: 
  686: sub userbrowser_javascript {
  687:     my $id_functions = &javascript_index_functions();
  688:     return <<"ENDUSERBRW";
  689: 
  690: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  691:     var url = '/adm/pickuser?';
  692:     var userdom = getDomainFromSelectbox(formname,udom);
  693:     if (userdom != null) {
  694:        if (userdom != '') {
  695:            url += 'srchdom='+userdom+'&';
  696:        }
  697:     }
  698:     url += 'form=' + formname + '&unameelement='+uname+
  699:                                 '&udomelement='+udom+
  700:                                 '&ulastelement='+ulast+
  701:                                 '&ufirstelement='+ufirst+
  702:                                 '&uemailelement='+uemail+
  703:                                 '&hideudomelement='+hideudom+
  704:                                 '&coursedom='+crsdom;
  705:     if ((caller != null) && (caller != undefined)) {
  706:         url += '&caller='+caller;
  707:     }
  708:     var title = 'User_Browser';
  709:     var options = 'scrollbars=1,resizable=1,menubar=0';
  710:     options += ',width=700,height=600';
  711:     var stdeditbrowser = open(url,title,options,'1');
  712:     stdeditbrowser.focus();
  713: }
  714: 
  715: function fix_domain (formname,udom,origdom,uname) {
  716:     var formid = getFormIdByName(formname);
  717:     if (formid > -1) {
  718:         var unameid = getIndexByName(formid,uname);
  719:         var domid = getIndexByName(formid,udom);
  720:         var hidedomid = getIndexByName(formid,origdom);
  721:         if (hidedomid > -1) {
  722:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  723:             var unameval = document.forms[formid].elements[unameid].value;
  724:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  725:                 if (domid > -1) {
  726:                     var slct = document.forms[formid].elements[domid];
  727:                     if (slct.type == 'select-one') {
  728:                         var i;
  729:                         for (i=0;i<slct.length;i++) {
  730:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  731:                         }
  732:                     }
  733:                     if (slct.type == 'hidden') {
  734:                         slct.value = fixeddom;
  735:                     }
  736:                 }
  737:             }
  738:         }
  739:     }
  740:     return;
  741: }
  742: 
  743: $id_functions
  744: ENDUSERBRW
  745: }
  746: 
  747: sub setsec_javascript {
  748:     my ($sec_element,$formname,$role_element) = @_;
  749:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  750:         $communityrolestr);
  751:     if ($role_element ne '') {
  752:         my @allroles = ('st','ta','ep','in','ad');
  753:         foreach my $crstype ('Course','Community') {
  754:             if ($crstype eq 'Community') {
  755:                 foreach my $role (@allroles) {
  756:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  757:                 }
  758:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  759:             } else {
  760:                 foreach my $role (@allroles) {
  761:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  762:                 }
  763:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  764:             }
  765:         }
  766:         $rolestr = '"'.join('","',@allroles).'"';
  767:         $courserolestr = '"'.join('","',@courserolenames).'"';
  768:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  769:     }
  770:     my $setsections = qq|
  771: function setSect(sectionlist) {
  772:     var sectionsArray = new Array();
  773:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  774:         sectionsArray = sectionlist.split(",");
  775:     }
  776:     var numSections = sectionsArray.length;
  777:     document.$formname.$sec_element.length = 0;
  778:     if (numSections == 0) {
  779:         document.$formname.$sec_element.multiple=false;
  780:         document.$formname.$sec_element.size=1;
  781:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  782:     } else {
  783:         if (numSections == 1) {
  784:             document.$formname.$sec_element.multiple=false;
  785:             document.$formname.$sec_element.size=1;
  786:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  787:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  788:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  789:         } else {
  790:             for (var i=0; i<numSections; i++) {
  791:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  792:             }
  793:             document.$formname.$sec_element.multiple=true
  794:             if (numSections < 3) {
  795:                 document.$formname.$sec_element.size=numSections;
  796:             } else {
  797:                 document.$formname.$sec_element.size=3;
  798:             }
  799:             document.$formname.$sec_element.options[0].selected = false
  800:         }
  801:     }
  802: }
  803: 
  804: function setRole(crstype) {
  805: |;
  806:     if ($role_element eq '') {
  807:         $setsections .= '    return;
  808: }
  809: ';
  810:     } else {
  811:         $setsections .= qq|
  812:     var elementLength = document.$formname.$role_element.length;
  813:     var allroles = Array($rolestr);
  814:     var courserolenames = Array($courserolestr);
  815:     var communityrolenames = Array($communityrolestr);
  816:     if (elementLength != undefined) {
  817:         if (document.$formname.$role_element.options[5].value == 'cc') {
  818:             if (crstype == 'Course') {
  819:                 return;
  820:             } else {
  821:                 allroles[5] = 'co';
  822:                 for (var i=0; i<6; i++) {
  823:                     document.$formname.$role_element.options[i].value = allroles[i];
  824:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  825:                 }
  826:             }
  827:         } else {
  828:             if (crstype == 'Community') {
  829:                 return;
  830:             } else {
  831:                 allroles[5] = 'cc';
  832:                 for (var i=0; i<6; i++) {
  833:                     document.$formname.$role_element.options[i].value = allroles[i];
  834:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  835:                 }
  836:             }
  837:         }
  838:     }
  839:     return;
  840: }
  841: |;
  842:     }
  843:     return $setsections;
  844: }
  845: 
  846: sub selectcourse_link {
  847:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  848:        $typeelement) = @_;
  849:    my $type = $selecttype;
  850:    my $linktext = &mt('Select Course');
  851:    if ($selecttype eq 'Community') {
  852:        $linktext = &mt('Select Community');
  853:    } elsif ($selecttype eq 'Course/Community') {
  854:        $linktext = &mt('Select Course/Community');
  855:        $type = '';
  856:    } elsif ($selecttype eq 'Select') {
  857:        $linktext = &mt('Select');
  858:        $type = '';
  859:    }
  860:    return '<span class="LC_nobreak">'
  861:          ."<a href='"
  862:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  863:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  864:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  865:          ."'>".$linktext.'</a>'
  866:          .'</span>';
  867: }
  868: 
  869: sub selectauthor_link {
  870:    my ($form,$udom)=@_;
  871:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  872:           &mt('Select Author').'</a>';
  873: }
  874: 
  875: sub selectuser_link {
  876:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  877:         $coursedom,$linktext,$caller) = @_;
  878:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  879:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  880:            ');">'.$linktext.'</a>';
  881: }
  882: 
  883: sub check_uncheck_jscript {
  884:     my $jscript = <<"ENDSCRT";
  885: function checkAll(field) {
  886:     if (field.length > 0) {
  887:         for (i = 0; i < field.length; i++) {
  888:             field[i].checked = true ;
  889:         }
  890:     } else {
  891:         field.checked = true
  892:     }
  893: }
  894:  
  895: function uncheckAll(field) {
  896:     if (field.length > 0) {
  897:         for (i = 0; i < field.length; i++) {
  898:             field[i].checked = false ;
  899:         }
  900:     } else {
  901:         field.checked = false ;
  902:     }
  903: }
  904: ENDSCRT
  905:     return $jscript;
  906: }
  907: 
  908: sub select_timezone {
  909:    my ($name,$selected,$onchange,$includeempty)=@_;
  910:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  911:    if ($includeempty) {
  912:        $output .= '<option value=""';
  913:        if (($selected eq '') || ($selected eq 'local')) {
  914:            $output .= ' selected="selected" ';
  915:        }
  916:        $output .= '> </option>';
  917:    }
  918:    my @timezones = DateTime::TimeZone->all_names;
  919:    foreach my $tzone (@timezones) {
  920:        $output.= '<option value="'.$tzone.'"';
  921:        if ($tzone eq $selected) {
  922:            $output.=' selected="selected"';
  923:        }
  924:        $output.=">$tzone</option>\n";
  925:    }
  926:    $output.="</select>";
  927:    return $output;
  928: }
  929: 
  930: sub select_datelocale {
  931:     my ($name,$selected,$onchange,$includeempty)=@_;
  932:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  933:     if ($includeempty) {
  934:         $output .= '<option value=""';
  935:         if ($selected eq '') {
  936:             $output .= ' selected="selected" ';
  937:         }
  938:         $output .= '> </option>';
  939:     }
  940:     my (@possibles,%locale_names);
  941:     my @locales = DateTime::Locale::Catalog::Locales;
  942:     foreach my $locale (@locales) {
  943:         if (ref($locale) eq 'HASH') {
  944:             my $id = $locale->{'id'};
  945:             if ($id ne '') {
  946:                 my $en_terr = $locale->{'en_territory'};
  947:                 my $native_terr = $locale->{'native_territory'};
  948:                 my @languages = &Apache::lonlocal::preferred_languages();
  949:                 if (grep(/^en$/,@languages) || !@languages) {
  950:                     if ($en_terr ne '') {
  951:                         $locale_names{$id} = '('.$en_terr.')';
  952:                     } elsif ($native_terr ne '') {
  953:                         $locale_names{$id} = $native_terr;
  954:                     }
  955:                 } else {
  956:                     if ($native_terr ne '') {
  957:                         $locale_names{$id} = $native_terr.' ';
  958:                     } elsif ($en_terr ne '') {
  959:                         $locale_names{$id} = '('.$en_terr.')';
  960:                     }
  961:                 }
  962:                 push (@possibles,$id);
  963:             }
  964:         }
  965:     }
  966:     foreach my $item (sort(@possibles)) {
  967:         $output.= '<option value="'.$item.'"';
  968:         if ($item eq $selected) {
  969:             $output.=' selected="selected"';
  970:         }
  971:         $output.=">$item";
  972:         if ($locale_names{$item} ne '') {
  973:             $output.="  $locale_names{$item}</option>\n";
  974:         }
  975:         $output.="</option>\n";
  976:     }
  977:     $output.="</select>";
  978:     return $output;
  979: }
  980: 
  981: sub select_language {
  982:     my ($name,$selected,$includeempty) = @_;
  983:     my %langchoices;
  984:     if ($includeempty) {
  985:         %langchoices = ('' => 'No language preference');
  986:     }
  987:     foreach my $id (&languageids()) {
  988:         my $code = &supportedlanguagecode($id);
  989:         if ($code) {
  990:             $langchoices{$code} = &plainlanguagedescription($id);
  991:         }
  992:     }
  993:     return &select_form($selected,$name,\%langchoices);
  994: }
  995: 
  996: =pod
  997: 
  998: =item * &linked_select_forms(...)
  999: 
 1000: linked_select_forms returns a string containing a <script></script> block
 1001: and html for two <select> menus.  The select menus will be linked in that
 1002: changing the value of the first menu will result in new values being placed
 1003: in the second menu.  The values in the select menu will appear in alphabetical
 1004: order unless a defined order is provided.
 1005: 
 1006: linked_select_forms takes the following ordered inputs:
 1007: 
 1008: =over 4
 1009: 
 1010: =item * $formname, the name of the <form> tag
 1011: 
 1012: =item * $middletext, the text which appears between the <select> tags
 1013: 
 1014: =item * $firstdefault, the default value for the first menu
 1015: 
 1016: =item * $firstselectname, the name of the first <select> tag
 1017: 
 1018: =item * $secondselectname, the name of the second <select> tag
 1019: 
 1020: =item * $hashref, a reference to a hash containing the data for the menus.
 1021: 
 1022: =item * $menuorder, the order of values in the first menu
 1023: 
 1024: =back 
 1025: 
 1026: Below is an example of such a hash.  Only the 'text', 'default', and 
 1027: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1028: values for the first select menu.  The text that coincides with the 
 1029: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1030: and text for the second menu are given in the hash pointed to by 
 1031: $menu{$choice1}->{'select2'}.  
 1032: 
 1033:  my %menu = ( A1 => { text =>"Choice A1" ,
 1034:                        default => "B3",
 1035:                        select2 => { 
 1036:                            B1 => "Choice B1",
 1037:                            B2 => "Choice B2",
 1038:                            B3 => "Choice B3",
 1039:                            B4 => "Choice B4"
 1040:                            },
 1041:                        order => ['B4','B3','B1','B2'],
 1042:                    },
 1043:                A2 => { text =>"Choice A2" ,
 1044:                        default => "C2",
 1045:                        select2 => { 
 1046:                            C1 => "Choice C1",
 1047:                            C2 => "Choice C2",
 1048:                            C3 => "Choice C3"
 1049:                            },
 1050:                        order => ['C2','C1','C3'],
 1051:                    },
 1052:                A3 => { text =>"Choice A3" ,
 1053:                        default => "D6",
 1054:                        select2 => { 
 1055:                            D1 => "Choice D1",
 1056:                            D2 => "Choice D2",
 1057:                            D3 => "Choice D3",
 1058:                            D4 => "Choice D4",
 1059:                            D5 => "Choice D5",
 1060:                            D6 => "Choice D6",
 1061:                            D7 => "Choice D7"
 1062:                            },
 1063:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1064:                    }
 1065:                );
 1066: 
 1067: =cut
 1068: 
 1069: sub linked_select_forms {
 1070:     my ($formname,
 1071:         $middletext,
 1072:         $firstdefault,
 1073:         $firstselectname,
 1074:         $secondselectname, 
 1075:         $hashref,
 1076:         $menuorder,
 1077:         ) = @_;
 1078:     my $second = "document.$formname.$secondselectname";
 1079:     my $first = "document.$formname.$firstselectname";
 1080:     # output the javascript to do the changing
 1081:     my $result = '';
 1082:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1083:     $result.="// <![CDATA[\n";
 1084:     $result.="var select2data = new Object();\n";
 1085:     $" = '","';
 1086:     my $debug = '';
 1087:     foreach my $s1 (sort(keys(%$hashref))) {
 1088:         $result.="select2data.d_$s1 = new Object();\n";        
 1089:         $result.="select2data.d_$s1.def = new String('".
 1090:             $hashref->{$s1}->{'default'}."');\n";
 1091:         $result.="select2data.d_$s1.values = new Array(";
 1092:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1093:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1094:             @s2values = @{$hashref->{$s1}->{'order'}};
 1095:         }
 1096:         $result.="\"@s2values\");\n";
 1097:         $result.="select2data.d_$s1.texts = new Array(";        
 1098:         my @s2texts;
 1099:         foreach my $value (@s2values) {
 1100:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1101:         }
 1102:         $result.="\"@s2texts\");\n";
 1103:     }
 1104:     $"=' ';
 1105:     $result.= <<"END";
 1106: 
 1107: function select1_changed() {
 1108:     // Determine new choice
 1109:     var newvalue = "d_" + $first.value;
 1110:     // update select2
 1111:     var values     = select2data[newvalue].values;
 1112:     var texts      = select2data[newvalue].texts;
 1113:     var select2def = select2data[newvalue].def;
 1114:     var i;
 1115:     // out with the old
 1116:     for (i = 0; i < $second.options.length; i++) {
 1117:         $second.options[i] = null;
 1118:     }
 1119:     // in with the nuclear
 1120:     for (i=0;i<values.length; i++) {
 1121:         $second.options[i] = new Option(values[i]);
 1122:         $second.options[i].value = values[i];
 1123:         $second.options[i].text = texts[i];
 1124:         if (values[i] == select2def) {
 1125:             $second.options[i].selected = true;
 1126:         }
 1127:     }
 1128: }
 1129: // ]]>
 1130: </script>
 1131: END
 1132:     # output the initial values for the selection lists
 1133:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1134:     my @order = sort(keys(%{$hashref}));
 1135:     if (ref($menuorder) eq 'ARRAY') {
 1136:         @order = @{$menuorder};
 1137:     }
 1138:     foreach my $value (@order) {
 1139:         $result.="    <option value=\"$value\" ";
 1140:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1141:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1142:     }
 1143:     $result .= "</select>\n";
 1144:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1145:     $result .= $middletext;
 1146:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1147:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1148:     
 1149:     my @secondorder = sort(keys(%select2));
 1150:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1151:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1152:     }
 1153:     foreach my $value (@secondorder) {
 1154:         $result.="    <option value=\"$value\" ";        
 1155:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1156:         $result.=">".&mt($select2{$value})."</option>\n";
 1157:     }
 1158:     $result .= "</select>\n";
 1159:     #    return $debug;
 1160:     return $result;
 1161: }   #  end of sub linked_select_forms {
 1162: 
 1163: =pod
 1164: 
 1165: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1166: 
 1167: Returns a string corresponding to an HTML link to the given help
 1168: $topic, where $topic corresponds to the name of a .tex file in
 1169: /home/httpd/html/adm/help/tex, with underscores replaced by
 1170: spaces. 
 1171: 
 1172: $text will optionally be linked to the same topic, allowing you to
 1173: link text in addition to the graphic. If you do not want to link
 1174: text, but wish to specify one of the later parameters, pass an
 1175: empty string. 
 1176: 
 1177: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1178: the link will not open a new window. If false, the link will open
 1179: a new window using Javascript. (Default is false.) 
 1180: 
 1181: $width and $height are optional numerical parameters that will
 1182: override the width and height of the popped up window, which may
 1183: be useful for certain help topics with big pictures included.
 1184: 
 1185: $imgid is the id of the img tag used for the help icon. This may be
 1186: used in a javascript call to switch the image src.  See 
 1187: lonhtmlcommon::htmlareaselectactive() for an example.
 1188: 
 1189: =cut
 1190: 
 1191: sub help_open_topic {
 1192:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1193:     $text = "" if (not defined $text);
 1194:     $stayOnPage = 0 if (not defined $stayOnPage);
 1195:     $width = 500 if (not defined $width);
 1196:     $height = 400 if (not defined $height);
 1197:     my $filename = $topic;
 1198:     $filename =~ s/ /_/g;
 1199: 
 1200:     my $template = "";
 1201:     my $link;
 1202:     
 1203:     $topic=~s/\W/\_/g;
 1204: 
 1205:     if (!$stayOnPage) {
 1206: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1207:     } elsif ($stayOnPage eq 'popup') {
 1208:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1209:     } else {
 1210: 	$link = "/adm/help/${filename}.hlp";
 1211:     }
 1212: 
 1213:     # Add the text
 1214:     if ($text ne "") {	
 1215: 	$template.='<span class="LC_help_open_topic">'
 1216:                   .'<a target="_top" href="'.$link.'">'
 1217:                   .$text.'</a>';
 1218:     }
 1219: 
 1220:     # (Always) Add the graphic
 1221:     my $title = &mt('Online Help');
 1222:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1223:     if ($imgid ne '') {
 1224:         $imgid = ' id="'.$imgid.'"';
 1225:     }
 1226:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1227:               .'<img src="'.$helpicon.'" border="0"'
 1228:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1229:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1230:               .' /></a>';
 1231:     if ($text ne "") {	
 1232:         $template.='</span>';
 1233:     }
 1234:     return $template;
 1235: 
 1236: }
 1237: 
 1238: # This is a quicky function for Latex cheatsheet editing, since it 
 1239: # appears in at least four places
 1240: sub helpLatexCheatsheet {
 1241:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1242:     my $out;
 1243:     my $addOther = '';
 1244:     if ($topic) {
 1245: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1246:     }
 1247:     $out = '<span>' # Start cheatsheet
 1248: 	  .$addOther
 1249:           .'<span>'
 1250: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1251: 	  .'</span> <span>'
 1252: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1253: 	  .'</span>';
 1254:     unless ($not_author) {
 1255:         $out .= ' <span>'
 1256: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1257: 	       .'</span>';
 1258:     }
 1259:     $out .= '</span>'; # End cheatsheet
 1260:     return $out;
 1261: }
 1262: 
 1263: sub general_help {
 1264:     my $helptopic='Student_Intro';
 1265:     if ($env{'request.role'}=~/^(ca|au)/) {
 1266: 	$helptopic='Authoring_Intro';
 1267:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1268: 	$helptopic='Course_Coordination_Intro';
 1269:     } elsif ($env{'request.role'}=~/^dc/) {
 1270:         $helptopic='Domain_Coordination_Intro';
 1271:     }
 1272:     return $helptopic;
 1273: }
 1274: 
 1275: sub update_help_link {
 1276:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1277:     my $origurl = $ENV{'REQUEST_URI'};
 1278:     $origurl=~s|^/~|/priv/|;
 1279:     my $timestamp = time;
 1280:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1281:         $$datum = &escape($$datum);
 1282:     }
 1283: 
 1284:     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";
 1285:     my $output .= <<"ENDOUTPUT";
 1286: <script type="text/javascript">
 1287: // <![CDATA[
 1288: banner_link = '$banner_link';
 1289: // ]]>
 1290: </script>
 1291: ENDOUTPUT
 1292:     return $output;
 1293: }
 1294: 
 1295: # now just updates the help link and generates a blue icon
 1296: sub help_open_menu {
 1297:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1298: 	= @_;    
 1299:     $stayOnPage = 1;
 1300:     my $output;
 1301:     if ($component_help) {
 1302: 	if (!$text) {
 1303: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1304: 				       $width,$height);
 1305: 	} else {
 1306: 	    my $help_text;
 1307: 	    $help_text=&unescape($topic);
 1308: 	    $output='<table><tr><td>'.
 1309: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1310: 				 $width,$height).'</td></tr></table>';
 1311: 	}
 1312:     }
 1313:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1314:     return $output.$banner_link;
 1315: }
 1316: 
 1317: sub top_nav_help {
 1318:     my ($text) = @_;
 1319:     $text = &mt($text);
 1320:     my $stay_on_page = 1;
 1321: 
 1322:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1323: 	                     : "javascript:helpMenu('open')";
 1324:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1325: 
 1326:     my $title = &mt('Get help');
 1327: 
 1328:     return <<"END";
 1329: $banner_link
 1330:  <a href="$link" title="$title">$text</a>
 1331: END
 1332: }
 1333: 
 1334: sub help_menu_js {
 1335:     my ($text) = @_;
 1336:     my $stayOnPage = 1;
 1337:     my $width = 620;
 1338:     my $height = 600;
 1339:     my $helptopic=&general_help();
 1340:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1341:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1342:     my $start_page =
 1343:         &Apache::loncommon::start_page('Help Menu', undef,
 1344: 				       {'frameset'    => 1,
 1345: 					'js_ready'    => 1,
 1346: 					'add_entries' => {
 1347: 					    'border' => '0',
 1348: 					    'rows'   => "110,*",},});
 1349:     my $end_page =
 1350:         &Apache::loncommon::end_page({'frameset' => 1,
 1351: 				      'js_ready' => 1,});
 1352: 
 1353:     my $template .= <<"ENDTEMPLATE";
 1354: <script type="text/javascript">
 1355: // <![CDATA[
 1356: // <!-- BEGIN LON-CAPA Internal
 1357: var banner_link = '';
 1358: function helpMenu(target) {
 1359:     var caller = this;
 1360:     if (target == 'open') {
 1361:         var newWindow = null;
 1362:         try {
 1363:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1364:         }
 1365:         catch(error) {
 1366:             writeHelp(caller);
 1367:             return;
 1368:         }
 1369:         if (newWindow) {
 1370:             caller = newWindow;
 1371:         }
 1372:     }
 1373:     writeHelp(caller);
 1374:     return;
 1375: }
 1376: function writeHelp(caller) {
 1377:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1378:     caller.document.close()
 1379:     caller.focus()
 1380: }
 1381: // END LON-CAPA Internal -->
 1382: // ]]>
 1383: </script>
 1384: ENDTEMPLATE
 1385:     return $template;
 1386: }
 1387: 
 1388: sub help_open_bug {
 1389:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1390:     unless ($env{'user.adv'}) { return ''; }
 1391:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1392:     $text = "" if (not defined $text);
 1393: 	$stayOnPage=1;
 1394:     $width = 600 if (not defined $width);
 1395:     $height = 600 if (not defined $height);
 1396: 
 1397:     $topic=~s/\W+/\+/g;
 1398:     my $link='';
 1399:     my $template='';
 1400:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1401: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1402:     if (!$stayOnPage)
 1403:     {
 1404: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1405:     }
 1406:     else
 1407:     {
 1408: 	$link = $url;
 1409:     }
 1410:     # Add the text
 1411:     if ($text ne "")
 1412:     {
 1413: 	$template .= 
 1414:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1415:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1416:     }
 1417: 
 1418:     # Add the graphic
 1419:     my $title = &mt('Report a Bug');
 1420:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1421:     $template .= <<"ENDTEMPLATE";
 1422:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1423: ENDTEMPLATE
 1424:     if ($text ne '') { $template.='</td></tr></table>' };
 1425:     return $template;
 1426: 
 1427: }
 1428: 
 1429: sub help_open_faq {
 1430:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1431:     unless ($env{'user.adv'}) { return ''; }
 1432:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1433:     $text = "" if (not defined $text);
 1434: 	$stayOnPage=1;
 1435:     $width = 350 if (not defined $width);
 1436:     $height = 400 if (not defined $height);
 1437: 
 1438:     $topic=~s/\W+/\+/g;
 1439:     my $link='';
 1440:     my $template='';
 1441:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1442:     if (!$stayOnPage)
 1443:     {
 1444: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1445:     }
 1446:     else
 1447:     {
 1448: 	$link = $url;
 1449:     }
 1450: 
 1451:     # Add the text
 1452:     if ($text ne "")
 1453:     {
 1454: 	$template .= 
 1455:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1456:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1457:     }
 1458: 
 1459:     # Add the graphic
 1460:     my $title = &mt('View the FAQ');
 1461:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1462:     $template .= <<"ENDTEMPLATE";
 1463:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1464: ENDTEMPLATE
 1465:     if ($text ne '') { $template.='</td></tr></table>' };
 1466:     return $template;
 1467: 
 1468: }
 1469: 
 1470: ###############################################################
 1471: ###############################################################
 1472: 
 1473: =pod
 1474: 
 1475: =item * &change_content_javascript():
 1476: 
 1477: This and the next function allow you to create small sections of an
 1478: otherwise static HTML page that you can update on the fly with
 1479: Javascript, even in Netscape 4.
 1480: 
 1481: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1482: must be written to the HTML page once. It will prove the Javascript
 1483: function "change(name, content)". Calling the change function with the
 1484: name of the section 
 1485: you want to update, matching the name passed to C<changable_area>, and
 1486: the new content you want to put in there, will put the content into
 1487: that area.
 1488: 
 1489: B<Note>: Netscape 4 only reserves enough space for the changable area
 1490: to contain room for the original contents. You need to "make space"
 1491: for whatever changes you wish to make, and be B<sure> to check your
 1492: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1493: it's adequate for updating a one-line status display, but little more.
 1494: This script will set the space to 100% width, so you only need to
 1495: worry about height in Netscape 4.
 1496: 
 1497: Modern browsers are much less limiting, and if you can commit to the
 1498: user not using Netscape 4, this feature may be used freely with
 1499: pretty much any HTML.
 1500: 
 1501: =cut
 1502: 
 1503: sub change_content_javascript {
 1504:     # If we're on Netscape 4, we need to use Layer-based code
 1505:     if ($env{'browser.type'} eq 'netscape' &&
 1506: 	$env{'browser.version'} =~ /^4\./) {
 1507: 	return (<<NETSCAPE4);
 1508: 	function change(name, content) {
 1509: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1510: 	    doc.open();
 1511: 	    doc.write(content);
 1512: 	    doc.close();
 1513: 	}
 1514: NETSCAPE4
 1515:     } else {
 1516: 	# Otherwise, we need to use semi-standards-compliant code
 1517: 	# (technically, "innerHTML" isn't standard but the equivalent
 1518: 	# is really scary, and every useful browser supports it
 1519: 	return (<<DOMBASED);
 1520: 	function change(name, content) {
 1521: 	    element = document.getElementById(name);
 1522: 	    element.innerHTML = content;
 1523: 	}
 1524: DOMBASED
 1525:     }
 1526: }
 1527: 
 1528: =pod
 1529: 
 1530: =item * &changable_area($name,$origContent):
 1531: 
 1532: This provides a "changable area" that can be modified on the fly via
 1533: the Javascript code provided in C<change_content_javascript>. $name is
 1534: the name you will use to reference the area later; do not repeat the
 1535: same name on a given HTML page more then once. $origContent is what
 1536: the area will originally contain, which can be left blank.
 1537: 
 1538: =cut
 1539: 
 1540: sub changable_area {
 1541:     my ($name, $origContent) = @_;
 1542: 
 1543:     if ($env{'browser.type'} eq 'netscape' &&
 1544: 	$env{'browser.version'} =~ /^4\./) {
 1545: 	# If this is netscape 4, we need to use the Layer tag
 1546: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1547:     } else {
 1548: 	return "<span id='$name'>$origContent</span>";
 1549:     }
 1550: }
 1551: 
 1552: =pod
 1553: 
 1554: =item * &viewport_geometry_js 
 1555: 
 1556: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1557: 
 1558: =cut
 1559: 
 1560: 
 1561: sub viewport_geometry_js { 
 1562:     return <<"GEOMETRY";
 1563: var Geometry = {};
 1564: function init_geometry() {
 1565:     if (Geometry.init) { return };
 1566:     Geometry.init=1;
 1567:     if (window.innerHeight) {
 1568:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1569:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1570:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1571:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1572:     }
 1573:     else if (document.documentElement && document.documentElement.clientHeight) {
 1574:         Geometry.getViewportHeight =
 1575:             function() { return document.documentElement.clientHeight; };
 1576:         Geometry.getViewportWidth =
 1577:             function() { return document.documentElement.clientWidth; };
 1578: 
 1579:         Geometry.getHorizontalScroll =
 1580:             function() { return document.documentElement.scrollLeft; };
 1581:         Geometry.getVerticalScroll =
 1582:             function() { return document.documentElement.scrollTop; };
 1583:     }
 1584:     else if (document.body.clientHeight) {
 1585:         Geometry.getViewportHeight =
 1586:             function() { return document.body.clientHeight; };
 1587:         Geometry.getViewportWidth =
 1588:             function() { return document.body.clientWidth; };
 1589:         Geometry.getHorizontalScroll =
 1590:             function() { return document.body.scrollLeft; };
 1591:         Geometry.getVerticalScroll =
 1592:             function() { return document.body.scrollTop; };
 1593:     }
 1594: }
 1595: 
 1596: GEOMETRY
 1597: }
 1598: 
 1599: =pod
 1600: 
 1601: =item * &viewport_size_js()
 1602: 
 1603: 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. 
 1604: 
 1605: =cut
 1606: 
 1607: sub viewport_size_js {
 1608:     my $geometry = &viewport_geometry_js();
 1609:     return <<"DIMS";
 1610: 
 1611: $geometry
 1612: 
 1613: function getViewportDims(width,height) {
 1614:     init_geometry();
 1615:     width.value = Geometry.getViewportWidth();
 1616:     height.value = Geometry.getViewportHeight();
 1617:     return;
 1618: }
 1619: 
 1620: DIMS
 1621: }
 1622: 
 1623: =pod
 1624: 
 1625: =item * &resize_textarea_js()
 1626: 
 1627: emits the needed javascript to resize a textarea to be as big as possible
 1628: 
 1629: creates a function resize_textrea that takes two IDs first should be
 1630: the id of the element to resize, second should be the id of a div that
 1631: surrounds everything that comes after the textarea, this routine needs
 1632: to be attached to the <body> for the onload and onresize events.
 1633: 
 1634: =back
 1635: 
 1636: =cut
 1637: 
 1638: sub resize_textarea_js {
 1639:     my $geometry = &viewport_geometry_js();
 1640:     return <<"RESIZE";
 1641:     <script type="text/javascript">
 1642: // <![CDATA[
 1643: $geometry
 1644: 
 1645: function getX(element) {
 1646:     var x = 0;
 1647:     while (element) {
 1648: 	x += element.offsetLeft;
 1649: 	element = element.offsetParent;
 1650:     }
 1651:     return x;
 1652: }
 1653: function getY(element) {
 1654:     var y = 0;
 1655:     while (element) {
 1656: 	y += element.offsetTop;
 1657: 	element = element.offsetParent;
 1658:     }
 1659:     return y;
 1660: }
 1661: 
 1662: 
 1663: function resize_textarea(textarea_id,bottom_id) {
 1664:     init_geometry();
 1665:     var textarea        = document.getElementById(textarea_id);
 1666:     //alert(textarea);
 1667: 
 1668:     var textarea_top    = getY(textarea);
 1669:     var textarea_height = textarea.offsetHeight;
 1670:     var bottom          = document.getElementById(bottom_id);
 1671:     var bottom_top      = getY(bottom);
 1672:     var bottom_height   = bottom.offsetHeight;
 1673:     var window_height   = Geometry.getViewportHeight();
 1674:     var fudge           = 23;
 1675:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1676:     if (new_height < 300) {
 1677: 	new_height = 300;
 1678:     }
 1679:     textarea.style.height=new_height+'px';
 1680: }
 1681: // ]]>
 1682: </script>
 1683: RESIZE
 1684: 
 1685: }
 1686: 
 1687: =pod
 1688: 
 1689: =head1 Excel and CSV file utility routines
 1690: 
 1691: =over 4
 1692: 
 1693: =cut
 1694: 
 1695: ###############################################################
 1696: ###############################################################
 1697: 
 1698: =pod
 1699: 
 1700: =item * &csv_translate($text) 
 1701: 
 1702: Translate $text to allow it to be output as a 'comma separated values' 
 1703: format.
 1704: 
 1705: =cut
 1706: 
 1707: ###############################################################
 1708: ###############################################################
 1709: sub csv_translate {
 1710:     my $text = shift;
 1711:     $text =~ s/\"/\"\"/g;
 1712:     $text =~ s/\n/ /g;
 1713:     return $text;
 1714: }
 1715: 
 1716: ###############################################################
 1717: ###############################################################
 1718: 
 1719: =pod
 1720: 
 1721: =item * &define_excel_formats()
 1722: 
 1723: Define some commonly used Excel cell formats.
 1724: 
 1725: Currently supported formats:
 1726: 
 1727: =over 4
 1728: 
 1729: =item header
 1730: 
 1731: =item bold
 1732: 
 1733: =item h1
 1734: 
 1735: =item h2
 1736: 
 1737: =item h3
 1738: 
 1739: =item h4
 1740: 
 1741: =item i
 1742: 
 1743: =item date
 1744: 
 1745: =back
 1746: 
 1747: Inputs: $workbook
 1748: 
 1749: Returns: $format, a hash reference.
 1750: 
 1751: 
 1752: =cut
 1753: 
 1754: ###############################################################
 1755: ###############################################################
 1756: sub define_excel_formats {
 1757:     my ($workbook) = @_;
 1758:     my $format;
 1759:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1760:                                                 bottom    => 1,
 1761:                                                 align     => 'center');
 1762:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1763:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1764:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1765:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1766:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1767:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1768:     $format->{'date'} = $workbook->add_format(num_format=>
 1769:                                             'mm/dd/yyyy hh:mm:ss');
 1770:     return $format;
 1771: }
 1772: 
 1773: ###############################################################
 1774: ###############################################################
 1775: 
 1776: =pod
 1777: 
 1778: =item * &create_workbook()
 1779: 
 1780: Create an Excel worksheet.  If it fails, output message on the
 1781: request object and return undefs.
 1782: 
 1783: Inputs: Apache request object
 1784: 
 1785: Returns (undef) on failure, 
 1786:     Excel worksheet object, scalar with filename, and formats 
 1787:     from &Apache::loncommon::define_excel_formats on success
 1788: 
 1789: =cut
 1790: 
 1791: ###############################################################
 1792: ###############################################################
 1793: sub create_workbook {
 1794:     my ($r) = @_;
 1795:         #
 1796:     # Create the excel spreadsheet
 1797:     my $filename = '/prtspool/'.
 1798:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1799:         time.'_'.rand(1000000000).'.xls';
 1800:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1801:     if (! defined($workbook)) {
 1802:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1803:         $r->print(
 1804:             '<p class="LC_error">'
 1805:            .&mt('Problems occurred in creating the new Excel file.')
 1806:            .' '.&mt('This error has been logged.')
 1807:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1808:            .'</p>'
 1809:         );
 1810:         return (undef);
 1811:     }
 1812:     #
 1813:     $workbook->set_tempdir(LONCAPA::tempdir());
 1814:     #
 1815:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1816:     return ($workbook,$filename,$format);
 1817: }
 1818: 
 1819: ###############################################################
 1820: ###############################################################
 1821: 
 1822: =pod
 1823: 
 1824: =item * &create_text_file()
 1825: 
 1826: Create a file to write to and eventually make available to the user.
 1827: If file creation fails, outputs an error message on the request object and 
 1828: return undefs.
 1829: 
 1830: Inputs: Apache request object, and file suffix
 1831: 
 1832: Returns (undef) on failure, 
 1833:     Filehandle and filename on success.
 1834: 
 1835: =cut
 1836: 
 1837: ###############################################################
 1838: ###############################################################
 1839: sub create_text_file {
 1840:     my ($r,$suffix) = @_;
 1841:     if (! defined($suffix)) { $suffix = 'txt'; };
 1842:     my $fh;
 1843:     my $filename = '/prtspool/'.
 1844:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1845:         time.'_'.rand(1000000000).'.'.$suffix;
 1846:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1847:     if (! defined($fh)) {
 1848:         $r->log_error("Couldn't open $filename for output $!");
 1849:         $r->print(
 1850:             '<p class="LC_error">'
 1851:            .&mt('Problems occurred in creating the output file.')
 1852:            .' '.&mt('This error has been logged.')
 1853:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1854:            .'</p>'
 1855:         );
 1856:     }
 1857:     return ($fh,$filename)
 1858: }
 1859: 
 1860: 
 1861: =pod 
 1862: 
 1863: =back
 1864: 
 1865: =cut
 1866: 
 1867: ###############################################################
 1868: ##        Home server <option> list generating code          ##
 1869: ###############################################################
 1870: 
 1871: # ------------------------------------------
 1872: 
 1873: sub domain_select {
 1874:     my ($name,$value,$multiple)=@_;
 1875:     my %domains=map { 
 1876: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1877:     } &Apache::lonnet::all_domains();
 1878:     if ($multiple) {
 1879: 	$domains{''}=&mt('Any domain');
 1880: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1881: 	return &multiple_select_form($name,$value,4,\%domains);
 1882:     } else {
 1883: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1884: 	return &select_form($name,$value,\%domains);
 1885:     }
 1886: }
 1887: 
 1888: #-------------------------------------------
 1889: 
 1890: =pod
 1891: 
 1892: =head1 Routines for form select boxes
 1893: 
 1894: =over 4
 1895: 
 1896: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1897: 
 1898: Returns a string containing a <select> element int multiple mode
 1899: 
 1900: 
 1901: Args:
 1902:   $name - name of the <select> element
 1903:   $value - scalar or array ref of values that should already be selected
 1904:   $size - number of rows long the select element is
 1905:   $hash - the elements should be 'option' => 'shown text'
 1906:           (shown text should already have been &mt())
 1907:   $order - (optional) array ref of the order to show the elements in
 1908: 
 1909: =cut
 1910: 
 1911: #-------------------------------------------
 1912: sub multiple_select_form {
 1913:     my ($name,$value,$size,$hash,$order)=@_;
 1914:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1915:     my $output='';
 1916:     if (! defined($size)) {
 1917:         $size = 4;
 1918:         if (scalar(keys(%$hash))<4) {
 1919:             $size = scalar(keys(%$hash));
 1920:         }
 1921:     }
 1922:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1923:     my @order;
 1924:     if (ref($order) eq 'ARRAY')  {
 1925:         @order = @{$order};
 1926:     } else {
 1927:         @order = sort(keys(%$hash));
 1928:     }
 1929:     if (exists($$hash{'select_form_order'})) {
 1930:         @order = @{$$hash{'select_form_order'}};
 1931:     }
 1932:         
 1933:     foreach my $key (@order) {
 1934:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1935:         $output.='selected="selected" ' if ($selected{$key});
 1936:         $output.='>'.$hash->{$key}."</option>\n";
 1937:     }
 1938:     $output.="</select>\n";
 1939:     return $output;
 1940: }
 1941: 
 1942: #-------------------------------------------
 1943: 
 1944: =pod
 1945: 
 1946: =item * &select_form($defdom,$name,$hashref,$onchange)
 1947: 
 1948: Returns a string containing a <select name='$name' size='1'> form to 
 1949: allow a user to select options from a ref to a hash containing:
 1950: option_name => displayed text. An optional $onchange can include
 1951: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1952: 
 1953: See lonrights.pm for an example invocation and use.
 1954: 
 1955: =cut
 1956: 
 1957: #-------------------------------------------
 1958: sub select_form {
 1959:     my ($def,$name,$hashref,$onchange) = @_;
 1960:     return unless (ref($hashref) eq 'HASH');
 1961:     if ($onchange) {
 1962:         $onchange = ' onchange="'.$onchange.'"';
 1963:     }
 1964:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1965:     my @keys;
 1966:     if (exists($hashref->{'select_form_order'})) {
 1967: 	@keys=@{$hashref->{'select_form_order'}};
 1968:     } else {
 1969: 	@keys=sort(keys(%{$hashref}));
 1970:     }
 1971:     foreach my $key (@keys) {
 1972:         $selectform.=
 1973: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1974:             ($key eq $def ? 'selected="selected" ' : '').
 1975:                 ">".$hashref->{$key}."</option>\n";
 1976:     }
 1977:     $selectform.="</select>";
 1978:     return $selectform;
 1979: }
 1980: 
 1981: # For display filters
 1982: 
 1983: sub display_filter {
 1984:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1985:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1986:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1987: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1988: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1989: 	   '</label></span> <span class="LC_nobreak">'.
 1990:            &mt('Filter [_1]',
 1991: 	   &select_form($env{'form.displayfilter'},
 1992: 			'displayfilter',
 1993: 			{'currentfolder' => 'Current folder/page',
 1994: 			 'containing' => 'Containing phrase',
 1995: 			 'none' => 'None'})).
 1996: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1997: }
 1998: 
 1999: sub gradeleveldescription {
 2000:     my $gradelevel=shift;
 2001:     my %gradelevels=(0 => 'Not specified',
 2002: 		     1 => 'Grade 1',
 2003: 		     2 => 'Grade 2',
 2004: 		     3 => 'Grade 3',
 2005: 		     4 => 'Grade 4',
 2006: 		     5 => 'Grade 5',
 2007: 		     6 => 'Grade 6',
 2008: 		     7 => 'Grade 7',
 2009: 		     8 => 'Grade 8',
 2010: 		     9 => 'Grade 9',
 2011: 		     10 => 'Grade 10',
 2012: 		     11 => 'Grade 11',
 2013: 		     12 => 'Grade 12',
 2014: 		     13 => 'Grade 13',
 2015: 		     14 => '100 Level',
 2016: 		     15 => '200 Level',
 2017: 		     16 => '300 Level',
 2018: 		     17 => '400 Level',
 2019: 		     18 => 'Graduate Level');
 2020:     return &mt($gradelevels{$gradelevel});
 2021: }
 2022: 
 2023: sub select_level_form {
 2024:     my ($deflevel,$name)=@_;
 2025:     unless ($deflevel) { $deflevel=0; }
 2026:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2027:     for (my $i=0; $i<=18; $i++) {
 2028:         $selectform.="<option value=\"$i\" ".
 2029:             ($i==$deflevel ? 'selected="selected" ' : '').
 2030:                 ">".&gradeleveldescription($i)."</option>\n";
 2031:     }
 2032:     $selectform.="</select>";
 2033:     return $selectform;
 2034: }
 2035: 
 2036: #-------------------------------------------
 2037: 
 2038: =pod
 2039: 
 2040: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2041: 
 2042: Returns a string containing a <select name='$name' size='1'> form to 
 2043: allow a user to select the domain to preform an operation in.  
 2044: See loncreateuser.pm for an example invocation and use.
 2045: 
 2046: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2047: selected");
 2048: 
 2049: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2050: 
 2051: 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.
 2052: 
 2053: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2054: 
 2055: =cut
 2056: 
 2057: #-------------------------------------------
 2058: sub select_dom_form {
 2059:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2060:     if ($onchange) {
 2061:         $onchange = ' onchange="'.$onchange.'"';
 2062:     }
 2063:     my @domains;
 2064:     if (ref($incdoms) eq 'ARRAY') {
 2065:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2066:     } else {
 2067:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2068:     }
 2069:     if ($includeempty) { @domains=('',@domains); }
 2070:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2071:     foreach my $dom (@domains) {
 2072:         $selectdomain.="<option value=\"$dom\" ".
 2073:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2074:         if ($showdomdesc) {
 2075:             if ($dom ne '') {
 2076:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2077:                 if ($domdesc ne '') {
 2078:                     $selectdomain .= ' ('.$domdesc.')';
 2079:                 }
 2080:             } 
 2081:         }
 2082:         $selectdomain .= "</option>\n";
 2083:     }
 2084:     $selectdomain.="</select>";
 2085:     return $selectdomain;
 2086: }
 2087: 
 2088: #-------------------------------------------
 2089: 
 2090: =pod
 2091: 
 2092: =item * &home_server_form_item($domain,$name,$defaultflag)
 2093: 
 2094: input: 4 arguments (two required, two optional) - 
 2095:     $domain - domain of new user
 2096:     $name - name of form element
 2097:     $default - Value of 'default' causes a default item to be first 
 2098:                             option, and selected by default. 
 2099:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2100:                             if 1 server found, or default, if 0 found.
 2101: output: returns 2 items: 
 2102: (a) form element which contains either:
 2103:    (i) <select name="$name">
 2104:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2105:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2106:        </select>
 2107:        form item if there are multiple library servers in $domain, or
 2108:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2109:        if there is only one library server in $domain.
 2110: 
 2111: (b) number of library servers found.
 2112: 
 2113: See loncreateuser.pm for example of use.
 2114: 
 2115: =cut
 2116: 
 2117: #-------------------------------------------
 2118: sub home_server_form_item {
 2119:     my ($domain,$name,$default,$hide) = @_;
 2120:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2121:     my $result;
 2122:     my $numlib = keys(%servers);
 2123:     if ($numlib > 1) {
 2124:         $result .= '<select name="'.$name.'" />'."\n";
 2125:         if ($default) {
 2126:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2127:                        '</option>'."\n";
 2128:         }
 2129:         foreach my $hostid (sort(keys(%servers))) {
 2130:             $result.= '<option value="'.$hostid.'">'.
 2131: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2132:         }
 2133:         $result .= '</select>'."\n";
 2134:     } elsif ($numlib == 1) {
 2135:         my $hostid;
 2136:         foreach my $item (keys(%servers)) {
 2137:             $hostid = $item;
 2138:         }
 2139:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2140:                    $hostid.'" />';
 2141:                    if (!$hide) {
 2142:                        $result .= $hostid.' '.$servers{$hostid};
 2143:                    }
 2144:                    $result .= "\n";
 2145:     } elsif ($default) {
 2146:         $result .= '<input type="hidden" name="'.$name.
 2147:                    '" value="default" />';
 2148:                    if (!$hide) {
 2149:                        $result .= &mt('default');
 2150:                    }
 2151:                    $result .= "\n";
 2152:     }
 2153:     return ($result,$numlib);
 2154: }
 2155: 
 2156: =pod
 2157: 
 2158: =back 
 2159: 
 2160: =cut
 2161: 
 2162: ###############################################################
 2163: ##                  Decoding User Agent                      ##
 2164: ###############################################################
 2165: 
 2166: =pod
 2167: 
 2168: =head1 Decoding the User Agent
 2169: 
 2170: =over 4
 2171: 
 2172: =item * &decode_user_agent()
 2173: 
 2174: Inputs: $r
 2175: 
 2176: Outputs:
 2177: 
 2178: =over 4
 2179: 
 2180: =item * $httpbrowser
 2181: 
 2182: =item * $clientbrowser
 2183: 
 2184: =item * $clientversion
 2185: 
 2186: =item * $clientmathml
 2187: 
 2188: =item * $clientunicode
 2189: 
 2190: =item * $clientos
 2191: 
 2192: =back
 2193: 
 2194: =back 
 2195: 
 2196: =cut
 2197: 
 2198: ###############################################################
 2199: ###############################################################
 2200: sub decode_user_agent {
 2201:     my ($r)=@_;
 2202:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2203:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2204:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2205:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2206:     my $clientbrowser='unknown';
 2207:     my $clientversion='0';
 2208:     my $clientmathml='';
 2209:     my $clientunicode='0';
 2210:     for (my $i=0;$i<=$#browsertype;$i++) {
 2211:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2212: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2213: 	    $clientbrowser=$bname;
 2214:             $httpbrowser=~/$vreg/i;
 2215: 	    $clientversion=$1;
 2216:             $clientmathml=($clientversion>=$minv);
 2217:             $clientunicode=($clientversion>=$univ);
 2218: 	}
 2219:     }
 2220:     my $clientos='unknown';
 2221:     if (($httpbrowser=~/linux/i) ||
 2222:         ($httpbrowser=~/unix/i) ||
 2223:         ($httpbrowser=~/ux/i) ||
 2224:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2225:     if (($httpbrowser=~/vax/i) ||
 2226:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2227:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2228:     if (($httpbrowser=~/mac/i) ||
 2229:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2230:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2231:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2232:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2233:             $clientunicode,$clientos,);
 2234: }
 2235: 
 2236: ###############################################################
 2237: ##    Authentication changing form generation subroutines    ##
 2238: ###############################################################
 2239: ##
 2240: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2241: ## hash, and have reasonable default values.
 2242: ##
 2243: ##    formname = the name given in the <form> tag.
 2244: #-------------------------------------------
 2245: 
 2246: =pod
 2247: 
 2248: =head1 Authentication Routines
 2249: 
 2250: =over 4
 2251: 
 2252: =item * &authform_xxxxxx()
 2253: 
 2254: The authform_xxxxxx subroutines provide javascript and html forms which 
 2255: handle some of the conveniences required for authentication forms.  
 2256: This is not an optimal method, but it works.  
 2257: 
 2258: =over 4
 2259: 
 2260: =item * authform_header
 2261: 
 2262: =item * authform_authorwarning
 2263: 
 2264: =item * authform_nochange
 2265: 
 2266: =item * authform_kerberos
 2267: 
 2268: =item * authform_internal
 2269: 
 2270: =item * authform_filesystem
 2271: 
 2272: =back
 2273: 
 2274: See loncreateuser.pm for invocation and use examples.
 2275: 
 2276: =cut
 2277: 
 2278: #-------------------------------------------
 2279: sub authform_header{  
 2280:     my %in = (
 2281:         formname => 'cu',
 2282:         kerb_def_dom => '',
 2283:         @_,
 2284:     );
 2285:     $in{'formname'} = 'document.' . $in{'formname'};
 2286:     my $result='';
 2287: 
 2288: #---------------------------------------------- Code for upper case translation
 2289:     my $Javascript_toUpperCase;
 2290:     unless ($in{kerb_def_dom}) {
 2291:         $Javascript_toUpperCase =<<"END";
 2292:         switch (choice) {
 2293:            case 'krb': currentform.elements[choicearg].value =
 2294:                currentform.elements[choicearg].value.toUpperCase();
 2295:                break;
 2296:            default:
 2297:         }
 2298: END
 2299:     } else {
 2300:         $Javascript_toUpperCase = "";
 2301:     }
 2302: 
 2303:     my $radioval = "'nochange'";
 2304:     if (defined($in{'curr_authtype'})) {
 2305:         if ($in{'curr_authtype'} ne '') {
 2306:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2307:         }
 2308:     }
 2309:     my $argfield = 'null';
 2310:     if (defined($in{'mode'})) {
 2311:         if ($in{'mode'} eq 'modifycourse')  {
 2312:             if (defined($in{'curr_autharg'})) {
 2313:                 if ($in{'curr_autharg'} ne '') {
 2314:                     $argfield = "'$in{'curr_autharg'}'";
 2315:                 }
 2316:             }
 2317:         }
 2318:     }
 2319: 
 2320:     $result.=<<"END";
 2321: var current = new Object();
 2322: current.radiovalue = $radioval;
 2323: current.argfield = $argfield;
 2324: 
 2325: function changed_radio(choice,currentform) {
 2326:     var choicearg = choice + 'arg';
 2327:     // If a radio button in changed, we need to change the argfield
 2328:     if (current.radiovalue != choice) {
 2329:         current.radiovalue = choice;
 2330:         if (current.argfield != null) {
 2331:             currentform.elements[current.argfield].value = '';
 2332:         }
 2333:         if (choice == 'nochange') {
 2334:             current.argfield = null;
 2335:         } else {
 2336:             current.argfield = choicearg;
 2337:             switch(choice) {
 2338:                 case 'krb': 
 2339:                     currentform.elements[current.argfield].value = 
 2340:                         "$in{'kerb_def_dom'}";
 2341:                 break;
 2342:               default:
 2343:                 break;
 2344:             }
 2345:         }
 2346:     }
 2347:     return;
 2348: }
 2349: 
 2350: function changed_text(choice,currentform) {
 2351:     var choicearg = choice + 'arg';
 2352:     if (currentform.elements[choicearg].value !='') {
 2353:         $Javascript_toUpperCase
 2354:         // clear old field
 2355:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2356:             currentform.elements[current.argfield].value = '';
 2357:         }
 2358:         current.argfield = choicearg;
 2359:     }
 2360:     set_auth_radio_buttons(choice,currentform);
 2361:     return;
 2362: }
 2363: 
 2364: function set_auth_radio_buttons(newvalue,currentform) {
 2365:     var numauthchoices = currentform.login.length;
 2366:     if (typeof numauthchoices  == "undefined") {
 2367:         return;
 2368:     } 
 2369:     var i=0;
 2370:     while (i < numauthchoices) {
 2371:         if (currentform.login[i].value == newvalue) { break; }
 2372:         i++;
 2373:     }
 2374:     if (i == numauthchoices) {
 2375:         return;
 2376:     }
 2377:     current.radiovalue = newvalue;
 2378:     currentform.login[i].checked = true;
 2379:     return;
 2380: }
 2381: END
 2382:     return $result;
 2383: }
 2384: 
 2385: sub authform_authorwarning{
 2386:     my $result='';
 2387:     $result='<i>'.
 2388:         &mt('As a general rule, only authors or co-authors should be '.
 2389:             'filesystem authenticated '.
 2390:             '(which allows access to the server filesystem).')."</i>\n";
 2391:     return $result;
 2392: }
 2393: 
 2394: sub authform_nochange{  
 2395:     my %in = (
 2396:               formname => 'document.cu',
 2397:               kerb_def_dom => 'MSU.EDU',
 2398:               @_,
 2399:           );
 2400:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2401:     my $result;
 2402:     if (keys(%can_assign) == 0) {
 2403:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2404:     } else {
 2405:         $result = '<label>'.&mt('[_1] Do not change login data',
 2406:                   '<input type="radio" name="login" value="nochange" '.
 2407:                   'checked="checked" onclick="'.
 2408:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2409: 	    '</label>';
 2410:     }
 2411:     return $result;
 2412: }
 2413: 
 2414: sub authform_kerberos {
 2415:     my %in = (
 2416:               formname => 'document.cu',
 2417:               kerb_def_dom => 'MSU.EDU',
 2418:               kerb_def_auth => 'krb4',
 2419:               @_,
 2420:               );
 2421:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2422:         $autharg,$jscall);
 2423:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2424:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2425:        $check5 = ' checked="checked"';
 2426:     } else {
 2427:        $check4 = ' checked="checked"';
 2428:     }
 2429:     $krbarg = $in{'kerb_def_dom'};
 2430:     if (defined($in{'curr_authtype'})) {
 2431:         if ($in{'curr_authtype'} eq 'krb') {
 2432:             $krbcheck = ' checked="checked"';
 2433:             if (defined($in{'mode'})) {
 2434:                 if ($in{'mode'} eq 'modifyuser') {
 2435:                     $krbcheck = '';
 2436:                 }
 2437:             }
 2438:             if (defined($in{'curr_kerb_ver'})) {
 2439:                 if ($in{'curr_krb_ver'} eq '5') {
 2440:                     $check5 = ' checked="checked"';
 2441:                     $check4 = '';
 2442:                 } else {
 2443:                     $check4 = ' checked="checked"';
 2444:                     $check5 = '';
 2445:                 }
 2446:             }
 2447:             if (defined($in{'curr_autharg'})) {
 2448:                 $krbarg = $in{'curr_autharg'};
 2449:             }
 2450:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2451:                 if (defined($in{'curr_autharg'})) {
 2452:                     $result = 
 2453:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2454:         $in{'curr_autharg'},$krbver);
 2455:                 } else {
 2456:                     $result =
 2457:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2458:                 }
 2459:                 return $result; 
 2460:             }
 2461:         }
 2462:     } else {
 2463:         if ($authnum == 1) {
 2464:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2465:         }
 2466:     }
 2467:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2468:         return;
 2469:     } elsif ($authtype eq '') {
 2470:         if (defined($in{'mode'})) {
 2471:             if ($in{'mode'} eq 'modifycourse') {
 2472:                 if ($authnum == 1) {
 2473:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2474:                 }
 2475:             }
 2476:         }
 2477:     }
 2478:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2479:     if ($authtype eq '') {
 2480:         $authtype = '<input type="radio" name="login" value="krb" '.
 2481:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2482:                     $krbcheck.' />';
 2483:     }
 2484:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2485:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2486:          $in{'curr_authtype'} eq 'krb5') ||
 2487:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2488:          $in{'curr_authtype'} eq 'krb4')) {
 2489:         $result .= &mt
 2490:         ('[_1] Kerberos authenticated with domain [_2] '.
 2491:          '[_3] Version 4 [_4] Version 5 [_5]',
 2492:          '<label>'.$authtype,
 2493:          '</label><input type="text" size="10" name="krbarg" '.
 2494:              'value="'.$krbarg.'" '.
 2495:              'onchange="'.$jscall.'" />',
 2496:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2497:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2498: 	 '</label>');
 2499:     } elsif ($can_assign{'krb4'}) {
 2500:         $result .= &mt
 2501:         ('[_1] Kerberos authenticated with domain [_2] '.
 2502:          '[_3] Version 4 [_4]',
 2503:          '<label>'.$authtype,
 2504:          '</label><input type="text" size="10" name="krbarg" '.
 2505:              'value="'.$krbarg.'" '.
 2506:              'onchange="'.$jscall.'" />',
 2507:          '<label><input type="hidden" name="krbver" value="4" />',
 2508:          '</label>');
 2509:     } elsif ($can_assign{'krb5'}) {
 2510:         $result .= &mt
 2511:         ('[_1] Kerberos authenticated with domain [_2] '.
 2512:          '[_3] Version 5 [_4]',
 2513:          '<label>'.$authtype,
 2514:          '</label><input type="text" size="10" name="krbarg" '.
 2515:              'value="'.$krbarg.'" '.
 2516:              'onchange="'.$jscall.'" />',
 2517:          '<label><input type="hidden" name="krbver" value="5" />',
 2518:          '</label>');
 2519:     }
 2520:     return $result;
 2521: }
 2522: 
 2523: sub authform_internal{  
 2524:     my %in = (
 2525:                 formname => 'document.cu',
 2526:                 kerb_def_dom => 'MSU.EDU',
 2527:                 @_,
 2528:                 );
 2529:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2530:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2531:     if (defined($in{'curr_authtype'})) {
 2532:         if ($in{'curr_authtype'} eq 'int') {
 2533:             if ($can_assign{'int'}) {
 2534:                 $intcheck = 'checked="checked" ';
 2535:                 if (defined($in{'mode'})) {
 2536:                     if ($in{'mode'} eq 'modifyuser') {
 2537:                         $intcheck = '';
 2538:                     }
 2539:                 }
 2540:                 if (defined($in{'curr_autharg'})) {
 2541:                     $intarg = $in{'curr_autharg'};
 2542:                 }
 2543:             } else {
 2544:                 $result = &mt('Currently internally authenticated.');
 2545:                 return $result;
 2546:             }
 2547:         }
 2548:     } else {
 2549:         if ($authnum == 1) {
 2550:             $authtype = '<input type="hidden" name="login" value="int" />';
 2551:         }
 2552:     }
 2553:     if (!$can_assign{'int'}) {
 2554:         return;
 2555:     } elsif ($authtype eq '') {
 2556:         if (defined($in{'mode'})) {
 2557:             if ($in{'mode'} eq 'modifycourse') {
 2558:                 if ($authnum == 1) {
 2559:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2560:                 }
 2561:             }
 2562:         }
 2563:     }
 2564:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2565:     if ($authtype eq '') {
 2566:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2567:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2568:     }
 2569:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2570:                $intarg.'" onchange="'.$jscall.'" />';
 2571:     $result = &mt
 2572:         ('[_1] Internally authenticated (with initial password [_2])',
 2573:          '<label>'.$authtype,'</label>'.$autharg);
 2574:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2575:     return $result;
 2576: }
 2577: 
 2578: sub authform_local{  
 2579:     my %in = (
 2580:               formname => 'document.cu',
 2581:               kerb_def_dom => 'MSU.EDU',
 2582:               @_,
 2583:               );
 2584:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2585:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2586:     if (defined($in{'curr_authtype'})) {
 2587:         if ($in{'curr_authtype'} eq 'loc') {
 2588:             if ($can_assign{'loc'}) {
 2589:                 $loccheck = 'checked="checked" ';
 2590:                 if (defined($in{'mode'})) {
 2591:                     if ($in{'mode'} eq 'modifyuser') {
 2592:                         $loccheck = '';
 2593:                     }
 2594:                 }
 2595:                 if (defined($in{'curr_autharg'})) {
 2596:                     $locarg = $in{'curr_autharg'};
 2597:                 }
 2598:             } else {
 2599:                 $result = &mt('Currently using local (institutional) authentication.');
 2600:                 return $result;
 2601:             }
 2602:         }
 2603:     } else {
 2604:         if ($authnum == 1) {
 2605:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2606:         }
 2607:     }
 2608:     if (!$can_assign{'loc'}) {
 2609:         return;
 2610:     } elsif ($authtype eq '') {
 2611:         if (defined($in{'mode'})) {
 2612:             if ($in{'mode'} eq 'modifycourse') {
 2613:                 if ($authnum == 1) {
 2614:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2615:                 }
 2616:             }
 2617:         }
 2618:     }
 2619:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2620:     if ($authtype eq '') {
 2621:         $authtype = '<input type="radio" name="login" value="loc" '.
 2622:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2623:                     $jscall.'" />';
 2624:     }
 2625:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2626:                $locarg.'" onchange="'.$jscall.'" />';
 2627:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2628:                   '<label>'.$authtype,'</label>'.$autharg);
 2629:     return $result;
 2630: }
 2631: 
 2632: sub authform_filesystem{  
 2633:     my %in = (
 2634:               formname => 'document.cu',
 2635:               kerb_def_dom => 'MSU.EDU',
 2636:               @_,
 2637:               );
 2638:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2639:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2640:     if (defined($in{'curr_authtype'})) {
 2641:         if ($in{'curr_authtype'} eq 'fsys') {
 2642:             if ($can_assign{'fsys'}) {
 2643:                 $fsyscheck = 'checked="checked" ';
 2644:                 if (defined($in{'mode'})) {
 2645:                     if ($in{'mode'} eq 'modifyuser') {
 2646:                         $fsyscheck = '';
 2647:                     }
 2648:                 }
 2649:             } else {
 2650:                 $result = &mt('Currently Filesystem Authenticated.');
 2651:                 return $result;
 2652:             }           
 2653:         }
 2654:     } else {
 2655:         if ($authnum == 1) {
 2656:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2657:         }
 2658:     }
 2659:     if (!$can_assign{'fsys'}) {
 2660:         return;
 2661:     } elsif ($authtype eq '') {
 2662:         if (defined($in{'mode'})) {
 2663:             if ($in{'mode'} eq 'modifycourse') {
 2664:                 if ($authnum == 1) {
 2665:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2666:                 }
 2667:             }
 2668:         }
 2669:     }
 2670:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2671:     if ($authtype eq '') {
 2672:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2673:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2674:                     $jscall.'" />';
 2675:     }
 2676:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2677:                ' onchange="'.$jscall.'" />';
 2678:     $result = &mt
 2679:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2680:          '<label><input type="radio" name="login" value="fsys" '.
 2681:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2682:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2683:                   'onchange="'.$jscall.'" />');
 2684:     return $result;
 2685: }
 2686: 
 2687: sub get_assignable_auth {
 2688:     my ($dom) = @_;
 2689:     if ($dom eq '') {
 2690:         $dom = $env{'request.role.domain'};
 2691:     }
 2692:     my %can_assign = (
 2693:                           krb4 => 1,
 2694:                           krb5 => 1,
 2695:                           int  => 1,
 2696:                           loc  => 1,
 2697:                      );
 2698:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2699:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2700:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2701:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2702:             my $context;
 2703:             if ($env{'request.role'} =~ /^au/) {
 2704:                 $context = 'author';
 2705:             } elsif ($env{'request.role'} =~ /^dc/) {
 2706:                 $context = 'domain';
 2707:             } elsif ($env{'request.course.id'}) {
 2708:                 $context = 'course';
 2709:             }
 2710:             if ($context) {
 2711:                 if (ref($authhash->{$context}) eq 'HASH') {
 2712:                    %can_assign = %{$authhash->{$context}}; 
 2713:                 }
 2714:             }
 2715:         }
 2716:     }
 2717:     my $authnum = 0;
 2718:     foreach my $key (keys(%can_assign)) {
 2719:         if ($can_assign{$key}) {
 2720:             $authnum ++;
 2721:         }
 2722:     }
 2723:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2724:         $authnum --;
 2725:     }
 2726:     return ($authnum,%can_assign);
 2727: }
 2728: 
 2729: ###############################################################
 2730: ##    Get Kerberos Defaults for Domain                 ##
 2731: ###############################################################
 2732: ##
 2733: ## Returns default kerberos version and an associated argument
 2734: ## as listed in file domain.tab. If not listed, provides
 2735: ## appropriate default domain and kerberos version.
 2736: ##
 2737: #-------------------------------------------
 2738: 
 2739: =pod
 2740: 
 2741: =item * &get_kerberos_defaults()
 2742: 
 2743: get_kerberos_defaults($target_domain) returns the default kerberos
 2744: version and domain. If not found, it defaults to version 4 and the 
 2745: domain of the server.
 2746: 
 2747: =over 4
 2748: 
 2749: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2750: 
 2751: =back
 2752: 
 2753: =back
 2754: 
 2755: =cut
 2756: 
 2757: #-------------------------------------------
 2758: sub get_kerberos_defaults {
 2759:     my $domain=shift;
 2760:     my ($krbdef,$krbdefdom);
 2761:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2762:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2763:         $krbdef = $domdefaults{'auth_def'};
 2764:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2765:     } else {
 2766:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2767:         my $krbdefdom=$1;
 2768:         $krbdefdom=~tr/a-z/A-Z/;
 2769:         $krbdef = "krb4";
 2770:     }
 2771:     return ($krbdef,$krbdefdom);
 2772: }
 2773: 
 2774: 
 2775: ###############################################################
 2776: ##                Thesaurus Functions                        ##
 2777: ###############################################################
 2778: 
 2779: =pod
 2780: 
 2781: =head1 Thesaurus Functions
 2782: 
 2783: =over 4
 2784: 
 2785: =item * &initialize_keywords()
 2786: 
 2787: Initializes the package variable %Keywords if it is empty.  Uses the
 2788: package variable $thesaurus_db_file.
 2789: 
 2790: =cut
 2791: 
 2792: ###################################################
 2793: 
 2794: sub initialize_keywords {
 2795:     return 1 if (scalar keys(%Keywords));
 2796:     # If we are here, %Keywords is empty, so fill it up
 2797:     #   Make sure the file we need exists...
 2798:     if (! -e $thesaurus_db_file) {
 2799:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2800:                                  " failed because it does not exist");
 2801:         return 0;
 2802:     }
 2803:     #   Set up the hash as a database
 2804:     my %thesaurus_db;
 2805:     if (! tie(%thesaurus_db,'GDBM_File',
 2806:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2807:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2808:                                  $thesaurus_db_file);
 2809:         return 0;
 2810:     } 
 2811:     #  Get the average number of appearances of a word.
 2812:     my $avecount = $thesaurus_db{'average.count'};
 2813:     #  Put keywords (those that appear > average) into %Keywords
 2814:     while (my ($word,$data)=each (%thesaurus_db)) {
 2815:         my ($count,undef) = split /:/,$data;
 2816:         $Keywords{$word}++ if ($count > $avecount);
 2817:     }
 2818:     untie %thesaurus_db;
 2819:     # Remove special values from %Keywords.
 2820:     foreach my $value ('total.count','average.count') {
 2821:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2822:   }
 2823:     return 1;
 2824: }
 2825: 
 2826: ###################################################
 2827: 
 2828: =pod
 2829: 
 2830: =item * &keyword($word)
 2831: 
 2832: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2833: than the average number of times in the thesaurus database.  Calls 
 2834: &initialize_keywords
 2835: 
 2836: =cut
 2837: 
 2838: ###################################################
 2839: 
 2840: sub keyword {
 2841:     return if (!&initialize_keywords());
 2842:     my $word=lc(shift());
 2843:     $word=~s/\W//g;
 2844:     return exists($Keywords{$word});
 2845: }
 2846: 
 2847: ###############################################################
 2848: 
 2849: =pod 
 2850: 
 2851: =item * &get_related_words()
 2852: 
 2853: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2854: an array of words.  If the keyword is not in the thesaurus, an empty array
 2855: will be returned.  The order of the words returned is determined by the
 2856: database which holds them.
 2857: 
 2858: Uses global $thesaurus_db_file.
 2859: 
 2860: 
 2861: =cut
 2862: 
 2863: ###############################################################
 2864: sub get_related_words {
 2865:     my $keyword = shift;
 2866:     my %thesaurus_db;
 2867:     if (! -e $thesaurus_db_file) {
 2868:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2869:                                  "failed because the file does not exist");
 2870:         return ();
 2871:     }
 2872:     if (! tie(%thesaurus_db,'GDBM_File',
 2873:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2874:         return ();
 2875:     } 
 2876:     my @Words=();
 2877:     my $count=0;
 2878:     if (exists($thesaurus_db{$keyword})) {
 2879: 	# The first element is the number of times
 2880: 	# the word appears.  We do not need it now.
 2881: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2882: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2883: 	my $threshold=$mostfrequentcount/10;
 2884:         foreach my $possibleword (@RelatedWords) {
 2885:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2886:             if ($wordcount>$threshold) {
 2887: 		push(@Words,$word);
 2888:                 $count++;
 2889:                 if ($count>10) { last; }
 2890: 	    }
 2891:         }
 2892:     }
 2893:     untie %thesaurus_db;
 2894:     return @Words;
 2895: }
 2896: 
 2897: =pod
 2898: 
 2899: =back
 2900: 
 2901: =cut
 2902: 
 2903: # -------------------------------------------------------------- Plaintext name
 2904: =pod
 2905: 
 2906: =head1 User Name Functions
 2907: 
 2908: =over 4
 2909: 
 2910: =item * &plainname($uname,$udom,$first)
 2911: 
 2912: Takes a users logon name and returns it as a string in
 2913: "first middle last generation" form 
 2914: if $first is set to 'lastname' then it returns it as
 2915: 'lastname generation, firstname middlename' if their is a lastname
 2916: 
 2917: =cut
 2918: 
 2919: 
 2920: ###############################################################
 2921: sub plainname {
 2922:     my ($uname,$udom,$first)=@_;
 2923:     return if (!defined($uname) || !defined($udom));
 2924:     my %names=&getnames($uname,$udom);
 2925:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2926: 					  $names{'middlename'},
 2927: 					  $names{'lastname'},
 2928: 					  $names{'generation'},$first);
 2929:     $name=~s/^\s+//;
 2930:     $name=~s/\s+$//;
 2931:     $name=~s/\s+/ /g;
 2932:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2933:     return $name;
 2934: }
 2935: 
 2936: # -------------------------------------------------------------------- Nickname
 2937: =pod
 2938: 
 2939: =item * &nickname($uname,$udom)
 2940: 
 2941: Gets a users name and returns it as a string as
 2942: 
 2943: "&quot;nickname&quot;"
 2944: 
 2945: if the user has a nickname or
 2946: 
 2947: "first middle last generation"
 2948: 
 2949: if the user does not
 2950: 
 2951: =cut
 2952: 
 2953: sub nickname {
 2954:     my ($uname,$udom)=@_;
 2955:     return if (!defined($uname) || !defined($udom));
 2956:     my %names=&getnames($uname,$udom);
 2957:     my $name=$names{'nickname'};
 2958:     if ($name) {
 2959:        $name='&quot;'.$name.'&quot;'; 
 2960:     } else {
 2961:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2962: 	     $names{'lastname'}.' '.$names{'generation'};
 2963:        $name=~s/\s+$//;
 2964:        $name=~s/\s+/ /g;
 2965:     }
 2966:     return $name;
 2967: }
 2968: 
 2969: sub getnames {
 2970:     my ($uname,$udom)=@_;
 2971:     return if (!defined($uname) || !defined($udom));
 2972:     if ($udom eq 'public' && $uname eq 'public') {
 2973: 	return ('lastname' => &mt('Public'));
 2974:     }
 2975:     my $id=$uname.':'.$udom;
 2976:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2977:     if ($cached) {
 2978: 	return %{$names};
 2979:     } else {
 2980: 	my %loadnames=&Apache::lonnet::get('environment',
 2981:                     ['firstname','middlename','lastname','generation','nickname'],
 2982: 					 $udom,$uname);
 2983: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2984: 	return %loadnames;
 2985:     }
 2986: }
 2987: 
 2988: # -------------------------------------------------------------------- getemails
 2989: 
 2990: =pod
 2991: 
 2992: =item * &getemails($uname,$udom)
 2993: 
 2994: Gets a user's email information and returns it as a hash with keys:
 2995: notification, critnotification, permanentemail
 2996: 
 2997: For notification and critnotification, values are comma-separated lists 
 2998: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2999:  
 3000: 
 3001: =cut
 3002: 
 3003: 
 3004: sub getemails {
 3005:     my ($uname,$udom)=@_;
 3006:     if ($udom eq 'public' && $uname eq 'public') {
 3007: 	return;
 3008:     }
 3009:     if (!$udom) { $udom=$env{'user.domain'}; }
 3010:     if (!$uname) { $uname=$env{'user.name'}; }
 3011:     my $id=$uname.':'.$udom;
 3012:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3013:     if ($cached) {
 3014: 	return %{$names};
 3015:     } else {
 3016: 	my %loadnames=&Apache::lonnet::get('environment',
 3017:                     			   ['notification','critnotification',
 3018: 					    'permanentemail'],
 3019: 					   $udom,$uname);
 3020: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3021: 	return %loadnames;
 3022:     }
 3023: }
 3024: 
 3025: sub flush_email_cache {
 3026:     my ($uname,$udom)=@_;
 3027:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3028:     if (!$uname) { $uname=$env{'user.name'};   }
 3029:     return if ($udom eq 'public' && $uname eq 'public');
 3030:     my $id=$uname.':'.$udom;
 3031:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3032: }
 3033: 
 3034: # -------------------------------------------------------------------- getlangs
 3035: 
 3036: =pod
 3037: 
 3038: =item * &getlangs($uname,$udom)
 3039: 
 3040: Gets a user's language preference and returns it as a hash with key:
 3041: language.
 3042: 
 3043: =cut
 3044: 
 3045: 
 3046: sub getlangs {
 3047:     my ($uname,$udom) = @_;
 3048:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3049:     if (!$uname) { $uname=$env{'user.name'};   }
 3050:     my $id=$uname.':'.$udom;
 3051:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3052:     if ($cached) {
 3053:         return %{$langs};
 3054:     } else {
 3055:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3056:                                            $udom,$uname);
 3057:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3058:         return %loadlangs;
 3059:     }
 3060: }
 3061: 
 3062: sub flush_langs_cache {
 3063:     my ($uname,$udom)=@_;
 3064:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3065:     if (!$uname) { $uname=$env{'user.name'};   }
 3066:     return if ($udom eq 'public' && $uname eq 'public');
 3067:     my $id=$uname.':'.$udom;
 3068:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3069: }
 3070: 
 3071: # ------------------------------------------------------------------ Screenname
 3072: 
 3073: =pod
 3074: 
 3075: =item * &screenname($uname,$udom)
 3076: 
 3077: Gets a users screenname and returns it as a string
 3078: 
 3079: =cut
 3080: 
 3081: sub screenname {
 3082:     my ($uname,$udom)=@_;
 3083:     if ($uname eq $env{'user.name'} &&
 3084: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3085:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3086:     return $names{'screenname'};
 3087: }
 3088: 
 3089: 
 3090: # ------------------------------------------------------------- Confirm Wrapper
 3091: =pod
 3092: 
 3093: =item confirmwrapper
 3094: 
 3095: Wrap messages about completion of operation in box
 3096: 
 3097: =cut
 3098: 
 3099: sub confirmwrapper {
 3100:     my ($message)=@_;
 3101:     if ($message) {
 3102:         return "\n".'<div class="LC_confirm_box">'."\n"
 3103:                .$message."\n"
 3104:                .'</div>'."\n";
 3105:     } else {
 3106:         return $message;
 3107:     }
 3108: }
 3109: 
 3110: # ------------------------------------------------------------- Message Wrapper
 3111: 
 3112: sub messagewrapper {
 3113:     my ($link,$username,$domain,$subject,$text)=@_;
 3114:     return 
 3115:         '<a href="/adm/email?compose=individual&amp;'.
 3116:         'recname='.$username.'&amp;recdom='.$domain.
 3117: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3118:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3119: }
 3120: 
 3121: # --------------------------------------------------------------- Notes Wrapper
 3122: 
 3123: sub noteswrapper {
 3124:     my ($link,$un,$do)=@_;
 3125:     return 
 3126: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3127: }
 3128: 
 3129: # ------------------------------------------------------------- Aboutme Wrapper
 3130: 
 3131: sub aboutmewrapper {
 3132:     my ($link,$username,$domain,$target,$class)=@_;
 3133:     if (!defined($username)  && !defined($domain)) {
 3134:         return;
 3135:     }
 3136:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3137: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3138: }
 3139: 
 3140: # ------------------------------------------------------------ Syllabus Wrapper
 3141: 
 3142: sub syllabuswrapper {
 3143:     my ($linktext,$coursedir,$domain)=@_;
 3144:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3145: }
 3146: 
 3147: # -----------------------------------------------------------------------------
 3148: 
 3149: sub track_student_link {
 3150:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3151:     my $link ="/adm/trackstudent?";
 3152:     my $title = 'View recent activity';
 3153:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3154:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3155:         $link .= "selected_student=$sname:$sdom";
 3156:         $title .= ' of this student';
 3157:     } 
 3158:     if (defined($target) && $target !~ /^\s*$/) {
 3159:         $target = qq{target="$target"};
 3160:     } else {
 3161:         $target = '';
 3162:     }
 3163:     if ($start) { $link.='&amp;start='.$start; }
 3164:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3165:     $title = &mt($title);
 3166:     $linktext = &mt($linktext);
 3167:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3168: 	&help_open_topic('View_recent_activity');
 3169: }
 3170: 
 3171: sub slot_reservations_link {
 3172:     my ($linktext,$sname,$sdom,$target) = @_;
 3173:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3174:     my $title = 'View slot reservation history';
 3175:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3176:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3177:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3178:         $title .= ' of this student';
 3179:     }
 3180:     if (defined($target) && $target !~ /^\s*$/) {
 3181:         $target = qq{target="$target"};
 3182:     } else {
 3183:         $target = '';
 3184:     }
 3185:     $title = &mt($title);
 3186:     $linktext = &mt($linktext);
 3187:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3188: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3189: 
 3190: }
 3191: 
 3192: # ===================================================== Display a student photo
 3193: 
 3194: 
 3195: sub student_image_tag {
 3196:     my ($domain,$user)=@_;
 3197:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3198:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3199: 	return '<img src="'.$imgsrc.'" align="right" />';
 3200:     } else {
 3201: 	return '';
 3202:     }
 3203: }
 3204: 
 3205: =pod
 3206: 
 3207: =back
 3208: 
 3209: =head1 Access .tab File Data
 3210: 
 3211: =over 4
 3212: 
 3213: =item * &languageids() 
 3214: 
 3215: returns list of all language ids
 3216: 
 3217: =cut
 3218: 
 3219: sub languageids {
 3220:     return sort(keys(%language));
 3221: }
 3222: 
 3223: =pod
 3224: 
 3225: =item * &languagedescription() 
 3226: 
 3227: returns description of a specified language id
 3228: 
 3229: =cut
 3230: 
 3231: sub languagedescription {
 3232:     my $code=shift;
 3233:     return  ($supported_language{$code}?'* ':'').
 3234:             $language{$code}.
 3235: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3236: }
 3237: 
 3238: =pod
 3239: 
 3240: =item * &plainlanguagedescription
 3241: 
 3242: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3243: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3244: 
 3245: =cut
 3246: 
 3247: sub plainlanguagedescription {
 3248:     my $code=shift;
 3249:     return $language{$code};
 3250: }
 3251: 
 3252: =pod
 3253: 
 3254: =item * &supportedlanguagecode
 3255: 
 3256: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3257: code.
 3258: 
 3259: =cut
 3260: 
 3261: sub supportedlanguagecode {
 3262:     my $code=shift;
 3263:     return $supported_language{$code};
 3264: }
 3265: 
 3266: =pod
 3267: 
 3268: =item * &latexlanguage()
 3269: 
 3270: Given a language key code returns the correspondnig language to use
 3271: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3272: is no supported hyphenation for the language code.
 3273: 
 3274: =cut
 3275: 
 3276: sub latexlanguage {
 3277:     my $code = shift;
 3278:     return $latex_language{$code};
 3279: }
 3280: 
 3281: =pod
 3282: 
 3283: =item * &latexhyphenation()
 3284: 
 3285: Same as above but what's supplied is the language as it might be stored
 3286: in the metadata.
 3287: 
 3288: =cut
 3289: 
 3290: sub latexhyphenation {
 3291:     my $key = shift;
 3292:     return $latex_language_bykey{$key};
 3293: }
 3294: 
 3295: =pod
 3296: 
 3297: =item * &copyrightids() 
 3298: 
 3299: returns list of all copyrights
 3300: 
 3301: =cut
 3302: 
 3303: sub copyrightids {
 3304:     return sort(keys(%cprtag));
 3305: }
 3306: 
 3307: =pod
 3308: 
 3309: =item * &copyrightdescription() 
 3310: 
 3311: returns description of a specified copyright id
 3312: 
 3313: =cut
 3314: 
 3315: sub copyrightdescription {
 3316:     return &mt($cprtag{shift(@_)});
 3317: }
 3318: 
 3319: =pod
 3320: 
 3321: =item * &source_copyrightids() 
 3322: 
 3323: returns list of all source copyrights
 3324: 
 3325: =cut
 3326: 
 3327: sub source_copyrightids {
 3328:     return sort(keys(%scprtag));
 3329: }
 3330: 
 3331: =pod
 3332: 
 3333: =item * &source_copyrightdescription() 
 3334: 
 3335: returns description of a specified source copyright id
 3336: 
 3337: =cut
 3338: 
 3339: sub source_copyrightdescription {
 3340:     return &mt($scprtag{shift(@_)});
 3341: }
 3342: 
 3343: =pod
 3344: 
 3345: =item * &filecategories() 
 3346: 
 3347: returns list of all file categories
 3348: 
 3349: =cut
 3350: 
 3351: sub filecategories {
 3352:     return sort(keys(%category_extensions));
 3353: }
 3354: 
 3355: =pod
 3356: 
 3357: =item * &filecategorytypes() 
 3358: 
 3359: returns list of file types belonging to a given file
 3360: category
 3361: 
 3362: =cut
 3363: 
 3364: sub filecategorytypes {
 3365:     my ($cat) = @_;
 3366:     return @{$category_extensions{lc($cat)}};
 3367: }
 3368: 
 3369: =pod
 3370: 
 3371: =item * &fileembstyle() 
 3372: 
 3373: returns embedding style for a specified file type
 3374: 
 3375: =cut
 3376: 
 3377: sub fileembstyle {
 3378:     return $fe{lc(shift(@_))};
 3379: }
 3380: 
 3381: sub filemimetype {
 3382:     return $fm{lc(shift(@_))};
 3383: }
 3384: 
 3385: 
 3386: sub filecategoryselect {
 3387:     my ($name,$value)=@_;
 3388:     return &select_form($value,$name,
 3389:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3390: }
 3391: 
 3392: =pod
 3393: 
 3394: =item * &filedescription() 
 3395: 
 3396: returns description for a specified file type
 3397: 
 3398: =cut
 3399: 
 3400: sub filedescription {
 3401:     my $file_description = $fd{lc(shift())};
 3402:     $file_description =~ s:([\[\]]):~$1:g;
 3403:     return &mt($file_description);
 3404: }
 3405: 
 3406: =pod
 3407: 
 3408: =item * &filedescriptionex() 
 3409: 
 3410: returns description for a specified file type with
 3411: extra formatting
 3412: 
 3413: =cut
 3414: 
 3415: sub filedescriptionex {
 3416:     my $ex=shift;
 3417:     my $file_description = $fd{lc($ex)};
 3418:     $file_description =~ s:([\[\]]):~$1:g;
 3419:     return '.'.$ex.' '.&mt($file_description);
 3420: }
 3421: 
 3422: # End of .tab access
 3423: =pod
 3424: 
 3425: =back
 3426: 
 3427: =cut
 3428: 
 3429: # ------------------------------------------------------------------ File Types
 3430: sub fileextensions {
 3431:     return sort(keys(%fe));
 3432: }
 3433: 
 3434: # ----------------------------------------------------------- Display Languages
 3435: # returns a hash with all desired display languages
 3436: #
 3437: 
 3438: sub display_languages {
 3439:     my %languages=();
 3440:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3441: 	$languages{$lang}=1;
 3442:     }
 3443:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3444:     if ($env{'form.displaylanguage'}) {
 3445: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3446: 	    $languages{$lang}=1;
 3447:         }
 3448:     }
 3449:     return %languages;
 3450: }
 3451: 
 3452: sub languages {
 3453:     my ($possible_langs) = @_;
 3454:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3455:     if (!ref($possible_langs)) {
 3456: 	if( wantarray ) {
 3457: 	    return @preferred_langs;
 3458: 	} else {
 3459: 	    return $preferred_langs[0];
 3460: 	}
 3461:     }
 3462:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3463:     my @preferred_possibilities;
 3464:     foreach my $preferred_lang (@preferred_langs) {
 3465: 	if (exists($possibilities{$preferred_lang})) {
 3466: 	    push(@preferred_possibilities, $preferred_lang);
 3467: 	}
 3468:     }
 3469:     if( wantarray ) {
 3470: 	return @preferred_possibilities;
 3471:     }
 3472:     return $preferred_possibilities[0];
 3473: }
 3474: 
 3475: sub user_lang {
 3476:     my ($touname,$toudom,$fromcid) = @_;
 3477:     my @userlangs;
 3478:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3479:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3480:                     $env{'course.'.$fromcid.'.languages'}));
 3481:     } else {
 3482:         my %langhash = &getlangs($touname,$toudom);
 3483:         if ($langhash{'languages'} ne '') {
 3484:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3485:         } else {
 3486:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3487:             if ($domdefs{'lang_def'} ne '') {
 3488:                 @userlangs = ($domdefs{'lang_def'});
 3489:             }
 3490:         }
 3491:     }
 3492:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3493:     my $user_lh = Apache::localize->get_handle(@languages);
 3494:     return $user_lh;
 3495: }
 3496: 
 3497: 
 3498: ###############################################################
 3499: ##               Student Answer Attempts                     ##
 3500: ###############################################################
 3501: 
 3502: =pod
 3503: 
 3504: =head1 Alternate Problem Views
 3505: 
 3506: =over 4
 3507: 
 3508: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3509:     $getattempt, $regexp, $gradesub)
 3510: 
 3511: Return string with previous attempt on problem. Arguments:
 3512: 
 3513: =over 4
 3514: 
 3515: =item * $symb: Problem, including path
 3516: 
 3517: =item * $username: username of the desired student
 3518: 
 3519: =item * $domain: domain of the desired student
 3520: 
 3521: =item * $course: Course ID
 3522: 
 3523: =item * $getattempt: Leave blank for all attempts, otherwise put
 3524:     something
 3525: 
 3526: =item * $regexp: if string matches this regexp, the string will be
 3527:     sent to $gradesub
 3528: 
 3529: =item * $gradesub: routine that processes the string if it matches $regexp
 3530: 
 3531: =back
 3532: 
 3533: The output string is a table containing all desired attempts, if any.
 3534: 
 3535: =cut
 3536: 
 3537: sub get_previous_attempt {
 3538:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3539:   my $prevattempts='';
 3540:   no strict 'refs';
 3541:   if ($symb) {
 3542:     my (%returnhash)=
 3543:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3544:     if ($returnhash{'version'}) {
 3545:       my %lasthash=();
 3546:       my $version;
 3547:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3548:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3549: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3550:         }
 3551:       }
 3552:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3553:       $prevattempts.='<th>'.&mt('History').'</th>';
 3554:       my (%typeparts,%lasthidden);
 3555:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3556:       foreach my $key (sort(keys(%lasthash))) {
 3557: 	my ($ign,@parts) = split(/\./,$key);
 3558: 	if ($#parts > 0) {
 3559: 	  my $data=$parts[-1];
 3560:           next if ($data eq 'foilorder');
 3561: 	  pop(@parts);
 3562:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3563:           if ($data eq 'type') {
 3564:               unless ($showsurv) {
 3565:                   my $id = join(',',@parts);
 3566:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3567:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3568:                       $lasthidden{$ign.'.'.$id} = 1;
 3569:                   }
 3570:               }
 3571:           } 
 3572: 	} else {
 3573: 	  if ($#parts == 0) {
 3574: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3575: 	  } else {
 3576: 	    $prevattempts.='<th>'.$ign.'</th>';
 3577: 	  }
 3578: 	}
 3579:       }
 3580:       $prevattempts.=&end_data_table_header_row();
 3581:       if ($getattempt eq '') {
 3582: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3583:             my @hidden;
 3584:             if (%typeparts) {
 3585:                 foreach my $id (keys(%typeparts)) {
 3586:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3587:                         push(@hidden,$id);
 3588:                     }
 3589:                 }
 3590:             }
 3591:             $prevattempts.=&start_data_table_row().
 3592:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3593:             if (@hidden) {
 3594:                 foreach my $key (sort(keys(%lasthash))) {
 3595:                     next if ($key =~ /\.foilorder$/);
 3596:                     my $hide;
 3597:                     foreach my $id (@hidden) {
 3598:                         if ($key =~ /^\Q$id\E/) {
 3599:                             $hide = 1;
 3600:                             last;
 3601:                         }
 3602:                     }
 3603:                     if ($hide) {
 3604:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3605:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3606:                             my $value = &format_previous_attempt_value($key,
 3607:                                              $returnhash{$version.':'.$key});
 3608:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3609:                         } else {
 3610:                             $prevattempts.='<td>&nbsp;</td>';
 3611:                         }
 3612:                     } else {
 3613:                         if ($key =~ /\./) {
 3614:                             my $value = &format_previous_attempt_value($key,
 3615:                                               $returnhash{$version.':'.$key});
 3616:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3617:                         } else {
 3618:                             $prevattempts.='<td>&nbsp;</td>';
 3619:                         }
 3620:                     }
 3621:                 }
 3622:             } else {
 3623: 	        foreach my $key (sort(keys(%lasthash))) {
 3624:                     next if ($key =~ /\.foilorder$/);
 3625: 		    my $value = &format_previous_attempt_value($key,
 3626: 			            $returnhash{$version.':'.$key});
 3627: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3628: 	        }
 3629:             }
 3630: 	    $prevattempts.=&end_data_table_row();
 3631: 	 }
 3632:       }
 3633:       my @currhidden = keys(%lasthidden);
 3634:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3635:       foreach my $key (sort(keys(%lasthash))) {
 3636:           next if ($key =~ /\.foilorder$/);
 3637:           if (%typeparts) {
 3638:               my $hidden;
 3639:               foreach my $id (@currhidden) {
 3640:                   if ($key =~ /^\Q$id\E/) {
 3641:                       $hidden = 1;
 3642:                       last;
 3643:                   }
 3644:               }
 3645:               if ($hidden) {
 3646:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3647:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3648:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3649:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3650:                           $value = &$gradesub($value);
 3651:                       }
 3652:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3653:                   } else {
 3654:                       $prevattempts.='<td>&nbsp;</td>';
 3655:                   }
 3656:               } else {
 3657:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3658:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3659:                       $value = &$gradesub($value);
 3660:                   }
 3661:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3662:               }
 3663:           } else {
 3664: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3665: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3666:                   $value = &$gradesub($value);
 3667:               }
 3668: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3669:           }
 3670:       }
 3671:       $prevattempts.= &end_data_table_row().&end_data_table();
 3672:     } else {
 3673:       $prevattempts=
 3674: 	  &start_data_table().&start_data_table_row().
 3675: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3676: 	  &end_data_table_row().&end_data_table();
 3677:     }
 3678:   } else {
 3679:     $prevattempts=
 3680: 	  &start_data_table().&start_data_table_row().
 3681: 	  '<td>'.&mt('No data.').'</td>'.
 3682: 	  &end_data_table_row().&end_data_table();
 3683:   }
 3684: }
 3685: 
 3686: sub format_previous_attempt_value {
 3687:     my ($key,$value) = @_;
 3688:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3689: 	$value = &Apache::lonlocal::locallocaltime($value);
 3690:     } elsif (ref($value) eq 'ARRAY') {
 3691: 	$value = '('.join(', ', @{ $value }).')';
 3692:     } elsif ($key =~ /answerstring$/) {
 3693:         my %answers = &Apache::lonnet::str2hash($value);
 3694:         my @anskeys = sort(keys(%answers));
 3695:         if (@anskeys == 1) {
 3696:             my $answer = $answers{$anskeys[0]};
 3697:             if ($answer =~ m{\0}) {
 3698:                 $answer =~ s{\0}{,}g;
 3699:             }
 3700:             my $tag_internal_answer_name = 'INTERNAL';
 3701:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3702:                 $value = $answer; 
 3703:             } else {
 3704:                 $value = $anskeys[0].'='.$answer;
 3705:             }
 3706:         } else {
 3707:             foreach my $ans (@anskeys) {
 3708:                 my $answer = $answers{$ans};
 3709:                 if ($answer =~ m{\0}) {
 3710:                     $answer =~ s{\0}{,}g;
 3711:                 }
 3712:                 $value .=  $ans.'='.$answer.'<br />';;
 3713:             } 
 3714:         }
 3715:     } else {
 3716: 	$value = &unescape($value);
 3717:     }
 3718:     return $value;
 3719: }
 3720: 
 3721: 
 3722: sub relative_to_absolute {
 3723:     my ($url,$output)=@_;
 3724:     my $parser=HTML::TokeParser->new(\$output);
 3725:     my $token;
 3726:     my $thisdir=$url;
 3727:     my @rlinks=();
 3728:     while ($token=$parser->get_token) {
 3729: 	if ($token->[0] eq 'S') {
 3730: 	    if ($token->[1] eq 'a') {
 3731: 		if ($token->[2]->{'href'}) {
 3732: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3733: 		}
 3734: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3735: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3736: 	    } elsif ($token->[1] eq 'base') {
 3737: 		$thisdir=$token->[2]->{'href'};
 3738: 	    }
 3739: 	}
 3740:     }
 3741:     $thisdir=~s-/[^/]*$--;
 3742:     foreach my $link (@rlinks) {
 3743: 	unless (($link=~/^https?\:\/\//i) ||
 3744: 		($link=~/^\//) ||
 3745: 		($link=~/^javascript:/i) ||
 3746: 		($link=~/^mailto:/i) ||
 3747: 		($link=~/^\#/)) {
 3748: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3749: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3750: 	}
 3751:     }
 3752: # -------------------------------------------------- Deal with Applet codebases
 3753:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3754:     return $output;
 3755: }
 3756: 
 3757: =pod
 3758: 
 3759: =item * &get_student_view()
 3760: 
 3761: show a snapshot of what student was looking at
 3762: 
 3763: =cut
 3764: 
 3765: sub get_student_view {
 3766:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3767:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3768:   my (%form);
 3769:   my @elements=('symb','courseid','domain','username');
 3770:   foreach my $element (@elements) {
 3771:       $form{'grade_'.$element}=eval '$'.$element #'
 3772:   }
 3773:   if (defined($moreenv)) {
 3774:       %form=(%form,%{$moreenv});
 3775:   }
 3776:   if (defined($target)) { $form{'grade_target'} = $target; }
 3777:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3778:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3779:   $userview=~s/\<body[^\>]*\>//gi;
 3780:   $userview=~s/\<\/body\>//gi;
 3781:   $userview=~s/\<html\>//gi;
 3782:   $userview=~s/\<\/html\>//gi;
 3783:   $userview=~s/\<head\>//gi;
 3784:   $userview=~s/\<\/head\>//gi;
 3785:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3786:   $userview=&relative_to_absolute($feedurl,$userview);
 3787:   if (wantarray) {
 3788:      return ($userview,$response);
 3789:   } else {
 3790:      return $userview;
 3791:   }
 3792: }
 3793: 
 3794: sub get_student_view_with_retries {
 3795:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3796: 
 3797:     my $ok = 0;                 # True if we got a good response.
 3798:     my $content;
 3799:     my $response;
 3800: 
 3801:     # Try to get the student_view done. within the retries count:
 3802:     
 3803:     do {
 3804:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3805:          $ok      = $response->is_success;
 3806:          if (!$ok) {
 3807:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3808:          }
 3809:          $retries--;
 3810:     } while (!$ok && ($retries > 0));
 3811:     
 3812:     if (!$ok) {
 3813:        $content = '';          # On error return an empty content.
 3814:     }
 3815:     if (wantarray) {
 3816:        return ($content, $response);
 3817:     } else {
 3818:        return $content;
 3819:     }
 3820: }
 3821: 
 3822: =pod
 3823: 
 3824: =item * &get_student_answers() 
 3825: 
 3826: show a snapshot of how student was answering problem
 3827: 
 3828: =cut
 3829: 
 3830: sub get_student_answers {
 3831:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3832:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3833:   my (%moreenv);
 3834:   my @elements=('symb','courseid','domain','username');
 3835:   foreach my $element (@elements) {
 3836:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3837:   }
 3838:   $moreenv{'grade_target'}='answer';
 3839:   %moreenv=(%form,%moreenv);
 3840:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3841:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3842:   return $userview;
 3843: }
 3844: 
 3845: =pod
 3846: 
 3847: =item * &submlink()
 3848: 
 3849: Inputs: $text $uname $udom $symb $target
 3850: 
 3851: Returns: A link to grades.pm such as to see the SUBM view of a student
 3852: 
 3853: =cut
 3854: 
 3855: ###############################################
 3856: sub submlink {
 3857:     my ($text,$uname,$udom,$symb,$target)=@_;
 3858:     if (!($uname && $udom)) {
 3859: 	(my $cursymb, my $courseid,$udom,$uname)=
 3860: 	    &Apache::lonnet::whichuser($symb);
 3861: 	if (!$symb) { $symb=$cursymb; }
 3862:     }
 3863:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3864:     $symb=&escape($symb);
 3865:     if ($target) { $target=" target=\"$target\""; }
 3866:     return
 3867:         '<a href="/adm/grades?command=submission'.
 3868:         '&amp;symb='.$symb.
 3869:         '&amp;student='.$uname.
 3870:         '&amp;userdom='.$udom.'"'.
 3871:         $target.'>'.$text.'</a>';
 3872: }
 3873: ##############################################
 3874: 
 3875: =pod
 3876: 
 3877: =item * &pgrdlink()
 3878: 
 3879: Inputs: $text $uname $udom $symb $target
 3880: 
 3881: Returns: A link to grades.pm such as to see the PGRD view of a student
 3882: 
 3883: =cut
 3884: 
 3885: ###############################################
 3886: sub pgrdlink {
 3887:     my $link=&submlink(@_);
 3888:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3889:     return $link;
 3890: }
 3891: ##############################################
 3892: 
 3893: =pod
 3894: 
 3895: =item * &pprmlink()
 3896: 
 3897: Inputs: $text $uname $udom $symb $target
 3898: 
 3899: Returns: A link to parmset.pm such as to see the PPRM view of a
 3900: student and a specific resource
 3901: 
 3902: =cut
 3903: 
 3904: ###############################################
 3905: sub pprmlink {
 3906:     my ($text,$uname,$udom,$symb,$target)=@_;
 3907:     if (!($uname && $udom)) {
 3908: 	(my $cursymb, my $courseid,$udom,$uname)=
 3909: 	    &Apache::lonnet::whichuser($symb);
 3910: 	if (!$symb) { $symb=$cursymb; }
 3911:     }
 3912:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3913:     $symb=&escape($symb);
 3914:     if ($target) { $target="target=\"$target\""; }
 3915:     return '<a href="/adm/parmset?command=set&amp;'.
 3916: 	'symb='.$symb.'&amp;uname='.$uname.
 3917: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3918: }
 3919: ##############################################
 3920: 
 3921: =pod
 3922: 
 3923: =back
 3924: 
 3925: =cut
 3926: 
 3927: ###############################################
 3928: 
 3929: 
 3930: sub timehash {
 3931:     my ($thistime) = @_;
 3932:     my $timezone = &Apache::lonlocal::gettimezone();
 3933:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3934:                      ->set_time_zone($timezone);
 3935:     my $wday = $dt->day_of_week();
 3936:     if ($wday == 7) { $wday = 0; }
 3937:     return ( 'second' => $dt->second(),
 3938:              'minute' => $dt->minute(),
 3939:              'hour'   => $dt->hour(),
 3940:              'day'     => $dt->day_of_month(),
 3941:              'month'   => $dt->month(),
 3942:              'year'    => $dt->year(),
 3943:              'weekday' => $wday,
 3944:              'dayyear' => $dt->day_of_year(),
 3945:              'dlsav'   => $dt->is_dst() );
 3946: }
 3947: 
 3948: sub utc_string {
 3949:     my ($date)=@_;
 3950:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3951: }
 3952: 
 3953: sub maketime {
 3954:     my %th=@_;
 3955:     my ($epoch_time,$timezone,$dt);
 3956:     $timezone = &Apache::lonlocal::gettimezone();
 3957:     eval {
 3958:         $dt = DateTime->new( year   => $th{'year'},
 3959:                              month  => $th{'month'},
 3960:                              day    => $th{'day'},
 3961:                              hour   => $th{'hour'},
 3962:                              minute => $th{'minute'},
 3963:                              second => $th{'second'},
 3964:                              time_zone => $timezone,
 3965:                          );
 3966:     };
 3967:     if (!$@) {
 3968:         $epoch_time = $dt->epoch;
 3969:         if ($epoch_time) {
 3970:             return $epoch_time;
 3971:         }
 3972:     }
 3973:     return POSIX::mktime(
 3974:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3975:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3976: }
 3977: 
 3978: #########################################
 3979: 
 3980: sub findallcourses {
 3981:     my ($roles,$uname,$udom) = @_;
 3982:     my %roles;
 3983:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3984:     my %courses;
 3985:     my $now=time;
 3986:     if (!defined($uname)) {
 3987:         $uname = $env{'user.name'};
 3988:     }
 3989:     if (!defined($udom)) {
 3990:         $udom = $env{'user.domain'};
 3991:     }
 3992:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3993:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3994:         if (!%roles) {
 3995:             %roles = (
 3996:                        cc => 1,
 3997:                        co => 1,
 3998:                        in => 1,
 3999:                        ep => 1,
 4000:                        ta => 1,
 4001:                        cr => 1,
 4002:                        st => 1,
 4003:              );
 4004:         }
 4005:         foreach my $entry (keys(%roleshash)) {
 4006:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4007:             if ($trole =~ /^cr/) { 
 4008:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4009:             } else {
 4010:                 next if (!exists($roles{$trole}));
 4011:             }
 4012:             if ($tend) {
 4013:                 next if ($tend < $now);
 4014:             }
 4015:             if ($tstart) {
 4016:                 next if ($tstart > $now);
 4017:             }
 4018:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4019:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4020:             my $value = $trole.'/'.$cdom.'/';
 4021:             if ($secpart eq '') {
 4022:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4023:                 $sec = 'none';
 4024:                 $value .= $cnum.'/';
 4025:             } else {
 4026:                 $cnum = $cnumpart;
 4027:                 ($sec,$role) = split(/_/,$secpart);
 4028:                 $value .= $cnum.'/'.$sec;
 4029:             }
 4030:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4031:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4032:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4033:                 }
 4034:             } else {
 4035:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4036:             }
 4037:         }
 4038:     } else {
 4039:         foreach my $key (keys(%env)) {
 4040: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4041:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4042: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4043: 	        next if ($role eq 'ca' || $role eq 'aa');
 4044: 	        next if (%roles && !exists($roles{$role}));
 4045: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4046:                 my $active=1;
 4047:                 if ($starttime) {
 4048: 		    if ($now<$starttime) { $active=0; }
 4049:                 }
 4050:                 if ($endtime) {
 4051:                     if ($now>$endtime) { $active=0; }
 4052:                 }
 4053:                 if ($active) {
 4054:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4055:                     if ($sec eq '') {
 4056:                         $sec = 'none';
 4057:                     } else {
 4058:                         $value .= $sec;
 4059:                     }
 4060:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4061:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4062:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4063:                         }
 4064:                     } else {
 4065:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4066:                     }
 4067:                 }
 4068:             }
 4069:         }
 4070:     }
 4071:     return %courses;
 4072: }
 4073: 
 4074: ###############################################
 4075: 
 4076: sub blockcheck {
 4077:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4078: 
 4079:     if (!defined($udom)) {
 4080:         $udom = $env{'user.domain'};
 4081:     }
 4082:     if (!defined($uname)) {
 4083:         $uname = $env{'user.name'};
 4084:     }
 4085: 
 4086:     # If uname and udom are for a course, check for blocks in the course.
 4087: 
 4088:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4089:         my ($startblock,$endblock,$triggerblock) = 
 4090:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4091:         return ($startblock,$endblock,$triggerblock);
 4092:     }
 4093: 
 4094:     my $startblock = 0;
 4095:     my $endblock = 0;
 4096:     my $triggerblock = '';
 4097:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4098: 
 4099:     # If uname is for a user, and activity is course-specific, i.e.,
 4100:     # boards, chat or groups, check for blocking in current course only.
 4101: 
 4102:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4103:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4104:         foreach my $key (keys(%live_courses)) {
 4105:             if ($key ne $env{'request.course.id'}) {
 4106:                 delete($live_courses{$key});
 4107:             }
 4108:         }
 4109:     }
 4110: 
 4111:     my $otheruser = 0;
 4112:     my %own_courses;
 4113:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4114:         # Resource belongs to user other than current user.
 4115:         $otheruser = 1;
 4116:         # Gather courses for current user
 4117:         %own_courses = 
 4118:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4119:     }
 4120: 
 4121:     # Gather active course roles - course coordinator, instructor, 
 4122:     # exam proctor, ta, student, or custom role.
 4123: 
 4124:     foreach my $course (keys(%live_courses)) {
 4125:         my ($cdom,$cnum);
 4126:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4127:             $cdom = $env{'course.'.$course.'.domain'};
 4128:             $cnum = $env{'course.'.$course.'.num'};
 4129:         } else {
 4130:             ($cdom,$cnum) = split(/_/,$course); 
 4131:         }
 4132:         my $no_ownblock = 0;
 4133:         my $no_userblock = 0;
 4134:         if ($otheruser && $activity ne 'com') {
 4135:             # Check if current user has 'evb' priv for this
 4136:             if (defined($own_courses{$course})) {
 4137:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4138:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4139:                     if ($sec ne 'none') {
 4140:                         $checkrole .= '/'.$sec;
 4141:                     }
 4142:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4143:                         $no_ownblock = 1;
 4144:                         last;
 4145:                     }
 4146:                 }
 4147:             }
 4148:             # if they have 'evb' priv and are currently not playing student
 4149:             next if (($no_ownblock) &&
 4150:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4151:         }
 4152:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4153:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4154:             if ($sec ne 'none') {
 4155:                 $checkrole .= '/'.$sec;
 4156:             }
 4157:             if ($otheruser) {
 4158:                 # Resource belongs to user other than current user.
 4159:                 # Assemble privs for that user, and check for 'evb' priv.
 4160:                 my (%allroles,%userroles);
 4161:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4162:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4163:                         my ($trole,$tdom,$tnum,$tsec);
 4164:                         if ($entry =~ /^cr/) {
 4165:                             ($trole,$tdom,$tnum,$tsec) = 
 4166:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4167:                         } else {
 4168:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4169:                         }
 4170:                         my ($spec,$area,$trest);
 4171:                         $area = '/'.$tdom.'/'.$tnum;
 4172:                         $trest = $tnum;
 4173:                         if ($tsec ne '') {
 4174:                             $area .= '/'.$tsec;
 4175:                             $trest .= '/'.$tsec;
 4176:                         }
 4177:                         $spec = $trole.'.'.$area;
 4178:                         if ($trole =~ /^cr/) {
 4179:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4180:                                                               $tdom,$spec,$trest,$area);
 4181:                         } else {
 4182:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4183:                                                                 $tdom,$spec,$trest,$area);
 4184:                         }
 4185:                     }
 4186:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4187:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4188:                         if ($1) {
 4189:                             $no_userblock = 1;
 4190:                             last;
 4191:                         }
 4192:                     }
 4193:                 }
 4194:             } else {
 4195:                 # Resource belongs to current user
 4196:                 # Check for 'evb' priv via lonnet::allowed().
 4197:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4198:                     $no_ownblock = 1;
 4199:                     last;
 4200:                 }
 4201:             }
 4202:         }
 4203:         # if they have the evb priv and are currently not playing student
 4204:         next if (($no_ownblock) &&
 4205:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4206:         next if ($no_userblock);
 4207: 
 4208:         # Retrieve blocking times and identity of locker for course
 4209:         # of specified user, unless user has 'evb' privilege.
 4210:         
 4211:         my ($start,$end,$trigger) = 
 4212:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4213:         if (($start != 0) && 
 4214:             (($startblock == 0) || ($startblock > $start))) {
 4215:             $startblock = $start;
 4216:             if ($trigger ne '') {
 4217:                 $triggerblock = $trigger;
 4218:             }
 4219:         }
 4220:         if (($end != 0)  &&
 4221:             (($endblock == 0) || ($endblock < $end))) {
 4222:             $endblock = $end;
 4223:             if ($trigger ne '') {
 4224:                 $triggerblock = $trigger;
 4225:             }
 4226:         }
 4227:     }
 4228:     return ($startblock,$endblock,$triggerblock);
 4229: }
 4230: 
 4231: sub get_blocks {
 4232:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4233:     my $startblock = 0;
 4234:     my $endblock = 0;
 4235:     my $triggerblock = '';
 4236:     my $course = $cdom.'_'.$cnum;
 4237:     $setters->{$course} = {};
 4238:     $setters->{$course}{'staff'} = [];
 4239:     $setters->{$course}{'times'} = [];
 4240:     $setters->{$course}{'triggers'} = [];
 4241:     my (@blockers,%triggered);
 4242:     my $now = time;
 4243:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4244:     if ($activity eq 'docs') {
 4245:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4246:         foreach my $block (@blockers) {
 4247:             if ($block =~ /^firstaccess____(.+)$/) {
 4248:                 my $item = $1;
 4249:                 my $type = 'map';
 4250:                 my $timersymb = $item;
 4251:                 if ($item eq 'course') {
 4252:                     $type = 'course';
 4253:                 } elsif ($item =~ /___\d+___/) {
 4254:                     $type = 'resource';
 4255:                 } else {
 4256:                     $timersymb = &Apache::lonnet::symbread($item);
 4257:                 }
 4258:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4259:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4260:                 $triggered{$block} = {
 4261:                                        start => $start,
 4262:                                        end   => $end,
 4263:                                        type  => $type,
 4264:                                      };
 4265:             }
 4266:         }
 4267:     } else {
 4268:         foreach my $block (keys(%commblocks)) {
 4269:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4270:                 my ($start,$end) = ($1,$2);
 4271:                 if ($start <= time && $end >= time) {
 4272:                     if (ref($commblocks{$block}) eq 'HASH') {
 4273:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4274:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4275:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4276:                                     push(@blockers,$block);
 4277:                                 }
 4278:                             }
 4279:                         }
 4280:                     }
 4281:                 }
 4282:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4283:                 my $item = $1;
 4284:                 my $timersymb = $item; 
 4285:                 my $type = 'map';
 4286:                 if ($item eq 'course') {
 4287:                     $type = 'course';
 4288:                 } elsif ($item =~ /___\d+___/) {
 4289:                     $type = 'resource';
 4290:                 } else {
 4291:                     $timersymb = &Apache::lonnet::symbread($item);
 4292:                 }
 4293:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4294:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4295:                 if ($start && $end) {
 4296:                     if (($start <= time) && ($end >= time)) {
 4297:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4298:                             push(@blockers,$block);
 4299:                             $triggered{$block} = {
 4300:                                                    start => $start,
 4301:                                                    end   => $end,
 4302:                                                    type  => $type,
 4303:                                                  };
 4304:                         }
 4305:                     }
 4306:                 }
 4307:             }
 4308:         }
 4309:     }
 4310:     foreach my $blocker (@blockers) {
 4311:         my ($staff_name,$staff_dom,$title,$blocks) =
 4312:             &parse_block_record($commblocks{$blocker});
 4313:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4314:         my ($start,$end,$triggertype);
 4315:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4316:             ($start,$end) = ($1,$2);
 4317:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4318:             $start = $triggered{$blocker}{'start'};
 4319:             $end = $triggered{$blocker}{'end'};
 4320:             $triggertype = $triggered{$blocker}{'type'};
 4321:         }
 4322:         if ($start) {
 4323:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4324:             if ($triggertype) {
 4325:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4326:             } else {
 4327:                 push(@{$$setters{$course}{'triggers'}},0);
 4328:             }
 4329:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4330:                 $startblock = $start;
 4331:                 if ($triggertype) {
 4332:                     $triggerblock = $blocker;
 4333:                 }
 4334:             }
 4335:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4336:                $endblock = $end;
 4337:                if ($triggertype) {
 4338:                    $triggerblock = $blocker;
 4339:                }
 4340:             }
 4341:         }
 4342:     }
 4343:     return ($startblock,$endblock,$triggerblock);
 4344: }
 4345: 
 4346: sub parse_block_record {
 4347:     my ($record) = @_;
 4348:     my ($setuname,$setudom,$title,$blocks);
 4349:     if (ref($record) eq 'HASH') {
 4350:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4351:         $title = &unescape($record->{'event'});
 4352:         $blocks = $record->{'blocks'};
 4353:     } else {
 4354:         my @data = split(/:/,$record,3);
 4355:         if (scalar(@data) eq 2) {
 4356:             $title = $data[1];
 4357:             ($setuname,$setudom) = split(/@/,$data[0]);
 4358:         } else {
 4359:             ($setuname,$setudom,$title) = @data;
 4360:         }
 4361:         $blocks = { 'com' => 'on' };
 4362:     }
 4363:     return ($setuname,$setudom,$title,$blocks);
 4364: }
 4365: 
 4366: sub blocking_status {
 4367:     my ($activity,$uname,$udom,$url) = @_;
 4368:     my %setters;
 4369: 
 4370: # check for active blocking
 4371:     my ($startblock,$endblock,$triggerblock) = 
 4372:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4373:     my $blocked = 0;
 4374:     if ($startblock && $endblock) {
 4375:         $blocked = 1;
 4376:     }
 4377: 
 4378: # caller just wants to know whether a block is active
 4379:     if (!wantarray) { return $blocked; }
 4380: 
 4381: # build a link to a popup window containing the details
 4382:     my $querystring  = "?activity=$activity";
 4383: # $uname and $udom decide whose portfolio the user is trying to look at
 4384:     if ($activity eq 'port') {
 4385:         $querystring .= "&amp;udom=$udom"      if $udom;
 4386:         $querystring .= "&amp;uname=$uname"    if $uname;
 4387:     } elsif ($activity eq 'docs') {
 4388:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4389:     }
 4390: 
 4391:     my $output .= <<'END_MYBLOCK';
 4392: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4393:     var options = "width=" + w + ",height=" + h + ",";
 4394:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4395:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4396:     var newWin = window.open(url, wdwName, options);
 4397:     newWin.focus();
 4398: }
 4399: END_MYBLOCK
 4400: 
 4401:     $output = Apache::lonhtmlcommon::scripttag($output);
 4402:   
 4403:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4404:     my $text = &mt('Communication Blocked');
 4405:     if ($activity eq 'docs') {
 4406:         $text = &mt('Content Access Blocked');
 4407:     } elsif ($activity eq 'printout') {
 4408:         $text = &mt('Printing Blocked');
 4409:     }
 4410:     $output .= <<"END_BLOCK";
 4411: <div class='LC_comblock'>
 4412:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4413:   title='$text'>
 4414:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4415:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4416:   title='$text'>$text</a>
 4417: </div>
 4418: 
 4419: END_BLOCK
 4420: 
 4421:     return ($blocked, $output);
 4422: }
 4423: 
 4424: ###############################################
 4425: 
 4426: sub check_ip_acc {
 4427:     my ($acc)=@_;
 4428:     &Apache::lonxml::debug("acc is $acc");
 4429:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4430:         return 1;
 4431:     }
 4432:     my $allowed=0;
 4433:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4434: 
 4435:     my $name;
 4436:     foreach my $pattern (split(',',$acc)) {
 4437:         $pattern =~ s/^\s*//;
 4438:         $pattern =~ s/\s*$//;
 4439:         if ($pattern =~ /\*$/) {
 4440:             #35.8.*
 4441:             $pattern=~s/\*//;
 4442:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4443:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4444:             #35.8.3.[34-56]
 4445:             my $low=$2;
 4446:             my $high=$3;
 4447:             $pattern=$1;
 4448:             if ($ip =~ /^\Q$pattern\E/) {
 4449:                 my $last=(split(/\./,$ip))[3];
 4450:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4451:             }
 4452:         } elsif ($pattern =~ /^\*/) {
 4453:             #*.msu.edu
 4454:             $pattern=~s/\*//;
 4455:             if (!defined($name)) {
 4456:                 use Socket;
 4457:                 my $netaddr=inet_aton($ip);
 4458:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4459:             }
 4460:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4461:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4462:             #127.0.0.1
 4463:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4464:         } else {
 4465:             #some.name.com
 4466:             if (!defined($name)) {
 4467:                 use Socket;
 4468:                 my $netaddr=inet_aton($ip);
 4469:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4470:             }
 4471:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4472:         }
 4473:         if ($allowed) { last; }
 4474:     }
 4475:     return $allowed;
 4476: }
 4477: 
 4478: ###############################################
 4479: 
 4480: =pod
 4481: 
 4482: =head1 Domain Template Functions
 4483: 
 4484: =over 4
 4485: 
 4486: =item * &determinedomain()
 4487: 
 4488: Inputs: $domain (usually will be undef)
 4489: 
 4490: Returns: Determines which domain should be used for designs
 4491: 
 4492: =cut
 4493: 
 4494: ###############################################
 4495: sub determinedomain {
 4496:     my $domain=shift;
 4497:     if (! $domain) {
 4498:         # Determine domain if we have not been given one
 4499:         $domain = &Apache::lonnet::default_login_domain();
 4500:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4501:         if ($env{'request.role.domain'}) { 
 4502:             $domain=$env{'request.role.domain'}; 
 4503:         }
 4504:     }
 4505:     return $domain;
 4506: }
 4507: ###############################################
 4508: 
 4509: sub devalidate_domconfig_cache {
 4510:     my ($udom)=@_;
 4511:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4512: }
 4513: 
 4514: # ---------------------- Get domain configuration for a domain
 4515: sub get_domainconf {
 4516:     my ($udom) = @_;
 4517:     my $cachetime=1800;
 4518:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4519:     if (defined($cached)) { return %{$result}; }
 4520: 
 4521:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4522: 					     ['login','rolecolors','autoenroll'],$udom);
 4523:     my (%designhash,%legacy);
 4524:     if (keys(%domconfig) > 0) {
 4525:         if (ref($domconfig{'login'}) eq 'HASH') {
 4526:             if (keys(%{$domconfig{'login'}})) {
 4527:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4528:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4529:                         if ($key eq 'loginvia') {
 4530:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4531:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4532:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4533:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4534:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4535:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4536:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4537: 
 4538:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4539:                                             } else {
 4540:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4541:                                             }
 4542:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4543:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4544:                                             }
 4545:                                         }
 4546:                                     }
 4547:                                 }
 4548:                             }
 4549:                         } else {
 4550:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4551:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4552:                                     $domconfig{'login'}{$key}{$img};
 4553:                             }
 4554:                         }
 4555:                     } else {
 4556:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4557:                     }
 4558:                 }
 4559:             } else {
 4560:                 $legacy{'login'} = 1;
 4561:             }
 4562:         } else {
 4563:             $legacy{'login'} = 1;
 4564:         }
 4565:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4566:             if (keys(%{$domconfig{'rolecolors'}})) {
 4567:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4568:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4569:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4570:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4571:                         }
 4572:                     }
 4573:                 }
 4574:             } else {
 4575:                 $legacy{'rolecolors'} = 1;
 4576:             }
 4577:         } else {
 4578:             $legacy{'rolecolors'} = 1;
 4579:         }
 4580:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4581:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4582:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4583:             }
 4584:         }
 4585:         if (keys(%legacy) > 0) {
 4586:             my %legacyhash = &get_legacy_domconf($udom);
 4587:             foreach my $item (keys(%legacyhash)) {
 4588:                 if ($item =~ /^\Q$udom\E\.login/) {
 4589:                     if ($legacy{'login'}) { 
 4590:                         $designhash{$item} = $legacyhash{$item};
 4591:                     }
 4592:                 } else {
 4593:                     if ($legacy{'rolecolors'}) {
 4594:                         $designhash{$item} = $legacyhash{$item};
 4595:                     }
 4596:                 }
 4597:             }
 4598:         }
 4599:     } else {
 4600:         %designhash = &get_legacy_domconf($udom); 
 4601:     }
 4602:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4603: 				  $cachetime);
 4604:     return %designhash;
 4605: }
 4606: 
 4607: sub get_legacy_domconf {
 4608:     my ($udom) = @_;
 4609:     my %legacyhash;
 4610:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4611:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4612:     if (-e $designfile) {
 4613:         if ( open (my $fh,"<$designfile") ) {
 4614:             while (my $line = <$fh>) {
 4615:                 next if ($line =~ /^\#/);
 4616:                 chomp($line);
 4617:                 my ($key,$val)=(split(/\=/,$line));
 4618:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4619:             }
 4620:             close($fh);
 4621:         }
 4622:     }
 4623:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4624:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4625:     }
 4626:     return %legacyhash;
 4627: }
 4628: 
 4629: =pod
 4630: 
 4631: =item * &domainlogo()
 4632: 
 4633: Inputs: $domain (usually will be undef)
 4634: 
 4635: Returns: A link to a domain logo, if the domain logo exists.
 4636: If the domain logo does not exist, a description of the domain.
 4637: 
 4638: =cut
 4639: 
 4640: ###############################################
 4641: sub domainlogo {
 4642:     my $domain = &determinedomain(shift);
 4643:     my %designhash = &get_domainconf($domain);    
 4644:     # See if there is a logo
 4645:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4646:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4647:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4648: 	    if ($imgsrc =~ m{^/res/}) {
 4649: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4650: 		&Apache::lonnet::repcopy($local_name);
 4651: 	    }
 4652: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4653:         } 
 4654:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4655:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4656:         return &Apache::lonnet::domain($domain,'description');
 4657:     } else {
 4658:         return '';
 4659:     }
 4660: }
 4661: ##############################################
 4662: 
 4663: =pod
 4664: 
 4665: =item * &designparm()
 4666: 
 4667: Inputs: $which parameter; $domain (usually will be undef)
 4668: 
 4669: Returns: value of designparamter $which
 4670: 
 4671: =cut
 4672: 
 4673: 
 4674: ##############################################
 4675: sub designparm {
 4676:     my ($which,$domain)=@_;
 4677:     if (exists($env{'environment.color.'.$which})) {
 4678:         return $env{'environment.color.'.$which};
 4679:     }
 4680:     $domain=&determinedomain($domain);
 4681:     my %domdesign;
 4682:     unless ($domain eq 'public') {
 4683:         %domdesign = &get_domainconf($domain);
 4684:     }
 4685:     my $output;
 4686:     if ($domdesign{$domain.'.'.$which} ne '') {
 4687:         $output = $domdesign{$domain.'.'.$which};
 4688:     } else {
 4689:         $output = $defaultdesign{$which};
 4690:     }
 4691:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4692:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4693:         if ($output =~ m{^/(adm|res)/}) {
 4694:             if ($output =~ m{^/res/}) {
 4695:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4696:                 &Apache::lonnet::repcopy($local_name);
 4697:             }
 4698:             $output = &lonhttpdurl($output);
 4699:         }
 4700:     }
 4701:     return $output;
 4702: }
 4703: 
 4704: ##############################################
 4705: =pod
 4706: 
 4707: =item * &authorspace()
 4708: 
 4709: Inputs: $url (usually will be undef).
 4710: 
 4711: Returns: Path to Construction Space containing the resource or 
 4712:          directory being viewed (or for which action is being taken). 
 4713:          If $url is provided, and begins /priv/<domain>/<uname>
 4714:          the path will be that portion of the $context argument.
 4715:          Otherwise the path will be for the author space of the current
 4716:          user when the current role is author, or for that of the 
 4717:          co-author/assistant co-author space when the current role 
 4718:          is co-author or assistant co-author.
 4719: 
 4720: =cut
 4721: 
 4722: sub authorspace {
 4723:     my ($url) = @_;
 4724:     if ($url ne '') {
 4725:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4726:            return $1;
 4727:         }
 4728:     }
 4729:     my $caname = '';
 4730:     my $cadom = '';
 4731:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4732:         ($cadom,$caname) =
 4733:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4734:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4735:         $caname = $env{'user.name'};
 4736:         $cadom = $env{'user.domain'};
 4737:     }
 4738:     if (($caname ne '') && ($cadom ne '')) {
 4739:         return "/priv/$cadom/$caname/";
 4740:     }
 4741:     return;
 4742: }
 4743: 
 4744: ##############################################
 4745: =pod
 4746: 
 4747: =item * &head_subbox()
 4748: 
 4749: Inputs: $content (contains HTML code with page functions, etc.)
 4750: 
 4751: Returns: HTML div with $content
 4752:          To be included in page header
 4753: 
 4754: =cut
 4755: 
 4756: sub head_subbox {
 4757:     my ($content)=@_;
 4758:     my $output =
 4759:         '<div class="LC_head_subbox">'
 4760:        .$content
 4761:        .'</div>'
 4762: }
 4763: 
 4764: ##############################################
 4765: =pod
 4766: 
 4767: =item * &CSTR_pageheader()
 4768: 
 4769: Input: (optional) filename from which breadcrumb trail is built.
 4770:        In most cases no input as needed, as $env{'request.filename'}
 4771:        is appropriate for use in building the breadcrumb trail.
 4772: 
 4773: Returns: HTML div with CSTR path and recent box
 4774:          To be included on Construction Space pages
 4775: 
 4776: =cut
 4777: 
 4778: sub CSTR_pageheader {
 4779:     my ($trailfile) = @_;
 4780:     if ($trailfile eq '') {
 4781:         $trailfile = $env{'request.filename'};
 4782:     }
 4783: 
 4784: # this is for resources; directories have customtitle, and crumbs
 4785: # and select recent are created in lonpubdir.pm
 4786: 
 4787:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4788:     my ($udom,$uname,$thisdisfn)=
 4789:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4790:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4791:     $formaction =~ s{/+}{/}g;
 4792: 
 4793:     my $parentpath = '';
 4794:     my $lastitem = '';
 4795:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4796:         $parentpath = $1;
 4797:         $lastitem = $2;
 4798:     } else {
 4799:         $lastitem = $thisdisfn;
 4800:     }
 4801: 
 4802:     my $output =
 4803:          '<div>'
 4804:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4805:         .'<b>'.&mt('Construction Space:').'</b> '
 4806:         .'<form name="dirs" method="post" action="'.$formaction
 4807:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4808:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4809: 
 4810:     if ($lastitem) {
 4811:         $output .=
 4812:              '<span class="LC_filename">'
 4813:             .$lastitem
 4814:             .'</span>';
 4815:     }
 4816:     $output .=
 4817:          '<br />'
 4818:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4819:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4820:         .'</form>'
 4821:         .&Apache::lonmenu::constspaceform()
 4822:         .'</div>';
 4823: 
 4824:     return $output;
 4825: }
 4826: 
 4827: ###############################################
 4828: ###############################################
 4829: 
 4830: =pod
 4831: 
 4832: =back
 4833: 
 4834: =head1 HTML Helpers
 4835: 
 4836: =over 4
 4837: 
 4838: =item * &bodytag()
 4839: 
 4840: Returns a uniform header for LON-CAPA web pages.
 4841: 
 4842: Inputs: 
 4843: 
 4844: =over 4
 4845: 
 4846: =item * $title, A title to be displayed on the page.
 4847: 
 4848: =item * $function, the current role (can be undef).
 4849: 
 4850: =item * $addentries, extra parameters for the <body> tag.
 4851: 
 4852: =item * $bodyonly, if defined, only return the <body> tag.
 4853: 
 4854: =item * $domain, if defined, force a given domain.
 4855: 
 4856: =item * $forcereg, if page should register as content page (relevant for 
 4857:             text interface only)
 4858: 
 4859: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4860:                      navigational links
 4861: 
 4862: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4863: 
 4864: =item * $args, optional argument valid values are
 4865:             no_auto_mt_title -> prevents &mt()ing the title arg
 4866:             inherit_jsmath -> when creating popup window in a page,
 4867:                               should it have jsmath forced on by the
 4868:                               current page
 4869: 
 4870: =back
 4871: 
 4872: Returns: A uniform header for LON-CAPA web pages.  
 4873: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4874: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4875: other decorations will be returned.
 4876: 
 4877: =cut
 4878: 
 4879: sub bodytag {
 4880:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4881:         $no_nav_bar,$bgcolor,$args)=@_;
 4882: 
 4883:     my $public;
 4884:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4885:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4886:         $public = 1;
 4887:     }
 4888:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4889: 
 4890:     $function = &get_users_function() if (!$function);
 4891:     my $img =    &designparm($function.'.img',$domain);
 4892:     my $font =   &designparm($function.'.font',$domain);
 4893:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4894: 
 4895:     my %design = ( 'style'   => 'margin-top: 0',
 4896: 		   'bgcolor' => $pgbg,
 4897: 		   'text'    => $font,
 4898:                    'alink'   => &designparm($function.'.alink',$domain),
 4899: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4900: 		   'link'    => &designparm($function.'.link',$domain),);
 4901:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4902: 
 4903:  # role and realm
 4904:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4905:     if ($role  eq 'ca') {
 4906:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4907:         $realm = &plainname($rname,$rdom);
 4908:     } 
 4909: # realm
 4910:     if ($env{'request.course.id'}) {
 4911:         if ($env{'request.role'} !~ /^cr/) {
 4912:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4913:         }
 4914:         if ($env{'request.course.sec'}) {
 4915:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4916:         }   
 4917: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4918:     } else {
 4919:         $role = &Apache::lonnet::plaintext($role);
 4920:     }
 4921: 
 4922:     if (!$realm) { $realm='&nbsp;'; }
 4923: 
 4924:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4925: 
 4926: # construct main body tag
 4927:     my $bodytag = "<body $extra_body_attr>".
 4928: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4929: 
 4930:     if ($bodyonly) {
 4931:         return $bodytag;
 4932:     } 
 4933: 
 4934:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4935:     if ($public) {
 4936: 	undef($role);
 4937:     } else {
 4938: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 4939:                                 undef,'LC_menubuttons_link');
 4940:     }
 4941:     
 4942:     my $titleinfo = '<h1>'.$title.'</h1>';
 4943:     #
 4944:     # Extra info if you are the DC
 4945:     my $dc_info = '';
 4946:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4947:                         $env{'course.'.$env{'request.course.id'}.
 4948:                                  '.domain'}.'/'})) {
 4949:         my $cid = $env{'request.course.id'};
 4950:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4951:         $dc_info =~ s/\s+$//;
 4952:     }
 4953: 
 4954:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4955:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4956: 
 4957:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4958:             return $bodytag; 
 4959:         } 
 4960: 
 4961:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4962: 
 4963:         #    if ($env{'request.state'} eq 'construct') {
 4964:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4965:         #    }
 4966: 
 4967: 
 4968: 
 4969:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4970:              if ($dc_info) {
 4971:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4972:              }
 4973:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4974:                 <em>$realm</em> $dc_info</div>|;
 4975:             return $bodytag;
 4976:         }
 4977: 
 4978:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4979:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4980:         }
 4981: 
 4982:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4983:             Apache::lonmenu::utilityfunctions(), 'start');
 4984: 
 4985:         $bodytag .= Apache::lonmenu::primary_menu();
 4986: 
 4987:         if ($dc_info) {
 4988:             $dc_info = &dc_courseid_toggle($dc_info);
 4989:         }
 4990:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4991: 
 4992:         #don't show menus for public users
 4993:         if (!$public){
 4994:             $bodytag .= Apache::lonmenu::secondary_menu();
 4995:             $bodytag .= Apache::lonmenu::serverform();
 4996:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4997:             if ($env{'request.state'} eq 'construct') {
 4998:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 4999:                                 $args->{'bread_crumbs'});
 5000:             } elsif ($forcereg) { 
 5001:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 5002:             }
 5003:         }else{
 5004:             # this is to seperate menu from content when there's no secondary
 5005:             # menu. Especially needed for public accessible ressources.
 5006:             $bodytag .= '<hr style="clear:both" />';
 5007:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5008:         }
 5009: 
 5010:         return $bodytag;
 5011: }
 5012: 
 5013: sub dc_courseid_toggle {
 5014:     my ($dc_info) = @_;
 5015:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5016:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5017:            &mt('(More ...)').'</a></span>'.
 5018:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5019: }
 5020: 
 5021: sub make_attr_string {
 5022:     my ($register,$attr_ref) = @_;
 5023: 
 5024:     if ($attr_ref && !ref($attr_ref)) {
 5025: 	die("addentries Must be a hash ref ".
 5026: 	    join(':',caller(1))." ".
 5027: 	    join(':',caller(0))." ");
 5028:     }
 5029: 
 5030:     if ($register) {
 5031: 	my ($on_load,$on_unload);
 5032: 	foreach my $key (keys(%{$attr_ref})) {
 5033: 	    if      (lc($key) eq 'onload') {
 5034: 		$on_load.=$attr_ref->{$key}.';';
 5035: 		delete($attr_ref->{$key});
 5036: 
 5037: 	    } elsif (lc($key) eq 'onunload') {
 5038: 		$on_unload.=$attr_ref->{$key}.';';
 5039: 		delete($attr_ref->{$key});
 5040: 	    }
 5041: 	}
 5042: 	$attr_ref->{'onload'}  = $on_load;
 5043: 	$attr_ref->{'onunload'}= $on_unload;
 5044:     }
 5045: 
 5046:     my $attr_string;
 5047:     foreach my $attr (keys(%$attr_ref)) {
 5048: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5049:     }
 5050:     return $attr_string;
 5051: }
 5052: 
 5053: 
 5054: ###############################################
 5055: ###############################################
 5056: 
 5057: =pod
 5058: 
 5059: =item * &endbodytag()
 5060: 
 5061: Returns a uniform footer for LON-CAPA web pages.
 5062: 
 5063: Inputs: 1 - optional reference to an args hash
 5064: If in the hash, key for noredirectlink has a value which evaluates to true,
 5065: a 'Continue' link is not displayed if the page contains an
 5066: internal redirect in the <head></head> section,
 5067: i.e., $env{'internal.head.redirect'} exists   
 5068: 
 5069: =cut
 5070: 
 5071: sub endbodytag {
 5072:     my ($args) = @_;
 5073:     my $endbodytag='</body>';
 5074:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5075:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5076:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5077: 	    $endbodytag=
 5078: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5079: 	        &mt('Continue').'</a>'.
 5080: 	        $endbodytag;
 5081:         }
 5082:     }
 5083:     return $endbodytag;
 5084: }
 5085: 
 5086: =pod
 5087: 
 5088: =item * &standard_css()
 5089: 
 5090: Returns a style sheet
 5091: 
 5092: Inputs: (all optional)
 5093:             domain         -> force to color decorate a page for a specific
 5094:                                domain
 5095:             function       -> force usage of a specific rolish color scheme
 5096:             bgcolor        -> override the default page bgcolor
 5097: 
 5098: =cut
 5099: 
 5100: sub standard_css {
 5101:     my ($function,$domain,$bgcolor) = @_;
 5102:     $function  = &get_users_function() if (!$function);
 5103:     my $img    = &designparm($function.'.img',   $domain);
 5104:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5105:     my $font   = &designparm($function.'.font',  $domain);
 5106:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5107: #second colour for later usage
 5108:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5109:     my $pgbg_or_bgcolor =
 5110: 	         $bgcolor ||
 5111: 	         &designparm($function.'.pgbg',  $domain);
 5112:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5113:     my $alink  = &designparm($function.'.alink', $domain);
 5114:     my $vlink  = &designparm($function.'.vlink', $domain);
 5115:     my $link   = &designparm($function.'.link',  $domain);
 5116: 
 5117:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5118:     my $mono                 = 'monospace';
 5119:     my $data_table_head      = $sidebg;
 5120:     my $data_table_light     = '#FAFAFA';
 5121:     my $data_table_dark      = '#E0E0E0';
 5122:     my $data_table_darker    = '#CCCCCC';
 5123:     my $data_table_highlight = '#FFFF00';
 5124:     my $mail_new             = '#FFBB77';
 5125:     my $mail_new_hover       = '#DD9955';
 5126:     my $mail_read            = '#BBBB77';
 5127:     my $mail_read_hover      = '#999944';
 5128:     my $mail_replied         = '#AAAA88';
 5129:     my $mail_replied_hover   = '#888855';
 5130:     my $mail_other           = '#99BBBB';
 5131:     my $mail_other_hover     = '#669999';
 5132:     my $table_header         = '#DDDDDD';
 5133:     my $feedback_link_bg     = '#BBBBBB';
 5134:     my $lg_border_color      = '#C8C8C8';
 5135:     my $button_hover         = '#BF2317';
 5136: 
 5137:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5138:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5139:                                              : '0 3px 0 4px';
 5140: 
 5141: 
 5142:     return <<END;
 5143: 
 5144: /* needed for iframe to allow 100% height in FF */
 5145: body, html { 
 5146:     margin: 0;
 5147:     padding: 0 0.5%;
 5148:     height: 99%; /* to avoid scrollbars */
 5149: }
 5150: 
 5151: body {
 5152:   font-family: $sans;
 5153:   line-height:130%;
 5154:   font-size:0.83em;
 5155:   color:$font;
 5156: }
 5157: 
 5158: a:focus,
 5159: a:focus img {
 5160:   color: red;
 5161: }
 5162: 
 5163: form, .inline {
 5164:   display: inline;
 5165: }
 5166: 
 5167: .LC_right {
 5168:   text-align:right;
 5169: }
 5170: 
 5171: .LC_middle {
 5172:   vertical-align:middle;
 5173: }
 5174: 
 5175: .LC_400Box {
 5176:   width:400px;
 5177: }
 5178: 
 5179: .LC_iframecontainer {
 5180:     width: 98%;
 5181:     margin: 0;
 5182:     position: fixed;
 5183:     top: 8.5em;
 5184:     bottom: 0;
 5185: }
 5186: 
 5187: .LC_iframecontainer iframe{
 5188:     border: none;
 5189:     width: 100%;
 5190:     height: 100%;
 5191: }
 5192: 
 5193: .LC_filename {
 5194:   font-family: $mono;
 5195:   white-space:pre;
 5196:   font-size: 120%;
 5197: }
 5198: 
 5199: .LC_fileicon {
 5200:   border: none;
 5201:   height: 1.3em;
 5202:   vertical-align: text-bottom;
 5203:   margin-right: 0.3em;
 5204:   text-decoration:none;
 5205: }
 5206: 
 5207: .LC_setting {
 5208:   text-decoration:underline;
 5209: }
 5210: 
 5211: .LC_error {
 5212:   color: red;
 5213:   font-size: larger;
 5214: }
 5215: 
 5216: .LC_warning,
 5217: .LC_diff_removed {
 5218:   color: red;
 5219: }
 5220: 
 5221: .LC_info,
 5222: .LC_success,
 5223: .LC_diff_added {
 5224:   color: green;
 5225: }
 5226: 
 5227: div.LC_confirm_box {
 5228:   background-color: #FAFAFA;
 5229:   border: 1px solid $lg_border_color;
 5230:   margin-right: 0;
 5231:   padding: 5px;
 5232: }
 5233: 
 5234: div.LC_confirm_box .LC_error img,
 5235: div.LC_confirm_box .LC_success img {
 5236:   vertical-align: middle;
 5237: }
 5238: 
 5239: .LC_icon {
 5240:   border: none;
 5241:   vertical-align: middle;
 5242: }
 5243: 
 5244: .LC_docs_spacer {
 5245:   width: 25px;
 5246:   height: 1px;
 5247:   border: none;
 5248: }
 5249: 
 5250: .LC_internal_info {
 5251:   color: #999999;
 5252: }
 5253: 
 5254: .LC_discussion {
 5255:   background: $data_table_dark;
 5256:   border: 1px solid black;
 5257:   margin: 2px;
 5258: }
 5259: 
 5260: .LC_disc_action_left {
 5261:   background: $sidebg;
 5262:   text-align: left;
 5263:   padding: 4px;
 5264:   margin: 2px;
 5265: }
 5266: 
 5267: .LC_disc_action_right {
 5268:   background: $sidebg;
 5269:   text-align: right;
 5270:   padding: 4px;
 5271:   margin: 2px;
 5272: }
 5273: 
 5274: .LC_disc_new_item {
 5275:   background: white;
 5276:   border: 2px solid red;
 5277:   margin: 4px;
 5278:   padding: 4px;
 5279: }
 5280: 
 5281: .LC_disc_old_item {
 5282:   background: white;
 5283:   margin: 4px;
 5284:   padding: 4px;
 5285: }
 5286: 
 5287: table.LC_pastsubmission {
 5288:   border: 1px solid black;
 5289:   margin: 2px;
 5290: }
 5291: 
 5292: table#LC_menubuttons {
 5293:   width: 100%;
 5294:   background: $pgbg;
 5295:   border: 2px;
 5296:   border-collapse: separate;
 5297:   padding: 0;
 5298: }
 5299: 
 5300: table#LC_title_bar a {
 5301:   color: $fontmenu;
 5302: }
 5303: 
 5304: table#LC_title_bar {
 5305:   clear: both;
 5306:   display: none;
 5307: }
 5308: 
 5309: table#LC_title_bar,
 5310: table.LC_breadcrumbs, /* obsolete? */
 5311: table#LC_title_bar.LC_with_remote {
 5312:   width: 100%;
 5313:   border-color: $pgbg;
 5314:   border-style: solid;
 5315:   border-width: $border;
 5316:   background: $pgbg;
 5317:   color: $fontmenu;
 5318:   border-collapse: collapse;
 5319:   padding: 0;
 5320:   margin: 0;
 5321: }
 5322: 
 5323: ul.LC_breadcrumb_tools_outerlist {
 5324:     margin: 0;
 5325:     padding: 0;
 5326:     position: relative;
 5327:     list-style: none;
 5328: }
 5329: ul.LC_breadcrumb_tools_outerlist li {
 5330:     display: inline;
 5331: }
 5332: 
 5333: .LC_breadcrumb_tools_navigation {
 5334:     padding: 0;
 5335:     margin: 0;
 5336:     float: left;
 5337: }
 5338: .LC_breadcrumb_tools_tools {
 5339:     padding: 0;
 5340:     margin: 0;
 5341:     float: right;
 5342: }
 5343: 
 5344: table#LC_title_bar td {
 5345:   background: $tabbg;
 5346: }
 5347: 
 5348: table#LC_menubuttons img {
 5349:   border: none;
 5350: }
 5351: 
 5352: .LC_breadcrumbs_component {
 5353:   float: right;
 5354:   margin: 0 1em;
 5355: }
 5356: .LC_breadcrumbs_component img {
 5357:   vertical-align: middle;
 5358: }
 5359: 
 5360: td.LC_table_cell_checkbox {
 5361:   text-align: center;
 5362: }
 5363: 
 5364: .LC_fontsize_small {
 5365:   font-size: 70%;
 5366: }
 5367: 
 5368: #LC_breadcrumbs {
 5369:   clear:both;
 5370:   background: $sidebg;
 5371:   border-bottom: 1px solid $lg_border_color;
 5372:   line-height: 2.5em;
 5373:   overflow: hidden;
 5374:   margin: 0;
 5375:   padding: 0;
 5376:   text-align: left;
 5377: }
 5378: 
 5379: .LC_head_subbox {
 5380:   clear:both;
 5381:   background: #F8F8F8; /* $sidebg; */
 5382:   border: 1px solid $sidebg;
 5383:   margin: 0 0 10px 0;      
 5384:   padding: 3px;
 5385:   text-align: left;
 5386: }
 5387: 
 5388: .LC_fontsize_medium {
 5389:   font-size: 85%;
 5390: }
 5391: 
 5392: .LC_fontsize_large {
 5393:   font-size: 120%;
 5394: }
 5395: 
 5396: .LC_menubuttons_inline_text {
 5397:   color: $font;
 5398:   font-size: 90%;
 5399:   padding-left:3px;
 5400: }
 5401: 
 5402: .LC_menubuttons_inline_text img{
 5403:   vertical-align: middle;
 5404: }
 5405: 
 5406: li.LC_menubuttons_inline_text img {
 5407:   cursor:pointer;
 5408:   text-decoration: none;
 5409: }
 5410: 
 5411: .LC_menubuttons_link {
 5412:   text-decoration: none;
 5413: }
 5414: 
 5415: .LC_menubuttons_category {
 5416:   color: $font;
 5417:   background: $pgbg;
 5418:   font-size: larger;
 5419:   font-weight: bold;
 5420: }
 5421: 
 5422: td.LC_menubuttons_text {
 5423:   color: $font;
 5424: }
 5425: 
 5426: .LC_current_location {
 5427:   background: $tabbg;
 5428: }
 5429: 
 5430: table.LC_data_table {
 5431:   border: 1px solid #000000;
 5432:   border-collapse: separate;
 5433:   border-spacing: 1px;
 5434:   background: $pgbg;
 5435: }
 5436: 
 5437: .LC_data_table_dense {
 5438:   font-size: small;
 5439: }
 5440: 
 5441: table.LC_nested_outer {
 5442:   border: 1px solid #000000;
 5443:   border-collapse: collapse;
 5444:   border-spacing: 0;
 5445:   width: 100%;
 5446: }
 5447: 
 5448: table.LC_innerpickbox,
 5449: table.LC_nested {
 5450:   border: none;
 5451:   border-collapse: collapse;
 5452:   border-spacing: 0;
 5453:   width: 100%;
 5454: }
 5455: 
 5456: table.LC_data_table tr th,
 5457: table.LC_calendar tr th,
 5458: table.LC_prior_tries tr th,
 5459: table.LC_innerpickbox tr th {
 5460:   font-weight: bold;
 5461:   background-color: $data_table_head;
 5462:   color:$fontmenu;
 5463:   font-size:90%;
 5464: }
 5465: 
 5466: table.LC_innerpickbox tr th,
 5467: table.LC_innerpickbox tr td {
 5468:   vertical-align: top;
 5469: }
 5470: 
 5471: table.LC_data_table tr.LC_info_row > td {
 5472:   background-color: #CCCCCC;
 5473:   font-weight: bold;
 5474:   text-align: left;
 5475: }
 5476: 
 5477: table.LC_data_table tr.LC_odd_row > td {
 5478:   background-color: $data_table_light;
 5479:   padding: 2px;
 5480:   vertical-align: top;
 5481: }
 5482: 
 5483: table.LC_pick_box tr > td.LC_odd_row {
 5484:   background-color: $data_table_light;
 5485:   vertical-align: top;
 5486: }
 5487: 
 5488: table.LC_data_table tr.LC_even_row > td {
 5489:   background-color: $data_table_dark;
 5490:   padding: 2px;
 5491:   vertical-align: top;
 5492: }
 5493: 
 5494: table.LC_pick_box tr > td.LC_even_row {
 5495:   background-color: $data_table_dark;
 5496:   vertical-align: top;
 5497: }
 5498: 
 5499: table.LC_data_table tr.LC_data_table_highlight td {
 5500:   background-color: $data_table_darker;
 5501: }
 5502: 
 5503: table.LC_data_table tr td.LC_leftcol_header {
 5504:   background-color: $data_table_head;
 5505:   font-weight: bold;
 5506: }
 5507: 
 5508: table.LC_data_table tr.LC_empty_row td,
 5509: table.LC_nested tr.LC_empty_row td {
 5510:   font-weight: bold;
 5511:   font-style: italic;
 5512:   text-align: center;
 5513:   padding: 8px;
 5514: }
 5515: 
 5516: table.LC_data_table tr.LC_empty_row td {
 5517:   background-color: $sidebg;
 5518: }
 5519: 
 5520: table.LC_nested tr.LC_empty_row td {
 5521:   background-color: #FFFFFF;
 5522: }
 5523: 
 5524: table.LC_caption {
 5525: }
 5526: 
 5527: table.LC_nested tr.LC_empty_row td {
 5528:   padding: 4ex
 5529: }
 5530: 
 5531: table.LC_nested_outer tr th {
 5532:   font-weight: bold;
 5533:   color:$fontmenu;
 5534:   background-color: $data_table_head;
 5535:   font-size: small;
 5536:   border-bottom: 1px solid #000000;
 5537: }
 5538: 
 5539: table.LC_nested_outer tr td.LC_subheader {
 5540:   background-color: $data_table_head;
 5541:   font-weight: bold;
 5542:   font-size: small;
 5543:   border-bottom: 1px solid #000000;
 5544:   text-align: right;
 5545: }
 5546: 
 5547: table.LC_nested tr.LC_info_row td {
 5548:   background-color: #CCCCCC;
 5549:   font-weight: bold;
 5550:   font-size: small;
 5551:   text-align: center;
 5552: }
 5553: 
 5554: table.LC_nested tr.LC_info_row td.LC_left_item,
 5555: table.LC_nested_outer tr th.LC_left_item {
 5556:   text-align: left;
 5557: }
 5558: 
 5559: table.LC_nested td {
 5560:   background-color: #FFFFFF;
 5561:   font-size: small;
 5562: }
 5563: 
 5564: table.LC_nested_outer tr th.LC_right_item,
 5565: table.LC_nested tr.LC_info_row td.LC_right_item,
 5566: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5567: table.LC_nested tr td.LC_right_item {
 5568:   text-align: right;
 5569: }
 5570: 
 5571: table.LC_nested tr.LC_odd_row td {
 5572:   background-color: #EEEEEE;
 5573: }
 5574: 
 5575: table.LC_createuser {
 5576: }
 5577: 
 5578: table.LC_createuser tr.LC_section_row td {
 5579:   font-size: small;
 5580: }
 5581: 
 5582: table.LC_createuser tr.LC_info_row td  {
 5583:   background-color: #CCCCCC;
 5584:   font-weight: bold;
 5585:   text-align: center;
 5586: }
 5587: 
 5588: table.LC_calendar {
 5589:   border: 1px solid #000000;
 5590:   border-collapse: collapse;
 5591:   width: 98%;
 5592: }
 5593: 
 5594: table.LC_calendar_pickdate {
 5595:   font-size: xx-small;
 5596: }
 5597: 
 5598: table.LC_calendar tr td {
 5599:   border: 1px solid #000000;
 5600:   vertical-align: top;
 5601:   width: 14%;
 5602: }
 5603: 
 5604: table.LC_calendar tr td.LC_calendar_day_empty {
 5605:   background-color: $data_table_dark;
 5606: }
 5607: 
 5608: table.LC_calendar tr td.LC_calendar_day_current {
 5609:   background-color: $data_table_highlight;
 5610: }
 5611: 
 5612: table.LC_data_table tr td.LC_mail_new {
 5613:   background-color: $mail_new;
 5614: }
 5615: 
 5616: table.LC_data_table tr.LC_mail_new:hover {
 5617:   background-color: $mail_new_hover;
 5618: }
 5619: 
 5620: table.LC_data_table tr td.LC_mail_read {
 5621:   background-color: $mail_read;
 5622: }
 5623: 
 5624: /*
 5625: table.LC_data_table tr.LC_mail_read:hover {
 5626:   background-color: $mail_read_hover;
 5627: }
 5628: */
 5629: 
 5630: table.LC_data_table tr td.LC_mail_replied {
 5631:   background-color: $mail_replied;
 5632: }
 5633: 
 5634: /*
 5635: table.LC_data_table tr.LC_mail_replied:hover {
 5636:   background-color: $mail_replied_hover;
 5637: }
 5638: */
 5639: 
 5640: table.LC_data_table tr td.LC_mail_other {
 5641:   background-color: $mail_other;
 5642: }
 5643: 
 5644: /*
 5645: table.LC_data_table tr.LC_mail_other:hover {
 5646:   background-color: $mail_other_hover;
 5647: }
 5648: */
 5649: 
 5650: table.LC_data_table tr > td.LC_browser_file,
 5651: table.LC_data_table tr > td.LC_browser_file_published {
 5652:   background: #AAEE77;
 5653: }
 5654: 
 5655: table.LC_data_table tr > td.LC_browser_file_locked,
 5656: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5657:   background: #FFAA99;
 5658: }
 5659: 
 5660: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5661:   background: #888888;
 5662: }
 5663: 
 5664: table.LC_data_table tr > td.LC_browser_file_modified,
 5665: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5666:   background: #F8F866;
 5667: }
 5668: 
 5669: table.LC_data_table tr.LC_browser_folder > td {
 5670:   background: #E0E8FF;
 5671: }
 5672: 
 5673: table.LC_data_table tr > td.LC_roles_is {
 5674:   /* background: #77FF77; */
 5675: }
 5676: 
 5677: table.LC_data_table tr > td.LC_roles_future {
 5678:   border-right: 8px solid #FFFF77;
 5679: }
 5680: 
 5681: table.LC_data_table tr > td.LC_roles_will {
 5682:   border-right: 8px solid #FFAA77;
 5683: }
 5684: 
 5685: table.LC_data_table tr > td.LC_roles_expired {
 5686:   border-right: 8px solid #FF7777;
 5687: }
 5688: 
 5689: table.LC_data_table tr > td.LC_roles_will_not {
 5690:   border-right: 8px solid #AAFF77;
 5691: }
 5692: 
 5693: table.LC_data_table tr > td.LC_roles_selected {
 5694:   border-right: 8px solid #11CC55;
 5695: }
 5696: 
 5697: span.LC_current_location {
 5698:   font-size:larger;
 5699:   background: $pgbg;
 5700: }
 5701: 
 5702: span.LC_current_nav_location {
 5703:   font-weight:bold;
 5704:   background: $sidebg;
 5705: }
 5706: 
 5707: span.LC_parm_menu_item {
 5708:   font-size: larger;
 5709: }
 5710: 
 5711: span.LC_parm_scope_all {
 5712:   color: red;
 5713: }
 5714: 
 5715: span.LC_parm_scope_folder {
 5716:   color: green;
 5717: }
 5718: 
 5719: span.LC_parm_scope_resource {
 5720:   color: orange;
 5721: }
 5722: 
 5723: span.LC_parm_part {
 5724:   color: blue;
 5725: }
 5726: 
 5727: span.LC_parm_folder,
 5728: span.LC_parm_symb {
 5729:   font-size: x-small;
 5730:   font-family: $mono;
 5731:   color: #AAAAAA;
 5732: }
 5733: 
 5734: ul.LC_parm_parmlist li {
 5735:   display: inline-block;
 5736:   padding: 0.3em 0.8em;
 5737:   vertical-align: top;
 5738:   width: 150px;
 5739:   border-top:1px solid $lg_border_color;
 5740: }
 5741: 
 5742: td.LC_parm_overview_level_menu,
 5743: td.LC_parm_overview_map_menu,
 5744: td.LC_parm_overview_parm_selectors,
 5745: td.LC_parm_overview_restrictions  {
 5746:   border: 1px solid black;
 5747:   border-collapse: collapse;
 5748: }
 5749: 
 5750: table.LC_parm_overview_restrictions td {
 5751:   border-width: 1px 4px 1px 4px;
 5752:   border-style: solid;
 5753:   border-color: $pgbg;
 5754:   text-align: center;
 5755: }
 5756: 
 5757: table.LC_parm_overview_restrictions th {
 5758:   background: $tabbg;
 5759:   border-width: 1px 4px 1px 4px;
 5760:   border-style: solid;
 5761:   border-color: $pgbg;
 5762: }
 5763: 
 5764: table#LC_helpmenu {
 5765:   border: none;
 5766:   height: 55px;
 5767:   border-spacing: 0;
 5768: }
 5769: 
 5770: table#LC_helpmenu fieldset legend {
 5771:   font-size: larger;
 5772: }
 5773: 
 5774: table#LC_helpmenu_links {
 5775:   width: 100%;
 5776:   border: 1px solid black;
 5777:   background: $pgbg;
 5778:   padding: 0;
 5779:   border-spacing: 1px;
 5780: }
 5781: 
 5782: table#LC_helpmenu_links tr td {
 5783:   padding: 1px;
 5784:   background: $tabbg;
 5785:   text-align: center;
 5786:   font-weight: bold;
 5787: }
 5788: 
 5789: table#LC_helpmenu_links a:link,
 5790: table#LC_helpmenu_links a:visited,
 5791: table#LC_helpmenu_links a:active {
 5792:   text-decoration: none;
 5793:   color: $font;
 5794: }
 5795: 
 5796: table#LC_helpmenu_links a:hover {
 5797:   text-decoration: underline;
 5798:   color: $vlink;
 5799: }
 5800: 
 5801: .LC_chrt_popup_exists {
 5802:   border: 1px solid #339933;
 5803:   margin: -1px;
 5804: }
 5805: 
 5806: .LC_chrt_popup_up {
 5807:   border: 1px solid yellow;
 5808:   margin: -1px;
 5809: }
 5810: 
 5811: .LC_chrt_popup {
 5812:   border: 1px solid #8888FF;
 5813:   background: #CCCCFF;
 5814: }
 5815: 
 5816: table.LC_pick_box {
 5817:   border-collapse: separate;
 5818:   background: white;
 5819:   border: 1px solid black;
 5820:   border-spacing: 1px;
 5821: }
 5822: 
 5823: table.LC_pick_box td.LC_pick_box_title {
 5824:   background: $sidebg;
 5825:   font-weight: bold;
 5826:   text-align: left;
 5827:   vertical-align: top;
 5828:   width: 184px;
 5829:   padding: 8px;
 5830: }
 5831: 
 5832: table.LC_pick_box td.LC_pick_box_value {
 5833:   text-align: left;
 5834:   padding: 8px;
 5835: }
 5836: 
 5837: table.LC_pick_box td.LC_pick_box_select {
 5838:   text-align: left;
 5839:   padding: 8px;
 5840: }
 5841: 
 5842: table.LC_pick_box td.LC_pick_box_separator {
 5843:   padding: 0;
 5844:   height: 1px;
 5845:   background: black;
 5846: }
 5847: 
 5848: table.LC_pick_box td.LC_pick_box_submit {
 5849:   text-align: right;
 5850: }
 5851: 
 5852: table.LC_pick_box td.LC_evenrow_value {
 5853:   text-align: left;
 5854:   padding: 8px;
 5855:   background-color: $data_table_light;
 5856: }
 5857: 
 5858: table.LC_pick_box td.LC_oddrow_value {
 5859:   text-align: left;
 5860:   padding: 8px;
 5861:   background-color: $data_table_light;
 5862: }
 5863: 
 5864: span.LC_helpform_receipt_cat {
 5865:   font-weight: bold;
 5866: }
 5867: 
 5868: table.LC_group_priv_box {
 5869:   background: white;
 5870:   border: 1px solid black;
 5871:   border-spacing: 1px;
 5872: }
 5873: 
 5874: table.LC_group_priv_box td.LC_pick_box_title {
 5875:   background: $tabbg;
 5876:   font-weight: bold;
 5877:   text-align: right;
 5878:   width: 184px;
 5879: }
 5880: 
 5881: table.LC_group_priv_box td.LC_groups_fixed {
 5882:   background: $data_table_light;
 5883:   text-align: center;
 5884: }
 5885: 
 5886: table.LC_group_priv_box td.LC_groups_optional {
 5887:   background: $data_table_dark;
 5888:   text-align: center;
 5889: }
 5890: 
 5891: table.LC_group_priv_box td.LC_groups_functionality {
 5892:   background: $data_table_darker;
 5893:   text-align: center;
 5894:   font-weight: bold;
 5895: }
 5896: 
 5897: table.LC_group_priv td {
 5898:   text-align: left;
 5899:   padding: 0;
 5900: }
 5901: 
 5902: .LC_navbuttons {
 5903:   margin: 2ex 0ex 2ex 0ex;
 5904: }
 5905: 
 5906: .LC_topic_bar {
 5907:   font-weight: bold;
 5908:   background: $tabbg;
 5909:   margin: 1em 0em 1em 2em;
 5910:   padding: 3px;
 5911:   font-size: 1.2em;
 5912: }
 5913: 
 5914: .LC_topic_bar span {
 5915:   left: 0.5em;
 5916:   position: absolute;
 5917:   vertical-align: middle;
 5918:   font-size: 1.2em;
 5919: }
 5920: 
 5921: table.LC_course_group_status {
 5922:   margin: 20px;
 5923: }
 5924: 
 5925: table.LC_status_selector td {
 5926:   vertical-align: top;
 5927:   text-align: center;
 5928:   padding: 4px;
 5929: }
 5930: 
 5931: div.LC_feedback_link {
 5932:   clear: both;
 5933:   background: $sidebg;
 5934:   width: 100%;
 5935:   padding-bottom: 10px;
 5936:   border: 1px $tabbg solid;
 5937:   height: 22px;
 5938:   line-height: 22px;
 5939:   padding-top: 5px;
 5940: }
 5941: 
 5942: div.LC_feedback_link img {
 5943:   height: 22px;
 5944:   vertical-align:middle;
 5945: }
 5946: 
 5947: div.LC_feedback_link a {
 5948:   text-decoration: none;
 5949: }
 5950: 
 5951: div.LC_comblock {
 5952:   display:inline;
 5953:   color:$font;
 5954:   font-size:90%;
 5955: }
 5956: 
 5957: div.LC_feedback_link div.LC_comblock {
 5958:   padding-left:5px;
 5959: }
 5960: 
 5961: div.LC_feedback_link div.LC_comblock a {
 5962:   color:$font;
 5963: }
 5964: 
 5965: span.LC_feedback_link {
 5966:   /* background: $feedback_link_bg; */
 5967:   font-size: larger;
 5968: }
 5969: 
 5970: span.LC_message_link {
 5971:   /* background: $feedback_link_bg; */
 5972:   font-size: larger;
 5973:   position: absolute;
 5974:   right: 1em;
 5975: }
 5976: 
 5977: table.LC_prior_tries {
 5978:   border: 1px solid #000000;
 5979:   border-collapse: separate;
 5980:   border-spacing: 1px;
 5981: }
 5982: 
 5983: table.LC_prior_tries td {
 5984:   padding: 2px;
 5985: }
 5986: 
 5987: .LC_answer_correct {
 5988:   background: lightgreen;
 5989:   color: darkgreen;
 5990:   padding: 6px;
 5991: }
 5992: 
 5993: .LC_answer_charged_try {
 5994:   background: #FFAAAA;
 5995:   color: darkred;
 5996:   padding: 6px;
 5997: }
 5998: 
 5999: .LC_answer_not_charged_try,
 6000: .LC_answer_no_grade,
 6001: .LC_answer_late {
 6002:   background: lightyellow;
 6003:   color: black;
 6004:   padding: 6px;
 6005: }
 6006: 
 6007: .LC_answer_previous {
 6008:   background: lightblue;
 6009:   color: darkblue;
 6010:   padding: 6px;
 6011: }
 6012: 
 6013: .LC_answer_no_message {
 6014:   background: #FFFFFF;
 6015:   color: black;
 6016:   padding: 6px;
 6017: }
 6018: 
 6019: .LC_answer_unknown {
 6020:   background: orange;
 6021:   color: black;
 6022:   padding: 6px;
 6023: }
 6024: 
 6025: span.LC_prior_numerical,
 6026: span.LC_prior_string,
 6027: span.LC_prior_custom,
 6028: span.LC_prior_reaction,
 6029: span.LC_prior_math {
 6030:   font-family: $mono;
 6031:   white-space: pre;
 6032: }
 6033: 
 6034: span.LC_prior_string {
 6035:   font-family: $mono;
 6036:   white-space: pre;
 6037: }
 6038: 
 6039: table.LC_prior_option {
 6040:   width: 100%;
 6041:   border-collapse: collapse;
 6042: }
 6043: 
 6044: table.LC_prior_rank,
 6045: table.LC_prior_match {
 6046:   border-collapse: collapse;
 6047: }
 6048: 
 6049: table.LC_prior_option tr td,
 6050: table.LC_prior_rank tr td,
 6051: table.LC_prior_match tr td {
 6052:   border: 1px solid #000000;
 6053: }
 6054: 
 6055: .LC_nobreak {
 6056:   white-space: nowrap;
 6057: }
 6058: 
 6059: span.LC_cusr_emph {
 6060:   font-style: italic;
 6061: }
 6062: 
 6063: span.LC_cusr_subheading {
 6064:   font-weight: normal;
 6065:   font-size: 85%;
 6066: }
 6067: 
 6068: div.LC_docs_entry_move {
 6069:   border: 1px solid #BBBBBB;
 6070:   background: #DDDDDD;
 6071:   width: 22px;
 6072:   padding: 1px;
 6073:   margin: 0;
 6074: }
 6075: 
 6076: table.LC_data_table tr > td.LC_docs_entry_commands,
 6077: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6078:   background: #DDDDDD;
 6079:   font-size: x-small;
 6080: }
 6081: 
 6082: .LC_docs_entry_parameter {
 6083:   white-space: nowrap;
 6084: }
 6085: 
 6086: .LC_docs_copy {
 6087:   color: #000099;
 6088: }
 6089: 
 6090: .LC_docs_cut {
 6091:   color: #550044;
 6092: }
 6093: 
 6094: .LC_docs_rename {
 6095:   color: #009900;
 6096: }
 6097: 
 6098: .LC_docs_remove {
 6099:   color: #990000;
 6100: }
 6101: 
 6102: .LC_docs_reinit_warn,
 6103: .LC_docs_ext_edit {
 6104:   font-size: x-small;
 6105: }
 6106: 
 6107: table.LC_docs_adddocs td,
 6108: table.LC_docs_adddocs th {
 6109:   border: 1px solid #BBBBBB;
 6110:   padding: 4px;
 6111:   background: #DDDDDD;
 6112: }
 6113: 
 6114: table.LC_sty_begin {
 6115:   background: #BBFFBB;
 6116: }
 6117: 
 6118: table.LC_sty_end {
 6119:   background: #FFBBBB;
 6120: }
 6121: 
 6122: table.LC_double_column {
 6123:   border-width: 0;
 6124:   border-collapse: collapse;
 6125:   width: 100%;
 6126:   padding: 2px;
 6127: }
 6128: 
 6129: table.LC_double_column tr td.LC_left_col {
 6130:   top: 2px;
 6131:   left: 2px;
 6132:   width: 47%;
 6133:   vertical-align: top;
 6134: }
 6135: 
 6136: table.LC_double_column tr td.LC_right_col {
 6137:   top: 2px;
 6138:   right: 2px;
 6139:   width: 47%;
 6140:   vertical-align: top;
 6141: }
 6142: 
 6143: div.LC_left_float {
 6144:   float: left;
 6145:   padding-right: 5%;
 6146:   padding-bottom: 4px;
 6147: }
 6148: 
 6149: div.LC_clear_float_header {
 6150:   padding-bottom: 2px;
 6151: }
 6152: 
 6153: div.LC_clear_float_footer {
 6154:   padding-top: 10px;
 6155:   clear: both;
 6156: }
 6157: 
 6158: div.LC_grade_show_user {
 6159: /*  border-left: 5px solid $sidebg; */
 6160:   border-top: 5px solid #000000;
 6161:   margin: 50px 0 0 0;
 6162:   padding: 15px 0 5px 10px;
 6163: }
 6164: 
 6165: div.LC_grade_show_user_odd_row {
 6166: /*  border-left: 5px solid #000000; */
 6167: }
 6168: 
 6169: div.LC_grade_show_user div.LC_Box {
 6170:   margin-right: 50px;
 6171: }
 6172: 
 6173: div.LC_grade_submissions,
 6174: div.LC_grade_message_center,
 6175: div.LC_grade_info_links {
 6176:   margin: 5px;
 6177:   width: 99%;
 6178:   background: #FFFFFF;
 6179: }
 6180: 
 6181: div.LC_grade_submissions_header,
 6182: div.LC_grade_message_center_header {
 6183:   font-weight: bold;
 6184:   font-size: large;
 6185: }
 6186: 
 6187: div.LC_grade_submissions_body,
 6188: div.LC_grade_message_center_body {
 6189:   border: 1px solid black;
 6190:   width: 99%;
 6191:   background: #FFFFFF;
 6192: }
 6193: 
 6194: table.LC_scantron_action {
 6195:   width: 100%;
 6196: }
 6197: 
 6198: table.LC_scantron_action tr th {
 6199:   font-weight:bold;
 6200:   font-style:normal;
 6201: }
 6202: 
 6203: .LC_edit_problem_header,
 6204: div.LC_edit_problem_footer {
 6205:   font-weight: normal;
 6206:   font-size:  medium;
 6207:   margin: 2px;
 6208:   background-color: $sidebg;
 6209: }
 6210: 
 6211: div.LC_edit_problem_header,
 6212: div.LC_edit_problem_header div,
 6213: div.LC_edit_problem_footer,
 6214: div.LC_edit_problem_footer div,
 6215: div.LC_edit_problem_editxml_header,
 6216: div.LC_edit_problem_editxml_header div {
 6217:   margin-top: 5px;
 6218: }
 6219: 
 6220: div.LC_edit_problem_header_title {
 6221:   font-weight: bold;
 6222:   font-size: larger;
 6223:   background: $tabbg;
 6224:   padding: 3px;
 6225:   margin: 0 0 5px 0;
 6226: }
 6227: 
 6228: table.LC_edit_problem_header_title {
 6229:   width: 100%;
 6230:   background: $tabbg;
 6231: }
 6232: 
 6233: div.LC_edit_problem_discards {
 6234:   float: left;
 6235:   padding-bottom: 5px;
 6236: }
 6237: 
 6238: div.LC_edit_problem_saves {
 6239:   float: right;
 6240:   padding-bottom: 5px;
 6241: }
 6242: 
 6243: img.stift {
 6244:   border-width: 0;
 6245:   vertical-align: middle;
 6246: }
 6247: 
 6248: table td.LC_mainmenu_col_fieldset {
 6249:   vertical-align: top;
 6250: }
 6251: 
 6252: div.LC_createcourse {
 6253:   margin: 10px 10px 10px 10px;
 6254: }
 6255: 
 6256: .LC_dccid {
 6257:   margin: 0.2em 0 0 0;
 6258:   padding: 0;
 6259:   font-size: 90%;
 6260:   display:none;
 6261: }
 6262: 
 6263: ol.LC_primary_menu a:hover,
 6264: ol#LC_MenuBreadcrumbs a:hover,
 6265: ol#LC_PathBreadcrumbs a:hover,
 6266: ul#LC_secondary_menu a:hover,
 6267: .LC_FormSectionClearButton input:hover
 6268: ul.LC_TabContent   li:hover a {
 6269:   color:$button_hover;
 6270:   text-decoration:none;
 6271: }
 6272: 
 6273: h1 {
 6274:   padding: 0;
 6275:   line-height:130%;
 6276: }
 6277: 
 6278: h2,
 6279: h3,
 6280: h4,
 6281: h5,
 6282: h6 {
 6283:   margin: 5px 0 5px 0;
 6284:   padding: 0;
 6285:   line-height:130%;
 6286: }
 6287: 
 6288: .LC_hcell {
 6289:   padding:3px 15px 3px 15px;
 6290:   margin: 0;
 6291:   background-color:$tabbg;
 6292:   color:$fontmenu;
 6293:   border-bottom:solid 1px $lg_border_color;
 6294: }
 6295: 
 6296: .LC_Box > .LC_hcell {
 6297:   margin: 0 -10px 10px -10px;
 6298: }
 6299: 
 6300: .LC_noBorder {
 6301:   border: 0;
 6302: }
 6303: 
 6304: .LC_FormSectionClearButton input {
 6305:   background-color:transparent;
 6306:   border: none;
 6307:   cursor:pointer;
 6308:   text-decoration:underline;
 6309: }
 6310: 
 6311: .LC_help_open_topic {
 6312:   color: #FFFFFF;
 6313:   background-color: #EEEEFF;
 6314:   margin: 1px;
 6315:   padding: 4px;
 6316:   border: 1px solid #000033;
 6317:   white-space: nowrap;
 6318:   /* vertical-align: middle; */
 6319: }
 6320: 
 6321: dl,
 6322: ul,
 6323: div,
 6324: fieldset {
 6325:   margin: 10px 10px 10px 0;
 6326:   /* overflow: hidden; */
 6327: }
 6328: 
 6329: fieldset > legend {
 6330:   font-weight: bold;
 6331:   padding: 0 5px 0 5px;
 6332: }
 6333: 
 6334: #LC_nav_bar {
 6335:   float: left;
 6336:   background-color: $pgbg_or_bgcolor;
 6337:   margin: 0 0 2px 0;
 6338: }
 6339: 
 6340: #LC_realm {
 6341:   margin: 0.2em 0 0 0;
 6342:   padding: 0;
 6343:   font-weight: bold;
 6344:   text-align: center;
 6345:   background-color: $pgbg_or_bgcolor;
 6346: }
 6347: 
 6348: #LC_nav_bar em {
 6349:   font-weight: bold;
 6350:   font-style: normal;
 6351: }
 6352: 
 6353: ol.LC_primary_menu {
 6354:   float: right;
 6355:   margin: 0;
 6356:   background-color: $pgbg_or_bgcolor;
 6357: }
 6358: 
 6359: ol#LC_PathBreadcrumbs {
 6360:   margin: 0;
 6361: }
 6362: 
 6363: ol.LC_primary_menu li {
 6364:   display: inline;
 6365:   padding: 5px 5px 0 10px;
 6366:   vertical-align: top;
 6367: }
 6368: 
 6369: ol.LC_primary_menu li img {
 6370:   vertical-align: bottom;
 6371:   height: 1.1em;
 6372: }
 6373: 
 6374: ol.LC_primary_menu a {
 6375:   color: RGB(80, 80, 80);
 6376:   text-decoration: none;
 6377: }
 6378: 
 6379: ol.LC_primary_menu a.LC_new_message {
 6380:   font-weight:bold;
 6381:   color: darkred;
 6382: }
 6383: 
 6384: ol.LC_docs_parameters {
 6385:   margin-left: 0;
 6386:   padding: 0;
 6387:   list-style: none;
 6388: }
 6389: 
 6390: ol.LC_docs_parameters li {
 6391:   margin: 0;
 6392:   padding-right: 20px;
 6393:   display: inline;
 6394: }
 6395: 
 6396: ol.LC_docs_parameters li:before {
 6397:   content: "\\002022 \\0020";
 6398: }
 6399: 
 6400: li.LC_docs_parameters_title {
 6401:   font-weight: bold;
 6402: }
 6403: 
 6404: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6405:   content: "";
 6406: }
 6407: 
 6408: ul#LC_secondary_menu {
 6409:   clear: both;
 6410:   color: $fontmenu;
 6411:   background: $tabbg;
 6412:   list-style: none;
 6413:   padding: 0;
 6414:   margin: 0;
 6415:   width: 100%;
 6416:   text-align: left;
 6417: }
 6418: 
 6419: ul#LC_secondary_menu li {
 6420:   font-weight: bold;
 6421:   line-height: 1.8em;
 6422:   padding: 0 0.8em;
 6423:   border-right: 1px solid black;
 6424:   display: inline;
 6425:   vertical-align: middle;
 6426: }
 6427: 
 6428: ul.LC_TabContent {
 6429:   display:block;
 6430:   background: $sidebg;
 6431:   border-bottom: solid 1px $lg_border_color;
 6432:   list-style:none;
 6433:   margin: -1px -10px 0 -10px;
 6434:   padding: 0;
 6435: }
 6436: 
 6437: ul.LC_TabContent li,
 6438: ul.LC_TabContentBigger li {
 6439:   float:left;
 6440: }
 6441: 
 6442: ul#LC_secondary_menu li a {
 6443:   color: $fontmenu;
 6444:   text-decoration: none;
 6445: }
 6446: 
 6447: ul.LC_TabContent {
 6448:   min-height:20px;
 6449: }
 6450: 
 6451: ul.LC_TabContent li {
 6452:   vertical-align:middle;
 6453:   padding: 0 16px 0 10px;
 6454:   background-color:$tabbg;
 6455:   border-bottom:solid 1px $lg_border_color;
 6456:   border-left: solid 1px $font;
 6457: }
 6458: 
 6459: ul.LC_TabContent .right {
 6460:   float:right;
 6461: }
 6462: 
 6463: ul.LC_TabContent li a,
 6464: ul.LC_TabContent li {
 6465:   color:rgb(47,47,47);
 6466:   text-decoration:none;
 6467:   font-size:95%;
 6468:   font-weight:bold;
 6469:   min-height:20px;
 6470: }
 6471: 
 6472: ul.LC_TabContent li a:hover,
 6473: ul.LC_TabContent li a:focus {
 6474:   color: $button_hover;
 6475:   background:none;
 6476:   outline:none;
 6477: }
 6478: 
 6479: ul.LC_TabContent li:hover {
 6480:   color: $button_hover;
 6481:   cursor:pointer;
 6482: }
 6483: 
 6484: ul.LC_TabContent li.active {
 6485:   color: $font;
 6486:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6487:   border-bottom:solid 1px #FFFFFF;
 6488:   cursor: default;
 6489: }
 6490: 
 6491: ul.LC_TabContent li.active a {
 6492:   color:$font;
 6493:   background:#FFFFFF;
 6494:   outline: none;
 6495: }
 6496: 
 6497: ul.LC_TabContent li.goback {
 6498:   float: left;
 6499:   border-left: none;
 6500: }
 6501: 
 6502: #maincoursedoc {
 6503:   clear:both;
 6504: }
 6505: 
 6506: ul.LC_TabContentBigger {
 6507:   display:block;
 6508:   list-style:none;
 6509:   padding: 0;
 6510: }
 6511: 
 6512: ul.LC_TabContentBigger li {
 6513:   vertical-align:bottom;
 6514:   height: 30px;
 6515:   font-size:110%;
 6516:   font-weight:bold;
 6517:   color: #737373;
 6518: }
 6519: 
 6520: ul.LC_TabContentBigger li.active {
 6521:   position: relative;
 6522:   top: 1px;
 6523: }
 6524: 
 6525: ul.LC_TabContentBigger li a {
 6526:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6527:   height: 30px;
 6528:   line-height: 30px;
 6529:   text-align: center;
 6530:   display: block;
 6531:   text-decoration: none;
 6532:   outline: none;  
 6533: }
 6534: 
 6535: ul.LC_TabContentBigger li.active a {
 6536:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6537:   color:$font;
 6538: }
 6539: 
 6540: ul.LC_TabContentBigger li b {
 6541:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6542:   display: block;
 6543:   float: left;
 6544:   padding: 0 30px;
 6545:   border-bottom: 1px solid $lg_border_color;
 6546: }
 6547: 
 6548: ul.LC_TabContentBigger li:hover b {
 6549:   color:$button_hover;
 6550: }
 6551: 
 6552: ul.LC_TabContentBigger li.active b {
 6553:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6554:   color:$font;
 6555:   border: 0;
 6556: }
 6557: 
 6558: 
 6559: ul.LC_CourseBreadcrumbs {
 6560:   background: $sidebg;
 6561:   height: 2em;
 6562:   padding-left: 10px;
 6563:   margin: 0;
 6564:   list-style-position: inside;
 6565: }
 6566: 
 6567: ol#LC_MenuBreadcrumbs,
 6568: ol#LC_PathBreadcrumbs {
 6569:   padding-left: 10px;
 6570:   margin: 0;
 6571:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6572: }
 6573: 
 6574: ol#LC_MenuBreadcrumbs li,
 6575: ol#LC_PathBreadcrumbs li,
 6576: ul.LC_CourseBreadcrumbs li {
 6577:   display: inline;
 6578:   white-space: normal;  
 6579: }
 6580: 
 6581: ol#LC_MenuBreadcrumbs li a,
 6582: ul.LC_CourseBreadcrumbs li a {
 6583:   text-decoration: none;
 6584:   font-size:90%;
 6585: }
 6586: 
 6587: ol#LC_MenuBreadcrumbs h1 {
 6588:   display: inline;
 6589:   font-size: 90%;
 6590:   line-height: 2.5em;
 6591:   margin: 0;
 6592:   padding: 0;
 6593: }
 6594: 
 6595: ol#LC_PathBreadcrumbs li a {
 6596:   text-decoration:none;
 6597:   font-size:100%;
 6598:   font-weight:bold;
 6599: }
 6600: 
 6601: .LC_Box {
 6602:   border: solid 1px $lg_border_color;
 6603:   padding: 0 10px 10px 10px;
 6604: }
 6605: 
 6606: .LC_DocsBox {
 6607:   border: solid 1px $lg_border_color;
 6608:   padding: 0 0 10px 10px;
 6609: }
 6610: 
 6611: .LC_AboutMe_Image {
 6612:   float:left;
 6613:   margin-right:10px;
 6614: }
 6615: 
 6616: .LC_Clear_AboutMe_Image {
 6617:   clear:left;
 6618: }
 6619: 
 6620: dl.LC_ListStyleClean dt {
 6621:   padding-right: 5px;
 6622:   display: table-header-group;
 6623: }
 6624: 
 6625: dl.LC_ListStyleClean dd {
 6626:   display: table-row;
 6627: }
 6628: 
 6629: .LC_ListStyleClean,
 6630: .LC_ListStyleSimple,
 6631: .LC_ListStyleNormal,
 6632: .LC_ListStyleSpecial {
 6633:   /* display:block; */
 6634:   list-style-position: inside;
 6635:   list-style-type: none;
 6636:   overflow: hidden;
 6637:   padding: 0;
 6638: }
 6639: 
 6640: .LC_ListStyleSimple li,
 6641: .LC_ListStyleSimple dd,
 6642: .LC_ListStyleNormal li,
 6643: .LC_ListStyleNormal dd,
 6644: .LC_ListStyleSpecial li,
 6645: .LC_ListStyleSpecial dd {
 6646:   margin: 0;
 6647:   padding: 5px 5px 5px 10px;
 6648:   clear: both;
 6649: }
 6650: 
 6651: .LC_ListStyleClean li,
 6652: .LC_ListStyleClean dd {
 6653:   padding-top: 0;
 6654:   padding-bottom: 0;
 6655: }
 6656: 
 6657: .LC_ListStyleSimple dd,
 6658: .LC_ListStyleSimple li {
 6659:   border-bottom: solid 1px $lg_border_color;
 6660: }
 6661: 
 6662: .LC_ListStyleSpecial li,
 6663: .LC_ListStyleSpecial dd {
 6664:   list-style-type: none;
 6665:   background-color: RGB(220, 220, 220);
 6666:   margin-bottom: 4px;
 6667: }
 6668: 
 6669: table.LC_SimpleTable {
 6670:   margin:5px;
 6671:   border:solid 1px $lg_border_color;
 6672: }
 6673: 
 6674: table.LC_SimpleTable tr {
 6675:   padding: 0;
 6676:   border:solid 1px $lg_border_color;
 6677: }
 6678: 
 6679: table.LC_SimpleTable thead {
 6680:   background:rgb(220,220,220);
 6681: }
 6682: 
 6683: div.LC_columnSection {
 6684:   display: block;
 6685:   clear: both;
 6686:   overflow: hidden;
 6687:   margin: 0;
 6688: }
 6689: 
 6690: div.LC_columnSection>* {
 6691:   float: left;
 6692:   margin: 10px 20px 10px 0;
 6693:   overflow:hidden;
 6694: }
 6695: 
 6696: table em {
 6697:   font-weight: bold;
 6698:   font-style: normal;
 6699: }
 6700: 
 6701: table.LC_tableBrowseRes,
 6702: table.LC_tableOfContent {
 6703:   border:none;
 6704:   border-spacing: 1px;
 6705:   padding: 3px;
 6706:   background-color: #FFFFFF;
 6707:   font-size: 90%;
 6708: }
 6709: 
 6710: table.LC_tableOfContent {
 6711:   border-collapse: collapse;
 6712: }
 6713: 
 6714: table.LC_tableBrowseRes a,
 6715: table.LC_tableOfContent a {
 6716:   background-color: transparent;
 6717:   text-decoration: none;
 6718: }
 6719: 
 6720: table.LC_tableOfContent img {
 6721:   border: none;
 6722:   height: 1.3em;
 6723:   vertical-align: text-bottom;
 6724:   margin-right: 0.3em;
 6725: }
 6726: 
 6727: a#LC_content_toolbar_firsthomework {
 6728:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6729: }
 6730: 
 6731: a#LC_content_toolbar_everything {
 6732:   background-image:url(/res/adm/pages/show-all.gif);
 6733: }
 6734: 
 6735: a#LC_content_toolbar_uncompleted {
 6736:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6737: }
 6738: 
 6739: #LC_content_toolbar_clearbubbles {
 6740:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6741: }
 6742: 
 6743: a#LC_content_toolbar_changefolder {
 6744:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6745: }
 6746: 
 6747: a#LC_content_toolbar_changefolder_toggled {
 6748:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6749: }
 6750: 
 6751: a#LC_content_toolbar_edittoplevel {
 6752:   background-image:url(/res/adm/pages/edittoplevel.gif);
 6753: }
 6754: 
 6755: ul#LC_toolbar li a:hover {
 6756:   background-position: bottom center;
 6757: }
 6758: 
 6759: ul#LC_toolbar {
 6760:   padding: 0;
 6761:   margin: 2px;
 6762:   list-style:none;
 6763:   position:relative;
 6764:   background-color:white;
 6765: }
 6766: 
 6767: ul#LC_toolbar li {
 6768:   border:1px solid white;
 6769:   padding: 0;
 6770:   margin: 0;
 6771:   float: left;
 6772:   display:inline;
 6773:   vertical-align:middle;
 6774: }
 6775: 
 6776: 
 6777: a.LC_toolbarItem {
 6778:   display:block;
 6779:   padding: 0;
 6780:   margin: 0;
 6781:   height: 32px;
 6782:   width: 32px;
 6783:   color:white;
 6784:   border: none;
 6785:   background-repeat:no-repeat;
 6786:   background-color:transparent;
 6787: }
 6788: 
 6789: ul.LC_funclist {
 6790:     margin: 0;
 6791:     padding: 0.5em 1em 0.5em 0;
 6792: }
 6793: 
 6794: ul.LC_funclist > li:first-child {
 6795:     font-weight:bold; 
 6796:     margin-left:0.8em;
 6797: }
 6798: 
 6799: ul.LC_funclist + ul.LC_funclist {
 6800:     /* 
 6801:        left border as a seperator if we have more than
 6802:        one list 
 6803:     */
 6804:     border-left: 1px solid $sidebg;
 6805:     /* 
 6806:        this hides the left border behind the border of the 
 6807:        outer box if element is wrapped to the next 'line' 
 6808:     */
 6809:     margin-left: -1px;
 6810: }
 6811: 
 6812: ul.LC_funclist li {
 6813:   display: inline;
 6814:   white-space: nowrap;
 6815:   margin: 0 0 0 25px;
 6816:   line-height: 150%;
 6817: }
 6818: 
 6819: .LC_hidden {
 6820:   display: none;
 6821: }
 6822: 
 6823: .LCmodal-overlay {
 6824: 		position:fixed;
 6825: 		top:0;
 6826: 		right:0;
 6827: 		bottom:0;
 6828: 		left:0;
 6829: 		height:100%;
 6830: 		width:100%;
 6831: 		margin:0;
 6832: 		padding:0;
 6833: 		background:#999;
 6834: 		opacity:.75;
 6835: 		filter: alpha(opacity=75);
 6836: 		-moz-opacity: 0.75;
 6837: 		z-index:101;
 6838: }
 6839: 
 6840: * html .LCmodal-overlay {   
 6841: 		position: absolute;
 6842: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 6843: }
 6844: 
 6845: .LCmodal-window {
 6846: 		position:fixed;
 6847: 		top:50%;
 6848: 		left:50%;
 6849: 		margin:0;
 6850: 		padding:0;
 6851: 		z-index:102;
 6852: 	}
 6853: 
 6854: * html .LCmodal-window {
 6855: 		position:absolute;
 6856: }
 6857: 
 6858: .LCclose-window {
 6859: 		position:absolute;
 6860: 		width:32px;
 6861: 		height:32px;
 6862: 		right:8px;
 6863: 		top:8px;
 6864: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 6865: 		text-indent:-99999px;
 6866: 		overflow:hidden;
 6867: 		cursor:pointer;
 6868: }
 6869: 
 6870: END
 6871: }
 6872: 
 6873: =pod
 6874: 
 6875: =item * &headtag()
 6876: 
 6877: Returns a uniform footer for LON-CAPA web pages.
 6878: 
 6879: Inputs: $title - optional title for the head
 6880:         $head_extra - optional extra HTML to put inside the <head>
 6881:         $args - optional arguments
 6882:             force_register - if is true call registerurl so the remote is 
 6883:                              informed
 6884:             redirect       -> array ref of
 6885:                                    1- seconds before redirect occurs
 6886:                                    2- url to redirect to
 6887:                                    3- whether the side effect should occur
 6888:                            (side effect of setting 
 6889:                                $env{'internal.head.redirect'} to the url 
 6890:                                redirected too)
 6891:             domain         -> force to color decorate a page for a specific
 6892:                                domain
 6893:             function       -> force usage of a specific rolish color scheme
 6894:             bgcolor        -> override the default page bgcolor
 6895:             no_auto_mt_title
 6896:                            -> prevent &mt()ing the title arg
 6897: 
 6898: =cut
 6899: 
 6900: sub headtag {
 6901:     my ($title,$head_extra,$args) = @_;
 6902:     
 6903:     my $function = $args->{'function'} || &get_users_function();
 6904:     my $domain   = $args->{'domain'}   || &determinedomain();
 6905:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6906:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6907: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6908: 		   #time(),
 6909: 		   $env{'environment.color.timestamp'},
 6910: 		   $function,$domain,$bgcolor);
 6911: 
 6912:     $url = '/adm/css/'.&escape($url).'.css';
 6913: 
 6914:     my $result =
 6915: 	'<head>'.
 6916: 	&font_settings();
 6917: 
 6918:     my $inhibitprint = &print_suppression();
 6919: 
 6920:     if (!$args->{'frameset'}) {
 6921: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6922:     }
 6923:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 6924:         $result .= Apache::lonxml::display_title();
 6925:     }
 6926:     if (!$args->{'no_nav_bar'} 
 6927: 	&& !$args->{'only_body'}
 6928: 	&& !$args->{'frameset'}) {
 6929: 	$result .= &help_menu_js();
 6930:         $result.=&modal_window();
 6931:         $result.=&togglebox_script();
 6932:         $result.=&wishlist_window();
 6933:         $result.=&LCprogressbarUpdate_script();
 6934:     } else {
 6935:         if ($args->{'add_modal'}) {
 6936:            $result.=&modal_window();
 6937:         }
 6938:         if ($args->{'add_wishlist'}) {
 6939:            $result.=&wishlist_window();
 6940:         }
 6941:         if ($args->{'add_togglebox'}) {
 6942:            $result.=&togglebox_script();
 6943:         }
 6944:         if ($args->{'add_progressbar'}) {
 6945:            $result.=&LCprogressbarUpdate_script();
 6946:         }
 6947:     }
 6948:     if (ref($args->{'redirect'})) {
 6949: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6950: 	$url = &Apache::lonenc::check_encrypt($url);
 6951: 	if (!$inhibit_continue) {
 6952: 	    $env{'internal.head.redirect'} = $url;
 6953: 	}
 6954: 	$result.=<<ADDMETA
 6955: <meta http-equiv="pragma" content="no-cache" />
 6956: <meta http-equiv="Refresh" content="$time; url=$url" />
 6957: ADDMETA
 6958:     }
 6959:     if (!defined($title)) {
 6960: 	$title = 'The LearningOnline Network with CAPA';
 6961:     }
 6962:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6963:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6964: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6965:         .$inhibitprint
 6966: 	.$head_extra;
 6967:     return $result.'</head>';
 6968: }
 6969: 
 6970: =pod
 6971: 
 6972: =item * &font_settings()
 6973: 
 6974: Returns neccessary <meta> to set the proper encoding
 6975: 
 6976: Inputs: none
 6977: 
 6978: =cut
 6979: 
 6980: sub font_settings {
 6981:     my $headerstring='';
 6982:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6983: 	$headerstring.=
 6984: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6985:     }
 6986:     return $headerstring;
 6987: }
 6988: 
 6989: =pod
 6990: 
 6991: =item * &print_suppression()
 6992: 
 6993: In course context returns css which causes the body to be blank when media="print",
 6994: if printout generation is unavailable for the current resource.
 6995: 
 6996: This could be because:
 6997: 
 6998: (a) printstartdate is in the future
 6999: 
 7000: (b) printenddate is in the past
 7001: 
 7002: (c) there is an active exam block with "printout"
 7003: functionality blocked
 7004: 
 7005: Users with pav, pfo or evb privileges are exempt.
 7006: 
 7007: Inputs: none
 7008: 
 7009: =cut
 7010: 
 7011: 
 7012: sub print_suppression {
 7013:     my $noprint;
 7014:     if ($env{'request.course.id'}) {
 7015:         my $scope = $env{'request.course.id'};
 7016:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7017:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7018:             return;
 7019:         }
 7020:         if ($env{'request.course.sec'} ne '') {
 7021:             $scope .= "/$env{'request.course.sec'}";
 7022:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7023:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7024:                 return;
 7025:             }
 7026:         }
 7027:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7028:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7029:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7030:         if ($blocked) {
 7031:             my $checkrole = "cm./$cdom/$cnum";
 7032:             if ($env{'request.course.sec'} ne '') {
 7033:                 $checkrole .= "/$env{'request.course.sec'}";
 7034:             }
 7035:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7036:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7037:                 $noprint = 1;
 7038:             }
 7039:         }
 7040:         unless ($noprint) {
 7041:             my $symb = &Apache::lonnet::symbread();
 7042:             if ($symb ne '') {
 7043:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7044:                 if (ref($navmap)) {
 7045:                     my $res = $navmap->getBySymb($symb);
 7046:                     if (ref($res)) {
 7047:                         if (!$res->resprintable()) {
 7048:                             $noprint = 1;
 7049:                         }
 7050:                     }
 7051:                 }
 7052:             }
 7053:         }
 7054:         if ($noprint) {
 7055:             return <<"ENDSTYLE";
 7056: <style type="text/css" media="print">
 7057:     body { display:none }
 7058: </style>
 7059: ENDSTYLE
 7060:         }
 7061:     }
 7062:     return;
 7063: }
 7064: 
 7065: =pod
 7066: 
 7067: =item * &xml_begin()
 7068: 
 7069: Returns the needed doctype and <html>
 7070: 
 7071: Inputs: none
 7072: 
 7073: =cut
 7074: 
 7075: sub xml_begin {
 7076:     my $output='';
 7077: 
 7078:     if ($env{'browser.mathml'}) {
 7079: 	$output='<?xml version="1.0"?>'
 7080:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7081: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7082:             
 7083: #	    .'<!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">] >'
 7084: 	    .'<!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">'
 7085:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7086: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7087:     } else {
 7088: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7089:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7090:     }
 7091:     return $output;
 7092: }
 7093: 
 7094: =pod
 7095: 
 7096: =item * &start_page()
 7097: 
 7098: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7099: 
 7100: Inputs:
 7101: 
 7102: =over 4
 7103: 
 7104: $title - optional title for the page
 7105: 
 7106: $head_extra - optional extra HTML to incude inside the <head>
 7107: 
 7108: $args - additional optional args supported are:
 7109: 
 7110: =over 8
 7111: 
 7112:              only_body      -> is true will set &bodytag() onlybodytag
 7113:                                     arg on
 7114:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7115:              add_entries    -> additional attributes to add to the  <body>
 7116:              domain         -> force to color decorate a page for a 
 7117:                                     specific domain
 7118:              function       -> force usage of a specific rolish color
 7119:                                     scheme
 7120:              redirect       -> see &headtag()
 7121:              bgcolor        -> override the default page bg color
 7122:              js_ready       -> return a string ready for being used in 
 7123:                                     a javascript writeln
 7124:              html_encode    -> return a string ready for being used in 
 7125:                                     a html attribute
 7126:              force_register -> if is true will turn on the &bodytag()
 7127:                                     $forcereg arg
 7128:              frameset       -> if true will start with a <frameset>
 7129:                                     rather than <body>
 7130:              skip_phases    -> hash ref of 
 7131:                                     head -> skip the <html><head> generation
 7132:                                     body -> skip all <body> generation
 7133:              no_auto_mt_title -> prevent &mt()ing the title arg
 7134:              inherit_jsmath -> when creating popup window in a page,
 7135:                                     should it have jsmath forced on by the
 7136:                                     current page
 7137:              bread_crumbs ->             Array containing breadcrumbs
 7138:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7139: 
 7140: =back
 7141: 
 7142: =back
 7143: 
 7144: =cut
 7145: 
 7146: sub start_page {
 7147:     my ($title,$head_extra,$args) = @_;
 7148:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7149: 
 7150:     $env{'internal.start_page'}++;
 7151:     my $result;
 7152: 
 7153:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7154:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7155:     }
 7156:     
 7157:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7158: 	if ($args->{'frameset'}) {
 7159: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7160: 						$args->{'add_entries'});
 7161: 	    $result .= "\n<frameset $attr_string>\n";
 7162:         } else {
 7163:             $result .=
 7164:                 &bodytag($title, 
 7165:                          $args->{'function'},       $args->{'add_entries'},
 7166:                          $args->{'only_body'},      $args->{'domain'},
 7167:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7168:                          $args->{'bgcolor'},        $args);
 7169:         }
 7170:     }
 7171: 
 7172:     if ($args->{'js_ready'}) {
 7173: 		$result = &js_ready($result);
 7174:     }
 7175:     if ($args->{'html_encode'}) {
 7176: 		$result = &html_encode($result);
 7177:     }
 7178: 
 7179:     # Preparation for new and consistent functionlist at top of screen
 7180:     # if ($args->{'functionlist'}) {
 7181:     #            $result .= &build_functionlist();
 7182:     #}
 7183: 
 7184:     # Don't add anything more if only_body wanted or in const space
 7185:     return $result if    $args->{'only_body'} 
 7186:                       || $env{'request.state'} eq 'construct';
 7187: 
 7188:     #Breadcrumbs
 7189:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7190: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7191: 		#if any br links exists, add them to the breadcrumbs
 7192: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7193: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7194: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7195: 			}
 7196: 		}
 7197: 
 7198: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7199: 		if(exists($args->{'bread_crumbs_component'})){
 7200: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7201: 		}else{
 7202: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7203: 		}
 7204:     }
 7205:     return $result;
 7206: }
 7207: 
 7208: sub end_page {
 7209:     my ($args) = @_;
 7210:     $env{'internal.end_page'}++;
 7211:     my $result;
 7212:     if ($args->{'discussion'}) {
 7213: 	my ($target,$parser);
 7214: 	if (ref($args->{'discussion'})) {
 7215: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7216: 				$args->{'discussion'}{'parser'});
 7217: 	}
 7218: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7219:     }
 7220:     if ($args->{'frameset'}) {
 7221: 	$result .= '</frameset>';
 7222:     } else {
 7223: 	$result .= &endbodytag($args);
 7224:     }
 7225:     $result .= "\n</html>";
 7226: 
 7227:     if ($args->{'js_ready'}) {
 7228: 	$result = &js_ready($result);
 7229:     }
 7230: 
 7231:     if ($args->{'html_encode'}) {
 7232: 	$result = &html_encode($result);
 7233:     }
 7234: 
 7235:     return $result;
 7236: }
 7237: 
 7238: sub wishlist_window {
 7239:     return(<<'ENDWISHLIST');
 7240: <script type="text/javascript">
 7241: // <![CDATA[
 7242: // <!-- BEGIN LON-CAPA Internal
 7243: function set_wishlistlink(title, path) {
 7244:     if (!title) {
 7245:         title = document.title;
 7246:         title = title.replace(/^LON-CAPA /,'');
 7247:     }
 7248:     if (!path) {
 7249:         path = location.pathname;
 7250:     }
 7251:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7252:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7253: }
 7254: // END LON-CAPA Internal -->
 7255: // ]]>
 7256: </script>
 7257: ENDWISHLIST
 7258: }
 7259: 
 7260: sub modal_window {
 7261:     return(<<'ENDMODAL');
 7262: <script type="text/javascript">
 7263: // <![CDATA[
 7264: // <!-- BEGIN LON-CAPA Internal
 7265: var modalWindow = {
 7266: 	parent:"body",
 7267: 	windowId:null,
 7268: 	content:null,
 7269: 	width:null,
 7270: 	height:null,
 7271: 	close:function()
 7272: 	{
 7273: 	        $(".LCmodal-window").remove();
 7274: 	        $(".LCmodal-overlay").remove();
 7275: 	},
 7276: 	open:function()
 7277: 	{
 7278: 		var modal = "";
 7279: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7280: 		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;\">";
 7281: 		modal += this.content;
 7282: 		modal += "</div>";	
 7283: 
 7284: 		$(this.parent).append(modal);
 7285: 
 7286: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7287: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7288: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7289: 	}
 7290: };
 7291: 	var openMyModal = function(source,width,height,scrolling)
 7292: 	{
 7293: 		modalWindow.windowId = "myModal";
 7294: 		modalWindow.width = width;
 7295: 		modalWindow.height = height;
 7296: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7297: 		modalWindow.open();
 7298: 	};	
 7299: // END LON-CAPA Internal -->
 7300: // ]]>
 7301: </script>
 7302: ENDMODAL
 7303: }
 7304: 
 7305: sub modal_link {
 7306:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7307:     unless ($width) { $width=480; }
 7308:     unless ($height) { $height=400; }
 7309:     unless ($scrolling) { $scrolling='yes'; }
 7310:     return '<a href="'.$link.'" target="'.$target.'" title="'.$title.'" onclick="openMyModal(\''.$link.'\','.$width.','.$height.',\''.$scrolling.'\'); return false;">'.
 7311:            $linktext.'</a>';
 7312: }
 7313: 
 7314: sub modal_adhoc_script {
 7315:     my ($funcname,$width,$height,$content)=@_;
 7316:     return (<<ENDADHOC);
 7317: <script type="text/javascript">
 7318: // <![CDATA[
 7319:         var $funcname = function()
 7320:         {
 7321:                 modalWindow.windowId = "myModal";
 7322:                 modalWindow.width = $width;
 7323:                 modalWindow.height = $height;
 7324:                 modalWindow.content = '$content';
 7325:                 modalWindow.open();
 7326:         };  
 7327: // ]]>
 7328: </script>
 7329: ENDADHOC
 7330: }
 7331: 
 7332: sub modal_adhoc_inner {
 7333:     my ($funcname,$width,$height,$content)=@_;
 7334:     my $innerwidth=$width-20;
 7335:     $content=&js_ready(
 7336:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7337:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7338:                     $content.
 7339:                  &end_scrollbox().
 7340:                &end_page()
 7341:              );
 7342:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7343: }
 7344: 
 7345: sub modal_adhoc_window {
 7346:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7347:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7348:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7349: }
 7350: 
 7351: sub modal_adhoc_launch {
 7352:     my ($funcname,$width,$height,$content)=@_;
 7353:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7354: <script type="text/javascript">
 7355: // <![CDATA[
 7356: $funcname();
 7357: // ]]>
 7358: </script>
 7359: ENDLAUNCH
 7360: }
 7361: 
 7362: sub modal_adhoc_close {
 7363:     return (<<ENDCLOSE);
 7364: <script type="text/javascript">
 7365: // <![CDATA[
 7366: modalWindow.close();
 7367: // ]]>
 7368: </script>
 7369: ENDCLOSE
 7370: }
 7371: 
 7372: sub togglebox_script {
 7373:    return(<<ENDTOGGLE);
 7374: <script type="text/javascript"> 
 7375: // <![CDATA[
 7376: function LCtoggleDisplay(id,hidetext,showtext) {
 7377:    link = document.getElementById(id + "link").childNodes[0];
 7378:    with (document.getElementById(id).style) {
 7379:       if (display == "none" ) {
 7380:           display = "inline";
 7381:           link.nodeValue = hidetext;
 7382:         } else {
 7383:           display = "none";
 7384:           link.nodeValue = showtext;
 7385:        }
 7386:    }
 7387: }
 7388: // ]]>
 7389: </script>
 7390: ENDTOGGLE
 7391: }
 7392: 
 7393: sub start_togglebox {
 7394:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7395:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7396:     unless ($showtext) { $showtext=&mt('show'); }
 7397:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7398:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7399:     return &start_data_table().
 7400:            &start_data_table_header_row().
 7401:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7402:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7403:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7404:            &end_data_table_header_row().
 7405:            '<tr id="'.$id.'" style="display:none""><td>';
 7406: }
 7407: 
 7408: sub end_togglebox {
 7409:     return '</td></tr>'.&end_data_table();
 7410: }
 7411: 
 7412: sub LCprogressbar_script {
 7413:    my ($id)=@_;
 7414:    return(<<ENDPROGRESS);
 7415: <script type="text/javascript">
 7416: // <![CDATA[
 7417: \$('#progressbar$id').progressbar({
 7418:   value: 0,
 7419:   change: function(event, ui) {
 7420:     var newVal = \$(this).progressbar('option', 'value');
 7421:     \$('.pblabel', this).text(LCprogressTxt);
 7422:   }
 7423: });
 7424: // ]]>
 7425: </script>
 7426: ENDPROGRESS
 7427: }
 7428: 
 7429: sub LCprogressbarUpdate_script {
 7430:    return(<<ENDPROGRESSUPDATE);
 7431: <style type="text/css">
 7432: .ui-progressbar { position:relative; }
 7433: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7434: </style>
 7435: <script type="text/javascript">
 7436: // <![CDATA[
 7437: var LCprogressTxt='---';
 7438: 
 7439: function LCupdateProgress(percent,progresstext,id) {
 7440:    LCprogressTxt=progresstext;
 7441:    \$('#progressbar'+id).progressbar('value',percent);
 7442: }
 7443: // ]]>
 7444: </script>
 7445: ENDPROGRESSUPDATE
 7446: }
 7447: 
 7448: my $LClastpercent;
 7449: my $LCidcnt;
 7450: my $LCcurrentid;
 7451: 
 7452: sub LCprogressbar {
 7453:     my ($r)=(@_);
 7454:     $LClastpercent=0;
 7455:     $LCidcnt++;
 7456:     $LCcurrentid=$$.'_'.$LCidcnt;
 7457:     my $starting=&mt('Starting');
 7458:     my $content=(<<ENDPROGBAR);
 7459: <p>
 7460:   <div id="progressbar$LCcurrentid">
 7461:     <span class="pblabel">$starting</span>
 7462:   </div>
 7463: </p>
 7464: ENDPROGBAR
 7465:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7466: }
 7467: 
 7468: sub LCprogressbarUpdate {
 7469:     my ($r,$val,$text)=@_;
 7470:     unless ($val) { 
 7471:        if ($LClastpercent) {
 7472:            $val=$LClastpercent;
 7473:        } else {
 7474:            $val=0;
 7475:        }
 7476:     }
 7477:     if ($val<0) { $val=0; }
 7478:     if ($val>100) { $val=0; }
 7479:     $LClastpercent=$val;
 7480:     unless ($text) { $text=$val.'%'; }
 7481:     $text=&js_ready($text);
 7482:     &r_print($r,<<ENDUPDATE);
 7483: <script type="text/javascript">
 7484: // <![CDATA[
 7485: LCupdateProgress($val,'$text','$LCcurrentid');
 7486: // ]]>
 7487: </script>
 7488: ENDUPDATE
 7489: }
 7490: 
 7491: sub LCprogressbarClose {
 7492:     my ($r)=@_;
 7493:     $LClastpercent=0;
 7494:     &r_print($r,<<ENDCLOSE);
 7495: <script type="text/javascript">
 7496: // <![CDATA[
 7497: \$("#progressbar$LCcurrentid").hide('slow'); 
 7498: // ]]>
 7499: </script>
 7500: ENDCLOSE
 7501: }
 7502: 
 7503: sub r_print {
 7504:     my ($r,$to_print)=@_;
 7505:     if ($r) {
 7506:       $r->print($to_print);
 7507:       $r->rflush();
 7508:     } else {
 7509:       print($to_print);
 7510:     }
 7511: }
 7512: 
 7513: sub html_encode {
 7514:     my ($result) = @_;
 7515: 
 7516:     $result = &HTML::Entities::encode($result,'<>&"');
 7517:     
 7518:     return $result;
 7519: }
 7520: 
 7521: sub js_ready {
 7522:     my ($result) = @_;
 7523: 
 7524:     $result =~ s/[\n\r]/ /xmsg;
 7525:     $result =~ s/\\/\\\\/xmsg;
 7526:     $result =~ s/'/\\'/xmsg;
 7527:     $result =~ s{</}{<\\/}xmsg;
 7528:     
 7529:     return $result;
 7530: }
 7531: 
 7532: sub validate_page {
 7533:     if (  exists($env{'internal.start_page'})
 7534: 	  &&     $env{'internal.start_page'} > 1) {
 7535: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7536: 				 $env{'internal.start_page'}.' '.
 7537: 				 $ENV{'request.filename'});
 7538:     }
 7539:     if (  exists($env{'internal.end_page'})
 7540: 	  &&     $env{'internal.end_page'} > 1) {
 7541: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7542: 				 $env{'internal.end_page'}.' '.
 7543: 				 $env{'request.filename'});
 7544:     }
 7545:     if (     exists($env{'internal.start_page'})
 7546: 	&& ! exists($env{'internal.end_page'})) {
 7547: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7548: 				 $env{'request.filename'});
 7549:     }
 7550:     if (   ! exists($env{'internal.start_page'})
 7551: 	&&   exists($env{'internal.end_page'})) {
 7552: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7553: 				 $env{'request.filename'});
 7554:     }
 7555: }
 7556: 
 7557: 
 7558: sub start_scrollbox {
 7559:     my ($outerwidth,$width,$height,$id)=@_;
 7560:     unless ($outerwidth) { $outerwidth='520px'; }
 7561:     unless ($width) { $width='500px'; }
 7562:     unless ($height) { $height='200px'; }
 7563:     my ($table_id,$div_id);
 7564:     if ($id ne '') {
 7565:         $table_id = " id='table_$id'";
 7566:         $div_id = " id='div_$id'";
 7567:     }
 7568:     return "<table style='width: $outerwidth; border: 1px solid none;'$table_id><tr><td style='width: $width;' bgcolor='#FFFFFF'><div style='overflow:auto; width:$width; height: $height;'$div_id>";
 7569: }
 7570: 
 7571: sub end_scrollbox {
 7572:     return '</div></td></tr></table>';
 7573: }
 7574: 
 7575: sub simple_error_page {
 7576:     my ($r,$title,$msg) = @_;
 7577:     my $page =
 7578: 	&Apache::loncommon::start_page($title).
 7579: 	&mt($msg).
 7580: 	&Apache::loncommon::end_page();
 7581:     if (ref($r)) {
 7582: 	$r->print($page);
 7583: 	return;
 7584:     }
 7585:     return $page;
 7586: }
 7587: 
 7588: {
 7589:     my @row_count;
 7590: 
 7591:     sub start_data_table_count {
 7592:         unshift(@row_count, 0);
 7593:         return;
 7594:     }
 7595: 
 7596:     sub end_data_table_count {
 7597:         shift(@row_count);
 7598:         return;
 7599:     }
 7600: 
 7601:     sub start_data_table {
 7602: 	my ($add_class,$id) = @_;
 7603: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7604:         my $table_id;
 7605:         if (defined($id)) {
 7606:             $table_id = ' id="'.$id.'"';
 7607:         }
 7608: 	&start_data_table_count();
 7609: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7610:     }
 7611: 
 7612:     sub end_data_table {
 7613: 	&end_data_table_count();
 7614: 	return '</table>'."\n";;
 7615:     }
 7616: 
 7617:     sub start_data_table_row {
 7618: 	my ($add_class, $id) = @_;
 7619: 	$row_count[0]++;
 7620: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7621: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7622:         $id = (' id="'.$id.'"') unless ($id eq '');
 7623:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7624:     }
 7625:     
 7626:     sub continue_data_table_row {
 7627: 	my ($add_class, $id) = @_;
 7628: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7629: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7630:         $id = (' id="'.$id.'"') unless ($id eq '');
 7631:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7632:     }
 7633: 
 7634:     sub end_data_table_row {
 7635: 	return '</tr>'."\n";;
 7636:     }
 7637: 
 7638:     sub start_data_table_empty_row {
 7639: #	$row_count[0]++;
 7640: 	return  '<tr class="LC_empty_row" >'."\n";;
 7641:     }
 7642: 
 7643:     sub end_data_table_empty_row {
 7644: 	return '</tr>'."\n";;
 7645:     }
 7646: 
 7647:     sub start_data_table_header_row {
 7648: 	return  '<tr class="LC_header_row">'."\n";;
 7649:     }
 7650: 
 7651:     sub end_data_table_header_row {
 7652: 	return '</tr>'."\n";;
 7653:     }
 7654: 
 7655:     sub data_table_caption {
 7656:         my $caption = shift;
 7657:         return "<caption class=\"LC_caption\">$caption</caption>";
 7658:     }
 7659: }
 7660: 
 7661: =pod
 7662: 
 7663: =item * &inhibit_menu_check($arg)
 7664: 
 7665: Checks for a inhibitmenu state and generates output to preserve it
 7666: 
 7667: Inputs:         $arg - can be any of
 7668:                      - undef - in which case the return value is a string 
 7669:                                to add  into arguments list of a uri
 7670:                      - 'input' - in which case the return value is a HTML
 7671:                                  <form> <input> field of type hidden to
 7672:                                  preserve the value
 7673:                      - a url - in which case the return value is the url with
 7674:                                the neccesary cgi args added to preserve the
 7675:                                inhibitmenu state
 7676:                      - a ref to a url - no return value, but the string is
 7677:                                         updated to include the neccessary cgi
 7678:                                         args to preserve the inhibitmenu state
 7679: 
 7680: =cut
 7681: 
 7682: sub inhibit_menu_check {
 7683:     my ($arg) = @_;
 7684:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7685:     if ($arg eq 'input') {
 7686: 	if ($env{'form.inhibitmenu'}) {
 7687: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7688: 	} else {
 7689: 	    return
 7690: 	}
 7691:     }
 7692:     if ($env{'form.inhibitmenu'}) {
 7693: 	if (ref($arg)) {
 7694: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7695: 	} elsif ($arg eq '') {
 7696: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7697: 	} else {
 7698: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7699: 	}
 7700:     }
 7701:     if (!ref($arg)) {
 7702: 	return $arg;
 7703:     }
 7704: }
 7705: 
 7706: ###############################################
 7707: 
 7708: =pod
 7709: 
 7710: =back
 7711: 
 7712: =head1 User Information Routines
 7713: 
 7714: =over 4
 7715: 
 7716: =item * &get_users_function()
 7717: 
 7718: Used by &bodytag to determine the current users primary role.
 7719: Returns either 'student','coordinator','admin', or 'author'.
 7720: 
 7721: =cut
 7722: 
 7723: ###############################################
 7724: sub get_users_function {
 7725:     my $function = 'norole';
 7726:     if ($env{'request.role'}=~/^(st)/) {
 7727:         $function='student';
 7728:     }
 7729:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7730:         $function='coordinator';
 7731:     }
 7732:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7733:         $function='admin';
 7734:     }
 7735:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7736:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 7737:         $function='author';
 7738:     }
 7739:     return $function;
 7740: }
 7741: 
 7742: ###############################################
 7743: 
 7744: =pod
 7745: 
 7746: =item * &show_course()
 7747: 
 7748: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7749: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7750: 
 7751: Inputs:
 7752: None
 7753: 
 7754: Outputs:
 7755: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7756: 
 7757: =cut
 7758: 
 7759: ###############################################
 7760: sub show_course {
 7761:     my $course = !$env{'user.adv'};
 7762:     if (!$env{'user.adv'}) {
 7763:         foreach my $env (keys(%env)) {
 7764:             next if ($env !~ m/^user\.priv\./);
 7765:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7766:                 $course = 0;
 7767:                 last;
 7768:             }
 7769:         }
 7770:     }
 7771:     return $course;
 7772: }
 7773: 
 7774: ###############################################
 7775: 
 7776: =pod
 7777: 
 7778: =item * &check_user_status()
 7779: 
 7780: Determines current status of supplied role for a
 7781: specific user. Roles can be active, previous or future.
 7782: 
 7783: Inputs: 
 7784: user's domain, user's username, course's domain,
 7785: course's number, optional section ID.
 7786: 
 7787: Outputs:
 7788: role status: active, previous or future. 
 7789: 
 7790: =cut
 7791: 
 7792: sub check_user_status {
 7793:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7794:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 7795:     my @uroles = keys %userinfo;
 7796:     my $srchstr;
 7797:     my $active_chk = 'none';
 7798:     my $now = time;
 7799:     if (@uroles > 0) {
 7800:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7801:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7802:         } else {
 7803:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7804:         }
 7805:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7806:             my $role_end = 0;
 7807:             my $role_start = 0;
 7808:             $active_chk = 'active';
 7809:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7810:                 $role_end = $1;
 7811:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7812:                     $role_start = $1;
 7813:                 }
 7814:             }
 7815:             if ($role_start > 0) {
 7816:                 if ($now < $role_start) {
 7817:                     $active_chk = 'future';
 7818:                 }
 7819:             }
 7820:             if ($role_end > 0) {
 7821:                 if ($now > $role_end) {
 7822:                     $active_chk = 'previous';
 7823:                 }
 7824:             }
 7825:         }
 7826:     }
 7827:     return $active_chk;
 7828: }
 7829: 
 7830: ###############################################
 7831: 
 7832: =pod
 7833: 
 7834: =item * &get_sections()
 7835: 
 7836: Determines all the sections for a course including
 7837: sections with students and sections containing other roles.
 7838: Incoming parameters: 
 7839: 
 7840: 1. domain
 7841: 2. course number 
 7842: 3. reference to array containing roles for which sections should 
 7843: be gathered (optional).
 7844: 4. reference to array containing status types for which sections 
 7845: should be gathered (optional).
 7846: 
 7847: If the third argument is undefined, sections are gathered for any role. 
 7848: If the fourth argument is undefined, sections are gathered for any status.
 7849: Permissible values are 'active' or 'future' or 'previous'.
 7850:  
 7851: Returns section hash (keys are section IDs, values are
 7852: number of users in each section), subject to the
 7853: optional roles filter, optional status filter 
 7854: 
 7855: =cut
 7856: 
 7857: ###############################################
 7858: sub get_sections {
 7859:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7860:     if (!defined($cdom) || !defined($cnum)) {
 7861:         my $cid =  $env{'request.course.id'};
 7862: 
 7863: 	return if (!defined($cid));
 7864: 
 7865:         $cdom = $env{'course.'.$cid.'.domain'};
 7866:         $cnum = $env{'course.'.$cid.'.num'};
 7867:     }
 7868: 
 7869:     my %sectioncount;
 7870:     my $now = time;
 7871: 
 7872:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7873: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7874: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7875: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7876:         my $start_index = &Apache::loncoursedata::CL_START();
 7877:         my $end_index = &Apache::loncoursedata::CL_END();
 7878:         my $status;
 7879: 	while (my ($student,$data) = each(%$classlist)) {
 7880: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7881: 				                     $data->[$status_index],
 7882:                                                      $data->[$start_index],
 7883:                                                      $data->[$end_index]);
 7884:             if ($stu_status eq 'Active') {
 7885:                 $status = 'active';
 7886:             } elsif ($end < $now) {
 7887:                 $status = 'previous';
 7888:             } elsif ($start > $now) {
 7889:                 $status = 'future';
 7890:             } 
 7891: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7892:                 if ((!defined($possible_status)) || (($status ne '') && 
 7893:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7894: 		    $sectioncount{$section}++;
 7895:                 }
 7896: 	    }
 7897: 	}
 7898:     }
 7899:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7900:     foreach my $user (sort(keys(%courseroles))) {
 7901: 	if ($user !~ /^(\w{2})/) { next; }
 7902: 	my ($role) = ($user =~ /^(\w{2})/);
 7903: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7904: 	my ($section,$status);
 7905: 	if ($role eq 'cr' &&
 7906: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7907: 	    $section=$1;
 7908: 	}
 7909: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7910: 	if (!defined($section) || $section eq '-1') { next; }
 7911:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7912:         if ($end == -1 && $start == -1) {
 7913:             next; #deleted role
 7914:         }
 7915:         if (!defined($possible_status)) { 
 7916:             $sectioncount{$section}++;
 7917:         } else {
 7918:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7919:                 $status = 'active';
 7920:             } elsif ($end < $now) {
 7921:                 $status = 'future';
 7922:             } elsif ($start > $now) {
 7923:                 $status = 'previous';
 7924:             }
 7925:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7926:                 $sectioncount{$section}++;
 7927:             }
 7928:         }
 7929:     }
 7930:     return %sectioncount;
 7931: }
 7932: 
 7933: ###############################################
 7934: 
 7935: =pod
 7936: 
 7937: =item * &get_course_users()
 7938: 
 7939: Retrieves usernames:domains for users in the specified course
 7940: with specific role(s), and access status. 
 7941: 
 7942: Incoming parameters:
 7943: 1. course domain
 7944: 2. course number
 7945: 3. access status: users must have - either active, 
 7946: previous, future, or all.
 7947: 4. reference to array of permissible roles
 7948: 5. reference to array of section restrictions (optional)
 7949: 6. reference to results object (hash of hashes).
 7950: 7. reference to optional userdata hash
 7951: 8. reference to optional statushash
 7952: 9. flag if privileged users (except those set to unhide in
 7953:    course settings) should be excluded    
 7954: Keys of top level results hash are roles.
 7955: Keys of inner hashes are username:domain, with 
 7956: values set to access type.
 7957: Optional userdata hash returns an array with arguments in the 
 7958: same order as loncoursedata::get_classlist() for student data.
 7959: 
 7960: Optional statushash returns
 7961: 
 7962: Entries for end, start, section and status are blank because
 7963: of the possibility of multiple values for non-student roles.
 7964: 
 7965: =cut
 7966: 
 7967: ###############################################
 7968: 
 7969: sub get_course_users {
 7970:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7971:     my %idx = ();
 7972:     my %seclists;
 7973: 
 7974:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7975:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7976:     $idx{end} = &Apache::loncoursedata::CL_END();
 7977:     $idx{start} = &Apache::loncoursedata::CL_START();
 7978:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7979:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7980:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7981:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7982: 
 7983:     if (grep(/^st$/,@{$roles})) {
 7984:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7985:         my $now = time;
 7986:         foreach my $student (keys(%{$classlist})) {
 7987:             my $match = 0;
 7988:             my $secmatch = 0;
 7989:             my $section = $$classlist{$student}[$idx{section}];
 7990:             my $status = $$classlist{$student}[$idx{status}];
 7991:             if ($section eq '') {
 7992:                 $section = 'none';
 7993:             }
 7994:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7995:                 if (grep(/^all$/,@{$sections})) {
 7996:                     $secmatch = 1;
 7997:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7998:                     if (grep(/^none$/,@{$sections})) {
 7999:                         $secmatch = 1;
 8000:                     }
 8001:                 } else {  
 8002: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8003: 		        $secmatch = 1;
 8004:                     }
 8005: 		}
 8006:                 if (!$secmatch) {
 8007:                     next;
 8008:                 }
 8009:             }
 8010:             if (defined($$types{'active'})) {
 8011:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8012:                     push(@{$$users{st}{$student}},'active');
 8013:                     $match = 1;
 8014:                 }
 8015:             }
 8016:             if (defined($$types{'previous'})) {
 8017:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8018:                     push(@{$$users{st}{$student}},'previous');
 8019:                     $match = 1;
 8020:                 }
 8021:             }
 8022:             if (defined($$types{'future'})) {
 8023:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8024:                     push(@{$$users{st}{$student}},'future');
 8025:                     $match = 1;
 8026:                 }
 8027:             }
 8028:             if ($match) {
 8029:                 push(@{$seclists{$student}},$section);
 8030:                 if (ref($userdata) eq 'HASH') {
 8031:                     $$userdata{$student} = $$classlist{$student};
 8032:                 }
 8033:                 if (ref($statushash) eq 'HASH') {
 8034:                     $statushash->{$student}{'st'}{$section} = $status;
 8035:                 }
 8036:             }
 8037:         }
 8038:     }
 8039:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8040:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8041:         my $now = time;
 8042:         my %displaystatus = ( previous => 'Expired',
 8043:                               active   => 'Active',
 8044:                               future   => 'Future',
 8045:                             );
 8046:         my %nothide;
 8047:         if ($hidepriv) {
 8048:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8049:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8050:                 if ($user !~ /:/) {
 8051:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8052:                 } else {
 8053:                     $nothide{$user} = 1;
 8054:                 }
 8055:             }
 8056:         }
 8057:         foreach my $person (sort(keys(%coursepersonnel))) {
 8058:             my $match = 0;
 8059:             my $secmatch = 0;
 8060:             my $status;
 8061:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8062:             $user =~ s/:$//;
 8063:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8064:             if ($end == -1 || $start == -1) {
 8065:                 next;
 8066:             }
 8067:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8068:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8069:                 my ($uname,$udom) = split(/:/,$user);
 8070:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8071:                     if (grep(/^all$/,@{$sections})) {
 8072:                         $secmatch = 1;
 8073:                     } elsif ($usec eq '') {
 8074:                         if (grep(/^none$/,@{$sections})) {
 8075:                             $secmatch = 1;
 8076:                         }
 8077:                     } else {
 8078:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8079:                             $secmatch = 1;
 8080:                         }
 8081:                     }
 8082:                     if (!$secmatch) {
 8083:                         next;
 8084:                     }
 8085:                 }
 8086:                 if ($usec eq '') {
 8087:                     $usec = 'none';
 8088:                 }
 8089:                 if ($uname ne '' && $udom ne '') {
 8090:                     if ($hidepriv) {
 8091:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8092:                             (!$nothide{$uname.':'.$udom})) {
 8093:                             next;
 8094:                         }
 8095:                     }
 8096:                     if ($end > 0 && $end < $now) {
 8097:                         $status = 'previous';
 8098:                     } elsif ($start > $now) {
 8099:                         $status = 'future';
 8100:                     } else {
 8101:                         $status = 'active';
 8102:                     }
 8103:                     foreach my $type (keys(%{$types})) { 
 8104:                         if ($status eq $type) {
 8105:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8106:                                 push(@{$$users{$role}{$user}},$type);
 8107:                             }
 8108:                             $match = 1;
 8109:                         }
 8110:                     }
 8111:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8112:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8113: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8114:                         }
 8115:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8116:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8117:                         }
 8118:                         if (ref($statushash) eq 'HASH') {
 8119:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8120:                         }
 8121:                     }
 8122:                 }
 8123:             }
 8124:         }
 8125:         if (grep(/^ow$/,@{$roles})) {
 8126:             if ((defined($cdom)) && (defined($cnum))) {
 8127:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8128:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8129:                     my $owner = $csettings{'internal.courseowner'};
 8130:                     next if ($owner eq '');
 8131:                     my ($ownername,$ownerdom);
 8132:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8133:                         $ownername = $1;
 8134:                         $ownerdom = $2;
 8135:                     } else {
 8136:                         $ownername = $owner;
 8137:                         $ownerdom = $cdom;
 8138:                         $owner = $ownername.':'.$ownerdom;
 8139:                     }
 8140:                     @{$$users{'ow'}{$owner}} = 'any';
 8141:                     if (defined($userdata) && 
 8142: 			!exists($$userdata{$owner})) {
 8143: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8144:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8145:                             push(@{$seclists{$owner}},'none');
 8146:                         }
 8147:                         if (ref($statushash) eq 'HASH') {
 8148:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8149:                         }
 8150: 		    }
 8151:                 }
 8152:             }
 8153:         }
 8154:         foreach my $user (keys(%seclists)) {
 8155:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8156:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8157:         }
 8158:     }
 8159:     return;
 8160: }
 8161: 
 8162: sub get_user_info {
 8163:     my ($udom,$uname,$idx,$userdata) = @_;
 8164:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8165: 	&plainname($uname,$udom,'lastname');
 8166:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8167:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8168:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8169:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8170:     return;
 8171: }
 8172: 
 8173: ###############################################
 8174: 
 8175: =pod
 8176: 
 8177: =item * &get_user_quota()
 8178: 
 8179: Retrieves quota assigned for storage of portfolio files for a user  
 8180: 
 8181: Incoming parameters:
 8182: 1. user's username
 8183: 2. user's domain
 8184: 
 8185: Returns:
 8186: 1. Disk quota (in Mb) assigned to student.
 8187: 2. (Optional) Type of setting: custom or default
 8188:    (individually assigned or default for user's 
 8189:    institutional status).
 8190: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8191:    or student - types as defined in localenroll::inst_usertypes 
 8192:    for user's domain, which determines default quota for user.
 8193: 4. (Optional) - Default quota which would apply to the user.
 8194: 
 8195: If a value has been stored in the user's environment, 
 8196: it will return that, otherwise it returns the maximal default
 8197: defined for the user's instituional status(es) in the domain.
 8198: 
 8199: =cut
 8200: 
 8201: ###############################################
 8202: 
 8203: 
 8204: sub get_user_quota {
 8205:     my ($uname,$udom) = @_;
 8206:     my ($quota,$quotatype,$settingstatus,$defquota);
 8207:     if (!defined($udom)) {
 8208:         $udom = $env{'user.domain'};
 8209:     }
 8210:     if (!defined($uname)) {
 8211:         $uname = $env{'user.name'};
 8212:     }
 8213:     if (($udom eq '' || $uname eq '') ||
 8214:         ($udom eq 'public') && ($uname eq 'public')) {
 8215:         $quota = 0;
 8216:         $quotatype = 'default';
 8217:         $defquota = 0; 
 8218:     } else {
 8219:         my $inststatus;
 8220:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8221:             $quota = $env{'environment.portfolioquota'};
 8222:             $inststatus = $env{'environment.inststatus'};
 8223:         } else {
 8224:             my %userenv = 
 8225:                 &Apache::lonnet::get('environment',['portfolioquota',
 8226:                                      'inststatus'],$udom,$uname);
 8227:             my ($tmp) = keys(%userenv);
 8228:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8229:                 $quota = $userenv{'portfolioquota'};
 8230:                 $inststatus = $userenv{'inststatus'};
 8231:             } else {
 8232:                 undef(%userenv);
 8233:             }
 8234:         }
 8235:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8236:         if ($quota eq '') {
 8237:             $quota = $defquota;
 8238:             $quotatype = 'default';
 8239:         } else {
 8240:             $quotatype = 'custom';
 8241:         }
 8242:     }
 8243:     if (wantarray) {
 8244:         return ($quota,$quotatype,$settingstatus,$defquota);
 8245:     } else {
 8246:         return $quota;
 8247:     }
 8248: }
 8249: 
 8250: ###############################################
 8251: 
 8252: =pod
 8253: 
 8254: =item * &default_quota()
 8255: 
 8256: Retrieves default quota assigned for storage of user portfolio files,
 8257: given an (optional) user's institutional status.
 8258: 
 8259: Incoming parameters:
 8260: 1. domain
 8261: 2. (Optional) institutional status(es).  This is a : separated list of 
 8262:    status types (e.g., faculty, staff, student etc.)
 8263:    which apply to the user for whom the default is being retrieved.
 8264:    If the institutional status string in undefined, the domain
 8265:    default quota will be returned. 
 8266: 
 8267: Returns:
 8268: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8269: 2. (Optional) institutional type which determined the value of the
 8270:    default quota.
 8271: 
 8272: If a value has been stored in the domain's configuration db,
 8273: it will return that, otherwise it returns 20 (for backwards 
 8274: compatibility with domains which have not set up a configuration
 8275: db file; the original statically defined portfolio quota was 20 Mb). 
 8276: 
 8277: If the user's status includes multiple types (e.g., staff and student),
 8278: the largest default quota which applies to the user determines the
 8279: default quota returned.
 8280: 
 8281: =back
 8282: 
 8283: =cut
 8284: 
 8285: ###############################################
 8286: 
 8287: 
 8288: sub default_quota {
 8289:     my ($udom,$inststatus) = @_;
 8290:     my ($defquota,$settingstatus);
 8291:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8292:                                             ['quotas'],$udom);
 8293:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8294:         if ($inststatus ne '') {
 8295:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8296:             foreach my $item (@statuses) {
 8297:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8298:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8299:                         if ($defquota eq '') {
 8300:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8301:                             $settingstatus = $item;
 8302:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8303:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8304:                             $settingstatus = $item;
 8305:                         }
 8306:                     }
 8307:                 } else {
 8308:                     if ($quotahash{'quotas'}{$item} ne '') {
 8309:                         if ($defquota eq '') {
 8310:                             $defquota = $quotahash{'quotas'}{$item};
 8311:                             $settingstatus = $item;
 8312:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8313:                             $defquota = $quotahash{'quotas'}{$item};
 8314:                             $settingstatus = $item;
 8315:                         }
 8316:                     }
 8317:                 }
 8318:             }
 8319:         }
 8320:         if ($defquota eq '') {
 8321:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8322:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8323:             } else {
 8324:                 $defquota = $quotahash{'quotas'}{'default'};
 8325:             }
 8326:             $settingstatus = 'default';
 8327:         }
 8328:     } else {
 8329:         $settingstatus = 'default';
 8330:         $defquota = 20;
 8331:     }
 8332:     if (wantarray) {
 8333:         return ($defquota,$settingstatus);
 8334:     } else {
 8335:         return $defquota;
 8336:     }
 8337: }
 8338: 
 8339: sub get_secgrprole_info {
 8340:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8341:     my %sections_count = &get_sections($cdom,$cnum);
 8342:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8343:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8344:     my @groups = sort(keys(%curr_groups));
 8345:     my $allroles = [];
 8346:     my $rolehash;
 8347:     my $accesshash = {
 8348:                      active => 'Currently has access',
 8349:                      future => 'Will have future access',
 8350:                      previous => 'Previously had access',
 8351:                   };
 8352:     if ($needroles) {
 8353:         $rolehash = {'all' => 'all'};
 8354:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8355: 	if (&Apache::lonnet::error(%user_roles)) {
 8356: 	    undef(%user_roles);
 8357: 	}
 8358:         foreach my $item (keys(%user_roles)) {
 8359:             my ($role)=split(/\:/,$item,2);
 8360:             if ($role eq 'cr') { next; }
 8361:             if ($role =~ /^cr/) {
 8362:                 $$rolehash{$role} = (split('/',$role))[3];
 8363:             } else {
 8364:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8365:             }
 8366:         }
 8367:         foreach my $key (sort(keys(%{$rolehash}))) {
 8368:             push(@{$allroles},$key);
 8369:         }
 8370:         push (@{$allroles},'st');
 8371:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8372:     }
 8373:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8374: }
 8375: 
 8376: sub user_picker {
 8377:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8378:     my $currdom = $dom;
 8379:     my %curr_selected = (
 8380:                         srchin => 'dom',
 8381:                         srchby => 'lastname',
 8382:                       );
 8383:     my $srchterm;
 8384:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8385:         if ($srch->{'srchby'} ne '') {
 8386:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8387:         }
 8388:         if ($srch->{'srchin'} ne '') {
 8389:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8390:         }
 8391:         if ($srch->{'srchtype'} ne '') {
 8392:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8393:         }
 8394:         if ($srch->{'srchdomain'} ne '') {
 8395:             $currdom = $srch->{'srchdomain'};
 8396:         }
 8397:         $srchterm = $srch->{'srchterm'};
 8398:     }
 8399:     my %lt=&Apache::lonlocal::texthash(
 8400:                     'usr'       => 'Search criteria',
 8401:                     'doma'      => 'Domain/institution to search',
 8402:                     'uname'     => 'username',
 8403:                     'lastname'  => 'last name',
 8404:                     'lastfirst' => 'last name, first name',
 8405:                     'crs'       => 'in this course',
 8406:                     'dom'       => 'in selected LON-CAPA domain', 
 8407:                     'alc'       => 'all LON-CAPA',
 8408:                     'instd'     => 'in institutional directory for selected domain',
 8409:                     'exact'     => 'is',
 8410:                     'contains'  => 'contains',
 8411:                     'begins'    => 'begins with',
 8412:                     'youm'      => "You must include some text to search for.",
 8413:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8414:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8415:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8416:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8417:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8418:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8419:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8420:                                        );
 8421:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8422:     my $srchinsel = ' <select name="srchin">';
 8423: 
 8424:     my @srchins = ('crs','dom','alc','instd');
 8425: 
 8426:     foreach my $option (@srchins) {
 8427:         # FIXME 'alc' option unavailable until 
 8428:         #       loncreateuser::print_user_query_page()
 8429:         #       has been completed.
 8430:         next if ($option eq 'alc');
 8431:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8432:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8433:         if ($curr_selected{'srchin'} eq $option) {
 8434:             $srchinsel .= ' 
 8435:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8436:         } else {
 8437:             $srchinsel .= '
 8438:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8439:         }
 8440:     }
 8441:     $srchinsel .= "\n  </select>\n";
 8442: 
 8443:     my $srchbysel =  ' <select name="srchby">';
 8444:     foreach my $option ('lastname','lastfirst','uname') {
 8445:         if ($curr_selected{'srchby'} eq $option) {
 8446:             $srchbysel .= '
 8447:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8448:         } else {
 8449:             $srchbysel .= '
 8450:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8451:          }
 8452:     }
 8453:     $srchbysel .= "\n  </select>\n";
 8454: 
 8455:     my $srchtypesel = ' <select name="srchtype">';
 8456:     foreach my $option ('begins','contains','exact') {
 8457:         if ($curr_selected{'srchtype'} eq $option) {
 8458:             $srchtypesel .= '
 8459:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8460:         } else {
 8461:             $srchtypesel .= '
 8462:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8463:         }
 8464:     }
 8465:     $srchtypesel .= "\n  </select>\n";
 8466: 
 8467:     my ($newuserscript,$new_user_create);
 8468:     my $context_dom = $env{'request.role.domain'};
 8469:     if ($context eq 'requestcrs') {
 8470:         if ($env{'form.coursedom'} ne '') { 
 8471:             $context_dom = $env{'form.coursedom'};
 8472:         }
 8473:     }
 8474:     if ($forcenewuser) {
 8475:         if (ref($srch) eq 'HASH') {
 8476:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8477:                 if ($cancreate) {
 8478:                     $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>';
 8479:                 } else {
 8480:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8481:                     my %usertypetext = (
 8482:                         official   => 'institutional',
 8483:                         unofficial => 'non-institutional',
 8484:                     );
 8485:                     $new_user_create = '<p class="LC_warning">'
 8486:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8487:                                       .' '
 8488:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8489:                                           ,'<a href="'.$helplink.'">','</a>')
 8490:                                       .'</p><br />';
 8491:                 }
 8492:             }
 8493:         }
 8494: 
 8495:         $newuserscript = <<"ENDSCRIPT";
 8496: 
 8497: function setSearch(createnew,callingForm) {
 8498:     if (createnew == 1) {
 8499:         for (var i=0; i<callingForm.srchby.length; i++) {
 8500:             if (callingForm.srchby.options[i].value == 'uname') {
 8501:                 callingForm.srchby.selectedIndex = i;
 8502:             }
 8503:         }
 8504:         for (var i=0; i<callingForm.srchin.length; i++) {
 8505:             if ( callingForm.srchin.options[i].value == 'dom') {
 8506: 		callingForm.srchin.selectedIndex = i;
 8507:             }
 8508:         }
 8509:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8510:             if (callingForm.srchtype.options[i].value == 'exact') {
 8511:                 callingForm.srchtype.selectedIndex = i;
 8512:             }
 8513:         }
 8514:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8515:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8516:                 callingForm.srchdomain.selectedIndex = i;
 8517:             }
 8518:         }
 8519:     }
 8520: }
 8521: ENDSCRIPT
 8522: 
 8523:     }
 8524: 
 8525:     my $output = <<"END_BLOCK";
 8526: <script type="text/javascript">
 8527: // <![CDATA[
 8528: function validateEntry(callingForm) {
 8529: 
 8530:     var checkok = 1;
 8531:     var srchin;
 8532:     for (var i=0; i<callingForm.srchin.length; i++) {
 8533: 	if ( callingForm.srchin[i].checked ) {
 8534: 	    srchin = callingForm.srchin[i].value;
 8535: 	}
 8536:     }
 8537: 
 8538:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8539:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8540:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8541:     var srchterm =  callingForm.srchterm.value;
 8542:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8543:     var msg = "";
 8544: 
 8545:     if (srchterm == "") {
 8546:         checkok = 0;
 8547:         msg += "$lt{'youm'}\\n";
 8548:     }
 8549: 
 8550:     if (srchtype== 'begins') {
 8551:         if (srchterm.length < 2) {
 8552:             checkok = 0;
 8553:             msg += "$lt{'thte'}\\n";
 8554:         }
 8555:     }
 8556: 
 8557:     if (srchtype== 'contains') {
 8558:         if (srchterm.length < 3) {
 8559:             checkok = 0;
 8560:             msg += "$lt{'thet'}\\n";
 8561:         }
 8562:     }
 8563:     if (srchin == 'instd') {
 8564:         if (srchdomain == '') {
 8565:             checkok = 0;
 8566:             msg += "$lt{'yomc'}\\n";
 8567:         }
 8568:     }
 8569:     if (srchin == 'dom') {
 8570:         if (srchdomain == '') {
 8571:             checkok = 0;
 8572:             msg += "$lt{'ymcd'}\\n";
 8573:         }
 8574:     }
 8575:     if (srchby == 'lastfirst') {
 8576:         if (srchterm.indexOf(",") == -1) {
 8577:             checkok = 0;
 8578:             msg += "$lt{'whus'}\\n";
 8579:         }
 8580:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8581:             checkok = 0;
 8582:             msg += "$lt{'whse'}\\n";
 8583:         }
 8584:     }
 8585:     if (checkok == 0) {
 8586:         alert("$lt{'thfo'}\\n"+msg);
 8587:         return;
 8588:     }
 8589:     if (checkok == 1) {
 8590:         callingForm.submit();
 8591:     }
 8592: }
 8593: 
 8594: $newuserscript
 8595: 
 8596: // ]]>
 8597: </script>
 8598: 
 8599: $new_user_create
 8600: 
 8601: END_BLOCK
 8602: 
 8603:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8604:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8605:                $domform.
 8606:                &Apache::lonhtmlcommon::row_closure().
 8607:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8608:                $srchbysel.
 8609:                $srchtypesel. 
 8610:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8611:                $srchinsel.
 8612:                &Apache::lonhtmlcommon::row_closure(1). 
 8613:                &Apache::lonhtmlcommon::end_pick_box().
 8614:                '<br />';
 8615:     return $output;
 8616: }
 8617: 
 8618: sub user_rule_check {
 8619:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8620:     my $response;
 8621:     if (ref($usershash) eq 'HASH') {
 8622:         foreach my $user (keys(%{$usershash})) {
 8623:             my ($uname,$udom) = split(/:/,$user);
 8624:             next if ($udom eq '' || $uname eq '');
 8625:             my ($id,$newuser);
 8626:             if (ref($usershash->{$user}) eq 'HASH') {
 8627:                 $newuser = $usershash->{$user}->{'newuser'};
 8628:                 $id = $usershash->{$user}->{'id'};
 8629:             }
 8630:             my $inst_response;
 8631:             if (ref($checks) eq 'HASH') {
 8632:                 if (defined($checks->{'username'})) {
 8633:                     ($inst_response,%{$inst_results->{$user}}) = 
 8634:                         &Apache::lonnet::get_instuser($udom,$uname);
 8635:                 } elsif (defined($checks->{'id'})) {
 8636:                     ($inst_response,%{$inst_results->{$user}}) =
 8637:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8638:                 }
 8639:             } else {
 8640:                 ($inst_response,%{$inst_results->{$user}}) =
 8641:                     &Apache::lonnet::get_instuser($udom,$uname);
 8642:                 return;
 8643:             }
 8644:             if (!$got_rules->{$udom}) {
 8645:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8646:                                                   ['usercreation'],$udom);
 8647:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8648:                     foreach my $item ('username','id') {
 8649:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8650:                             $$curr_rules{$udom}{$item} = 
 8651:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8652:                         }
 8653:                     }
 8654:                 }
 8655:                 $got_rules->{$udom} = 1;  
 8656:             }
 8657:             foreach my $item (keys(%{$checks})) {
 8658:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8659:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8660:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8661:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8662:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8663:                                 if ($rule_check{$rule}) {
 8664:                                     $$rulematch{$user}{$item} = $rule;
 8665:                                     if ($inst_response eq 'ok') {
 8666:                                         if (ref($inst_results) eq 'HASH') {
 8667:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8668:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8669:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8670:                                                 }
 8671:                                             }
 8672:                                         }
 8673:                                     }
 8674:                                     last;
 8675:                                 }
 8676:                             }
 8677:                         }
 8678:                     }
 8679:                 }
 8680:             }
 8681:         }
 8682:     }
 8683:     return;
 8684: }
 8685: 
 8686: sub user_rule_formats {
 8687:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8688:     my %text = ( 
 8689:                  'username' => 'Usernames',
 8690:                  'id'       => 'IDs',
 8691:                );
 8692:     my $output;
 8693:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8694:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8695:         if (@{$ruleorder} > 0) {
 8696:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
 8697:             foreach my $rule (@{$ruleorder}) {
 8698:                 if (ref($curr_rules) eq 'ARRAY') {
 8699:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8700:                         if (ref($rules->{$rule}) eq 'HASH') {
 8701:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8702:                                         $rules->{$rule}{'desc'}.'</li>';
 8703:                         }
 8704:                     }
 8705:                 }
 8706:             }
 8707:             $output .= '</ul>';
 8708:         }
 8709:     }
 8710:     return $output;
 8711: }
 8712: 
 8713: sub instrule_disallow_msg {
 8714:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8715:     my $response;
 8716:     my %text = (
 8717:                   item   => 'username',
 8718:                   items  => 'usernames',
 8719:                   match  => 'matches',
 8720:                   do     => 'does',
 8721:                   action => 'a username',
 8722:                   one    => 'one',
 8723:                );
 8724:     if ($count > 1) {
 8725:         $text{'item'} = 'usernames';
 8726:         $text{'match'} ='match';
 8727:         $text{'do'} = 'do';
 8728:         $text{'action'} = 'usernames',
 8729:         $text{'one'} = 'ones';
 8730:     }
 8731:     if ($checkitem eq 'id') {
 8732:         $text{'items'} = 'IDs';
 8733:         $text{'item'} = 'ID';
 8734:         $text{'action'} = 'an ID';
 8735:         if ($count > 1) {
 8736:             $text{'item'} = 'IDs';
 8737:             $text{'action'} = 'IDs';
 8738:         }
 8739:     }
 8740:     $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 />';
 8741:     if ($mode eq 'upload') {
 8742:         if ($checkitem eq 'username') {
 8743:             $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'}.");
 8744:         } elsif ($checkitem eq 'id') {
 8745:             $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.");
 8746:         }
 8747:     } elsif ($mode eq 'selfcreate') {
 8748:         if ($checkitem eq 'id') {
 8749:             $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.");
 8750:         }
 8751:     } else {
 8752:         if ($checkitem eq 'username') {
 8753:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8754:         } elsif ($checkitem eq 'id') {
 8755:             $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.");
 8756:         }
 8757:     }
 8758:     return $response;
 8759: }
 8760: 
 8761: sub personal_data_fieldtitles {
 8762:     my %fieldtitles = &Apache::lonlocal::texthash (
 8763:                         id => 'Student/Employee ID',
 8764:                         permanentemail => 'E-mail address',
 8765:                         lastname => 'Last Name',
 8766:                         firstname => 'First Name',
 8767:                         middlename => 'Middle Name',
 8768:                         generation => 'Generation',
 8769:                         gen => 'Generation',
 8770:                         inststatus => 'Affiliation',
 8771:                    );
 8772:     return %fieldtitles;
 8773: }
 8774: 
 8775: sub sorted_inst_types {
 8776:     my ($dom) = @_;
 8777:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8778:     my $othertitle = &mt('All users');
 8779:     if ($env{'request.course.id'}) {
 8780:         $othertitle  = &mt('Any users');
 8781:     }
 8782:     my @types;
 8783:     if (ref($order) eq 'ARRAY') {
 8784:         @types = @{$order};
 8785:     }
 8786:     if (@types == 0) {
 8787:         if (ref($usertypes) eq 'HASH') {
 8788:             @types = sort(keys(%{$usertypes}));
 8789:         }
 8790:     }
 8791:     if (keys(%{$usertypes}) > 0) {
 8792:         $othertitle = &mt('Other users');
 8793:     }
 8794:     return ($othertitle,$usertypes,\@types);
 8795: }
 8796: 
 8797: sub get_institutional_codes {
 8798:     my ($settings,$allcourses,$LC_code) = @_;
 8799: # Get complete list of course sections to update
 8800:     my @currsections = ();
 8801:     my @currxlists = ();
 8802:     my $coursecode = $$settings{'internal.coursecode'};
 8803: 
 8804:     if ($$settings{'internal.sectionnums'} ne '') {
 8805:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8806:     }
 8807: 
 8808:     if ($$settings{'internal.crosslistings'} ne '') {
 8809:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8810:     }
 8811: 
 8812:     if (@currxlists > 0) {
 8813:         foreach (@currxlists) {
 8814:             if (m/^([^:]+):(\w*)$/) {
 8815:                 unless (grep/^$1$/,@{$allcourses}) {
 8816:                     push @{$allcourses},$1;
 8817:                     $$LC_code{$1} = $2;
 8818:                 }
 8819:             }
 8820:         }
 8821:     }
 8822:  
 8823:     if (@currsections > 0) {
 8824:         foreach (@currsections) {
 8825:             if (m/^(\w+):(\w*)$/) {
 8826:                 my $sec = $coursecode.$1;
 8827:                 my $lc_sec = $2;
 8828:                 unless (grep/^$sec$/,@{$allcourses}) {
 8829:                     push @{$allcourses},$sec;
 8830:                     $$LC_code{$sec} = $lc_sec;
 8831:                 }
 8832:             }
 8833:         }
 8834:     }
 8835:     return;
 8836: }
 8837: 
 8838: sub get_standard_codeitems {
 8839:     return ('Year','Semester','Department','Number','Section');
 8840: }
 8841: 
 8842: =pod
 8843: 
 8844: =head1 Slot Helpers
 8845: 
 8846: =over 4
 8847: 
 8848: =item * sorted_slots()
 8849: 
 8850: Sorts an array of slot names in order of an optional sort key,
 8851: default sort is by slot start time (earliest first). 
 8852: 
 8853: Inputs:
 8854: 
 8855: =over 4
 8856: 
 8857: slotsarr  - Reference to array of unsorted slot names.
 8858: 
 8859: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8860: 
 8861: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 8862: 
 8863: =back
 8864: 
 8865: Returns:
 8866: 
 8867: =over 4
 8868: 
 8869: sorted   - An array of slot names sorted by a specified sort key 
 8870:            (default sort key is start time of the slot).
 8871: 
 8872: =back
 8873: 
 8874: =cut
 8875: 
 8876: 
 8877: sub sorted_slots {
 8878:     my ($slotsarr,$slots,$sortkey) = @_;
 8879:     if ($sortkey eq '') {
 8880:         $sortkey = 'starttime';
 8881:     }
 8882:     my @sorted;
 8883:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8884:         @sorted =
 8885:             sort {
 8886:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8887:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 8888:                      }
 8889:                      if (ref($slots->{$a})) { return -1;}
 8890:                      if (ref($slots->{$b})) { return 1;}
 8891:                      return 0;
 8892:                  } @{$slotsarr};
 8893:     }
 8894:     return @sorted;
 8895: }
 8896: 
 8897: =pod
 8898: 
 8899: =item * get_future_slots()
 8900: 
 8901: Inputs:
 8902: 
 8903: =over 4
 8904: 
 8905: cnum - course number
 8906: 
 8907: cdom - course domain
 8908: 
 8909: now - current UNIX time
 8910: 
 8911: symb - optional symb
 8912: 
 8913: =back
 8914: 
 8915: Returns:
 8916: 
 8917: =over 4
 8918: 
 8919: sorted_reservable - ref to array of student_schedulable slots currently 
 8920:                     reservable, ordered by end date of reservation period.
 8921: 
 8922: reservable_now - ref to hash of student_schedulable slots currently
 8923:                  reservable.
 8924: 
 8925:     Keys in inner hash are:
 8926:     (a) symb: either blank or symb to which slot use is restricted.
 8927:     (b) endreserve: end date of reservation period. 
 8928: 
 8929: sorted_future - ref to array of student_schedulable slots reservable in
 8930:                 the future, ordered by start date of reservation period.
 8931: 
 8932: future_reservable - ref to hash of student_schedulable slots reservable
 8933:                     in the future.
 8934: 
 8935:     Keys in inner hash are:
 8936:     (a) symb: either blank or symb to which slot use is restricted.
 8937:     (b) startreserve:  start date of reservation period.
 8938: 
 8939: =back
 8940: 
 8941: =cut
 8942: 
 8943: sub get_future_slots {
 8944:     my ($cnum,$cdom,$now,$symb) = @_;
 8945:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 8946:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 8947:     foreach my $slot (keys(%slots)) {
 8948:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 8949:         if ($symb) {
 8950:             next if (($slots{$slot}->{'symb'} ne '') && 
 8951:                      ($slots{$slot}->{'symb'} ne $symb));
 8952:         }
 8953:         if (($slots{$slot}->{'starttime'} > $now) &&
 8954:             ($slots{$slot}->{'endtime'} > $now)) {
 8955:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 8956:                 my $userallowed = 0;
 8957:                 if ($slots{$slot}->{'allowedsections'}) {
 8958:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 8959:                     if (!defined($env{'request.role.sec'})
 8960:                         && grep(/^No section assigned$/,@allowed_sec)) {
 8961:                         $userallowed=1;
 8962:                     } else {
 8963:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 8964:                             $userallowed=1;
 8965:                         }
 8966:                     }
 8967:                     unless ($userallowed) {
 8968:                         if (defined($env{'request.course.groups'})) {
 8969:                             my @groups = split(/:/,$env{'request.course.groups'});
 8970:                             foreach my $group (@groups) {
 8971:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 8972:                                     $userallowed=1;
 8973:                                     last;
 8974:                                 }
 8975:                             }
 8976:                         }
 8977:                     }
 8978:                 }
 8979:                 if ($slots{$slot}->{'allowedusers'}) {
 8980:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 8981:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 8982:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 8983:                         $userallowed = 1;
 8984:                     }
 8985:                 }
 8986:                 next unless($userallowed);
 8987:             }
 8988:             my $startreserve = $slots{$slot}->{'startreserve'};
 8989:             my $endreserve = $slots{$slot}->{'endreserve'};
 8990:             my $symb = $slots{$slot}->{'symb'};
 8991:             if (($startreserve < $now) &&
 8992:                 (!$endreserve || $endreserve > $now)) {
 8993:                 my $lastres = $endreserve;
 8994:                 if (!$lastres) {
 8995:                     $lastres = $slots{$slot}->{'starttime'};
 8996:                 }
 8997:                 $reservable_now{$slot} = {
 8998:                                            symb       => $symb,
 8999:                                            endreserve => $lastres
 9000:                                          };
 9001:             } elsif (($startreserve > $now) &&
 9002:                      (!$endreserve || $endreserve > $startreserve)) {
 9003:                 $future_reservable{$slot} = {
 9004:                                               symb         => $symb,
 9005:                                               startreserve => $startreserve
 9006:                                             };
 9007:             }
 9008:         }
 9009:     }
 9010:     my @unsorted_reservable = keys(%reservable_now);
 9011:     if (@unsorted_reservable > 0) {
 9012:         @sorted_reservable = 
 9013:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9014:     }
 9015:     my @unsorted_future = keys(%future_reservable);
 9016:     if (@unsorted_future > 0) {
 9017:         @sorted_future =
 9018:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9019:     }
 9020:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9021: }
 9022: 
 9023: =pod
 9024: 
 9025: =back
 9026: 
 9027: =head1 HTTP Helpers
 9028: 
 9029: =over 4
 9030: 
 9031: =item * &get_unprocessed_cgi($query,$possible_names)
 9032: 
 9033: Modify the %env hash to contain unprocessed CGI form parameters held in
 9034: $query.  The parameters listed in $possible_names (an array reference),
 9035: will be set in $env{'form.name'} if they do not already exist.
 9036: 
 9037: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9038: $possible_names is an ref to an array of form element names.  As an example:
 9039: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9040: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9041: 
 9042: =cut
 9043: 
 9044: sub get_unprocessed_cgi {
 9045:   my ($query,$possible_names)= @_;
 9046:   # $Apache::lonxml::debug=1;
 9047:   foreach my $pair (split(/&/,$query)) {
 9048:     my ($name, $value) = split(/=/,$pair);
 9049:     $name = &unescape($name);
 9050:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9051:       $value =~ tr/+/ /;
 9052:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9053:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9054:     }
 9055:   }
 9056: }
 9057: 
 9058: =pod
 9059: 
 9060: =item * &cacheheader() 
 9061: 
 9062: returns cache-controlling header code
 9063: 
 9064: =cut
 9065: 
 9066: sub cacheheader {
 9067:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9068:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9069:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9070:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9071:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9072:     return $output;
 9073: }
 9074: 
 9075: =pod
 9076: 
 9077: =item * &no_cache($r) 
 9078: 
 9079: specifies header code to not have cache
 9080: 
 9081: =cut
 9082: 
 9083: sub no_cache {
 9084:     my ($r) = @_;
 9085:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9086: 	$env{'request.method'} ne 'GET') { return ''; }
 9087:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9088:     $r->no_cache(1);
 9089:     $r->header_out("Expires" => $date);
 9090:     $r->header_out("Pragma" => "no-cache");
 9091: }
 9092: 
 9093: sub content_type {
 9094:     my ($r,$type,$charset) = @_;
 9095:     if ($r) {
 9096: 	#  Note that printout.pl calls this with undef for $r.
 9097: 	&no_cache($r);
 9098:     }
 9099:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9100:     unless ($charset) {
 9101: 	$charset=&Apache::lonlocal::current_encoding;
 9102:     }
 9103:     if ($charset) { $type.='; charset='.$charset; }
 9104:     if ($r) {
 9105: 	$r->content_type($type);
 9106:     } else {
 9107: 	print("Content-type: $type\n\n");
 9108:     }
 9109: }
 9110: 
 9111: =pod
 9112: 
 9113: =item * &add_to_env($name,$value) 
 9114: 
 9115: adds $name to the %env hash with value
 9116: $value, if $name already exists, the entry is converted to an array
 9117: reference and $value is added to the array.
 9118: 
 9119: =cut
 9120: 
 9121: sub add_to_env {
 9122:   my ($name,$value)=@_;
 9123:   if (defined($env{$name})) {
 9124:     if (ref($env{$name})) {
 9125:       #already have multiple values
 9126:       push(@{ $env{$name} },$value);
 9127:     } else {
 9128:       #first time seeing multiple values, convert hash entry to an arrayref
 9129:       my $first=$env{$name};
 9130:       undef($env{$name});
 9131:       push(@{ $env{$name} },$first,$value);
 9132:     }
 9133:   } else {
 9134:     $env{$name}=$value;
 9135:   }
 9136: }
 9137: 
 9138: =pod
 9139: 
 9140: =item * &get_env_multiple($name) 
 9141: 
 9142: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9143: values may be defined and end up as an array ref.
 9144: 
 9145: returns an array of values
 9146: 
 9147: =cut
 9148: 
 9149: sub get_env_multiple {
 9150:     my ($name) = @_;
 9151:     my @values;
 9152:     if (defined($env{$name})) {
 9153:         # exists is it an array
 9154:         if (ref($env{$name})) {
 9155:             @values=@{ $env{$name} };
 9156:         } else {
 9157:             $values[0]=$env{$name};
 9158:         }
 9159:     }
 9160:     return(@values);
 9161: }
 9162: 
 9163: sub ask_for_embedded_content {
 9164:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9165:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9166:         %currsubfile,%unused);
 9167:     my $counter = 0;
 9168:     my $numnew = 0;
 9169:     my $numremref = 0;
 9170:     my $numinvalid = 0;
 9171:     my $numpathchg = 0;
 9172:     my $numexisting = 0;
 9173:     my $numunused = 0;
 9174:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9175:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9176:     my $heading = &mt('Upload embedded files');
 9177:     my $buttontext = &mt('Upload');
 9178: 
 9179:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9180:         my $current_path='/';
 9181:         if ($env{'form.currentpath'}) {
 9182:             $current_path = $env{'form.currentpath'};
 9183:         }
 9184:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9185:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9186:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9187:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9188:         } else {
 9189:             $udom = $env{'user.domain'};
 9190:             $uname = $env{'user.name'};
 9191:             $url = '/userfiles/portfolio';
 9192:         }
 9193:         $toplevel = $url.'/';
 9194:         $url .= $current_path;
 9195:         $getpropath = 1;
 9196:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9197:              ($actionurl eq '/adm/imsimport')) { 
 9198:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9199:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9200:         $toplevel = $url;
 9201:         if ($rest ne '') {
 9202:             $url .= $rest;
 9203:         }
 9204:     } elsif ($actionurl eq '/adm/coursedocs') {
 9205:         if (ref($args) eq 'HASH') {
 9206:             $url = $args->{'docs_url'};
 9207:             $toplevel = $url;
 9208:         }
 9209:     } elsif ($actionurl eq '/adm/dependencies') {
 9210:         if ($env{'request.course.id'} ne '') {
 9211:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9212:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9213:             if (ref($args) eq 'HASH') {
 9214:                 $url = $args->{'docs_url'};
 9215:                 $title = $args->{'docs_title'};
 9216:                 $toplevel = "/$url";
 9217:                 ($path) =  
 9218:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9219:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9220:                 $fileloc =~ s{^/}{};
 9221:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9222:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9223:             }
 9224:         }
 9225:     }
 9226:     my $now = time();
 9227:     foreach my $embed_file (keys(%{$allfiles})) {
 9228:         my $absolutepath;
 9229:         if ($embed_file =~ m{^\w+://}) {
 9230:             $newfiles{$embed_file} = 1;
 9231:             $mapping{$embed_file} = $embed_file;
 9232:         } else {
 9233:             if ($embed_file =~ m{^/}) {
 9234:                 $absolutepath = $embed_file;
 9235:                 $embed_file =~ s{^(/+)}{};
 9236:             }
 9237:             if ($embed_file =~ m{/}) {
 9238:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9239:                 $path = &check_for_traversal($path,$url,$toplevel);
 9240:                 my $item = $fname;
 9241:                 if ($path ne '') {
 9242:                     $item = $path.'/'.$fname;
 9243:                     $subdependencies{$path}{$fname} = 1;
 9244:                 } else {
 9245:                     $dependencies{$item} = 1;
 9246:                 }
 9247:                 if ($absolutepath) {
 9248:                     $mapping{$item} = $absolutepath;
 9249:                 } else {
 9250:                     $mapping{$item} = $embed_file;
 9251:                 }
 9252:             } else {
 9253:                 $dependencies{$embed_file} = 1;
 9254:                 if ($absolutepath) {
 9255:                     $mapping{$embed_file} = $absolutepath;
 9256:                 } else {
 9257:                     $mapping{$embed_file} = $embed_file;
 9258:                 }
 9259:             }
 9260:         }
 9261:     }
 9262:     my $dirptr = 16384;
 9263:     foreach my $path (keys(%subdependencies)) {
 9264:         $currsubfile{$path} = {};
 9265:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9266:             my ($sublistref,$listerror) =
 9267:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9268:             if (ref($sublistref) eq 'ARRAY') {
 9269:                 foreach my $line (@{$sublistref}) {
 9270:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9271:                     $currsubfile{$path}{$file_name} = 1;
 9272:                 }
 9273:             }
 9274:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9275:             if (opendir(my $dir,$url.'/'.$path)) {
 9276:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9277:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9278:             }
 9279:         } elsif ($actionurl eq '/adm/dependencies') {
 9280:             if ($env{'request.course.id'} ne '') {
 9281:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9282:                 if ($dir ne '') {
 9283:                     my ($sublistref,$listerror) =
 9284:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9285:                     if (ref($sublistref) eq 'ARRAY') {
 9286:                         foreach my $line (@{$sublistref}) {
 9287:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9288:                                 undef,$mtime)=split(/\&/,$line,12);
 9289:                             unless (($testdir&$dirptr) ||
 9290:                                     ($file_name =~ /^\.\.?$/)) {
 9291:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9292:                             }
 9293:                         }
 9294:                     }
 9295:                 }
 9296:             }
 9297:         }
 9298:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9299:             if (exists($currsubfile{$path}{$file})) {
 9300:                 my $item = $path.'/'.$file;
 9301:                 unless ($mapping{$item} eq $item) {
 9302:                     $pathchanges{$item} = 1;
 9303:                 }
 9304:                 $existing{$item} = 1;
 9305:                 $numexisting ++;
 9306:             } else {
 9307:                 $newfiles{$path.'/'.$file} = 1;
 9308:             }
 9309:         }
 9310:         if ($actionurl eq '/adm/dependencies') {
 9311:             foreach my $path (keys(%currsubfile)) {
 9312:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9313:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9314:                          unless ($subdependencies{$path}{$file}) {
 9315:                              $unused{$path.'/'.$file} = 1; 
 9316:                          }
 9317:                     }
 9318:                 }
 9319:             }
 9320:         }
 9321:     }
 9322:     my %currfile;
 9323:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9324:         my ($dirlistref,$listerror) =
 9325:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9326:         if (ref($dirlistref) eq 'ARRAY') {
 9327:             foreach my $line (@{$dirlistref}) {
 9328:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9329:                 $currfile{$file_name} = 1;
 9330:             }
 9331:         }
 9332:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9333:         if (opendir(my $dir,$url)) {
 9334:             my @dir_list = grep(!/^\./,readdir($dir));
 9335:             map {$currfile{$_} = 1;} @dir_list;
 9336:         }
 9337:     } elsif ($actionurl eq '/adm/dependencies') {
 9338:         if ($env{'request.course.id'} ne '') {
 9339:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9340:             if ($dir ne '') {
 9341:                 my ($dirlistref,$listerror) =
 9342:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9343:                 if (ref($dirlistref) eq 'ARRAY') {
 9344:                     foreach my $line (@{$dirlistref}) {
 9345:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9346:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9347:                         unless (($testdir&$dirptr) ||
 9348:                                 ($file_name =~ /^\.\.?$/)) {
 9349:                             $currfile{$file_name} = [$size,$mtime];
 9350:                         }
 9351:                     }
 9352:                 }
 9353:             }
 9354:         }
 9355:     }
 9356:     foreach my $file (keys(%dependencies)) {
 9357:         if (exists($currfile{$file})) {
 9358:             unless ($mapping{$file} eq $file) {
 9359:                 $pathchanges{$file} = 1;
 9360:             }
 9361:             $existing{$file} = 1;
 9362:             $numexisting ++;
 9363:         } else {
 9364:             $newfiles{$file} = 1;
 9365:         }
 9366:     }
 9367:     foreach my $file (keys(%currfile)) {
 9368:         unless (($file eq $filename) ||
 9369:                 ($file eq $filename.'.bak') ||
 9370:                 ($dependencies{$file})) {
 9371:             $unused{$file} = 1;
 9372:         }
 9373:     }
 9374:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9375:         if ($actionurl eq '/adm/dependencies') {
 9376:             next if ($embed_file =~ m{^\w+://});
 9377:         }
 9378:         $upload_output .= &start_data_table_row().
 9379:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9380:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9381:         unless ($mapping{$embed_file} eq $embed_file) {
 9382:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9383:         }
 9384:         $upload_output .= '</td><td>';
 9385:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9386:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9387:             $numremref++;
 9388:         } elsif ($args->{'error_on_invalid_names'}
 9389:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9390: 
 9391:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9392:             $numinvalid++;
 9393:         } else {
 9394:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9395:                                                      $embed_file,\%mapping,
 9396:                                                      $allfiles,$codebase,'upload');
 9397:             $counter ++;
 9398:             $numnew ++;
 9399:         }
 9400:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9401:     }
 9402:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9403:         if ($actionurl eq '/adm/dependencies') {
 9404:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9405:             $modify_output .= &start_data_table_row().
 9406:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9407:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9408:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9409:                               '<td>'.$size.'</td>'.
 9410:                               '<td>'.$mtime.'</td>'.
 9411:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9412:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9413:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9414:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9415:                               &embedded_file_element('upload_embedded',$counter,
 9416:                                                      $embed_file,\%mapping,
 9417:                                                      $allfiles,$codebase,'modify').
 9418:                               '</div></td>'.
 9419:                               &end_data_table_row()."\n";
 9420:             $counter ++;
 9421:         } else {
 9422:             $upload_output .= &start_data_table_row().
 9423:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9424:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9425:                               &Apache::loncommon::end_data_table_row()."\n";
 9426:         }
 9427:     }
 9428:     my $delidx = $counter;
 9429:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9430:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9431:         $delete_output .= &start_data_table_row().
 9432:                           '<td><img src="'.&icon($oldfile).'" />'.
 9433:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9434:                           '<td>'.$size.'</td>'.
 9435:                           '<td>'.$mtime.'</td>'.
 9436:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9437:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9438:                           &embedded_file_element('upload_embedded',$delidx,
 9439:                                                  $oldfile,\%mapping,$allfiles,
 9440:                                                  $codebase,'delete').'</td>'.
 9441:                           &end_data_table_row()."\n"; 
 9442:         $numunused ++;
 9443:         $delidx ++;
 9444:     }
 9445:     if ($upload_output) {
 9446:         $upload_output = &start_data_table().
 9447:                          $upload_output.
 9448:                          &end_data_table()."\n";
 9449:     }
 9450:     if ($modify_output) {
 9451:         $modify_output = &start_data_table().
 9452:                          &start_data_table_header_row().
 9453:                          '<th>'.&mt('File').'</th>'.
 9454:                          '<th>'.&mt('Size (KB)').'</th>'.
 9455:                          '<th>'.&mt('Modified').'</th>'.
 9456:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9457:                          &end_data_table_header_row().
 9458:                          $modify_output.
 9459:                          &end_data_table()."\n";
 9460:     }
 9461:     if ($delete_output) {
 9462:         $delete_output = &start_data_table().
 9463:                          &start_data_table_header_row().
 9464:                          '<th>'.&mt('File').'</th>'.
 9465:                          '<th>'.&mt('Size (KB)').'</th>'.
 9466:                          '<th>'.&mt('Modified').'</th>'.
 9467:                          '<th>'.&mt('Delete?').'</th>'.
 9468:                          &end_data_table_header_row().
 9469:                          $delete_output.
 9470:                          &end_data_table()."\n";
 9471:     }
 9472:     my $applies = 0;
 9473:     if ($numremref) {
 9474:         $applies ++;
 9475:     }
 9476:     if ($numinvalid) {
 9477:         $applies ++;
 9478:     }
 9479:     if ($numexisting) {
 9480:         $applies ++;
 9481:     }
 9482:     if ($counter || $numunused) {
 9483:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9484:                   ' method="post" enctype="multipart/form-data">'."\n".
 9485:                   $state.'<h3>'.$heading.'</h3>'; 
 9486:         if ($actionurl eq '/adm/dependencies') {
 9487:             if ($numnew) {
 9488:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9489:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9490:                            $upload_output.'<br />'."\n";
 9491:             }
 9492:             if ($numexisting) {
 9493:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9494:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9495:                            $modify_output.'<br />'."\n";
 9496:                            $buttontext = &mt('Save changes');
 9497:             }
 9498:             if ($numunused) {
 9499:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9500:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9501:                            $delete_output.'<br />'."\n";
 9502:                            $buttontext = &mt('Save changes');
 9503:             }
 9504:         } else {
 9505:             $output .= $upload_output.'<br />'."\n";
 9506:         }
 9507:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9508:                    $counter.'" />'."\n";
 9509:         if ($actionurl eq '/adm/dependencies') { 
 9510:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9511:                        $numnew.'" />'."\n";
 9512:         } elsif ($actionurl eq '') {
 9513:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9514:         }
 9515:     } elsif ($applies) {
 9516:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9517:         if ($applies > 1) {
 9518:             $output .=  
 9519:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9520:             if ($numremref) {
 9521:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9522:             }
 9523:             if ($numinvalid) {
 9524:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9525:             }
 9526:             if ($numexisting) {
 9527:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9528:             }
 9529:             $output .= '</ul><br />';
 9530:         } elsif ($numremref) {
 9531:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9532:         } elsif ($numinvalid) {
 9533:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9534:         } elsif ($numexisting) {
 9535:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9536:         }
 9537:         $output .= $upload_output.'<br />';
 9538:     }
 9539:     my ($pathchange_output,$chgcount);
 9540:     $chgcount = $counter;
 9541:     if (keys(%pathchanges) > 0) {
 9542:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9543:             if ($counter) {
 9544:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9545:                                                   $embed_file,\%mapping,
 9546:                                                   $allfiles,$codebase,'change');
 9547:             } else {
 9548:                 $pathchange_output .= 
 9549:                     &start_data_table_row().
 9550:                     '<td><input type ="checkbox" name="namechange" value="'.
 9551:                     $chgcount.'" checked="checked" /></td>'.
 9552:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9553:                     '<td>'.$embed_file.
 9554:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9555:                                            \%mapping,$allfiles,$codebase,'change').
 9556:                     '</td>'.&end_data_table_row();
 9557:             }
 9558:             $numpathchg ++;
 9559:             $chgcount ++;
 9560:         }
 9561:     }
 9562:     if ($counter) {
 9563:         if ($numpathchg) {
 9564:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9565:                        $numpathchg.'" />'."\n";
 9566:         }
 9567:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9568:             ($actionurl eq '/adm/imsimport')) {
 9569:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9570:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9571:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9572:         } elsif ($actionurl eq '/adm/dependencies') {
 9573:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9574:         }
 9575:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9576:     } elsif ($numpathchg) {
 9577:         my %pathchange = ();
 9578:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9579:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9580:             $output .= '<p>'.&mt('or').'</p>'; 
 9581:         } 
 9582:     }
 9583:     return ($output,$counter,$numpathchg);
 9584: }
 9585: 
 9586: sub embedded_file_element {
 9587:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9588:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9589:                    (ref($codebase) eq 'HASH'));
 9590:     my $output;
 9591:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9592:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9593:     }
 9594:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9595:                &escape($embed_file).'" />';
 9596:     unless (($context eq 'upload_embedded') && 
 9597:             ($mapping->{$embed_file} eq $embed_file)) {
 9598:         $output .='
 9599:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9600:     }
 9601:     my $attrib;
 9602:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9603:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9604:     }
 9605:     $output .=
 9606:         "\n\t\t".
 9607:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9608:         $attrib.'" />';
 9609:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9610:         $output .=
 9611:             "\n\t\t".
 9612:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9613:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9614:     }
 9615:     return $output;
 9616: }
 9617: 
 9618: sub get_dependency_details {
 9619:     my ($currfile,$currsubfile,$embed_file) = @_;
 9620:     my ($size,$mtime,$showsize,$showmtime);
 9621:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9622:         if ($embed_file =~ m{/}) {
 9623:             my ($path,$fname) = split(/\//,$embed_file);
 9624:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9625:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9626:             }
 9627:         } else {
 9628:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
 9629:                 ($size,$mtime) = @{$currfile->{$embed_file}};
 9630:             }
 9631:         }
 9632:         $showsize = $size/1024.0;
 9633:         $showsize = sprintf("%.1f",$showsize);
 9634:         if ($mtime > 0) {
 9635:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
 9636:         }
 9637:     }
 9638:     return ($showsize,$showmtime);
 9639: }
 9640: 
 9641: sub ask_embedded_js {
 9642:     return <<"END";
 9643: <script type="text/javascript"">
 9644: // <![CDATA[
 9645: function toggleBrowse(counter) {
 9646:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
 9647:     var fileid = document.getElementById('embedded_item_'+counter);
 9648:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
 9649:     if (chkboxid.checked == true) {
 9650:         uploaddivid.style.display='block';
 9651:     } else {
 9652:         uploaddivid.style.display='none';
 9653:         fileid.value = '';
 9654:     }
 9655: }
 9656: // ]]>
 9657: </script>
 9658: 
 9659: END
 9660: }
 9661: 
 9662: sub upload_embedded {
 9663:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 9664:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 9665:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 9666:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 9667:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 9668:         my $orig_uploaded_filename =
 9669:             $env{'form.embedded_item_'.$i.'.filename'};
 9670:         foreach my $type ('orig','ref','attrib','codebase') {
 9671:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 9672:                 $env{'form.embedded_'.$type.'_'.$i} =
 9673:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 9674:             }
 9675:         }
 9676:         my ($path,$fname) =
 9677:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 9678:         # no path, whole string is fname
 9679:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 9680:         $fname = &Apache::lonnet::clean_filename($fname);
 9681:         # See if there is anything left
 9682:         next if ($fname eq '');
 9683: 
 9684:         # Check if file already exists as a file or directory.
 9685:         my ($state,$msg);
 9686:         if ($context eq 'portfolio') {
 9687:             my $port_path = $dirpath;
 9688:             if ($group ne '') {
 9689:                 $port_path = "groups/$group/$port_path";
 9690:             }
 9691:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 9692:                                               $fname,$group,'embedded_item_'.$i,
 9693:                                               $dir_root,$port_path,$disk_quota,
 9694:                                               $current_disk_usage,$uname,$udom);
 9695:             if ($state eq 'will_exceed_quota'
 9696:                 || $state eq 'file_locked') {
 9697:                 $output .= $msg;
 9698:                 next;
 9699:             }
 9700:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 9701:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 9702:             if ($state eq 'exists') {
 9703:                 $output .= $msg;
 9704:                 next;
 9705:             }
 9706:         }
 9707:         # Check if extension is valid
 9708:         if (($fname =~ /\.(\w+)$/) &&
 9709:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 9710:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 9711:             next;
 9712:         } elsif (($fname =~ /\.(\w+)$/) &&
 9713:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 9714:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 9715:             next;
 9716:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 9717:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 9718:             next;
 9719:         }
 9720:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 9721:         if ($context eq 'portfolio') {
 9722:             my $result;
 9723:             if ($state eq 'existingfile') {
 9724:                 $result=
 9725:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 9726:                                                     $dirpath.$env{'form.currentpath'}.$path);
 9727:             } else {
 9728:                 $result=
 9729:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 9730:                                                     $dirpath.
 9731:                                                     $env{'form.currentpath'}.$path);
 9732:                 if ($result !~ m|^/uploaded/|) {
 9733:                     $output .= '<span class="LC_error">'
 9734:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 9735:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 9736:                                .'</span><br />';
 9737:                     next;
 9738:                 } else {
 9739:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 9740:                                $path.$fname.'</span>').'<br />';     
 9741:                 }
 9742:             }
 9743:         } elsif ($context eq 'coursedoc') {
 9744:             my $result =
 9745:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 9746:                                                 $dirpath.'/'.$path);
 9747:             if ($result !~ m|^/uploaded/|) {
 9748:                 $output .= '<span class="LC_error">'
 9749:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 9750:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 9751:                            .'</span><br />';
 9752:                     next;
 9753:             } else {
 9754:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 9755:                            $path.$fname.'</span>').'<br />';
 9756:             }
 9757:         } else {
 9758: # Save the file
 9759:             my $target = $env{'form.embedded_item_'.$i};
 9760:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 9761:             my $dest = $fullpath.$fname;
 9762:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 9763:             my @parts=split(/\//,"$dirpath/$path");
 9764:             my $count;
 9765:             my $filepath = $dir_root;
 9766:             foreach my $subdir (@parts) {
 9767:                 $filepath .= "/$subdir";
 9768:                 if (!-e $filepath) {
 9769:                     mkdir($filepath,0770);
 9770:                 }
 9771:             }
 9772:             my $fh;
 9773:             if (!open($fh,'>'.$dest)) {
 9774:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 9775:                 $output .= '<span class="LC_error">'.
 9776:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
 9777:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 9778:                            '</span><br />';
 9779:             } else {
 9780:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 9781:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 9782:                     $output .= '<span class="LC_error">'.
 9783:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
 9784:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 9785:                               '</span><br />';
 9786:                 } else {
 9787:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 9788:                                $url.'</span>').'<br />';
 9789:                     unless ($context eq 'testbank') {
 9790:                         $footer .= &mt('View embedded file: [_1]',
 9791:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 9792:                     }
 9793:                 }
 9794:                 close($fh);
 9795:             }
 9796:         }
 9797:         if ($env{'form.embedded_ref_'.$i}) {
 9798:             $pathchange{$i} = 1;
 9799:         }
 9800:     }
 9801:     if ($output) {
 9802:         $output = '<p>'.$output.'</p>';
 9803:     }
 9804:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 9805:     $returnflag = 'ok';
 9806:     my $numpathchgs = scalar(keys(%pathchange));
 9807:     if ($numpathchgs > 0) {
 9808:         if ($context eq 'portfolio') {
 9809:             $output .= '<p>'.&mt('or').'</p>';
 9810:         } elsif ($context eq 'testbank') {
 9811:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
 9812:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 9813:             $returnflag = 'modify_orightml';
 9814:         }
 9815:     }
 9816:     return ($output.$footer,$returnflag,$numpathchgs);
 9817: }
 9818: 
 9819: sub modify_html_form {
 9820:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 9821:     my $end = 0;
 9822:     my $modifyform;
 9823:     if ($context eq 'upload_embedded') {
 9824:         return unless (ref($pathchange) eq 'HASH');
 9825:         if ($env{'form.number_embedded_items'}) {
 9826:             $end += $env{'form.number_embedded_items'};
 9827:         }
 9828:         if ($env{'form.number_pathchange_items'}) {
 9829:             $end += $env{'form.number_pathchange_items'};
 9830:         }
 9831:         if ($end) {
 9832:             for (my $i=0; $i<$end; $i++) {
 9833:                 if ($i < $env{'form.number_embedded_items'}) {
 9834:                     next unless($pathchange->{$i});
 9835:                 }
 9836:                 $modifyform .=
 9837:                     &start_data_table_row().
 9838:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 9839:                     'checked="checked" /></td>'.
 9840:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 9841:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 9842:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 9843:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 9844:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 9845:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 9846:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 9847:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 9848:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 9849:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 9850:                     &end_data_table_row();
 9851:             }
 9852:         }
 9853:     } else {
 9854:         $modifyform = $pathchgtable;
 9855:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9856:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 9857:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9858:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 9859:         }
 9860:     }
 9861:     if ($modifyform) {
 9862:         if ($actionurl eq '/adm/dependencies') {
 9863:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
 9864:         }
 9865:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 9866:                '<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".
 9867:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 9868:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 9869:                '</ol></p>'."\n".'<p>'.
 9870:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 9871:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 9872:                &start_data_table()."\n".
 9873:                &start_data_table_header_row().
 9874:                '<th>'.&mt('Change?').'</th>'.
 9875:                '<th>'.&mt('Current reference').'</th>'.
 9876:                '<th>'.&mt('Required reference').'</th>'.
 9877:                &end_data_table_header_row()."\n".
 9878:                $modifyform.
 9879:                &end_data_table().'<br />'."\n".$hiddenstate.
 9880:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 9881:                '</form>'."\n";
 9882:     }
 9883:     return;
 9884: }
 9885: 
 9886: sub modify_html_refs {
 9887:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 9888:     my $container;
 9889:     if ($context eq 'portfolio') {
 9890:         $container = $env{'form.container'};
 9891:     } elsif ($context eq 'coursedoc') {
 9892:         $container = $env{'form.primaryurl'};
 9893:     } elsif ($context eq 'manage_dependencies') {
 9894:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
 9895:         $container = "/$container";
 9896:     } else {
 9897:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
 9898:     }
 9899:     my (%allfiles,%codebase,$output,$content);
 9900:     my @changes = &get_env_multiple('form.namechange');
 9901:     unless (@changes > 0) {
 9902:         if (wantarray) {
 9903:             return ('',0,0); 
 9904:         } else {
 9905:             return;
 9906:         }
 9907:     }
 9908:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
 9909:         ($context eq 'manage_dependencies')) {
 9910:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
 9911:             if (wantarray) {
 9912:                 return ('',0,0);
 9913:             } else {
 9914:                 return;
 9915:             }
 9916:         } 
 9917:         $content = &Apache::lonnet::getfile($container);
 9918:         if ($content eq '-1') {
 9919:             if (wantarray) {
 9920:                 return ('',0,0);
 9921:             } else {
 9922:                 return;
 9923:             }
 9924:         }
 9925:     } else {
 9926:         unless ($container =~ /^\Q$dir_root\E/) {
 9927:             if (wantarray) {
 9928:                 return ('',0,0);
 9929:             } else {
 9930:                 return;
 9931:             }
 9932:         } 
 9933:         if (open(my $fh,"<$container")) {
 9934:             $content = join('', <$fh>);
 9935:             close($fh);
 9936:         } else {
 9937:             if (wantarray) {
 9938:                 return ('',0,0);
 9939:             } else {
 9940:                 return;
 9941:             }
 9942:         }
 9943:     }
 9944:     my ($count,$codebasecount) = (0,0);
 9945:     my $mm = new File::MMagic;
 9946:     my $mime_type = $mm->checktype_contents($content);
 9947:     if ($mime_type eq 'text/html') {
 9948:         my $parse_result = 
 9949:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 9950:                                                     \%codebase,\$content);
 9951:         if ($parse_result eq 'ok') {
 9952:             foreach my $i (@changes) {
 9953:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 9954:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 9955:                 if ($allfiles{$ref}) {
 9956:                     my $newname =  $orig;
 9957:                     my ($attrib_regexp,$codebase);
 9958:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 9959:                     if ($attrib_regexp =~ /:/) {
 9960:                         $attrib_regexp =~ s/\:/|/g;
 9961:                     }
 9962:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 9963:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 9964:                         $count += $numchg;
 9965:                     }
 9966:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 9967:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 9968:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 9969:                         $codebasecount ++;
 9970:                     }
 9971:                 }
 9972:             }
 9973:             if ($count || $codebasecount) {
 9974:                 my $saveresult;
 9975:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
 9976:                     ($context eq 'manage_dependencies')) {
 9977:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 9978:                     if ($url eq $container) {
 9979:                         my ($fname) = ($container =~ m{/([^/]+)$});
 9980:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9981:                                             $count,'<span class="LC_filename">'.
 9982:                                             $fname.'</span>').'</p>';
 9983:                     } else {
 9984:                          $output = '<p class="LC_error">'.
 9985:                                    &mt('Error: update failed for: [_1].',
 9986:                                    '<span class="LC_filename">'.
 9987:                                    $container.'</span>').'</p>';
 9988:                     }
 9989:                 } else {
 9990:                     if (open(my $fh,">$container")) {
 9991:                         print $fh $content;
 9992:                         close($fh);
 9993:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 9994:                                   $count,'<span class="LC_filename">'.
 9995:                                   $container.'</span>').'</p>';
 9996:                     } else {
 9997:                          $output = '<p class="LC_error">'.
 9998:                                    &mt('Error: could not update [_1].',
 9999:                                    '<span class="LC_filename">'.
10000:                                    $container.'</span>').'</p>';
10001:                     }
10002:                 }
10003:             }
10004:         } else {
10005:             &logthis('Failed to parse '.$container.
10006:                      ' to modify references: '.$parse_result);
10007:         }
10008:     }
10009:     if (wantarray) {
10010:         return ($output,$count,$codebasecount);
10011:     } else {
10012:         return $output;
10013:     }
10014: }
10015: 
10016: sub check_for_existing {
10017:     my ($path,$fname,$element) = @_;
10018:     my ($state,$msg);
10019:     if (-d $path.'/'.$fname) {
10020:         $state = 'exists';
10021:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10022:     } elsif (-e $path.'/'.$fname) {
10023:         $state = 'exists';
10024:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10025:     }
10026:     if ($state eq 'exists') {
10027:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10028:     }
10029:     return ($state,$msg);
10030: }
10031: 
10032: sub check_for_upload {
10033:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10034:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10035:     my $filesize = length($env{'form.'.$element});
10036:     if (!$filesize) {
10037:         my $msg = '<span class="LC_error">'.
10038:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10039:                       '<span class="LC_filename">'.$fname.'</span>',
10040:                       $filesize).'<br />'.
10041:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10042:                   '</span>';
10043:         return ('zero_bytes',$msg);
10044:     }
10045:     $filesize =  $filesize/1000; #express in k (1024?)
10046:     my $getpropath = 1;
10047:     my ($dirlistref,$listerror) =
10048:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10049:     my $found_file = 0;
10050:     my $locked_file = 0;
10051:     my @lockers;
10052:     my $navmap;
10053:     if ($env{'request.course.id'}) {
10054:         $navmap = Apache::lonnavmaps::navmap->new();
10055:     }
10056:     if (ref($dirlistref) eq 'ARRAY') {
10057:         foreach my $line (@{$dirlistref}) {
10058:             my ($file_name,$rest)=split(/\&/,$line,2);
10059:             if ($file_name eq $fname){
10060:                 $file_name = $path.$file_name;
10061:                 if ($group ne '') {
10062:                     $file_name = $group.$file_name;
10063:                 }
10064:                 $found_file = 1;
10065:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10066:                     foreach my $lock (@lockers) {
10067:                         if (ref($lock) eq 'ARRAY') {
10068:                             my ($symb,$crsid) = @{$lock};
10069:                             if ($crsid eq $env{'request.course.id'}) {
10070:                                 if (ref($navmap)) {
10071:                                     my $res = $navmap->getBySymb($symb);
10072:                                     foreach my $part (@{$res->parts()}) { 
10073:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10074:                                         unless (($slot_status == $res->RESERVED) ||
10075:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10076:                                             $locked_file = 1;
10077:                                         }
10078:                                     }
10079:                                 } else {
10080:                                     $locked_file = 1;
10081:                                 }
10082:                             } else {
10083:                                 $locked_file = 1;
10084:                             }
10085:                         }
10086:                    }
10087:                 } else {
10088:                     my @info = split(/\&/,$rest);
10089:                     my $currsize = $info[6]/1000;
10090:                     if ($currsize < $filesize) {
10091:                         my $extra = $filesize - $currsize;
10092:                         if (($current_disk_usage + $extra) > $disk_quota) {
10093:                             my $msg = '<span class="LC_error">'.
10094:                                       &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.',
10095:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10096:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10097:                                                    $disk_quota,$current_disk_usage);
10098:                             return ('will_exceed_quota',$msg);
10099:                         }
10100:                     }
10101:                 }
10102:             }
10103:         }
10104:     }
10105:     if (($current_disk_usage + $filesize) > $disk_quota){
10106:         my $msg = '<span class="LC_error">'.
10107:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10108:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10109:         return ('will_exceed_quota',$msg);
10110:     } elsif ($found_file) {
10111:         if ($locked_file) {
10112:             my $msg = '<span class="LC_error">';
10113:             $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>');
10114:             $msg .= '</span><br />';
10115:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10116:             return ('file_locked',$msg);
10117:         } else {
10118:             my $msg = '<span class="LC_error">';
10119:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10120:             $msg .= '</span>';
10121:             return ('existingfile',$msg);
10122:         }
10123:     }
10124: }
10125: 
10126: sub check_for_traversal {
10127:     my ($path,$url,$toplevel) = @_;
10128:     my @parts=split(/\//,$path);
10129:     my $cleanpath;
10130:     my $fullpath = $url;
10131:     for (my $i=0;$i<@parts;$i++) {
10132:         next if ($parts[$i] eq '.');
10133:         if ($parts[$i] eq '..') {
10134:             $fullpath =~ s{([^/]+/)$}{};
10135:         } else {
10136:             $fullpath .= $parts[$i].'/';
10137:         }
10138:     }
10139:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10140:         $cleanpath = $1;
10141:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10142:         my $curr_toprel = $1;
10143:         my @parts = split(/\//,$curr_toprel);
10144:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10145:         my @urlparts = split(/\//,$url_toprel);
10146:         my $doubledots;
10147:         my $startdiff = -1;
10148:         for (my $i=0; $i<@urlparts; $i++) {
10149:             if ($startdiff == -1) {
10150:                 unless ($urlparts[$i] eq $parts[$i]) {
10151:                     $startdiff = $i;
10152:                     $doubledots .= '../';
10153:                 }
10154:             } else {
10155:                 $doubledots .= '../';
10156:             }
10157:         }
10158:         if ($startdiff > -1) {
10159:             $cleanpath = $doubledots;
10160:             for (my $i=$startdiff; $i<@parts; $i++) {
10161:                 $cleanpath .= $parts[$i].'/';
10162:             }
10163:         }
10164:     }
10165:     $cleanpath =~ s{(/)$}{};
10166:     return $cleanpath;
10167: }
10168: 
10169: sub is_archive_file {
10170:     my ($mimetype) = @_;
10171:     if (($mimetype eq 'application/octet-stream') ||
10172:         ($mimetype eq 'application/x-stuffit') ||
10173:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10174:         return 1;
10175:     }
10176:     return;
10177: }
10178: 
10179: sub decompress_form {
10180:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10181:     my %lt = &Apache::lonlocal::texthash (
10182:         this => 'This file is an archive file.',
10183:         camt => 'This file is a Camtasia archive file.',
10184:         itsc => 'Its contents are as follows:',
10185:         youm => 'You may wish to extract its contents.',
10186:         extr => 'Extract contents',
10187:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10188:         proa => 'Process automatically?',
10189:         yes  => 'Yes',
10190:         no   => 'No',
10191:         fold => 'Title for folder containing movie',
10192:         movi => 'Title for page containing embedded movie', 
10193:     );
10194:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10195:     my ($is_camtasia,$topdir,%toplevel,@paths);
10196:     my $info = &list_archive_contents($fileloc,\@paths);
10197:     if (@paths) {
10198:         foreach my $path (@paths) {
10199:             $path =~ s{^/}{};
10200:             if ($path =~ m{^([^/]+)/$}) {
10201:                 $topdir = $1;
10202:             }
10203:             if ($path =~ m{^([^/]+)/}) {
10204:                 $toplevel{$1} = $path;
10205:             } else {
10206:                 $toplevel{$path} = $path;
10207:             }
10208:         }
10209:     }
10210:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10211:         my @camtasia = ("$topdir/","$topdir/index.html",
10212:                         "$topdir/media/",
10213:                         "$topdir/media/$topdir.mp4",
10214:                         "$topdir/media/FirstFrame.png",
10215:                         "$topdir/media/player.swf",
10216:                         "$topdir/media/swfobject.js",
10217:                         "$topdir/media/expressInstall.swf");
10218:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10219:         if (@diffs == 0) {
10220:             $is_camtasia = 1;
10221:         }
10222:     }
10223:     my $output;
10224:     if ($is_camtasia) {
10225:         $output = <<"ENDCAM";
10226: <script type="text/javascript" language="Javascript">
10227: // <![CDATA[
10228: 
10229: function camtasiaToggle() {
10230:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10231:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10232:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10233: 
10234:                 document.getElementById('camtasia_titles').style.display='block';
10235:             } else {
10236:                 document.getElementById('camtasia_titles').style.display='none';
10237:             }
10238:         }
10239:     }
10240:     return;
10241: }
10242: 
10243: // ]]>
10244: </script>
10245: <p>$lt{'camt'}</p>
10246: ENDCAM
10247:     } else {
10248:         $output = '<p>'.$lt{'this'};
10249:         if ($info eq '') {
10250:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10251:         } else {
10252:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10253:                        '<div><pre>'.$info.'</pre></div>';
10254:         }
10255:     }
10256:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10257:     my $duplicates;
10258:     my $num = 0;
10259:     if (ref($dirlist) eq 'ARRAY') {
10260:         foreach my $item (@{$dirlist}) {
10261:             if (ref($item) eq 'ARRAY') {
10262:                 if (exists($toplevel{$item->[0]})) {
10263:                     $duplicates .= 
10264:                         &start_data_table_row().
10265:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10266:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10267:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10268:                         'value="1" />'.&mt('Yes').'</label>'.
10269:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10270:                         '<td>'.$item->[0].'</td>';
10271:                     if ($item->[2]) {
10272:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10273:                     } else {
10274:                         $duplicates .= '<td>'.&mt('File').'</td>';
10275:                     }
10276:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10277:                                    '<td>'.
10278:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10279:                                    '</td>'.
10280:                                    &end_data_table_row();
10281:                     $num ++;
10282:                 }
10283:             }
10284:         }
10285:     }
10286:     my $itemcount;
10287:     if (@paths > 0) {
10288:         $itemcount = scalar(@paths);
10289:     } else {
10290:         $itemcount = 1;
10291:     }
10292:     if ($is_camtasia) {
10293:         $output .= $lt{'auto'}.'<br />'.
10294:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10295:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10296:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10297:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10298:                    $lt{'no'}.'</label></span><br />'.
10299:                    '<div id="camtasia_titles" style="display:block">'.
10300:                    &Apache::lonhtmlcommon::start_pick_box().
10301:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10302:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10303:                    &Apache::lonhtmlcommon::row_closure().
10304:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10305:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10306:                    &Apache::lonhtmlcommon::row_closure(1).
10307:                    &Apache::lonhtmlcommon::end_pick_box().
10308:                    '</div>';
10309:     }
10310:     $output .= 
10311:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10312:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10313:         "\n";
10314:     if ($duplicates ne '') {
10315:         $output .= '<p><span class="LC_warning">'.
10316:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10317:                    &start_data_table().
10318:                    &start_data_table_header_row().
10319:                    '<th>'.&mt('Overwrite?').'</th>'.
10320:                    '<th>'.&mt('Name').'</th>'.
10321:                    '<th>'.&mt('Type').'</th>'.
10322:                    '<th>'.&mt('Size').'</th>'.
10323:                    '<th>'.&mt('Last modified').'</th>'.
10324:                    &end_data_table_header_row().
10325:                    $duplicates.
10326:                    &end_data_table().
10327:                    '</p>';
10328:     }
10329:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10330:     if (ref($hiddenelements) eq 'HASH') {
10331:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10332:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10333:         }
10334:     }
10335:     $output .= <<"END";
10336: <br />
10337: <input type="submit" name="decompress" value="$lt{'extr'}" />
10338: </form>
10339: $noextract
10340: END
10341:     return $output;
10342: }
10343: 
10344: sub decompression_utility {
10345:     my ($program) = @_;
10346:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10347:     my $location;
10348:     if (grep(/^\Q$program\E$/,@utilities)) { 
10349:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10350:                          '/usr/sbin/') {
10351:             if (-x $dir.$program) {
10352:                 $location = $dir.$program;
10353:                 last;
10354:             }
10355:         }
10356:     }
10357:     return $location;
10358: }
10359: 
10360: sub list_archive_contents {
10361:     my ($file,$pathsref) = @_;
10362:     my (@cmd,$output);
10363:     my $needsregexp;
10364:     if ($file =~ /\.zip$/) {
10365:         @cmd = (&decompression_utility('unzip'),"-l");
10366:         $needsregexp = 1;
10367:     } elsif (($file =~ m/\.tar\.gz$/) ||
10368:              ($file =~ /\.tgz$/)) {
10369:         @cmd = (&decompression_utility('tar'),"-ztf");
10370:     } elsif ($file =~ /\.tar\.bz2$/) {
10371:         @cmd = (&decompression_utility('tar'),"-jtf");
10372:     } elsif ($file =~ m|\.tar$|) {
10373:         @cmd = (&decompression_utility('tar'),"-tf");
10374:     }
10375:     if (@cmd) {
10376:         undef($!);
10377:         undef($@);
10378:         if (open(my $fh,"-|", @cmd, $file)) {
10379:             while (my $line = <$fh>) {
10380:                 $output .= $line;
10381:                 chomp($line);
10382:                 my $item;
10383:                 if ($needsregexp) {
10384:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10385:                 } else {
10386:                     $item = $line;
10387:                 }
10388:                 if ($item ne '') {
10389:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10390:                         push(@{$pathsref},$item);
10391:                     } 
10392:                 }
10393:             }
10394:             close($fh);
10395:         }
10396:     }
10397:     return $output;
10398: }
10399: 
10400: sub decompress_uploaded_file {
10401:     my ($file,$dir) = @_;
10402:     &Apache::lonnet::appenv({'cgi.file' => $file});
10403:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10404:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10405:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10406:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10407:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10408:     my $decompressed = $env{'cgi.decompressed'};
10409:     &Apache::lonnet::delenv('cgi.file');
10410:     &Apache::lonnet::delenv('cgi.dir');
10411:     &Apache::lonnet::delenv('cgi.decompressed');
10412:     return ($decompressed,$result);
10413: }
10414: 
10415: sub process_decompression {
10416:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10417:     my ($dir,$error,$warning,$output);
10418:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10419:         $error = &mt('File name not a supported archive file type.').
10420:                  '<br />'.&mt('File name should end with one of: [_1].',
10421:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10422:     } else {
10423:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10424:         if ($docuhome eq 'no_host') {
10425:             $error = &mt('Could not determine home server for course.');
10426:         } else {
10427:             my @ids=&Apache::lonnet::current_machine_ids();
10428:             my $currdir = "$dir_root/$destination";
10429:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10430:                 $dir = &LONCAPA::propath($docudom,$docuname).
10431:                        "$dir_root/$destination";
10432:             } else {
10433:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10434:                        "$dir_root/$docudom/$docuname/$destination";
10435:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10436:                     $error = &mt('Archive file not found.');
10437:                 }
10438:             }
10439:             my (@to_overwrite,@to_skip);
10440:             if ($env{'form.archive_overwrite_total'} > 0) {
10441:                 my $total = $env{'form.archive_overwrite_total'};
10442:                 for (my $i=0; $i<$total; $i++) {
10443:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10444:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10445:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10446:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10447:                     }
10448:                 }
10449:             }
10450:             my $numskip = scalar(@to_skip);
10451:             if (($numskip > 0) && 
10452:                 ($numskip == $env{'form.archive_itemcount'})) {
10453:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10454:             } elsif ($dir eq '') {
10455:                 $error = &mt('Directory containing archive file unavailable.');
10456:             } elsif (!$error) {
10457:                 my ($decompressed,$display);
10458:                 if ($numskip > 0) {
10459:                     my $tempdir = time.'_'.$$.int(rand(10000));
10460:                     mkdir("$dir/$tempdir",0755);
10461:                     system("mv $dir/$file $dir/$tempdir/$file");
10462:                     ($decompressed,$display) = 
10463:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10464:                     foreach my $item (@to_skip) {
10465:                         if (($item ne '') && ($item !~ /\.\./)) {
10466:                             if (-f "$dir/$tempdir/$item") { 
10467:                                 unlink("$dir/$tempdir/$item");
10468:                             } elsif (-d "$dir/$tempdir/$item") {
10469:                                 system("rm -rf $dir/$tempdir/$item");
10470:                             }
10471:                         }
10472:                     }
10473:                     system("mv $dir/$tempdir/* $dir");
10474:                     rmdir("$dir/$tempdir");   
10475:                 } else {
10476:                     ($decompressed,$display) = 
10477:                         &decompress_uploaded_file($file,$dir);
10478:                 }
10479:                 if ($decompressed eq 'ok') {
10480:                     $output = '<p class="LC_info">'.
10481:                               &mt('Files extracted successfully from archive.').
10482:                               '</p>'."\n";
10483:                     my ($warning,$result,@contents);
10484:                     my ($newdirlistref,$newlisterror) =
10485:                         &Apache::lonnet::dirlist($currdir,$docudom,
10486:                                                  $docuname,1);
10487:                     my (%is_dir,%changes,@newitems);
10488:                     my $dirptr = 16384;
10489:                     if (ref($newdirlistref) eq 'ARRAY') {
10490:                         foreach my $dir_line (@{$newdirlistref}) {
10491:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10492:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10493:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10494:                                 push(@newitems,$item);
10495:                                 if ($dirptr&$testdir) {
10496:                                     $is_dir{$item} = 1;
10497:                                 }
10498:                                 $changes{$item} = 1;
10499:                             }
10500:                         }
10501:                     }
10502:                     if (keys(%changes) > 0) {
10503:                         foreach my $item (sort(@newitems)) {
10504:                             if ($changes{$item}) {
10505:                                 push(@contents,$item);
10506:                             }
10507:                         }
10508:                     }
10509:                     if (@contents > 0) {
10510:                         my $wantform;
10511:                         unless ($env{'form.autoextract_camtasia'}) {
10512:                             $wantform = 1;
10513:                         }
10514:                         my (%children,%parent,%dirorder,%titles);
10515:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10516:                                                                 $currdir,\%is_dir,
10517:                                                                 \%children,\%parent,
10518:                                                                 \@contents,\%dirorder,
10519:                                                                 \%titles,$wantform);
10520:                         if ($datatable ne '') {
10521:                             $output .= &archive_options_form('decompressed',$datatable,
10522:                                                              $count,$hiddenelem);
10523:                             my $startcount = 6;
10524:                             $output .= &archive_javascript($startcount,$count,
10525:                                                            \%titles,\%children);
10526:                         }
10527:                         if ($env{'form.autoextract_camtasia'}) {
10528:                             my %displayed;
10529:                             my $total = 1;
10530:                             $env{'form.archive_directory'} = [];
10531:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10532:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10533:                                 $path =~ s{/$}{};
10534:                                 my $item;
10535:                                 if ($path ne '') {
10536:                                     $item = "$path/$titles{$i}";
10537:                                 } else {
10538:                                     $item = $titles{$i};
10539:                                 }
10540:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10541:                                 if ($item eq $contents[0]) {
10542:                                     push(@{$env{'form.archive_directory'}},$i);
10543:                                     $env{'form.archive_'.$i} = 'display';
10544:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10545:                                     $displayed{'folder'} = $i;
10546:                                 } elsif ($item eq "$contents[0]/index.html") {
10547:                                     $env{'form.archive_'.$i} = 'display';
10548:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10549:                                     $displayed{'web'} = $i;
10550:                                 } else {
10551:                                     if ($item eq "$contents[0]/media") {
10552:                                         push(@{$env{'form.archive_directory'}},$i);
10553:                                     }
10554:                                     $env{'form.archive_'.$i} = 'dependency';
10555:                                 }
10556:                                 $total ++;
10557:                             }
10558:                             for (my $i=1; $i<$total; $i++) {
10559:                                 next if ($i == $displayed{'web'});
10560:                                 next if ($i == $displayed{'folder'});
10561:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10562:                             }
10563:                             $env{'form.phase'} = 'decompress_cleanup';
10564:                             $env{'form.archivedelete'} = 1;
10565:                             $env{'form.archive_count'} = $total-1;
10566:                             $output .=
10567:                                 &process_extracted_files('coursedocs',$docudom,
10568:                                                          $docuname,$destination,
10569:                                                          $dir_root,$hiddenelem);
10570:                         }
10571:                     } else {
10572:                         $warning = &mt('No new items extracted from archive file.');
10573:                     }
10574:                 } else {
10575:                     $output = $display;
10576:                     $error = &mt('An error occurred during extraction from the archive file.');
10577:                 }
10578:             }
10579:         }
10580:     }
10581:     if ($error) {
10582:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10583:                    $error.'</p>'."\n";
10584:     }
10585:     if ($warning) {
10586:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10587:     }
10588:     return $output;
10589: }
10590: 
10591: sub get_extracted {
10592:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10593:         $titles,$wantform) = @_;
10594:     my $count = 0;
10595:     my $depth = 0;
10596:     my $datatable;
10597:     my @hierarchy;
10598:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10599:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10600:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10601:     foreach my $item (@{$contents}) {
10602:         $count ++;
10603:         @{$dirorder->{$count}} = @hierarchy;
10604:         $titles->{$count} = $item;
10605:         &archive_hierarchy($depth,$count,$parent,$children);
10606:         if ($wantform) {
10607:             $datatable .= &archive_row($is_dir->{$item},$item,
10608:                                        $currdir,$depth,$count);
10609:         }
10610:         if ($is_dir->{$item}) {
10611:             $depth ++;
10612:             push(@hierarchy,$count);
10613:             $parent->{$depth} = $count;
10614:             $datatable .=
10615:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10616:                                            \$depth,\$count,\@hierarchy,$dirorder,
10617:                                            $children,$parent,$titles,$wantform);
10618:             $depth --;
10619:             pop(@hierarchy);
10620:         }
10621:     }
10622:     return ($count,$datatable);
10623: }
10624: 
10625: sub recurse_extracted_archive {
10626:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10627:         $children,$parent,$titles,$wantform) = @_;
10628:     my $result='';
10629:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
10630:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
10631:             (ref($dirorder) eq 'HASH')) {
10632:         return $result;
10633:     }
10634:     my $dirptr = 16384;
10635:     my ($newdirlistref,$newlisterror) =
10636:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
10637:     if (ref($newdirlistref) eq 'ARRAY') {
10638:         foreach my $dir_line (@{$newdirlistref}) {
10639:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10640:             unless ($item =~ /^\.+$/) {
10641:                 $$count ++;
10642:                 @{$dirorder->{$$count}} = @{$hierarchy};
10643:                 $titles->{$$count} = $item;
10644:                 &archive_hierarchy($$depth,$$count,$parent,$children);
10645: 
10646:                 my $is_dir;
10647:                 if ($dirptr&$testdir) {
10648:                     $is_dir = 1;
10649:                 }
10650:                 if ($wantform) {
10651:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
10652:                 }
10653:                 if ($is_dir) {
10654:                     $$depth ++;
10655:                     push(@{$hierarchy},$$count);
10656:                     $parent->{$$depth} = $$count;
10657:                     $result .=
10658:                         &recurse_extracted_archive("$currdir/$item",$docudom,
10659:                                                    $docuname,$depth,$count,
10660:                                                    $hierarchy,$dirorder,$children,
10661:                                                    $parent,$titles,$wantform);
10662:                     $$depth --;
10663:                     pop(@{$hierarchy});
10664:                 }
10665:             }
10666:         }
10667:     }
10668:     return $result;
10669: }
10670: 
10671: sub archive_hierarchy {
10672:     my ($depth,$count,$parent,$children) =@_;
10673:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
10674:         if (exists($parent->{$depth})) {
10675:              $children->{$parent->{$depth}} .= $count.':';
10676:         }
10677:     }
10678:     return;
10679: }
10680: 
10681: sub archive_row {
10682:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
10683:     my ($name) = ($item =~ m{([^/]+)$});
10684:     my %choices = &Apache::lonlocal::texthash (
10685:                                        'display'    => 'Add as file',
10686:                                        'dependency' => 'Include as dependency',
10687:                                        'discard'    => 'Discard',
10688:                                       );
10689:     if ($is_dir) {
10690:         $choices{'display'} = &mt('Add as folder'); 
10691:     }
10692:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
10693:     my $offset = 0;
10694:     foreach my $action ('display','dependency','discard') {
10695:         $offset ++;
10696:         if ($action ne 'display') {
10697:             $offset ++;
10698:         }  
10699:         $output .= '<td><span class="LC_nobreak">'.
10700:                    '<label><input type="radio" name="archive_'.$count.
10701:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
10702:         my $text = $choices{$action};
10703:         if ($is_dir) {
10704:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
10705:             if ($action eq 'display') {
10706:                 $text = &mt('Add as folder');
10707:             }
10708:         } else {
10709:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
10710: 
10711:         }
10712:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
10713:         if ($action eq 'dependency') {
10714:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
10715:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
10716:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
10717:                        '<option value=""></option>'."\n".
10718:                        '</select>'."\n".
10719:                        '</div>';
10720:         } elsif ($action eq 'display') {
10721:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
10722:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
10723:                        '</div>';
10724:         }
10725:         $output .= '</td>';
10726:     }
10727:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
10728:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
10729:     for (my $i=0; $i<$depth; $i++) {
10730:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
10731:     }
10732:     if ($is_dir) {
10733:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
10734:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
10735:     } else {
10736:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
10737:     }
10738:     $output .= '&nbsp;'.$name.'</td>'."\n".
10739:                &end_data_table_row();
10740:     return $output;
10741: }
10742: 
10743: sub archive_options_form {
10744:     my ($form,$display,$count,$hiddenelem) = @_;
10745:     my %lt = &Apache::lonlocal::texthash(
10746:                perm => 'Permanently remove archive file?',
10747:                hows => 'How should each extracted item be incorporated in the course?',
10748:                cont => 'Content actions for all',
10749:                addf => 'Add as folder/file',
10750:                incd => 'Include as dependency for a displayed file',
10751:                disc => 'Discard',
10752:                no   => 'No',
10753:                yes  => 'Yes',
10754:                save => 'Save',
10755:     );
10756:     my $output = <<"END";
10757: <form name="$form" method="post" action="">
10758: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
10759: <label>
10760:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
10761: </label>
10762: &nbsp;
10763: <label>
10764:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
10765: </span>
10766: </p>
10767: <input type="hidden" name="phase" value="decompress_cleanup" />
10768: <br />$lt{'hows'}
10769: <div class="LC_columnSection">
10770:   <fieldset>
10771:     <legend>$lt{'cont'}</legend>
10772:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
10773:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
10774:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
10775:   </fieldset>
10776: </div>
10777: END
10778:     return $output.
10779:            &start_data_table()."\n".
10780:            $display."\n".
10781:            &end_data_table()."\n".
10782:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
10783:            $hiddenelem.
10784:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
10785:            '</form>';
10786: }
10787: 
10788: sub archive_javascript {
10789:     my ($startcount,$numitems,$titles,$children) = @_;
10790:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
10791:     my $maintitle = $env{'form.comment'};
10792:     my $scripttag = <<START;
10793: <script type="text/javascript">
10794: // <![CDATA[
10795: 
10796: function checkAll(form,prefix) {
10797:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
10798:     for (var i=0; i < form.elements.length; i++) {
10799:         var id = form.elements[i].id;
10800:         if ((id != '') && (id != undefined)) {
10801:             if (idstr.test(id)) {
10802:                 if (form.elements[i].type == 'radio') {
10803:                     form.elements[i].checked = true;
10804:                     var nostart = i-$startcount;
10805:                     var offset = nostart%7;
10806:                     var count = (nostart-offset)/7;    
10807:                     dependencyCheck(form,count,offset);
10808:                 }
10809:             }
10810:         }
10811:     }
10812: }
10813: 
10814: function propagateCheck(form,count) {
10815:     if (count > 0) {
10816:         var startelement = $startcount + ((count-1) * 7);
10817:         for (var j=1; j<6; j++) {
10818:             if ((j != 2) && (j != 4)) {
10819:                 var item = startelement + j; 
10820:                 if (form.elements[item].type == 'radio') {
10821:                     if (form.elements[item].checked) {
10822:                         containerCheck(form,count,j);
10823:                         break;
10824:                     }
10825:                 }
10826:             }
10827:         }
10828:     }
10829: }
10830: 
10831: numitems = $numitems
10832: var titles = new Array(numitems);
10833: var parents = new Array(numitems);
10834: for (var i=0; i<numitems; i++) {
10835:     parents[i] = new Array;
10836: }
10837: var maintitle = '$maintitle';
10838: 
10839: START
10840: 
10841:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
10842:         my @contents = split(/:/,$children->{$container});
10843:         for (my $i=0; $i<@contents; $i ++) {
10844:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
10845:         }
10846:     }
10847: 
10848:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
10849:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
10850:     }
10851: 
10852:     $scripttag .= <<END;
10853: 
10854: function containerCheck(form,count,offset) {
10855:     if (count > 0) {
10856:         dependencyCheck(form,count,offset);
10857:         var item = (offset+$startcount)+7*(count-1);
10858:         form.elements[item].checked = true;
10859:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
10860:             if (parents[count].length > 0) {
10861:                 for (var j=0; j<parents[count].length; j++) {
10862:                     containerCheck(form,parents[count][j],offset);
10863:                 }
10864:             }
10865:         }
10866:     }
10867: }
10868: 
10869: function dependencyCheck(form,count,offset) {
10870:     if (count > 0) {
10871:         var chosen = (offset+$startcount)+7*(count-1);
10872:         var depitem = $startcount + ((count-1) * 7) + 4;
10873:         var currtype = form.elements[depitem].type;
10874:         if (form.elements[chosen].value == 'dependency') {
10875:             document.getElementById('arc_depon_'+count).style.display='block'; 
10876:             form.elements[depitem].options.length = 0;
10877:             form.elements[depitem].options[0] = new Option('Select','',true,true);
10878:             for (var i=1; i<count; i++) {
10879:                 var startelement = $startcount + (i-1) * 7;
10880:                 for (var j=1; j<6; j++) {
10881:                     if ((j != 2) && (j!= 4)) {
10882:                         var item = startelement + j;
10883:                         if (form.elements[item].type == 'radio') {
10884:                             if (form.elements[item].checked) {
10885:                                 if (form.elements[item].value == 'display') {
10886:                                     var n = form.elements[depitem].options.length;
10887:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
10888:                                 }
10889:                             }
10890:                         }
10891:                     }
10892:                 }
10893:             }
10894:         } else {
10895:             document.getElementById('arc_depon_'+count).style.display='none';
10896:             form.elements[depitem].options.length = 0;
10897:             form.elements[depitem].options[0] = new Option('Select','',true,true);
10898:         }
10899:         titleCheck(form,count,offset);
10900:     }
10901: }
10902: 
10903: function propagateSelect(form,count,offset) {
10904:     if (count > 0) {
10905:         var item = (1+offset+$startcount)+7*(count-1);
10906:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
10907:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10908:             if (parents[count].length > 0) {
10909:                 for (var j=0; j<parents[count].length; j++) {
10910:                     containerSelect(form,parents[count][j],offset,picked);
10911:                 }
10912:             }
10913:         }
10914:     }
10915: }
10916: 
10917: function containerSelect(form,count,offset,picked) {
10918:     if (count > 0) {
10919:         var item = (offset+$startcount)+7*(count-1);
10920:         if (form.elements[item].type == 'radio') {
10921:             if (form.elements[item].value == 'dependency') {
10922:                 if (form.elements[item+1].type == 'select-one') {
10923:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
10924:                         if (form.elements[item+1].options[i].value == picked) {
10925:                             form.elements[item+1].selectedIndex = i;
10926:                             break;
10927:                         }
10928:                     }
10929:                 }
10930:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10931:                     if (parents[count].length > 0) {
10932:                         for (var j=0; j<parents[count].length; j++) {
10933:                             containerSelect(form,parents[count][j],offset,picked);
10934:                         }
10935:                     }
10936:                 }
10937:             }
10938:         }
10939:     }
10940: }
10941: 
10942: function titleCheck(form,count,offset) {
10943:     if (count > 0) {
10944:         var chosen = (offset+$startcount)+7*(count-1);
10945:         var depitem = $startcount + ((count-1) * 7) + 2;
10946:         var currtype = form.elements[depitem].type;
10947:         if (form.elements[chosen].value == 'display') {
10948:             document.getElementById('arc_title_'+count).style.display='block';
10949:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
10950:                 document.getElementById('archive_title_'+count).value=maintitle;
10951:             }
10952:         } else {
10953:             document.getElementById('arc_title_'+count).style.display='none';
10954:             if (currtype == 'text') { 
10955:                 document.getElementById('archive_title_'+count).value='';
10956:             }
10957:         }
10958:     }
10959:     return;
10960: }
10961: 
10962: // ]]>
10963: </script>
10964: END
10965:     return $scripttag;
10966: }
10967: 
10968: sub process_extracted_files {
10969:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
10970:     my $numitems = $env{'form.archive_count'};
10971:     return unless ($numitems);
10972:     my @ids=&Apache::lonnet::current_machine_ids();
10973:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
10974:         %folders,%containers,%mapinner,%prompttofetch);
10975:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10976:     if (grep(/^\Q$docuhome\E$/,@ids)) {
10977:         $prefix = &LONCAPA::propath($docudom,$docuname);
10978:         $pathtocheck = "$dir_root/$destination";
10979:         $dir = $dir_root;
10980:         $ishome = 1;
10981:     } else {
10982:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
10983:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
10984:         $dir = "$dir_root/$docudom/$docuname";    
10985:     }
10986:     my $currdir = "$dir_root/$destination";
10987:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
10988:     if ($env{'form.folderpath'}) {
10989:         my @items = split('&',$env{'form.folderpath'});
10990:         $folders{'0'} = $items[-2];
10991:         $containers{'0'}='sequence';
10992:     } elsif ($env{'form.pagepath'}) {
10993:         my @items = split('&',$env{'form.pagepath'});
10994:         $folders{'0'} = $items[-2];
10995:         $containers{'0'}='page';
10996:     }
10997:     my @archdirs = &get_env_multiple('form.archive_directory');
10998:     if ($numitems) {
10999:         for (my $i=1; $i<=$numitems; $i++) {
11000:             my $path = $env{'form.archive_content_'.$i};
11001:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11002:                 my $item = $1;
11003:                 $toplevelitems{$item} = $i;
11004:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11005:                     $is_dir{$item} = 1;
11006:                 }
11007:             }
11008:         }
11009:     }
11010:     my ($output,%children,%parent,%titles,%dirorder,$result);
11011:     if (keys(%toplevelitems) > 0) {
11012:         my @contents = sort(keys(%toplevelitems));
11013:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11014:                                            \%parent,\@contents,\%dirorder,\%titles);
11015:     }
11016:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11017:     if ($numitems) {
11018:         for (my $i=1; $i<=$numitems; $i++) {
11019:             my $path = $env{'form.archive_content_'.$i};
11020:             if ($path =~ /^\Q$pathtocheck\E/) {
11021:                 if ($env{'form.archive_'.$i} eq 'discard') {
11022:                     if ($prefix ne '' && $path ne '') {
11023:                         if (-e $prefix.$path) {
11024:                             if ((@archdirs > 0) && 
11025:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11026:                                 $todeletedir{$prefix.$path} = 1;
11027:                             } else {
11028:                                 $todelete{$prefix.$path} = 1;
11029:                             }
11030:                         }
11031:                     }
11032:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11033:                     my ($docstitle,$title,$url,$outer);
11034:                     ($title) = ($path =~ m{/([^/]+)$});
11035:                     $docstitle = $env{'form.archive_title_'.$i};
11036:                     if ($docstitle eq '') {
11037:                         $docstitle = $title;
11038:                     }
11039:                     $outer = 0;
11040:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11041:                         if (@{$dirorder{$i}} > 0) {
11042:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11043:                                 if ($env{'form.archive_'.$item} eq 'display') {
11044:                                     $outer = $item;
11045:                                     last;
11046:                                 }
11047:                             }
11048:                         }
11049:                     }
11050:                     my ($errtext,$fatal) = 
11051:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11052:                                                '/'.$folders{$outer}.'.'.
11053:                                                $containers{$outer});
11054:                     next if ($fatal);
11055:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11056:                         if ($context eq 'coursedocs') {
11057:                             $mapinner{$i} = time;
11058:                             $folders{$i} = 'default_'.$mapinner{$i};
11059:                             $containers{$i} = 'sequence';
11060:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11061:                                       $folders{$i}.'.'.$containers{$i};
11062:                             my $newidx = &LONCAPA::map::getresidx();
11063:                             $LONCAPA::map::resources[$newidx]=
11064:                                 $docstitle.':'.$url.':false:normal:res';
11065:                             push(@LONCAPA::map::order,$newidx);
11066:                             my ($outtext,$errtext) =
11067:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11068:                                                         $docuname.'/'.$folders{$outer}.
11069:                                                         '.'.$containers{$outer},1);
11070:                             $newseqid{$i} = $newidx;
11071:                             unless ($errtext) {
11072:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11073:                             }
11074:                         }
11075:                     } else {
11076:                         if ($context eq 'coursedocs') {
11077:                             my $newidx=&LONCAPA::map::getresidx();
11078:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11079:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11080:                                       $title;
11081:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11082:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11083:                             }
11084:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11085:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11086:                             }
11087:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11088:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11089:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11090:                                 unless ($ishome) {
11091:                                     my $fetch = "$newdest{$i}/$title";
11092:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11093:                                     $prompttofetch{$fetch} = 1;
11094:                                 }
11095:                             }
11096:                             $LONCAPA::map::resources[$newidx]=
11097:                                 $docstitle.':'.$url.':false:normal:res';
11098:                             push(@LONCAPA::map::order, $newidx);
11099:                             my ($outtext,$errtext)=
11100:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11101:                                                         $docuname.'/'.$folders{$outer}.
11102:                                                         '.'.$containers{$outer},1);
11103:                             unless ($errtext) {
11104:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11105:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11106:                                 }
11107:                             }
11108:                         }
11109:                     }
11110:                 } elsif ($env{'form.archive_'.$i} eq 'dependency') {
11111:                     my ($title) = ($path =~ m{/([^/]+)$});
11112:                     $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11113:                     if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11114:                         if (ref($dirorder{$i}) eq 'ARRAY') {
11115:                             my ($itemidx,$fullpath,$relpath);
11116:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11117:                                 if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11118:                                     my $container = $dirorder{$referrer{$i}}->[-1];
11119:                                     for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11120:                                         if ($dirorder{$i}->[$j] eq $container) {
11121:                                             $itemidx = $j;
11122:                                         }
11123:                                     }
11124:                                 }
11125:                             }
11126:                             if ($itemidx ne '') {
11127:                                 if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11128:                                     if ($mapinner{$referrer{$i}}) {
11129:                                         $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11130:                                         for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11131:                                             if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11132:                                                 unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11133:                                                     $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11134:                                                     $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11135:                                                     if (!-e $fullpath) {
11136:                                                         mkdir($fullpath,0755);
11137:                                                     }
11138:                                                 }
11139:                                             } else {
11140:                                                 last;
11141:                                             }
11142:                                         }
11143:                                     }
11144:                                 } elsif ($newdest{$referrer{$i}}) {
11145:                                     $fullpath = $newdest{$referrer{$i}};
11146:                                     for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11147:                                         if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11148:                                             $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11149:                                             last;
11150:                                         } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11151:                                             unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11152:                                                 $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11153:                                                 $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11154:                                                 if (!-e $fullpath) {
11155:                                                     mkdir($fullpath,0755);
11156:                                                 }
11157:                                             }
11158:                                         } else {
11159:                                             last;
11160:                                         }
11161:                                     }
11162:                                 }
11163:                                 if ($fullpath ne '') {
11164:                                     if (-e "$prefix$path") {
11165:                                         system("mv $prefix$path $fullpath/$title");
11166:                                     }
11167:                                     if (-e "$fullpath/$title") {
11168:                                         my $showpath;
11169:                                         if ($relpath ne '') {
11170:                                             $showpath = "$relpath/$title";
11171:                                         } else {
11172:                                             $showpath = "/$title";
11173:                                         } 
11174:                                         $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11175:                                     } 
11176:                                     unless ($ishome) {
11177:                                         my $fetch = "$fullpath/$title";
11178:                                         $fetch =~ s/^\Q$prefix$dir\E//; 
11179:                                         $prompttofetch{$fetch} = 1;
11180:                                     }
11181:                                 }
11182:                             }
11183:                         }
11184:                     } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11185:                         $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11186:                                         $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11187:                     }
11188:                 }
11189:             } else {
11190:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11191:             }
11192:         }
11193:         if (keys(%todelete)) {
11194:             foreach my $key (keys(%todelete)) {
11195:                 unlink($key);
11196:             }
11197:         }
11198:         if (keys(%todeletedir)) {
11199:             foreach my $key (keys(%todeletedir)) {
11200:                 rmdir($key);
11201:             }
11202:         }
11203:         foreach my $dir (sort(keys(%is_dir))) {
11204:             if (($pathtocheck ne '') && ($dir ne ''))  {
11205:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11206:             }
11207:         }
11208:         if ($result ne '') {
11209:             $output .= '<ul>'."\n".
11210:                        $result."\n".
11211:                        '</ul>';
11212:         }
11213:         unless ($ishome) {
11214:             my $replicationfail;
11215:             foreach my $item (keys(%prompttofetch)) {
11216:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11217:                 unless ($fetchresult eq 'ok') {
11218:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11219:                 }
11220:             }
11221:             if ($replicationfail) {
11222:                 $output .= '<p class="LC_error">'.
11223:                            &mt('Course home server failed to retrieve:').'<ul>'.
11224:                            $replicationfail.
11225:                            '</ul></p>';
11226:             }
11227:         }
11228:     } else {
11229:         $warning = &mt('No items found in archive.');
11230:     }
11231:     if ($error) {
11232:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11233:                    $error.'</p>'."\n";
11234:     }
11235:     if ($warning) {
11236:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11237:     }
11238:     return $output;
11239: }
11240: 
11241: sub cleanup_empty_dirs {
11242:     my ($path) = @_;
11243:     if (($path ne '') && (-d $path)) {
11244:         if (opendir(my $dirh,$path)) {
11245:             my @dircontents = grep(!/^\./,readdir($dirh));
11246:             my $numitems = 0;
11247:             foreach my $item (@dircontents) {
11248:                 if (-d "$path/$item") {
11249:                     &recurse_dirs("$path/$item");
11250:                     if (-e "$path/$item") {
11251:                         $numitems ++;
11252:                     }
11253:                 } else {
11254:                     $numitems ++;
11255:                 }
11256:             }
11257:             if ($numitems == 0) {
11258:                 rmdir($path);
11259:             }
11260:             closedir($dirh);
11261:         }
11262:     }
11263:     return;
11264: }
11265: 
11266: =pod
11267: 
11268: =item &get_folder_hierarchy()
11269: 
11270: Provides hierarchy of names of folders/sub-folders containing the current
11271: item,
11272: 
11273: Inputs: 3
11274:      - $navmap - navmaps object
11275: 
11276:      - $map - url for map (either the trigger itself, or map containing
11277:                            the resource, which is the trigger).
11278: 
11279:      - $showitem - 1 => show title for map itself; 0 => do not show.
11280: 
11281: Outputs: 1 @pathitems - array of folder/subfolder names.
11282: 
11283: =cut
11284: 
11285: sub get_folder_hierarchy {
11286:     my ($navmap,$map,$showitem) = @_;
11287:     my @pathitems;
11288:     if (ref($navmap)) {
11289:         my $mapres = $navmap->getResourceByUrl($map);
11290:         if (ref($mapres)) {
11291:             my $pcslist = $mapres->map_hierarchy();
11292:             if ($pcslist ne '') {
11293:                 my @pcs = split(/,/,$pcslist);
11294:                 foreach my $pc (@pcs) {
11295:                     if ($pc == 1) {
11296:                         push(@pathitems,&mt('Main Course Documents'));
11297:                     } else {
11298:                         my $res = $navmap->getByMapPc($pc);
11299:                         if (ref($res)) {
11300:                             my $title = $res->compTitle();
11301:                             $title =~ s/\W+/_/g;
11302:                             if ($title ne '') {
11303:                                 push(@pathitems,$title);
11304:                             }
11305:                         }
11306:                     }
11307:                 }
11308:             }
11309:             if ($showitem) {
11310:                 if ($mapres->{ID} eq '0.0') {
11311:                     push(@pathitems,&mt('Main Course Documents'));
11312:                 } else {
11313:                     my $maptitle = $mapres->compTitle();
11314:                     $maptitle =~ s/\W+/_/g;
11315:                     if ($maptitle ne '') {
11316:                         push(@pathitems,$maptitle);
11317:                     }
11318:                 }
11319:             }
11320:         }
11321:     }
11322:     return @pathitems;
11323: }
11324: 
11325: =pod
11326: 
11327: =item * &get_turnedin_filepath()
11328: 
11329: Determines path in a user's portfolio file for storage of files uploaded
11330: to a specific essayresponse or dropbox item.
11331: 
11332: Inputs: 3 required + 1 optional.
11333: $symb is symb for resource, $uname and $udom are for current user (required).
11334: $caller is optional (can be "submission", if routine is called when storing
11335: an upoaded file when "Submit Answer" button was pressed).
11336: 
11337: Returns array containing $path and $multiresp. 
11338: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11339: than one file upload item.  Callers of routine should append partid as a 
11340: subdirectory to $path in cases where $multiresp is 1.
11341: 
11342: Called by: homework/essayresponse.pm and homework/structuretags.pm
11343: 
11344: =cut
11345: 
11346: sub get_turnedin_filepath {
11347:     my ($symb,$uname,$udom,$caller) = @_;
11348:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11349:     my $turnindir;
11350:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11351:     $turnindir = $userhash{'turnindir'};
11352:     my ($path,$multiresp);
11353:     if ($turnindir eq '') {
11354:         if ($caller eq 'submission') {
11355:             $turnindir = &mt('turned in');
11356:             $turnindir =~ s/\W+/_/g;
11357:             my %newhash = (
11358:                             'turnindir' => $turnindir,
11359:                           );
11360:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11361:         }
11362:     }
11363:     if ($turnindir ne '') {
11364:         $path = '/'.$turnindir.'/';
11365:         my ($multipart,$turnin,@pathitems);
11366:         my $navmap = Apache::lonnavmaps::navmap->new();
11367:         if (defined($navmap)) {
11368:             my $mapres = $navmap->getResourceByUrl($map);
11369:             if (ref($mapres)) {
11370:                 my $pcslist = $mapres->map_hierarchy();
11371:                 if ($pcslist ne '') {
11372:                     foreach my $pc (split(/,/,$pcslist)) {
11373:                         my $res = $navmap->getByMapPc($pc);
11374:                         if (ref($res)) {
11375:                             my $title = $res->compTitle();
11376:                             $title =~ s/\W+/_/g;
11377:                             if ($title ne '') {
11378:                                 push(@pathitems,$title);
11379:                             }
11380:                         }
11381:                     }
11382:                 }
11383:                 my $maptitle = $mapres->compTitle();
11384:                 $maptitle =~ s/\W+/_/g;
11385:                 if ($maptitle ne '') {
11386:                     push(@pathitems,$maptitle);
11387:                 }
11388:                 unless ($env{'request.state'} eq 'construct') {
11389:                     my $res = $navmap->getBySymb($symb);
11390:                     if (ref($res)) {
11391:                         my $partlist = $res->parts();
11392:                         my $totaluploads = 0;
11393:                         if (ref($partlist) eq 'ARRAY') {
11394:                             foreach my $part (@{$partlist}) {
11395:                                 my @types = $res->responseType($part);
11396:                                 my @ids = $res->responseIds($part);
11397:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11398:                                     if ($types[$i] eq 'essay') {
11399:                                         my $partid = $part.'_'.$ids[$i];
11400:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11401:                                             $totaluploads ++;
11402:                                         }
11403:                                     }
11404:                                 }
11405:                             }
11406:                             if ($totaluploads > 1) {
11407:                                 $multiresp = 1;
11408:                             }
11409:                         }
11410:                     }
11411:                 }
11412:             } else {
11413:                 return;
11414:             }
11415:         } else {
11416:             return;
11417:         }
11418:         my $restitle=&Apache::lonnet::gettitle($symb);
11419:         $restitle =~ s/\W+/_/g;
11420:         if ($restitle eq '') {
11421:             $restitle = ($resurl =~ m{/[^/]+$});
11422:             if ($restitle eq '') {
11423:                 $restitle = time;
11424:             }
11425:         }
11426:         push(@pathitems,$restitle);
11427:         $path .= join('/',@pathitems);
11428:     }
11429:     return ($path,$multiresp);
11430: }
11431: 
11432: =pod
11433: 
11434: =back
11435: 
11436: =head1 CSV Upload/Handling functions
11437: 
11438: =over 4
11439: 
11440: =item * &upfile_store($r)
11441: 
11442: Store uploaded file, $r should be the HTTP Request object,
11443: needs $env{'form.upfile'}
11444: returns $datatoken to be put into hidden field
11445: 
11446: =cut
11447: 
11448: sub upfile_store {
11449:     my $r=shift;
11450:     $env{'form.upfile'}=~s/\r/\n/gs;
11451:     $env{'form.upfile'}=~s/\f/\n/gs;
11452:     $env{'form.upfile'}=~s/\n+/\n/gs;
11453:     $env{'form.upfile'}=~s/\n+$//gs;
11454: 
11455:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11456: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11457:     {
11458:         my $datafile = $r->dir_config('lonDaemons').
11459:                            '/tmp/'.$datatoken.'.tmp';
11460:         if ( open(my $fh,">$datafile") ) {
11461:             print $fh $env{'form.upfile'};
11462:             close($fh);
11463:         }
11464:     }
11465:     return $datatoken;
11466: }
11467: 
11468: =pod
11469: 
11470: =item * &load_tmp_file($r)
11471: 
11472: Load uploaded file from tmp, $r should be the HTTP Request object,
11473: needs $env{'form.datatoken'},
11474: sets $env{'form.upfile'} to the contents of the file
11475: 
11476: =cut
11477: 
11478: sub load_tmp_file {
11479:     my $r=shift;
11480:     my @studentdata=();
11481:     {
11482:         my $studentfile = $r->dir_config('lonDaemons').
11483:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11484:         if ( open(my $fh,"<$studentfile") ) {
11485:             @studentdata=<$fh>;
11486:             close($fh);
11487:         }
11488:     }
11489:     $env{'form.upfile'}=join('',@studentdata);
11490: }
11491: 
11492: =pod
11493: 
11494: =item * &upfile_record_sep()
11495: 
11496: Separate uploaded file into records
11497: returns array of records,
11498: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11499: 
11500: =cut
11501: 
11502: sub upfile_record_sep {
11503:     if ($env{'form.upfiletype'} eq 'xml') {
11504:     } else {
11505: 	my @records;
11506: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11507: 	    if ($line=~/^\s*$/) { next; }
11508: 	    push(@records,$line);
11509: 	}
11510: 	return @records;
11511:     }
11512: }
11513: 
11514: =pod
11515: 
11516: =item * &record_sep($record)
11517: 
11518: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11519: 
11520: =cut
11521: 
11522: sub takeleft {
11523:     my $index=shift;
11524:     return substr('0000'.$index,-4,4);
11525: }
11526: 
11527: sub record_sep {
11528:     my $record=shift;
11529:     my %components=();
11530:     if ($env{'form.upfiletype'} eq 'xml') {
11531:     } elsif ($env{'form.upfiletype'} eq 'space') {
11532:         my $i=0;
11533:         foreach my $field (split(/\s+/,$record)) {
11534:             $field=~s/^(\"|\')//;
11535:             $field=~s/(\"|\')$//;
11536:             $components{&takeleft($i)}=$field;
11537:             $i++;
11538:         }
11539:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11540:         my $i=0;
11541:         foreach my $field (split(/\t/,$record)) {
11542:             $field=~s/^(\"|\')//;
11543:             $field=~s/(\"|\')$//;
11544:             $components{&takeleft($i)}=$field;
11545:             $i++;
11546:         }
11547:     } else {
11548:         my $separator=',';
11549:         if ($env{'form.upfiletype'} eq 'semisv') {
11550:             $separator=';';
11551:         }
11552:         my $i=0;
11553: # the character we are looking for to indicate the end of a quote or a record 
11554:         my $looking_for=$separator;
11555: # do not add the characters to the fields
11556:         my $ignore=0;
11557: # we just encountered a separator (or the beginning of the record)
11558:         my $just_found_separator=1;
11559: # store the field we are working on here
11560:         my $field='';
11561: # work our way through all characters in record
11562:         foreach my $character ($record=~/(.)/g) {
11563:             if ($character eq $looking_for) {
11564:                if ($character ne $separator) {
11565: # Found the end of a quote, again looking for separator
11566:                   $looking_for=$separator;
11567:                   $ignore=1;
11568:                } else {
11569: # Found a separator, store away what we got
11570:                   $components{&takeleft($i)}=$field;
11571: 	          $i++;
11572:                   $just_found_separator=1;
11573:                   $ignore=0;
11574:                   $field='';
11575:                }
11576:                next;
11577:             }
11578: # single or double quotation marks after a separator indicate beginning of a quote
11579: # we are now looking for the end of the quote and need to ignore separators
11580:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11581:                $looking_for=$character;
11582:                next;
11583:             }
11584: # ignore would be true after we reached the end of a quote
11585:             if ($ignore) { next; }
11586:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11587:             $field.=$character;
11588:             $just_found_separator=0; 
11589:         }
11590: # catch the very last entry, since we never encountered the separator
11591:         $components{&takeleft($i)}=$field;
11592:     }
11593:     return %components;
11594: }
11595: 
11596: ######################################################
11597: ######################################################
11598: 
11599: =pod
11600: 
11601: =item * &upfile_select_html()
11602: 
11603: Return HTML code to select a file from the users machine and specify 
11604: the file type.
11605: 
11606: =cut
11607: 
11608: ######################################################
11609: ######################################################
11610: sub upfile_select_html {
11611:     my %Types = (
11612:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11613:                  semisv => &mt('Semicolon separated values'),
11614:                  space => &mt('Space separated'),
11615:                  tab   => &mt('Tabulator separated'),
11616: #                 xml   => &mt('HTML/XML'),
11617:                  );
11618:     my $Str = '<input type="file" name="upfile" size="50" />'.
11619:         '<br />'.&mt('Type').': <select name="upfiletype">';
11620:     foreach my $type (sort(keys(%Types))) {
11621:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
11622:     }
11623:     $Str .= "</select>\n";
11624:     return $Str;
11625: }
11626: 
11627: sub get_samples {
11628:     my ($records,$toget) = @_;
11629:     my @samples=({});
11630:     my $got=0;
11631:     foreach my $rec (@$records) {
11632: 	my %temp = &record_sep($rec);
11633: 	if (! grep(/\S/, values(%temp))) { next; }
11634: 	if (%temp) {
11635: 	    $samples[$got]=\%temp;
11636: 	    $got++;
11637: 	    if ($got == $toget) { last; }
11638: 	}
11639:     }
11640:     return \@samples;
11641: }
11642: 
11643: ######################################################
11644: ######################################################
11645: 
11646: =pod
11647: 
11648: =item * &csv_print_samples($r,$records)
11649: 
11650: Prints a table of sample values from each column uploaded $r is an
11651: Apache Request ref, $records is an arrayref from
11652: &Apache::loncommon::upfile_record_sep
11653: 
11654: =cut
11655: 
11656: ######################################################
11657: ######################################################
11658: sub csv_print_samples {
11659:     my ($r,$records) = @_;
11660:     my $samples = &get_samples($records,5);
11661: 
11662:     $r->print(&mt('Samples').'<br />'.&start_data_table().
11663:               &start_data_table_header_row());
11664:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
11665:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
11666:     $r->print(&end_data_table_header_row());
11667:     foreach my $hash (@$samples) {
11668: 	$r->print(&start_data_table_row());
11669: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11670: 	    $r->print('<td>');
11671: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
11672: 	    $r->print('</td>');
11673: 	}
11674: 	$r->print(&end_data_table_row());
11675:     }
11676:     $r->print(&end_data_table().'<br />'."\n");
11677: }
11678: 
11679: ######################################################
11680: ######################################################
11681: 
11682: =pod
11683: 
11684: =item * &csv_print_select_table($r,$records,$d)
11685: 
11686: Prints a table to create associations between values and table columns.
11687: 
11688: $r is an Apache Request ref,
11689: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11690: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
11691: 
11692: =cut
11693: 
11694: ######################################################
11695: ######################################################
11696: sub csv_print_select_table {
11697:     my ($r,$records,$d) = @_;
11698:     my $i=0;
11699:     my $samples = &get_samples($records,1);
11700:     $r->print(&mt('Associate columns with student attributes.')."\n".
11701: 	      &start_data_table().&start_data_table_header_row().
11702:               '<th>'.&mt('Attribute').'</th>'.
11703:               '<th>'.&mt('Column').'</th>'.
11704:               &end_data_table_header_row()."\n");
11705:     foreach my $array_ref (@$d) {
11706: 	my ($value,$display,$defaultcol)=@{ $array_ref };
11707: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
11708: 
11709: 	$r->print('<td><select name="f'.$i.'"'.
11710: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
11711: 	$r->print('<option value="none"></option>');
11712: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11713: 	    $r->print('<option value="'.$sample.'"'.
11714:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
11715:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
11716: 	}
11717: 	$r->print('</select></td>'.&end_data_table_row()."\n");
11718: 	$i++;
11719:     }
11720:     $r->print(&end_data_table());
11721:     $i--;
11722:     return $i;
11723: }
11724: 
11725: ######################################################
11726: ######################################################
11727: 
11728: =pod
11729: 
11730: =item * &csv_samples_select_table($r,$records,$d)
11731: 
11732: Prints a table of sample values from the upload and can make associate samples to internal names.
11733: 
11734: $r is an Apache Request ref,
11735: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11736: $d is an array of 2 element arrays (internal name, displayed name)
11737: 
11738: =cut
11739: 
11740: ######################################################
11741: ######################################################
11742: sub csv_samples_select_table {
11743:     my ($r,$records,$d) = @_;
11744:     my $i=0;
11745:     #
11746:     my $max_samples = 5;
11747:     my $samples = &get_samples($records,$max_samples);
11748:     $r->print(&start_data_table().
11749:               &start_data_table_header_row().'<th>'.
11750:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
11751:               &end_data_table_header_row());
11752: 
11753:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
11754: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
11755: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
11756: 	foreach my $option (@$d) {
11757: 	    my ($value,$display,$defaultcol)=@{ $option };
11758: 	    $r->print('<option value="'.$value.'"'.
11759:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
11760:                       $display.'</option>');
11761: 	}
11762: 	$r->print('</select></td><td>');
11763: 	foreach my $line (0..($max_samples-1)) {
11764: 	    if (defined($samples->[$line]{$key})) { 
11765: 		$r->print($samples->[$line]{$key}."<br />\n"); 
11766: 	    }
11767: 	}
11768: 	$r->print('</td>'.&end_data_table_row());
11769: 	$i++;
11770:     }
11771:     $r->print(&end_data_table());
11772:     $i--;
11773:     return($i);
11774: }
11775: 
11776: ######################################################
11777: ######################################################
11778: 
11779: =pod
11780: 
11781: =item * &clean_excel_name($name)
11782: 
11783: Returns a replacement for $name which does not contain any illegal characters.
11784: 
11785: =cut
11786: 
11787: ######################################################
11788: ######################################################
11789: sub clean_excel_name {
11790:     my ($name) = @_;
11791:     $name =~ s/[:\*\?\/\\]//g;
11792:     if (length($name) > 31) {
11793:         $name = substr($name,0,31);
11794:     }
11795:     return $name;
11796: }
11797: 
11798: =pod
11799: 
11800: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
11801: 
11802: Returns either 1 or undef
11803: 
11804: 1 if the part is to be hidden, undef if it is to be shown
11805: 
11806: Arguments are:
11807: 
11808: $id the id of the part to be checked
11809: $symb, optional the symb of the resource to check
11810: $udom, optional the domain of the user to check for
11811: $uname, optional the username of the user to check for
11812: 
11813: =cut
11814: 
11815: sub check_if_partid_hidden {
11816:     my ($id,$symb,$udom,$uname) = @_;
11817:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
11818: 					 $symb,$udom,$uname);
11819:     my $truth=1;
11820:     #if the string starts with !, then the list is the list to show not hide
11821:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
11822:     my @hiddenlist=split(/,/,$hiddenparts);
11823:     foreach my $checkid (@hiddenlist) {
11824: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
11825:     }
11826:     return !$truth;
11827: }
11828: 
11829: 
11830: ############################################################
11831: ############################################################
11832: 
11833: =pod
11834: 
11835: =back 
11836: 
11837: =head1 cgi-bin script and graphing routines
11838: 
11839: =over 4
11840: 
11841: =item * &get_cgi_id()
11842: 
11843: Inputs: none
11844: 
11845: Returns an id which can be used to pass environment variables
11846: to various cgi-bin scripts.  These environment variables will
11847: be removed from the users environment after a given time by
11848: the routine &Apache::lonnet::transfer_profile_to_env.
11849: 
11850: =cut
11851: 
11852: ############################################################
11853: ############################################################
11854: my $uniq=0;
11855: sub get_cgi_id {
11856:     $uniq=($uniq+1)%100000;
11857:     return (time.'_'.$$.'_'.$uniq);
11858: }
11859: 
11860: ############################################################
11861: ############################################################
11862: 
11863: =pod
11864: 
11865: =item * &DrawBarGraph()
11866: 
11867: Facilitates the plotting of data in a (stacked) bar graph.
11868: Puts plot definition data into the users environment in order for 
11869: graph.png to plot it.  Returns an <img> tag for the plot.
11870: The bars on the plot are labeled '1','2',...,'n'.
11871: 
11872: Inputs:
11873: 
11874: =over 4
11875: 
11876: =item $Title: string, the title of the plot
11877: 
11878: =item $xlabel: string, text describing the X-axis of the plot
11879: 
11880: =item $ylabel: string, text describing the Y-axis of the plot
11881: 
11882: =item $Max: scalar, the maximum Y value to use in the plot
11883: If $Max is < any data point, the graph will not be rendered.
11884: 
11885: =item $colors: array ref holding the colors to be used for the data sets when
11886: they are plotted.  If undefined, default values will be used.
11887: 
11888: =item $labels: array ref holding the labels to use on the x-axis for the bars.
11889: 
11890: =item @Values: An array of array references.  Each array reference holds data
11891: to be plotted in a stacked bar chart.
11892: 
11893: =item If the final element of @Values is a hash reference the key/value
11894: pairs will be added to the graph definition.
11895: 
11896: =back
11897: 
11898: Returns:
11899: 
11900: An <img> tag which references graph.png and the appropriate identifying
11901: information for the plot.
11902: 
11903: =cut
11904: 
11905: ############################################################
11906: ############################################################
11907: sub DrawBarGraph {
11908:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
11909:     #
11910:     if (! defined($colors)) {
11911:         $colors = ['#33ff00', 
11912:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
11913:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
11914:                   ]; 
11915:     }
11916:     my $extra_settings = {};
11917:     if (ref($Values[-1]) eq 'HASH') {
11918:         $extra_settings = pop(@Values);
11919:     }
11920:     #
11921:     my $identifier = &get_cgi_id();
11922:     my $id = 'cgi.'.$identifier;        
11923:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
11924:         return '';
11925:     }
11926:     #
11927:     my @Labels;
11928:     if (defined($labels)) {
11929:         @Labels = @$labels;
11930:     } else {
11931:         for (my $i=0;$i<@{$Values[0]};$i++) {
11932:             push (@Labels,$i+1);
11933:         }
11934:     }
11935:     #
11936:     my $NumBars = scalar(@{$Values[0]});
11937:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
11938:     my %ValuesHash;
11939:     my $NumSets=1;
11940:     foreach my $array (@Values) {
11941:         next if (! ref($array));
11942:         $ValuesHash{$id.'.data.'.$NumSets++} = 
11943:             join(',',@$array);
11944:     }
11945:     #
11946:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
11947:     if ($NumBars < 3) {
11948:         $width = 120+$NumBars*32;
11949:         $xskip = 1;
11950:         $bar_width = 30;
11951:     } elsif ($NumBars < 5) {
11952:         $width = 120+$NumBars*20;
11953:         $xskip = 1;
11954:         $bar_width = 20;
11955:     } elsif ($NumBars < 10) {
11956:         $width = 120+$NumBars*15;
11957:         $xskip = 1;
11958:         $bar_width = 15;
11959:     } elsif ($NumBars <= 25) {
11960:         $width = 120+$NumBars*11;
11961:         $xskip = 5;
11962:         $bar_width = 8;
11963:     } elsif ($NumBars <= 50) {
11964:         $width = 120+$NumBars*8;
11965:         $xskip = 5;
11966:         $bar_width = 4;
11967:     } else {
11968:         $width = 120+$NumBars*8;
11969:         $xskip = 5;
11970:         $bar_width = 4;
11971:     }
11972:     #
11973:     $Max = 1 if ($Max < 1);
11974:     if ( int($Max) < $Max ) {
11975:         $Max++;
11976:         $Max = int($Max);
11977:     }
11978:     $Title  = '' if (! defined($Title));
11979:     $xlabel = '' if (! defined($xlabel));
11980:     $ylabel = '' if (! defined($ylabel));
11981:     $ValuesHash{$id.'.title'}    = &escape($Title);
11982:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
11983:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
11984:     $ValuesHash{$id.'.y_max_value'} = $Max;
11985:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
11986:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
11987:     $ValuesHash{$id.'.PlotType'} = 'bar';
11988:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
11989:     $ValuesHash{$id.'.height'}   = $height;
11990:     $ValuesHash{$id.'.width'}    = $width;
11991:     $ValuesHash{$id.'.xskip'}    = $xskip;
11992:     $ValuesHash{$id.'.bar_width'} = $bar_width;
11993:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
11994:     #
11995:     # Deal with other parameters
11996:     while (my ($key,$value) = each(%$extra_settings)) {
11997:         $ValuesHash{$id.'.'.$key} = $value;
11998:     }
11999:     #
12000:     &Apache::lonnet::appenv(\%ValuesHash);
12001:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12002: }
12003: 
12004: ############################################################
12005: ############################################################
12006: 
12007: =pod
12008: 
12009: =item * &DrawXYGraph()
12010: 
12011: Facilitates the plotting of data in an XY graph.
12012: Puts plot definition data into the users environment in order for 
12013: graph.png to plot it.  Returns an <img> tag for the plot.
12014: 
12015: Inputs:
12016: 
12017: =over 4
12018: 
12019: =item $Title: string, the title of the plot
12020: 
12021: =item $xlabel: string, text describing the X-axis of the plot
12022: 
12023: =item $ylabel: string, text describing the Y-axis of the plot
12024: 
12025: =item $Max: scalar, the maximum Y value to use in the plot
12026: If $Max is < any data point, the graph will not be rendered.
12027: 
12028: =item $colors: Array ref containing the hex color codes for the data to be 
12029: plotted in.  If undefined, default values will be used.
12030: 
12031: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12032: 
12033: =item $Ydata: Array ref containing Array refs.  
12034: Each of the contained arrays will be plotted as a separate curve.
12035: 
12036: =item %Values: hash indicating or overriding any default values which are 
12037: passed to graph.png.  
12038: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12039: 
12040: =back
12041: 
12042: Returns:
12043: 
12044: An <img> tag which references graph.png and the appropriate identifying
12045: information for the plot.
12046: 
12047: =cut
12048: 
12049: ############################################################
12050: ############################################################
12051: sub DrawXYGraph {
12052:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12053:     #
12054:     # Create the identifier for the graph
12055:     my $identifier = &get_cgi_id();
12056:     my $id = 'cgi.'.$identifier;
12057:     #
12058:     $Title  = '' if (! defined($Title));
12059:     $xlabel = '' if (! defined($xlabel));
12060:     $ylabel = '' if (! defined($ylabel));
12061:     my %ValuesHash = 
12062:         (
12063:          $id.'.title'  => &escape($Title),
12064:          $id.'.xlabel' => &escape($xlabel),
12065:          $id.'.ylabel' => &escape($ylabel),
12066:          $id.'.y_max_value'=> $Max,
12067:          $id.'.labels'     => join(',',@$Xlabels),
12068:          $id.'.PlotType'   => 'XY',
12069:          );
12070:     #
12071:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12072:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12073:     }
12074:     #
12075:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12076:         return '';
12077:     }
12078:     my $NumSets=1;
12079:     foreach my $array (@{$Ydata}){
12080:         next if (! ref($array));
12081:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12082:     }
12083:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12084:     #
12085:     # Deal with other parameters
12086:     while (my ($key,$value) = each(%Values)) {
12087:         $ValuesHash{$id.'.'.$key} = $value;
12088:     }
12089:     #
12090:     &Apache::lonnet::appenv(\%ValuesHash);
12091:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12092: }
12093: 
12094: ############################################################
12095: ############################################################
12096: 
12097: =pod
12098: 
12099: =item * &DrawXYYGraph()
12100: 
12101: Facilitates the plotting of data in an XY graph with two Y axes.
12102: Puts plot definition data into the users environment in order for 
12103: graph.png to plot it.  Returns an <img> tag for the plot.
12104: 
12105: Inputs:
12106: 
12107: =over 4
12108: 
12109: =item $Title: string, the title of the plot
12110: 
12111: =item $xlabel: string, text describing the X-axis of the plot
12112: 
12113: =item $ylabel: string, text describing the Y-axis of the plot
12114: 
12115: =item $colors: Array ref containing the hex color codes for the data to be 
12116: plotted in.  If undefined, default values will be used.
12117: 
12118: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12119: 
12120: =item $Ydata1: The first data set
12121: 
12122: =item $Min1: The minimum value of the left Y-axis
12123: 
12124: =item $Max1: The maximum value of the left Y-axis
12125: 
12126: =item $Ydata2: The second data set
12127: 
12128: =item $Min2: The minimum value of the right Y-axis
12129: 
12130: =item $Max2: The maximum value of the left Y-axis
12131: 
12132: =item %Values: hash indicating or overriding any default values which are 
12133: passed to graph.png.  
12134: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12135: 
12136: =back
12137: 
12138: Returns:
12139: 
12140: An <img> tag which references graph.png and the appropriate identifying
12141: information for the plot.
12142: 
12143: =cut
12144: 
12145: ############################################################
12146: ############################################################
12147: sub DrawXYYGraph {
12148:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12149:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12150:     #
12151:     # Create the identifier for the graph
12152:     my $identifier = &get_cgi_id();
12153:     my $id = 'cgi.'.$identifier;
12154:     #
12155:     $Title  = '' if (! defined($Title));
12156:     $xlabel = '' if (! defined($xlabel));
12157:     $ylabel = '' if (! defined($ylabel));
12158:     my %ValuesHash = 
12159:         (
12160:          $id.'.title'  => &escape($Title),
12161:          $id.'.xlabel' => &escape($xlabel),
12162:          $id.'.ylabel' => &escape($ylabel),
12163:          $id.'.labels' => join(',',@$Xlabels),
12164:          $id.'.PlotType' => 'XY',
12165:          $id.'.NumSets' => 2,
12166:          $id.'.two_axes' => 1,
12167:          $id.'.y1_max_value' => $Max1,
12168:          $id.'.y1_min_value' => $Min1,
12169:          $id.'.y2_max_value' => $Max2,
12170:          $id.'.y2_min_value' => $Min2,
12171:          );
12172:     #
12173:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12174:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12175:     }
12176:     #
12177:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12178:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12179:         return '';
12180:     }
12181:     my $NumSets=1;
12182:     foreach my $array ($Ydata1,$Ydata2){
12183:         next if (! ref($array));
12184:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12185:     }
12186:     #
12187:     # Deal with other parameters
12188:     while (my ($key,$value) = each(%Values)) {
12189:         $ValuesHash{$id.'.'.$key} = $value;
12190:     }
12191:     #
12192:     &Apache::lonnet::appenv(\%ValuesHash);
12193:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12194: }
12195: 
12196: ############################################################
12197: ############################################################
12198: 
12199: =pod
12200: 
12201: =back 
12202: 
12203: =head1 Statistics helper routines?  
12204: 
12205: Bad place for them but what the hell.
12206: 
12207: =over 4
12208: 
12209: =item * &chartlink()
12210: 
12211: Returns a link to the chart for a specific student.  
12212: 
12213: Inputs:
12214: 
12215: =over 4
12216: 
12217: =item $linktext: The text of the link
12218: 
12219: =item $sname: The students username
12220: 
12221: =item $sdomain: The students domain
12222: 
12223: =back
12224: 
12225: =back
12226: 
12227: =cut
12228: 
12229: ############################################################
12230: ############################################################
12231: sub chartlink {
12232:     my ($linktext, $sname, $sdomain) = @_;
12233:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12234:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12235:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12236:        '">'.$linktext.'</a>';
12237: }
12238: 
12239: #######################################################
12240: #######################################################
12241: 
12242: =pod
12243: 
12244: =head1 Course Environment Routines
12245: 
12246: =over 4
12247: 
12248: =item * &restore_course_settings()
12249: 
12250: =item * &store_course_settings()
12251: 
12252: Restores/Store indicated form parameters from the course environment.
12253: Will not overwrite existing values of the form parameters.
12254: 
12255: Inputs: 
12256: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12257: 
12258: a hash ref describing the data to be stored.  For example:
12259:    
12260: %Save_Parameters = ('Status' => 'scalar',
12261:     'chartoutputmode' => 'scalar',
12262:     'chartoutputdata' => 'scalar',
12263:     'Section' => 'array',
12264:     'Group' => 'array',
12265:     'StudentData' => 'array',
12266:     'Maps' => 'array');
12267: 
12268: Returns: both routines return nothing
12269: 
12270: =back
12271: 
12272: =cut
12273: 
12274: #######################################################
12275: #######################################################
12276: sub store_course_settings {
12277:     return &store_settings($env{'request.course.id'},@_);
12278: }
12279: 
12280: sub store_settings {
12281:     # save to the environment
12282:     # appenv the same items, just to be safe
12283:     my $udom  = $env{'user.domain'};
12284:     my $uname = $env{'user.name'};
12285:     my ($context,$prefix,$Settings) = @_;
12286:     my %SaveHash;
12287:     my %AppHash;
12288:     while (my ($setting,$type) = each(%$Settings)) {
12289:         my $basename = join('.','internal',$context,$prefix,$setting);
12290:         my $envname = 'environment.'.$basename;
12291:         if (exists($env{'form.'.$setting})) {
12292:             # Save this value away
12293:             if ($type eq 'scalar' &&
12294:                 (! exists($env{$envname}) || 
12295:                  $env{$envname} ne $env{'form.'.$setting})) {
12296:                 $SaveHash{$basename} = $env{'form.'.$setting};
12297:                 $AppHash{$envname}   = $env{'form.'.$setting};
12298:             } elsif ($type eq 'array') {
12299:                 my $stored_form;
12300:                 if (ref($env{'form.'.$setting})) {
12301:                     $stored_form = join(',',
12302:                                         map {
12303:                                             &escape($_);
12304:                                         } sort(@{$env{'form.'.$setting}}));
12305:                 } else {
12306:                     $stored_form = 
12307:                         &escape($env{'form.'.$setting});
12308:                 }
12309:                 # Determine if the array contents are the same.
12310:                 if ($stored_form ne $env{$envname}) {
12311:                     $SaveHash{$basename} = $stored_form;
12312:                     $AppHash{$envname}   = $stored_form;
12313:                 }
12314:             }
12315:         }
12316:     }
12317:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12318:                                           $udom,$uname);
12319:     if ($put_result !~ /^(ok|delayed)/) {
12320:         &Apache::lonnet::logthis('unable to save form parameters, '.
12321:                                  'got error:'.$put_result);
12322:     }
12323:     # Make sure these settings stick around in this session, too
12324:     &Apache::lonnet::appenv(\%AppHash);
12325:     return;
12326: }
12327: 
12328: sub restore_course_settings {
12329:     return &restore_settings($env{'request.course.id'},@_);
12330: }
12331: 
12332: sub restore_settings {
12333:     my ($context,$prefix,$Settings) = @_;
12334:     while (my ($setting,$type) = each(%$Settings)) {
12335:         next if (exists($env{'form.'.$setting}));
12336:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12337:             '.'.$setting;
12338:         if (exists($env{$envname})) {
12339:             if ($type eq 'scalar') {
12340:                 $env{'form.'.$setting} = $env{$envname};
12341:             } elsif ($type eq 'array') {
12342:                 $env{'form.'.$setting} = [ 
12343:                                            map { 
12344:                                                &unescape($_); 
12345:                                            } split(',',$env{$envname})
12346:                                            ];
12347:             }
12348:         }
12349:     }
12350: }
12351: 
12352: #######################################################
12353: #######################################################
12354: 
12355: =pod
12356: 
12357: =head1 Domain E-mail Routines  
12358: 
12359: =over 4
12360: 
12361: =item * &build_recipient_list()
12362: 
12363: Build recipient lists for five types of e-mail:
12364: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12365: (d) Help requests, (e) Course requests needing approval,  generated by
12366: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12367: loncoursequeueadmin.pm respectively.
12368: 
12369: Inputs:
12370: defmail (scalar - email address of default recipient), 
12371: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12372: defdom (domain for which to retrieve configuration settings),
12373: origmail (scalar - email address of recipient from loncapa.conf, 
12374: i.e., predates configuration by DC via domainprefs.pm 
12375: 
12376: Returns: comma separated list of addresses to which to send e-mail.
12377: 
12378: =back
12379: 
12380: =cut
12381: 
12382: ############################################################
12383: ############################################################
12384: sub build_recipient_list {
12385:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12386:     my @recipients;
12387:     my $otheremails;
12388:     my %domconfig =
12389:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12390:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12391:         if (exists($domconfig{'contacts'}{$mailing})) {
12392:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12393:                 my @contacts = ('adminemail','supportemail');
12394:                 foreach my $item (@contacts) {
12395:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12396:                         my $addr = $domconfig{'contacts'}{$item}; 
12397:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12398:                             push(@recipients,$addr);
12399:                         }
12400:                     }
12401:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12402:                 }
12403:             }
12404:         } elsif ($origmail ne '') {
12405:             push(@recipients,$origmail);
12406:         }
12407:     } elsif ($origmail ne '') {
12408:         push(@recipients,$origmail);
12409:     }
12410:     if (defined($defmail)) {
12411:         if ($defmail ne '') {
12412:             push(@recipients,$defmail);
12413:         }
12414:     }
12415:     if ($otheremails) {
12416:         my @others;
12417:         if ($otheremails =~ /,/) {
12418:             @others = split(/,/,$otheremails);
12419:         } else {
12420:             push(@others,$otheremails);
12421:         }
12422:         foreach my $addr (@others) {
12423:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12424:                 push(@recipients,$addr);
12425:             }
12426:         }
12427:     }
12428:     my $recipientlist = join(',',@recipients); 
12429:     return $recipientlist;
12430: }
12431: 
12432: ############################################################
12433: ############################################################
12434: 
12435: =pod
12436: 
12437: =head1 Course Catalog Routines
12438: 
12439: =over 4
12440: 
12441: =item * &gather_categories()
12442: 
12443: Converts category definitions - keys of categories hash stored in  
12444: coursecategories in configuration.db on the primary library server in a 
12445: domain - to an array.  Also generates javascript and idx hash used to 
12446: generate Domain Coordinator interface for editing Course Categories.
12447: 
12448: Inputs:
12449: 
12450: categories (reference to hash of category definitions).
12451: 
12452: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12453:       categories and subcategories).
12454: 
12455: idx (reference to hash of counters used in Domain Coordinator interface for 
12456:       editing Course Categories).
12457: 
12458: jsarray (reference to array of categories used to create Javascript arrays for
12459:          Domain Coordinator interface for editing Course Categories).
12460: 
12461: Returns: nothing
12462: 
12463: Side effects: populates cats, idx and jsarray. 
12464: 
12465: =cut
12466: 
12467: sub gather_categories {
12468:     my ($categories,$cats,$idx,$jsarray) = @_;
12469:     my %counters;
12470:     my $num = 0;
12471:     foreach my $item (keys(%{$categories})) {
12472:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12473:         if ($container eq '' && $depth == 0) {
12474:             $cats->[$depth][$categories->{$item}] = $cat;
12475:         } else {
12476:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12477:         }
12478:         my ($escitem,$tail) = split(/:/,$item,2);
12479:         if ($counters{$tail} eq '') {
12480:             $counters{$tail} = $num;
12481:             $num ++;
12482:         }
12483:         if (ref($idx) eq 'HASH') {
12484:             $idx->{$item} = $counters{$tail};
12485:         }
12486:         if (ref($jsarray) eq 'ARRAY') {
12487:             push(@{$jsarray->[$counters{$tail}]},$item);
12488:         }
12489:     }
12490:     return;
12491: }
12492: 
12493: =pod
12494: 
12495: =item * &extract_categories()
12496: 
12497: Used to generate breadcrumb trails for course categories.
12498: 
12499: Inputs:
12500: 
12501: categories (reference to hash of category definitions).
12502: 
12503: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12504:       categories and subcategories).
12505: 
12506: trails (reference to array of breacrumb trails for each category).
12507: 
12508: allitems (reference to hash - key is category key 
12509:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12510: 
12511: idx (reference to hash of counters used in Domain Coordinator interface for
12512:       editing Course Categories).
12513: 
12514: jsarray (reference to array of categories used to create Javascript arrays for
12515:          Domain Coordinator interface for editing Course Categories).
12516: 
12517: subcats (reference to hash of arrays containing all subcategories within each 
12518:          category, -recursive)
12519: 
12520: Returns: nothing
12521: 
12522: Side effects: populates trails and allitems hash references.
12523: 
12524: =cut
12525: 
12526: sub extract_categories {
12527:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12528:     if (ref($categories) eq 'HASH') {
12529:         &gather_categories($categories,$cats,$idx,$jsarray);
12530:         if (ref($cats->[0]) eq 'ARRAY') {
12531:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12532:                 my $name = $cats->[0][$i];
12533:                 my $item = &escape($name).'::0';
12534:                 my $trailstr;
12535:                 if ($name eq 'instcode') {
12536:                     $trailstr = &mt('Official courses (with institutional codes)');
12537:                 } elsif ($name eq 'communities') {
12538:                     $trailstr = &mt('Communities');
12539:                 } else {
12540:                     $trailstr = $name;
12541:                 }
12542:                 if ($allitems->{$item} eq '') {
12543:                     push(@{$trails},$trailstr);
12544:                     $allitems->{$item} = scalar(@{$trails})-1;
12545:                 }
12546:                 my @parents = ($name);
12547:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12548:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12549:                         my $category = $cats->[1]{$name}[$j];
12550:                         if (ref($subcats) eq 'HASH') {
12551:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12552:                         }
12553:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12554:                     }
12555:                 } else {
12556:                     if (ref($subcats) eq 'HASH') {
12557:                         $subcats->{$item} = [];
12558:                     }
12559:                 }
12560:             }
12561:         }
12562:     }
12563:     return;
12564: }
12565: 
12566: =pod
12567: 
12568: =item *&recurse_categories()
12569: 
12570: Recursively used to generate breadcrumb trails for course categories.
12571: 
12572: Inputs:
12573: 
12574: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12575:       categories and subcategories).
12576: 
12577: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12578: 
12579: category (current course category, for which breadcrumb trail is being generated).
12580: 
12581: trails (reference to array of breadcrumb trails for each category).
12582: 
12583: allitems (reference to hash - key is category key
12584:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12585: 
12586: parents (array containing containers directories for current category, 
12587:          back to top level). 
12588: 
12589: Returns: nothing
12590: 
12591: Side effects: populates trails and allitems hash references
12592: 
12593: =cut
12594: 
12595: sub recurse_categories {
12596:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12597:     my $shallower = $depth - 1;
12598:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12599:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12600:             my $name = $cats->[$depth]{$category}[$k];
12601:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12602:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12603:             if ($allitems->{$item} eq '') {
12604:                 push(@{$trails},$trailstr);
12605:                 $allitems->{$item} = scalar(@{$trails})-1;
12606:             }
12607:             my $deeper = $depth+1;
12608:             push(@{$parents},$category);
12609:             if (ref($subcats) eq 'HASH') {
12610:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12611:                 for (my $j=@{$parents}; $j>=0; $j--) {
12612:                     my $higher;
12613:                     if ($j > 0) {
12614:                         $higher = &escape($parents->[$j]).':'.
12615:                                   &escape($parents->[$j-1]).':'.$j;
12616:                     } else {
12617:                         $higher = &escape($parents->[$j]).'::'.$j;
12618:                     }
12619:                     push(@{$subcats->{$higher}},$subcat);
12620:                 }
12621:             }
12622:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
12623:                                 $subcats);
12624:             pop(@{$parents});
12625:         }
12626:     } else {
12627:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12628:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
12629:         if ($allitems->{$item} eq '') {
12630:             push(@{$trails},$trailstr);
12631:             $allitems->{$item} = scalar(@{$trails})-1;
12632:         }
12633:     }
12634:     return;
12635: }
12636: 
12637: =pod
12638: 
12639: =item *&assign_categories_table()
12640: 
12641: Create a datatable for display of hierarchical categories in a domain,
12642: with checkboxes to allow a course to be categorized. 
12643: 
12644: Inputs:
12645: 
12646: cathash - reference to hash of categories defined for the domain (from
12647:           configuration.db)
12648: 
12649: currcat - scalar with an & separated list of categories assigned to a course. 
12650: 
12651: type    - scalar contains course type (Course or Community).
12652: 
12653: Returns: $output (markup to be displayed) 
12654: 
12655: =cut
12656: 
12657: sub assign_categories_table {
12658:     my ($cathash,$currcat,$type) = @_;
12659:     my $output;
12660:     if (ref($cathash) eq 'HASH') {
12661:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
12662:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
12663:         $maxdepth = scalar(@cats);
12664:         if (@cats > 0) {
12665:             my $itemcount = 0;
12666:             if (ref($cats[0]) eq 'ARRAY') {
12667:                 my @currcategories;
12668:                 if ($currcat ne '') {
12669:                     @currcategories = split('&',$currcat);
12670:                 }
12671:                 my $table;
12672:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
12673:                     my $parent = $cats[0][$i];
12674:                     next if ($parent eq 'instcode');
12675:                     if ($type eq 'Community') {
12676:                         next unless ($parent eq 'communities');
12677:                     } else {
12678:                         next if ($parent eq 'communities');
12679:                     }
12680:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12681:                     my $item = &escape($parent).'::0';
12682:                     my $checked = '';
12683:                     if (@currcategories > 0) {
12684:                         if (grep(/^\Q$item\E$/,@currcategories)) {
12685:                             $checked = ' checked="checked"';
12686:                         }
12687:                     }
12688:                     my $parent_title = $parent;
12689:                     if ($parent eq 'communities') {
12690:                         $parent_title = &mt('Communities');
12691:                     }
12692:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
12693:                               '<input type="checkbox" name="usecategory" value="'.
12694:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
12695:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
12696:                     my $depth = 1;
12697:                     push(@path,$parent);
12698:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
12699:                     pop(@path);
12700:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
12701:                     $itemcount ++;
12702:                 }
12703:                 if ($itemcount) {
12704:                     $output = &Apache::loncommon::start_data_table().
12705:                               $table.
12706:                               &Apache::loncommon::end_data_table();
12707:                 }
12708:             }
12709:         }
12710:     }
12711:     return $output;
12712: }
12713: 
12714: =pod
12715: 
12716: =item *&assign_category_rows()
12717: 
12718: Create a datatable row for display of nested categories in a domain,
12719: with checkboxes to allow a course to be categorized,called recursively.
12720: 
12721: Inputs:
12722: 
12723: itemcount - track row number for alternating colors
12724: 
12725: cats - reference to array of arrays/hashes which encapsulates hierarchy of
12726:       categories and subcategories.
12727: 
12728: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
12729: 
12730: parent - parent of current category item
12731: 
12732: path - Array containing all categories back up through the hierarchy from the
12733:        current category to the top level.
12734: 
12735: currcategories - reference to array of current categories assigned to the course
12736: 
12737: Returns: $output (markup to be displayed).
12738: 
12739: =cut
12740: 
12741: sub assign_category_rows {
12742:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
12743:     my ($text,$name,$item,$chgstr);
12744:     if (ref($cats) eq 'ARRAY') {
12745:         my $maxdepth = scalar(@{$cats});
12746:         if (ref($cats->[$depth]) eq 'HASH') {
12747:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
12748:                 my $numchildren = @{$cats->[$depth]{$parent}};
12749:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12750:                 $text .= '<td><table class="LC_datatable">';
12751:                 for (my $j=0; $j<$numchildren; $j++) {
12752:                     $name = $cats->[$depth]{$parent}[$j];
12753:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
12754:                     my $deeper = $depth+1;
12755:                     my $checked = '';
12756:                     if (ref($currcategories) eq 'ARRAY') {
12757:                         if (@{$currcategories} > 0) {
12758:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
12759:                                 $checked = ' checked="checked"';
12760:                             }
12761:                         }
12762:                     }
12763:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
12764:                              '<input type="checkbox" name="usecategory" value="'.
12765:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
12766:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
12767:                              '</td><td>';
12768:                     if (ref($path) eq 'ARRAY') {
12769:                         push(@{$path},$name);
12770:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
12771:                         pop(@{$path});
12772:                     }
12773:                     $text .= '</td></tr>';
12774:                 }
12775:                 $text .= '</table></td>';
12776:             }
12777:         }
12778:     }
12779:     return $text;
12780: }
12781: 
12782: ############################################################
12783: ############################################################
12784: 
12785: 
12786: sub commit_customrole {
12787:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
12788:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
12789:                          ($start?', '.&mt('starting').' '.localtime($start):'').
12790:                          ($end?', ending '.localtime($end):'').': <b>'.
12791:               &Apache::lonnet::assigncustomrole(
12792:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
12793:                  '</b><br />';
12794:     return $output;
12795: }
12796: 
12797: sub commit_standardrole {
12798:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
12799:     my ($output,$logmsg,$linefeed);
12800:     if ($context eq 'auto') {
12801:         $linefeed = "\n";
12802:     } else {
12803:         $linefeed = "<br />\n";
12804:     }  
12805:     if ($three eq 'st') {
12806:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
12807:                                          $one,$two,$sec,$context);
12808:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
12809:             ($result eq 'unknown_course') || ($result eq 'refused')) {
12810:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
12811:         } else {
12812:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
12813:                ($start?', '.&mt('starting').' '.localtime($start):'').
12814:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
12815:             if ($context eq 'auto') {
12816:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
12817:             } else {
12818:                $output .= '<b>'.$result.'</b>'.$linefeed.
12819:                &mt('Add to classlist').': <b>ok</b>';
12820:             }
12821:             $output .= $linefeed;
12822:         }
12823:     } else {
12824:         $output = &mt('Assigning').' '.$three.' in '.$url.
12825:                ($start?', '.&mt('starting').' '.localtime($start):'').
12826:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
12827:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
12828:         if ($context eq 'auto') {
12829:             $output .= $result.$linefeed;
12830:         } else {
12831:             $output .= '<b>'.$result.'</b>'.$linefeed;
12832:         }
12833:     }
12834:     return $output;
12835: }
12836: 
12837: sub commit_studentrole {
12838:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
12839:     my ($result,$linefeed,$oldsecurl,$newsecurl);
12840:     if ($context eq 'auto') {
12841:         $linefeed = "\n";
12842:     } else {
12843:         $linefeed = '<br />'."\n";
12844:     }
12845:     if (defined($one) && defined($two)) {
12846:         my $cid=$one.'_'.$two;
12847:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
12848:         my $secchange = 0;
12849:         my $expire_role_result;
12850:         my $modify_section_result;
12851:         if ($oldsec ne '-1') { 
12852:             if ($oldsec ne $sec) {
12853:                 $secchange = 1;
12854:                 my $now = time;
12855:                 my $uurl='/'.$cid;
12856:                 $uurl=~s/\_/\//g;
12857:                 if ($oldsec) {
12858:                     $uurl.='/'.$oldsec;
12859:                 }
12860:                 $oldsecurl = $uurl;
12861:                 $expire_role_result = 
12862:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
12863:                 if ($env{'request.course.sec'} ne '') { 
12864:                     if ($expire_role_result eq 'refused') {
12865:                         my @roles = ('st');
12866:                         my @statuses = ('previous');
12867:                         my @roledoms = ($one);
12868:                         my $withsec = 1;
12869:                         my %roleshash = 
12870:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
12871:                                               \@statuses,\@roles,\@roledoms,$withsec);
12872:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
12873:                             my ($oldstart,$oldend) = 
12874:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
12875:                             if ($oldend > 0 && $oldend <= $now) {
12876:                                 $expire_role_result = 'ok';
12877:                             }
12878:                         }
12879:                     }
12880:                 }
12881:                 $result = $expire_role_result;
12882:             }
12883:         }
12884:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
12885:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
12886:             if ($modify_section_result =~ /^ok/) {
12887:                 if ($secchange == 1) {
12888:                     if ($sec eq '') {
12889:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
12890:                     } else {
12891:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
12892:                     }
12893:                 } elsif ($oldsec eq '-1') {
12894:                     if ($sec eq '') {
12895:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
12896:                     } else {
12897:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12898:                     }
12899:                 } else {
12900:                     if ($sec eq '') {
12901:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
12902:                     } else {
12903:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12904:                     }
12905:                 }
12906:             } else {
12907:                 if ($secchange) {       
12908:                     $$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;
12909:                 } else {
12910:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
12911:                 }
12912:             }
12913:             $result = $modify_section_result;
12914:         } elsif ($secchange == 1) {
12915:             if ($oldsec eq '') {
12916:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
12917:             } else {
12918:                 $$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;
12919:             }
12920:             if ($expire_role_result eq 'refused') {
12921:                 my $newsecurl = '/'.$cid;
12922:                 $newsecurl =~ s/\_/\//g;
12923:                 if ($sec ne '') {
12924:                     $newsecurl.='/'.$sec;
12925:                 }
12926:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
12927:                     if ($sec eq '') {
12928:                         $$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;
12929:                     } else {
12930:                         $$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;
12931:                     }
12932:                 }
12933:             }
12934:         }
12935:     } else {
12936:         $$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;
12937:         $result = "error: incomplete course id\n";
12938:     }
12939:     return $result;
12940: }
12941: 
12942: ############################################################
12943: ############################################################
12944: 
12945: sub check_clone {
12946:     my ($args,$linefeed) = @_;
12947:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
12948:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
12949:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
12950:     my $clonemsg;
12951:     my $can_clone = 0;
12952:     my $lctype = lc($args->{'crstype'});
12953:     if ($lctype ne 'community') {
12954:         $lctype = 'course';
12955:     }
12956:     if ($clonehome eq 'no_host') {
12957:         if ($args->{'crstype'} eq 'Community') {
12958:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
12959:         } else {
12960:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
12961:         }     
12962:     } else {
12963: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
12964:         if ($args->{'crstype'} eq 'Community') {
12965:             if ($clonedesc{'type'} ne 'Community') {
12966:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
12967:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
12968:             }
12969:         }
12970: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
12971:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
12972: 	    $can_clone = 1;
12973: 	} else {
12974: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
12975: 						 $args->{'clonedomain'},$args->{'clonecourse'});
12976: 	    my @cloners = split(/,/,$clonehash{'cloners'});
12977:             if (grep(/^\*$/,@cloners)) {
12978:                 $can_clone = 1;
12979:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
12980:                 $can_clone = 1;
12981:             } else {
12982:                 my $ccrole = 'cc';
12983:                 if ($args->{'crstype'} eq 'Community') {
12984:                     $ccrole = 'co';
12985:                 }
12986: 	        my %roleshash =
12987: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
12988: 					 $args->{'ccdomain'},
12989:                                          'userroles',['active'],[$ccrole],
12990: 					 [$args->{'clonedomain'}]);
12991: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
12992:                     $can_clone = 1;
12993:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
12994:                     $can_clone = 1;
12995:                 } else {
12996:                     if ($args->{'crstype'} eq 'Community') {
12997:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
12998:                     } else {
12999:                         $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
13000:                     }
13001: 	        }
13002: 	    }
13003:         }
13004:     }
13005:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13006: }
13007: 
13008: sub construct_course {
13009:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13010:     my $outcome;
13011:     my $linefeed =  '<br />'."\n";
13012:     if ($context eq 'auto') {
13013:         $linefeed = "\n";
13014:     }
13015: 
13016: #
13017: # Are we cloning?
13018: #
13019:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13020:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13021: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13022: 	if ($context ne 'auto') {
13023:             if ($clonemsg ne '') {
13024: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13025:             }
13026: 	}
13027: 	$outcome .= $clonemsg.$linefeed;
13028: 
13029:         if (!$can_clone) {
13030: 	    return (0,$outcome);
13031: 	}
13032:     }
13033: 
13034: #
13035: # Open course
13036: #
13037:     my $crstype = lc($args->{'crstype'});
13038:     my %cenv=();
13039:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13040:                                              $args->{'cdescr'},
13041:                                              $args->{'curl'},
13042:                                              $args->{'course_home'},
13043:                                              $args->{'nonstandard'},
13044:                                              $args->{'crscode'},
13045:                                              $args->{'ccuname'}.':'.
13046:                                              $args->{'ccdomain'},
13047:                                              $args->{'crstype'},
13048:                                              $cnum,$context,$category);
13049: 
13050:     # Note: The testing routines depend on this being output; see 
13051:     # Utils::Course. This needs to at least be output as a comment
13052:     # if anyone ever decides to not show this, and Utils::Course::new
13053:     # will need to be suitably modified.
13054:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13055:     if ($$courseid =~ /^error:/) {
13056:         return (0,$outcome);
13057:     }
13058: 
13059: #
13060: # Check if created correctly
13061: #
13062:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13063:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13064:     if ($crsuhome eq 'no_host') {
13065:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13066:         return (0,$outcome);
13067:     }
13068:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13069: 
13070: #
13071: # Do the cloning
13072: #   
13073:     if ($can_clone && $cloneid) {
13074: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13075: 	if ($context ne 'auto') {
13076: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13077: 	}
13078: 	$outcome .= $clonemsg.$linefeed;
13079: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13080: # Copy all files
13081: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13082: # Restore URL
13083: 	$cenv{'url'}=$oldcenv{'url'};
13084: # Restore title
13085: 	$cenv{'description'}=$oldcenv{'description'};
13086: # Restore creation date, creator and creation context.
13087:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13088:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13089:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13090: # Mark as cloned
13091: 	$cenv{'clonedfrom'}=$cloneid;
13092: # Need to clone grading mode
13093:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13094:         $cenv{'grading'}=$newenv{'grading'};
13095: # Do not clone these environment entries
13096:         &Apache::lonnet::del('environment',
13097:                   ['default_enrollment_start_date',
13098:                    'default_enrollment_end_date',
13099:                    'question.email',
13100:                    'policy.email',
13101:                    'comment.email',
13102:                    'pch.users.denied',
13103:                    'plc.users.denied',
13104:                    'hidefromcat',
13105:                    'categories'],
13106:                    $$crsudom,$$crsunum);
13107:     }
13108: 
13109: #
13110: # Set environment (will override cloned, if existing)
13111: #
13112:     my @sections = ();
13113:     my @xlists = ();
13114:     if ($args->{'crstype'}) {
13115:         $cenv{'type'}=$args->{'crstype'};
13116:     }
13117:     if ($args->{'crsid'}) {
13118:         $cenv{'courseid'}=$args->{'crsid'};
13119:     }
13120:     if ($args->{'crscode'}) {
13121:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13122:     }
13123:     if ($args->{'crsquota'} ne '') {
13124:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13125:     } else {
13126:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13127:     }
13128:     if ($args->{'ccuname'}) {
13129:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13130:                                         ':'.$args->{'ccdomain'};
13131:     } else {
13132:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13133:     }
13134:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13135:     if ($args->{'crssections'}) {
13136:         $cenv{'internal.sectionnums'} = '';
13137:         if ($args->{'crssections'} =~ m/,/) {
13138:             @sections = split/,/,$args->{'crssections'};
13139:         } else {
13140:             $sections[0] = $args->{'crssections'};
13141:         }
13142:         if (@sections > 0) {
13143:             foreach my $item (@sections) {
13144:                 my ($sec,$gp) = split/:/,$item;
13145:                 my $class = $args->{'crscode'}.$sec;
13146:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13147:                 $cenv{'internal.sectionnums'} .= $item.',';
13148:                 unless ($addcheck eq 'ok') {
13149:                     push @badclasses, $class;
13150:                 }
13151:             }
13152:             $cenv{'internal.sectionnums'} =~ s/,$//;
13153:         }
13154:     }
13155: # do not hide course coordinator from staff listing, 
13156: # even if privileged
13157:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13158: # add crosslistings
13159:     if ($args->{'crsxlist'}) {
13160:         $cenv{'internal.crosslistings'}='';
13161:         if ($args->{'crsxlist'} =~ m/,/) {
13162:             @xlists = split/,/,$args->{'crsxlist'};
13163:         } else {
13164:             $xlists[0] = $args->{'crsxlist'};
13165:         }
13166:         if (@xlists > 0) {
13167:             foreach my $item (@xlists) {
13168:                 my ($xl,$gp) = split/:/,$item;
13169:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13170:                 $cenv{'internal.crosslistings'} .= $item.',';
13171:                 unless ($addcheck eq 'ok') {
13172:                     push @badclasses, $xl;
13173:                 }
13174:             }
13175:             $cenv{'internal.crosslistings'} =~ s/,$//;
13176:         }
13177:     }
13178:     if ($args->{'autoadds'}) {
13179:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13180:     }
13181:     if ($args->{'autodrops'}) {
13182:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13183:     }
13184: # check for notification of enrollment changes
13185:     my @notified = ();
13186:     if ($args->{'notify_owner'}) {
13187:         if ($args->{'ccuname'} ne '') {
13188:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13189:         }
13190:     }
13191:     if ($args->{'notify_dc'}) {
13192:         if ($uname ne '') { 
13193:             push(@notified,$uname.':'.$udom);
13194:         }
13195:     }
13196:     if (@notified > 0) {
13197:         my $notifylist;
13198:         if (@notified > 1) {
13199:             $notifylist = join(',',@notified);
13200:         } else {
13201:             $notifylist = $notified[0];
13202:         }
13203:         $cenv{'internal.notifylist'} = $notifylist;
13204:     }
13205:     if (@badclasses > 0) {
13206:         my %lt=&Apache::lonlocal::texthash(
13207:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
13208:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13209:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13210:         );
13211:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13212:                            ' ('.$lt{'adby'}.')';
13213:         if ($context eq 'auto') {
13214:             $outcome .= $badclass_msg.$linefeed;
13215:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13216:             foreach my $item (@badclasses) {
13217:                 if ($context eq 'auto') {
13218:                     $outcome .= " - $item\n";
13219:                 } else {
13220:                     $outcome .= "<li>$item</li>\n";
13221:                 }
13222:             }
13223:             if ($context eq 'auto') {
13224:                 $outcome .= $linefeed;
13225:             } else {
13226:                 $outcome .= "</ul><br /><br /></div>\n";
13227:             }
13228:         } 
13229:     }
13230:     if ($args->{'no_end_date'}) {
13231:         $args->{'endaccess'} = 0;
13232:     }
13233:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13234:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13235:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13236:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13237:     if ($args->{'showphotos'}) {
13238:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13239:     }
13240:     $cenv{'internal.authtype'} = $args->{'authtype'};
13241:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13242:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13243:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13244:             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'); 
13245:             if ($context eq 'auto') {
13246:                 $outcome .= $krb_msg;
13247:             } else {
13248:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13249:             }
13250:             $outcome .= $linefeed;
13251:         }
13252:     }
13253:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13254:        if ($args->{'setpolicy'}) {
13255:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13256:        }
13257:        if ($args->{'setcontent'}) {
13258:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13259:        }
13260:     }
13261:     if ($args->{'reshome'}) {
13262: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13263: 	$cenv{'reshome'}=~s/\/+$/\//;
13264:     }
13265: #
13266: # course has keyed access
13267: #
13268:     if ($args->{'setkeys'}) {
13269:        $cenv{'keyaccess'}='yes';
13270:     }
13271: # if specified, key authority is not course, but user
13272: # only active if keyaccess is yes
13273:     if ($args->{'keyauth'}) {
13274: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13275: 	$user = &LONCAPA::clean_username($user);
13276: 	$domain = &LONCAPA::clean_username($domain);
13277: 	if ($user ne '' && $domain ne '') {
13278: 	    $cenv{'keyauth'}=$user.':'.$domain;
13279: 	}
13280:     }
13281: 
13282:     if ($args->{'disresdis'}) {
13283:         $cenv{'pch.roles.denied'}='st';
13284:     }
13285:     if ($args->{'disablechat'}) {
13286:         $cenv{'plc.roles.denied'}='st';
13287:     }
13288: 
13289:     # Record we've not yet viewed the Course Initialization Helper for this 
13290:     # course
13291:     $cenv{'course.helper.not.run'} = 1;
13292:     #
13293:     # Use new Randomseed
13294:     #
13295:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13296:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13297:     #
13298:     # The encryption code and receipt prefix for this course
13299:     #
13300:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13301:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13302:     #
13303:     # By default, use standard grading
13304:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13305: 
13306:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13307:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13308: #
13309: # Open all assignments
13310: #
13311:     if ($args->{'openall'}) {
13312:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13313:        my %storecontent = ($storeunder         => time,
13314:                            $storeunder.'.type' => 'date_start');
13315:        
13316:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13317:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13318:    }
13319: #
13320: # Set first page
13321: #
13322:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13323: 	    || ($cloneid)) {
13324: 	use LONCAPA::map;
13325: 	$outcome .= &mt('Setting first resource').': ';
13326: 
13327: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13328:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13329: 
13330:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13331:         my $title; my $url;
13332:         if ($args->{'firstres'} eq 'syl') {
13333: 	    $title=&mt('Syllabus');
13334:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13335:         } else {
13336:             $title=&mt('Table of Contents');
13337:             $url='/adm/navmaps';
13338:         }
13339: 
13340:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13341: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13342: 
13343: 	if ($errtext) { $fatal=2; }
13344:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13345:     }
13346: 
13347:     return (1,$outcome);
13348: }
13349: 
13350: ############################################################
13351: ############################################################
13352: 
13353: #SD
13354: # only Community and Course, or anything else?
13355: sub course_type {
13356:     my ($cid) = @_;
13357:     if (!defined($cid)) {
13358:         $cid = $env{'request.course.id'};
13359:     }
13360:     if (defined($env{'course.'.$cid.'.type'})) {
13361:         return $env{'course.'.$cid.'.type'};
13362:     } else {
13363:         return 'Course';
13364:     }
13365: }
13366: 
13367: sub group_term {
13368:     my $crstype = &course_type();
13369:     my %names = (
13370:                   'Course' => 'group',
13371:                   'Community' => 'group',
13372:                 );
13373:     return $names{$crstype};
13374: }
13375: 
13376: sub course_types {
13377:     my @types = ('official','unofficial','community');
13378:     my %typename = (
13379:                          official   => 'Official course',
13380:                          unofficial => 'Unofficial course',
13381:                          community  => 'Community',
13382:                    );
13383:     return (\@types,\%typename);
13384: }
13385: 
13386: sub icon {
13387:     my ($file)=@_;
13388:     my $curfext = lc((split(/\./,$file))[-1]);
13389:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13390:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13391:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13392: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13393: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13394: 	            $curfext.".gif") {
13395: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13396: 		$curfext.".gif";
13397: 	}
13398:     }
13399:     return &lonhttpdurl($iconname);
13400: } 
13401: 
13402: sub lonhttpdurl {
13403: #
13404: # Had been used for "small fry" static images on separate port 8080.
13405: # Modify here if lightweight http functionality desired again.
13406: # Currently eliminated due to increasing firewall issues.
13407: #
13408:     my ($url)=@_;
13409:     return $url;
13410: }
13411: 
13412: sub connection_aborted {
13413:     my ($r)=@_;
13414:     $r->print(" ");$r->rflush();
13415:     my $c = $r->connection;
13416:     return $c->aborted();
13417: }
13418: 
13419: #    Escapes strings that may have embedded 's that will be put into
13420: #    strings as 'strings'.
13421: sub escape_single {
13422:     my ($input) = @_;
13423:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13424:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13425:     return $input;
13426: }
13427: 
13428: #  Same as escape_single, but escape's "'s  This 
13429: #  can be used for  "strings"
13430: sub escape_double {
13431:     my ($input) = @_;
13432:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13433:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13434:     return $input;
13435: }
13436:  
13437: #   Escapes the last element of a full URL.
13438: sub escape_url {
13439:     my ($url)   = @_;
13440:     my @urlslices = split(/\//, $url,-1);
13441:     my $lastitem = &escape(pop(@urlslices));
13442:     return join('/',@urlslices).'/'.$lastitem;
13443: }
13444: 
13445: sub compare_arrays {
13446:     my ($arrayref1,$arrayref2) = @_;
13447:     my (@difference,%count);
13448:     @difference = ();
13449:     %count = ();
13450:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13451:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13452:         foreach my $element (keys(%count)) {
13453:             if ($count{$element} == 1) {
13454:                 push(@difference,$element);
13455:             }
13456:         }
13457:     }
13458:     return @difference;
13459: }
13460: 
13461: # -------------------------------------------------------- Initialize user login
13462: sub init_user_environment {
13463:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13464:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13465: 
13466:     my $public=($username eq 'public' && $domain eq 'public');
13467: 
13468: # See if old ID present, if so, remove
13469: 
13470:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13471:     my $now=time;
13472: 
13473:     if ($public) {
13474: 	my $max_public=100;
13475: 	my $oldest;
13476: 	my $oldest_time=0;
13477: 	for(my $next=1;$next<=$max_public;$next++) {
13478: 	    if (-e $lonids."/publicuser_$next.id") {
13479: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13480: 		if ($mtime<$oldest_time || !$oldest_time) {
13481: 		    $oldest_time=$mtime;
13482: 		    $oldest=$next;
13483: 		}
13484: 	    } else {
13485: 		$cookie="publicuser_$next";
13486: 		last;
13487: 	    }
13488: 	}
13489: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13490:     } else {
13491: 	# if this isn't a robot, kill any existing non-robot sessions
13492: 	if (!$args->{'robot'}) {
13493: 	    opendir(DIR,$lonids);
13494: 	    while ($filename=readdir(DIR)) {
13495: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13496: 		    unlink($lonids.'/'.$filename);
13497: 		}
13498: 	    }
13499: 	    closedir(DIR);
13500: 	}
13501: # Give them a new cookie
13502: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13503: 		                   : $now.$$.int(rand(10000)));
13504: 	$cookie="$username\_$id\_$domain\_$authhost";
13505:     
13506: # Initialize roles
13507: 
13508: 	($userroles,$firstaccenv,$timerintenv) = 
13509:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13510:     }
13511: # ------------------------------------ Check browser type and MathML capability
13512: 
13513:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13514:         $clientunicode,$clientos) = &decode_user_agent($r);
13515: 
13516: # ------------------------------------------------------------- Get environment
13517: 
13518:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13519:     my ($tmp) = keys(%userenv);
13520:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13521:     } else {
13522: 	undef(%userenv);
13523:     }
13524:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13525: 	$form->{'interface'}=$userenv{'interface'};
13526:     }
13527:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13528: 
13529: # --------------- Do not trust query string to be put directly into environment
13530:     foreach my $option ('interface','localpath','localres') {
13531:         $form->{$option}=~s/[\n\r\=]//gs;
13532:     }
13533: # --------------------------------------------------------- Write first profile
13534: 
13535:     {
13536: 	my %initial_env = 
13537: 	    ("user.name"          => $username,
13538: 	     "user.domain"        => $domain,
13539: 	     "user.home"          => $authhost,
13540: 	     "browser.type"       => $clientbrowser,
13541: 	     "browser.version"    => $clientversion,
13542: 	     "browser.mathml"     => $clientmathml,
13543: 	     "browser.unicode"    => $clientunicode,
13544: 	     "browser.os"         => $clientos,
13545: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13546: 	     "request.course.fn"  => '',
13547: 	     "request.course.uri" => '',
13548: 	     "request.course.sec" => '',
13549: 	     "request.role"       => 'cm',
13550: 	     "request.role.adv"   => $env{'user.adv'},
13551: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13552: 
13553:         if ($form->{'localpath'}) {
13554: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13555: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13556:         }
13557: 	
13558: 	if ($form->{'interface'}) {
13559: 	    $form->{'interface'}=~s/\W//gs;
13560: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13561: 	    $env{'browser.interface'}=$form->{'interface'};
13562: 	}
13563: 
13564:         my %is_adv = ( is_adv => $env{'user.adv'} );
13565:         my %domdef;
13566:         unless ($domain eq 'public') {
13567:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13568:         }
13569: 
13570:         foreach my $tool ('aboutme','blog','portfolio') {
13571:             $userenv{'availabletools.'.$tool} = 
13572:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13573:                                                   undef,\%userenv,\%domdef,\%is_adv);
13574:         }
13575: 
13576:         foreach my $crstype ('official','unofficial','community') {
13577:             $userenv{'canrequest.'.$crstype} =
13578:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13579:                                                   'reload','requestcourses',
13580:                                                   \%userenv,\%domdef,\%is_adv);
13581:         }
13582: 
13583: 	$env{'user.environment'} = "$lonids/$cookie.id";
13584: 
13585: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
13586: 		 &GDBM_WRCREAT(),0640)) {
13587: 	    &_add_to_env(\%disk_env,\%initial_env);
13588: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
13589: 	    &_add_to_env(\%disk_env,$userroles);
13590:             if (ref($firstaccenv) eq 'HASH') {
13591:                 &_add_to_env(\%disk_env,$firstaccenv);
13592:             }
13593:             if (ref($timerintenv) eq 'HASH') {
13594:                 &_add_to_env(\%disk_env,$timerintenv);
13595:             }
13596: 	    if (ref($args->{'extra_env'})) {
13597: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
13598: 	    }
13599: 	    untie(%disk_env);
13600: 	} else {
13601: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
13602: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
13603: 	    return 'error: '.$!;
13604: 	}
13605:     }
13606:     $env{'request.role'}='cm';
13607:     $env{'request.role.adv'}=$env{'user.adv'};
13608:     $env{'browser.type'}=$clientbrowser;
13609: 
13610:     return $cookie;
13611: 
13612: }
13613: 
13614: sub _add_to_env {
13615:     my ($idf,$env_data,$prefix) = @_;
13616:     if (ref($env_data) eq 'HASH') {
13617:         while (my ($key,$value) = each(%$env_data)) {
13618: 	    $idf->{$prefix.$key} = $value;
13619: 	    $env{$prefix.$key}   = $value;
13620:         }
13621:     }
13622: }
13623: 
13624: # --- Get the symbolic name of a problem and the url
13625: sub get_symb {
13626:     my ($request,$silent) = @_;
13627:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
13628:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
13629:     if ($symb eq '') {
13630:         if (!$silent) {
13631:             if (ref($request)) { 
13632:                 $request->print("Unable to handle ambiguous references:$url:.");
13633:             }
13634:             return ();
13635:         }
13636:     }
13637:     &Apache::lonenc::check_decrypt(\$symb);
13638:     return ($symb);
13639: }
13640: 
13641: # --------------------------------------------------------------Get annotation
13642: 
13643: sub get_annotation {
13644:     my ($symb,$enc) = @_;
13645: 
13646:     my $key = $symb;
13647:     if (!$enc) {
13648:         $key =
13649:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
13650:     }
13651:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
13652:     return $annotation{$key};
13653: }
13654: 
13655: sub clean_symb {
13656:     my ($symb,$delete_enc) = @_;
13657: 
13658:     &Apache::lonenc::check_decrypt(\$symb);
13659:     my $enc = $env{'request.enc'};
13660:     if ($delete_enc) {
13661:         delete($env{'request.enc'});
13662:     }
13663: 
13664:     return ($symb,$enc);
13665: }
13666: 
13667: sub build_release_hashes {
13668:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
13669:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
13670:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
13671:                   (ref($randomizetry) eq 'HASH'));
13672:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
13673:         my ($item,$name,$value) = split(/:/,$key);
13674:         if ($item eq 'parameter') {
13675:             if (ref($checkparms->{$name}) eq 'ARRAY') {
13676:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
13677:                     push(@{$checkparms->{$name}},$value);
13678:                 }
13679:             } else {
13680:                 push(@{$checkparms->{$name}},$value);
13681:             }
13682:         } elsif ($item eq 'resourcetag') {
13683:             if ($name eq 'responsetype') {
13684:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
13685:             }
13686:         } elsif ($item eq 'course') {
13687:             if ($name eq 'crstype') {
13688:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
13689:             }
13690:         }
13691:     }
13692:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
13693:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
13694:     return;
13695: }
13696: 
13697: =pod
13698: 
13699: =back
13700: 
13701: =cut
13702: 
13703: 1;
13704: __END__;
13705: 

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