File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.45: download - view: text, annotated - select for diffs
Tue Aug 13 19:32:09 2013 UTC (10 years, 9 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1145

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.45 2013/08/13 19:32:09 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Authen::Captcha;
   76: use Captcha::reCAPTCHA;
   77: 
   78: # ---------------------------------------------- Designs
   79: use vars qw(%defaultdesign);
   80: 
   81: my $readit;
   82: 
   83: 
   84: ##
   85: ## Global Variables
   86: ##
   87: 
   88: 
   89: # ----------------------------------------------- SSI with retries:
   90: #
   91: 
   92: =pod
   93: 
   94: =head1 Server Side include with retries:
   95: 
   96: =over 4
   97: 
   98: =item * &ssi_with_retries(resource,retries form)
   99: 
  100: Performs an ssi with some number of retries.  Retries continue either
  101: until the result is ok or until the retry count supplied by the
  102: caller is exhausted.  
  103: 
  104: Inputs:
  105: 
  106: =over 4
  107: 
  108: resource   - Identifies the resource to insert.
  109: 
  110: retries    - Count of the number of retries allowed.
  111: 
  112: form       - Hash that identifies the rendering options.
  113: 
  114: =back
  115: 
  116: Returns:
  117: 
  118: =over 4
  119: 
  120: content    - The content of the response.  If retries were exhausted this is empty.
  121: 
  122: response   - The response from the last attempt (which may or may not have been successful.
  123: 
  124: =back
  125: 
  126: =back
  127: 
  128: =cut
  129: 
  130: sub ssi_with_retries {
  131:     my ($resource, $retries, %form) = @_;
  132: 
  133: 
  134:     my $ok = 0;			# True if we got a good response.
  135:     my $content;
  136:     my $response;
  137: 
  138:     # Try to get the ssi done. within the retries count:
  139: 
  140:     do {
  141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  142: 	$ok      = $response->is_success;
  143:         if (!$ok) {
  144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  145:         }
  146: 	$retries--;
  147:     } while (!$ok && ($retries > 0));
  148: 
  149:     if (!$ok) {
  150: 	$content = '';		# On error return an empty content.
  151:     }
  152:     return ($content, $response);
  153: 
  154: }
  155: 
  156: 
  157: 
  158: # ----------------------------------------------- Filetypes/Languages/Copyright
  159: my %language;
  160: my %supported_language;
  161: my %latex_language;		# For choosing hyphenation in <transl..>
  162: my %latex_language_bykey;	# for choosing hyphenation from metadata
  163: my %cprtag;
  164: my %scprtag;
  165: my %fe; my %fd; my %fm;
  166: my %category_extensions;
  167: 
  168: # ---------------------------------------------- Thesaurus variables
  169: #
  170: # %Keywords:
  171: #      A hash used by &keyword to determine if a word is considered a keyword.
  172: # $thesaurus_db_file 
  173: #      Scalar containing the full path to the thesaurus database.
  174: 
  175: my %Keywords;
  176: my $thesaurus_db_file;
  177: 
  178: #
  179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  180: # thesaurus.tab, and filecategories.tab.
  181: #
  182: BEGIN {
  183:     # Variable initialization
  184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  185:     #
  186:     unless ($readit) {
  187: # ------------------------------------------------------------------- languages
  188:     {
  189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  190:                                    '/language.tab';
  191:         if ( open(my $fh,"<$langtabfile") ) {
  192:             while (my $line = <$fh>) {
  193:                 next if ($line=~/^\#/);
  194:                 chomp($line);
  195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  196:                 $language{$key}=$val.' - '.$enc;
  197:                 if ($sup) {
  198:                     $supported_language{$key}=$sup;
  199:                 }
  200: 		if ($latex) {
  201: 		    $latex_language_bykey{$key} = $latex;
  202: 		    $latex_language{$two} = $latex;
  203: 		}
  204:             }
  205:             close($fh);
  206:         }
  207:     }
  208: # ------------------------------------------------------------------ copyrights
  209:     {
  210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  211:                                   '/copyright.tab';
  212:         if ( open (my $fh,"<$copyrightfile") ) {
  213:             while (my $line = <$fh>) {
  214:                 next if ($line=~/^\#/);
  215:                 chomp($line);
  216:                 my ($key,$val)=(split(/\s+/,$line,2));
  217:                 $cprtag{$key}=$val;
  218:             }
  219:             close($fh);
  220:         }
  221:     }
  222: # ----------------------------------------------------------- source copyrights
  223:     {
  224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  225:                                   '/source_copyright.tab';
  226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  227:             while (my $line = <$fh>) {
  228:                 next if ($line =~ /^\#/);
  229:                 chomp($line);
  230:                 my ($key,$val)=(split(/\s+/,$line,2));
  231:                 $scprtag{$key}=$val;
  232:             }
  233:             close($fh);
  234:         }
  235:     }
  236: 
  237: # -------------------------------------------------------------- default domain designs
  238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  239:     my $designfile = $designdir.'/default.tab';
  240:     if ( open (my $fh,"<$designfile") ) {
  241:         while (my $line = <$fh>) {
  242:             next if ($line =~ /^\#/);
  243:             chomp($line);
  244:             my ($key,$val)=(split(/\=/,$line));
  245:             if ($val) { $defaultdesign{$key}=$val; }
  246:         }
  247:         close($fh);
  248:     }
  249: 
  250: # ------------------------------------------------------------- file categories
  251:     {
  252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  253:                                   '/filecategories.tab';
  254:         if ( open (my $fh,"<$categoryfile") ) {
  255: 	    while (my $line = <$fh>) {
  256: 		next if ($line =~ /^\#/);
  257: 		chomp($line);
  258:                 my ($extension,$category)=(split(/\s+/,$line,2));
  259:                 push @{$category_extensions{lc($category)}},$extension;
  260:             }
  261:             close($fh);
  262:         }
  263: 
  264:     }
  265: # ------------------------------------------------------------------ file types
  266:     {
  267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  268:                '/filetypes.tab';
  269:         if ( open (my $fh,"<$typesfile") ) {
  270:             while (my $line = <$fh>) {
  271: 		next if ($line =~ /^\#/);
  272: 		chomp($line);
  273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  274:                 if ($descr ne '') {
  275:                     $fe{$ending}=lc($emb);
  276:                     $fd{$ending}=$descr;
  277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  278:                 }
  279:             }
  280:             close($fh);
  281:         }
  282:     }
  283:     &Apache::lonnet::logthis(
  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
  285:     $readit=1;
  286:     }  # end of unless($readit) 
  287:     
  288: }
  289: 
  290: ###############################################################
  291: ##           HTML and Javascript Helper Functions            ##
  292: ###############################################################
  293: 
  294: =pod 
  295: 
  296: =head1 HTML and Javascript Functions
  297: 
  298: =over 4
  299: 
  300: =item * &browser_and_searcher_javascript()
  301: 
  302: X<browsing, javascript>X<searching, javascript>Returns a string
  303: containing javascript with two functions, C<openbrowser> and
  304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  305: tags.
  306: 
  307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  308: 
  309: inputs: formname, elementname, only, omit
  310: 
  311: formname and elementname indicate the name of the html form and name of
  312: the element that the results of the browsing selection are to be placed in. 
  313: 
  314: Specifying 'only' will restrict the browser to displaying only files
  315: with the given extension.  Can be a comma separated list.
  316: 
  317: Specifying 'omit' will restrict the browser to NOT displaying files
  318: with the given extension.  Can be a comma separated list.
  319: 
  320: =item * &opensearcher(formname,elementname) [javascript]
  321: 
  322: Inputs: formname, elementname
  323: 
  324: formname and elementname specify the name of the html form and the name
  325: of the element the selection from the search results will be placed in.
  326: 
  327: =cut
  328: 
  329: sub browser_and_searcher_javascript {
  330:     my ($mode)=@_;
  331:     if (!defined($mode)) { $mode='edit'; }
  332:     my $resurl=&escape_single(&lastresurl());
  333:     return <<END;
  334: // <!-- BEGIN LON-CAPA Internal
  335:     var editbrowser = null;
  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
  337:         var url = '$resurl/?';
  338:         if (editbrowser == null) {
  339:             url += 'launch=1&';
  340:         }
  341:         url += 'catalogmode=interactive&';
  342:         url += 'mode=$mode&';
  343:         url += 'inhibitmenu=yes&';
  344:         url += 'form=' + formname + '&';
  345:         if (only != null) {
  346:             url += 'only=' + only + '&';
  347:         } else {
  348:             url += 'only=&';
  349: 	}
  350:         if (omit != null) {
  351:             url += 'omit=' + omit + '&';
  352:         } else {
  353:             url += 'omit=&';
  354: 	}
  355:         if (titleelement != null) {
  356:             url += 'titleelement=' + titleelement + '&';
  357:         } else {
  358: 	    url += 'titleelement=&';
  359: 	}
  360:         url += 'element=' + elementname + '';
  361:         var title = 'Browser';
  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  363:         options += ',width=700,height=600';
  364:         editbrowser = open(url,title,options,'1');
  365:         editbrowser.focus();
  366:     }
  367:     var editsearcher;
  368:     function opensearcher(formname,elementname,titleelement) {
  369:         var url = '/adm/searchcat?';
  370:         if (editsearcher == null) {
  371:             url += 'launch=1&';
  372:         }
  373:         url += 'catalogmode=interactive&';
  374:         url += 'mode=$mode&';
  375:         url += 'form=' + formname + '&';
  376:         if (titleelement != null) {
  377:             url += 'titleelement=' + titleelement + '&';
  378:         } else {
  379: 	    url += 'titleelement=&';
  380: 	}
  381:         url += 'element=' + elementname + '';
  382:         var title = 'Search';
  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  384:         options += ',width=700,height=600';
  385:         editsearcher = open(url,title,options,'1');
  386:         editsearcher.focus();
  387:     }
  388: // END LON-CAPA Internal -->
  389: END
  390: }
  391: 
  392: sub lastresurl {
  393:     if ($env{'environment.lastresurl'}) {
  394: 	return $env{'environment.lastresurl'}
  395:     } else {
  396: 	return '/res';
  397:     }
  398: }
  399: 
  400: sub storeresurl {
  401:     my $resurl=&Apache::lonnet::clutter(shift);
  402:     unless ($resurl=~/^\/res/) { return 0; }
  403:     $resurl=~s/\/$//;
  404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  406:     return 1;
  407: }
  408: 
  409: sub studentbrowser_javascript {
  410:    unless (
  411:             (($env{'request.course.id'}) && 
  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  414: 					  '/'.$env{'request.course.sec'})
  415: 	      ))
  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
  417:           ) { return ''; }  
  418:    return (<<'ENDSTDBRW');
  419: <script type="text/javascript" language="Javascript">
  420: // <![CDATA[
  421:     var stdeditbrowser;
  422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  423:         var url = '/adm/pickstudent?';
  424:         var filter;
  425: 	if (!ignorefilter) {
  426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  427: 	}
  428:         if (filter != null) {
  429:            if (filter != '') {
  430:                url += 'filter='+filter+'&';
  431: 	   }
  432:         }
  433:         url += 'form=' + formname + '&unameelement='+uname+
  434:                                     '&udomelement='+udom+
  435:                                     '&clicker='+clicker;
  436: 	if (roleflag) { url+="&roles=1"; }
  437:         if (courseadvonly) { url+="&courseadvonly=1"; }
  438:         var title = 'Student_Browser';
  439:         var options = 'scrollbars=1,resizable=1,menubar=0';
  440:         options += ',width=700,height=600';
  441:         stdeditbrowser = open(url,title,options,'1');
  442:         stdeditbrowser.focus();
  443:     }
  444: // ]]>
  445: </script>
  446: ENDSTDBRW
  447: }
  448: 
  449: sub resourcebrowser_javascript {
  450:    unless ($env{'request.course.id'}) { return ''; }
  451:    return (<<'ENDRESBRW');
  452: <script type="text/javascript" language="Javascript">
  453: // <![CDATA[
  454:     var reseditbrowser;
  455:     function openresbrowser(formname,reslink) {
  456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  457:         var title = 'Resource_Browser';
  458:         var options = 'scrollbars=1,resizable=1,menubar=0';
  459:         options += ',width=700,height=500';
  460:         reseditbrowser = open(url,title,options,'1');
  461:         reseditbrowser.focus();
  462:     }
  463: // ]]>
  464: </script>
  465: ENDRESBRW
  466: }
  467: 
  468: sub selectstudent_link {
  469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  473:    if ($env{'request.course.id'}) {  
  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  476: 					'/'.$env{'request.course.sec'})) {
  477: 	   return '';
  478:        }
  479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  480:        if ($courseadvonly)  {
  481:            $callargs .= ",'',1,1";
  482:        }
  483:        return '<span class="LC_nobreak">'.
  484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  485:               &mt('Select User').'</a></span>';
  486:    }
  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  488:        $callargs .= ",'',1"; 
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    return '';
  494: }
  495: 
  496: sub selectresource_link {
  497:    my ($form,$reslink,$arg)=@_;
  498:    
  499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  501:    unless ($env{'request.course.id'}) { return $arg; }
  502:    return '<span class="LC_nobreak">'.
  503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  504:               $arg.'</a></span>';
  505: }
  506: 
  507: 
  508: 
  509: sub authorbrowser_javascript {
  510:     return <<"ENDAUTHORBRW";
  511: <script type="text/javascript" language="JavaScript">
  512: // <![CDATA[
  513: var stdeditbrowser;
  514: 
  515: function openauthorbrowser(formname,udom) {
  516:     var url = '/adm/pickauthor?';
  517:     url += 'form='+formname+'&roledom='+udom;
  518:     var title = 'Author_Browser';
  519:     var options = 'scrollbars=1,resizable=1,menubar=0';
  520:     options += ',width=700,height=600';
  521:     stdeditbrowser = open(url,title,options,'1');
  522:     stdeditbrowser.focus();
  523: }
  524: 
  525: // ]]>
  526: </script>
  527: ENDAUTHORBRW
  528: }
  529: 
  530: sub coursebrowser_javascript {
  531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  532:         $credits_element) = @_;
  533:     my $wintitle = 'Course_Browser';
  534:     if ($crstype eq 'Community') {
  535:         $wintitle = 'Community_Browser';
  536:     }
  537:     my $id_functions = &javascript_index_functions();
  538:     my $output = '
  539: <script type="text/javascript" language="JavaScript">
  540: // <![CDATA[
  541:     var stdeditbrowser;'."\n";
  542: 
  543:     $output .= <<"ENDSTDBRW";
  544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  545:         var url = '/adm/pickcourse?';
  546:         var formid = getFormIdByName(formname);
  547:         var domainfilter = getDomainFromSelectbox(formname,udom);
  548:         if (domainfilter != null) {
  549:            if (domainfilter != '') {
  550:                url += 'domainfilter='+domainfilter+'&';
  551: 	   }
  552:         }
  553:         url += 'form=' + formname + '&cnumelement='+uname+
  554: 	                            '&cdomelement='+udom+
  555:                                     '&cnameelement='+desc;
  556:         if (extra_element !=null && extra_element != '') {
  557:             if (formname == 'rolechoice' || formname == 'studentform') {
  558:                 url += '&roleelement='+extra_element;
  559:                 if (domainfilter == null || domainfilter == '') {
  560:                     url += '&domainfilter='+extra_element;
  561:                 }
  562:             }
  563:             else {
  564:                 if (formname == 'portform') {
  565:                     url += '&setroles='+extra_element;
  566:                 } else {
  567:                     if (formname == 'rules') {
  568:                         url += '&fixeddom='+extra_element; 
  569:                     }
  570:                 }
  571:             }     
  572:         }
  573:         if (type != null && type != '') {
  574:             url += '&type='+type;
  575:         }
  576:         if (type_elem != null && type_elem != '') {
  577:             url += '&typeelement='+type_elem;
  578:         }
  579:         if (formname == 'ccrs') {
  580:             var ownername = document.forms[formid].ccuname.value;
  581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  582:             url += '&cloner='+ownername+':'+ownerdom;
  583:         }
  584:         if (multflag !=null && multflag != '') {
  585:             url += '&multiple='+multflag;
  586:         }
  587:         var title = '$wintitle';
  588:         var options = 'scrollbars=1,resizable=1,menubar=0';
  589:         options += ',width=700,height=600';
  590:         stdeditbrowser = open(url,title,options,'1');
  591:         stdeditbrowser.focus();
  592:     }
  593: $id_functions
  594: ENDSTDBRW
  595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  597:                                       $credits_element);
  598:     }
  599:     $output .= '
  600: // ]]>
  601: </script>';
  602:     return $output;
  603: }
  604: 
  605: sub javascript_index_functions {
  606:     return <<"ENDJS";
  607: 
  608: function getFormIdByName(formname) {
  609:     for (var i=0;i<document.forms.length;i++) {
  610:         if (document.forms[i].name == formname) {
  611:             return i;
  612:         }
  613:     }
  614:     return -1;
  615: }
  616: 
  617: function getIndexByName(formid,item) {
  618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  619:         if (document.forms[formid].elements[i].name == item) {
  620:             return i;
  621:         }
  622:     }
  623:     return -1;
  624: }
  625: 
  626: function getDomainFromSelectbox(formname,udom) {
  627:     var userdom;
  628:     var formid = getFormIdByName(formname);
  629:     if (formid > -1) {
  630:         var domid = getIndexByName(formid,udom);
  631:         if (domid > -1) {
  632:             if (document.forms[formid].elements[domid].type == 'select-one') {
  633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  634:             }
  635:             if (document.forms[formid].elements[domid].type == 'hidden') {
  636:                 userdom=document.forms[formid].elements[domid].value;
  637:             }
  638:         }
  639:     }
  640:     return userdom;
  641: }
  642: 
  643: ENDJS
  644: 
  645: }
  646: 
  647: sub javascript_array_indexof {
  648:     return <<ENDJS;
  649: <script type="text/javascript" language="JavaScript">
  650: // <![CDATA[
  651: 
  652: if (!Array.prototype.indexOf) {
  653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  654:         "use strict";
  655:         if (this === void 0 || this === null) {
  656:             throw new TypeError();
  657:         }
  658:         var t = Object(this);
  659:         var len = t.length >>> 0;
  660:         if (len === 0) {
  661:             return -1;
  662:         }
  663:         var n = 0;
  664:         if (arguments.length > 0) {
  665:             n = Number(arguments[1]);
  666:             if (n !== n) { // shortcut for verifying if it's NaN
  667:                 n = 0;
  668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  670:             }
  671:         }
  672:         if (n >= len) {
  673:             return -1;
  674:         }
  675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  676:         for (; k < len; k++) {
  677:             if (k in t && t[k] === searchElement) {
  678:                 return k;
  679:             }
  680:         }
  681:         return -1;
  682:     }
  683: }
  684: 
  685: // ]]>
  686: </script>
  687: 
  688: ENDJS
  689: 
  690: }
  691: 
  692: sub userbrowser_javascript {
  693:     my $id_functions = &javascript_index_functions();
  694:     return <<"ENDUSERBRW";
  695: 
  696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  697:     var url = '/adm/pickuser?';
  698:     var userdom = getDomainFromSelectbox(formname,udom);
  699:     if (userdom != null) {
  700:        if (userdom != '') {
  701:            url += 'srchdom='+userdom+'&';
  702:        }
  703:     }
  704:     url += 'form=' + formname + '&unameelement='+uname+
  705:                                 '&udomelement='+udom+
  706:                                 '&ulastelement='+ulast+
  707:                                 '&ufirstelement='+ufirst+
  708:                                 '&uemailelement='+uemail+
  709:                                 '&hideudomelement='+hideudom+
  710:                                 '&coursedom='+crsdom;
  711:     if ((caller != null) && (caller != undefined)) {
  712:         url += '&caller='+caller;
  713:     }
  714:     var title = 'User_Browser';
  715:     var options = 'scrollbars=1,resizable=1,menubar=0';
  716:     options += ',width=700,height=600';
  717:     var stdeditbrowser = open(url,title,options,'1');
  718:     stdeditbrowser.focus();
  719: }
  720: 
  721: function fix_domain (formname,udom,origdom,uname) {
  722:     var formid = getFormIdByName(formname);
  723:     if (formid > -1) {
  724:         var unameid = getIndexByName(formid,uname);
  725:         var domid = getIndexByName(formid,udom);
  726:         var hidedomid = getIndexByName(formid,origdom);
  727:         if (hidedomid > -1) {
  728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  729:             var unameval = document.forms[formid].elements[unameid].value;
  730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  731:                 if (domid > -1) {
  732:                     var slct = document.forms[formid].elements[domid];
  733:                     if (slct.type == 'select-one') {
  734:                         var i;
  735:                         for (i=0;i<slct.length;i++) {
  736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  737:                         }
  738:                     }
  739:                     if (slct.type == 'hidden') {
  740:                         slct.value = fixeddom;
  741:                     }
  742:                 }
  743:             }
  744:         }
  745:     }
  746:     return;
  747: }
  748: 
  749: $id_functions
  750: ENDUSERBRW
  751: }
  752: 
  753: sub setsec_javascript {
  754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  756:         $communityrolestr);
  757:     if ($role_element ne '') {
  758:         my @allroles = ('st','ta','ep','in','ad');
  759:         foreach my $crstype ('Course','Community') {
  760:             if ($crstype eq 'Community') {
  761:                 foreach my $role (@allroles) {
  762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  763:                 }
  764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  765:             } else {
  766:                 foreach my $role (@allroles) {
  767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  768:                 }
  769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  770:             }
  771:         }
  772:         $rolestr = '"'.join('","',@allroles).'"';
  773:         $courserolestr = '"'.join('","',@courserolenames).'"';
  774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  775:     }
  776:     my $setsections = qq|
  777: function setSect(sectionlist) {
  778:     var sectionsArray = new Array();
  779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  780:         sectionsArray = sectionlist.split(",");
  781:     }
  782:     var numSections = sectionsArray.length;
  783:     document.$formname.$sec_element.length = 0;
  784:     if (numSections == 0) {
  785:         document.$formname.$sec_element.multiple=false;
  786:         document.$formname.$sec_element.size=1;
  787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  788:     } else {
  789:         if (numSections == 1) {
  790:             document.$formname.$sec_element.multiple=false;
  791:             document.$formname.$sec_element.size=1;
  792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  795:         } else {
  796:             for (var i=0; i<numSections; i++) {
  797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  798:             }
  799:             document.$formname.$sec_element.multiple=true
  800:             if (numSections < 3) {
  801:                 document.$formname.$sec_element.size=numSections;
  802:             } else {
  803:                 document.$formname.$sec_element.size=3;
  804:             }
  805:             document.$formname.$sec_element.options[0].selected = false
  806:         }
  807:     }
  808: }
  809: 
  810: function setRole(crstype) {
  811: |;
  812:     if ($role_element eq '') {
  813:         $setsections .= '    return;
  814: }
  815: ';
  816:     } else {
  817:         $setsections .= qq|
  818:     var elementLength = document.$formname.$role_element.length;
  819:     var allroles = Array($rolestr);
  820:     var courserolenames = Array($courserolestr);
  821:     var communityrolenames = Array($communityrolestr);
  822:     if (elementLength != undefined) {
  823:         if (document.$formname.$role_element.options[5].value == 'cc') {
  824:             if (crstype == 'Course') {
  825:                 return;
  826:             } else {
  827:                 allroles[5] = 'co';
  828:                 for (var i=0; i<6; i++) {
  829:                     document.$formname.$role_element.options[i].value = allroles[i];
  830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  831:                 }
  832:             }
  833:         } else {
  834:             if (crstype == 'Community') {
  835:                 return;
  836:             } else {
  837:                 allroles[5] = 'cc';
  838:                 for (var i=0; i<6; i++) {
  839:                     document.$formname.$role_element.options[i].value = allroles[i];
  840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  841:                 }
  842:             }
  843:         }
  844:     }
  845:     return;
  846: }
  847: |;
  848:     }
  849:     if ($credits_element) {
  850:         $setsections .= qq|
  851: function setCredits(defaultcredits) {
  852:     document.$formname.$credits_element.value = defaultcredits;
  853:     return;
  854: }
  855: |;
  856:     }
  857:     return $setsections;
  858: }
  859: 
  860: sub selectcourse_link {
  861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  862:        $typeelement) = @_;
  863:    my $type = $selecttype;
  864:    my $linktext = &mt('Select Course');
  865:    if ($selecttype eq 'Community') {
  866:        $linktext = &mt('Select Community');
  867:    } elsif ($selecttype eq 'Course/Community') {
  868:        $linktext = &mt('Select Course/Community');
  869:        $type = '';
  870:    } elsif ($selecttype eq 'Select') {
  871:        $linktext = &mt('Select');
  872:        $type = '';
  873:    }
  874:    return '<span class="LC_nobreak">'
  875:          ."<a href='"
  876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  879:          ."'>".$linktext.'</a>'
  880:          .'</span>';
  881: }
  882: 
  883: sub selectauthor_link {
  884:    my ($form,$udom)=@_;
  885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  886:           &mt('Select Author').'</a>';
  887: }
  888: 
  889: sub selectuser_link {
  890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  891:         $coursedom,$linktext,$caller) = @_;
  892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  894:            ');">'.$linktext.'</a>';
  895: }
  896: 
  897: sub check_uncheck_jscript {
  898:     my $jscript = <<"ENDSCRT";
  899: function checkAll(field) {
  900:     if (field.length > 0) {
  901:         for (i = 0; i < field.length; i++) {
  902:             if (!field[i].disabled) {
  903:                 field[i].checked = true;
  904:             }
  905:         }
  906:     } else {
  907:         if (!field.disabled) {
  908:             field.checked = true;
  909:         }
  910:     }
  911: }
  912:  
  913: function uncheckAll(field) {
  914:     if (field.length > 0) {
  915:         for (i = 0; i < field.length; i++) {
  916:             field[i].checked = false ;
  917:         }
  918:     } else {
  919:         field.checked = false ;
  920:     }
  921: }
  922: ENDSCRT
  923:     return $jscript;
  924: }
  925: 
  926: sub select_timezone {
  927:    my ($name,$selected,$onchange,$includeempty)=@_;
  928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  929:    if ($includeempty) {
  930:        $output .= '<option value=""';
  931:        if (($selected eq '') || ($selected eq 'local')) {
  932:            $output .= ' selected="selected" ';
  933:        }
  934:        $output .= '> </option>';
  935:    }
  936:    my @timezones = DateTime::TimeZone->all_names;
  937:    foreach my $tzone (@timezones) {
  938:        $output.= '<option value="'.$tzone.'"';
  939:        if ($tzone eq $selected) {
  940:            $output.=' selected="selected"';
  941:        }
  942:        $output.=">$tzone</option>\n";
  943:    }
  944:    $output.="</select>";
  945:    return $output;
  946: }
  947: 
  948: sub select_datelocale {
  949:     my ($name,$selected,$onchange,$includeempty)=@_;
  950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  951:     if ($includeempty) {
  952:         $output .= '<option value=""';
  953:         if ($selected eq '') {
  954:             $output .= ' selected="selected" ';
  955:         }
  956:         $output .= '> </option>';
  957:     }
  958:     my (@possibles,%locale_names);
  959:     my @locales = DateTime::Locale::Catalog::Locales;
  960:     foreach my $locale (@locales) {
  961:         if (ref($locale) eq 'HASH') {
  962:             my $id = $locale->{'id'};
  963:             if ($id ne '') {
  964:                 my $en_terr = $locale->{'en_territory'};
  965:                 my $native_terr = $locale->{'native_territory'};
  966:                 my @languages = &Apache::lonlocal::preferred_languages();
  967:                 if (grep(/^en$/,@languages) || !@languages) {
  968:                     if ($en_terr ne '') {
  969:                         $locale_names{$id} = '('.$en_terr.')';
  970:                     } elsif ($native_terr ne '') {
  971:                         $locale_names{$id} = $native_terr;
  972:                     }
  973:                 } else {
  974:                     if ($native_terr ne '') {
  975:                         $locale_names{$id} = $native_terr.' ';
  976:                     } elsif ($en_terr ne '') {
  977:                         $locale_names{$id} = '('.$en_terr.')';
  978:                     }
  979:                 }
  980:                 push (@possibles,$id);
  981:             }
  982:         }
  983:     }
  984:     foreach my $item (sort(@possibles)) {
  985:         $output.= '<option value="'.$item.'"';
  986:         if ($item eq $selected) {
  987:             $output.=' selected="selected"';
  988:         }
  989:         $output.=">$item";
  990:         if ($locale_names{$item} ne '') {
  991:             $output.="  $locale_names{$item}</option>\n";
  992:         }
  993:         $output.="</option>\n";
  994:     }
  995:     $output.="</select>";
  996:     return $output;
  997: }
  998: 
  999: sub select_language {
 1000:     my ($name,$selected,$includeempty) = @_;
 1001:     my %langchoices;
 1002:     if ($includeempty) {
 1003:         %langchoices = ('' => 'No language preference');
 1004:     }
 1005:     foreach my $id (&languageids()) {
 1006:         my $code = &supportedlanguagecode($id);
 1007:         if ($code) {
 1008:             $langchoices{$code} = &plainlanguagedescription($id);
 1009:         }
 1010:     }
 1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1012:     return &select_form($selected,$name,\%langchoices);
 1013: }
 1014: 
 1015: =pod
 1016: 
 1017: =item * &linked_select_forms(...)
 1018: 
 1019: linked_select_forms returns a string containing a <script></script> block
 1020: and html for two <select> menus.  The select menus will be linked in that
 1021: changing the value of the first menu will result in new values being placed
 1022: in the second menu.  The values in the select menu will appear in alphabetical
 1023: order unless a defined order is provided.
 1024: 
 1025: linked_select_forms takes the following ordered inputs:
 1026: 
 1027: =over 4
 1028: 
 1029: =item * $formname, the name of the <form> tag
 1030: 
 1031: =item * $middletext, the text which appears between the <select> tags
 1032: 
 1033: =item * $firstdefault, the default value for the first menu
 1034: 
 1035: =item * $firstselectname, the name of the first <select> tag
 1036: 
 1037: =item * $secondselectname, the name of the second <select> tag
 1038: 
 1039: =item * $hashref, a reference to a hash containing the data for the menus.
 1040: 
 1041: =item * $menuorder, the order of values in the first menu
 1042: 
 1043: =item * $onchangefirst, additional javascript call to execute for an onchange
 1044:         event for the first <select> tag
 1045: 
 1046: =item * $onchangesecond, additional javascript call to execute for an onchange
 1047:         event for the second <select> tag
 1048: 
 1049: =back 
 1050: 
 1051: Below is an example of such a hash.  Only the 'text', 'default', and 
 1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1053: values for the first select menu.  The text that coincides with the 
 1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1055: and text for the second menu are given in the hash pointed to by 
 1056: $menu{$choice1}->{'select2'}.  
 1057: 
 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
 1059:                        default => "B3",
 1060:                        select2 => { 
 1061:                            B1 => "Choice B1",
 1062:                            B2 => "Choice B2",
 1063:                            B3 => "Choice B3",
 1064:                            B4 => "Choice B4"
 1065:                            },
 1066:                        order => ['B4','B3','B1','B2'],
 1067:                    },
 1068:                A2 => { text =>"Choice A2" ,
 1069:                        default => "C2",
 1070:                        select2 => { 
 1071:                            C1 => "Choice C1",
 1072:                            C2 => "Choice C2",
 1073:                            C3 => "Choice C3"
 1074:                            },
 1075:                        order => ['C2','C1','C3'],
 1076:                    },
 1077:                A3 => { text =>"Choice A3" ,
 1078:                        default => "D6",
 1079:                        select2 => { 
 1080:                            D1 => "Choice D1",
 1081:                            D2 => "Choice D2",
 1082:                            D3 => "Choice D3",
 1083:                            D4 => "Choice D4",
 1084:                            D5 => "Choice D5",
 1085:                            D6 => "Choice D6",
 1086:                            D7 => "Choice D7"
 1087:                            },
 1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1089:                    }
 1090:                );
 1091: 
 1092: =cut
 1093: 
 1094: sub linked_select_forms {
 1095:     my ($formname,
 1096:         $middletext,
 1097:         $firstdefault,
 1098:         $firstselectname,
 1099:         $secondselectname, 
 1100:         $hashref,
 1101:         $menuorder,
 1102:         $onchangefirst,
 1103:         $onchangesecond
 1104:         ) = @_;
 1105:     my $second = "document.$formname.$secondselectname";
 1106:     my $first = "document.$formname.$firstselectname";
 1107:     # output the javascript to do the changing
 1108:     my $result = '';
 1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1110:     $result.="// <![CDATA[\n";
 1111:     $result.="var select2data = new Object();\n";
 1112:     $" = '","';
 1113:     my $debug = '';
 1114:     foreach my $s1 (sort(keys(%$hashref))) {
 1115:         $result.="select2data.d_$s1 = new Object();\n";        
 1116:         $result.="select2data.d_$s1.def = new String('".
 1117:             $hashref->{$s1}->{'default'}."');\n";
 1118:         $result.="select2data.d_$s1.values = new Array(";
 1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1121:             @s2values = @{$hashref->{$s1}->{'order'}};
 1122:         }
 1123:         $result.="\"@s2values\");\n";
 1124:         $result.="select2data.d_$s1.texts = new Array(";        
 1125:         my @s2texts;
 1126:         foreach my $value (@s2values) {
 1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1128:         }
 1129:         $result.="\"@s2texts\");\n";
 1130:     }
 1131:     $"=' ';
 1132:     $result.= <<"END";
 1133: 
 1134: function select1_changed() {
 1135:     // Determine new choice
 1136:     var newvalue = "d_" + $first.value;
 1137:     // update select2
 1138:     var values     = select2data[newvalue].values;
 1139:     var texts      = select2data[newvalue].texts;
 1140:     var select2def = select2data[newvalue].def;
 1141:     var i;
 1142:     // out with the old
 1143:     for (i = 0; i < $second.options.length; i++) {
 1144:         $second.options[i] = null;
 1145:     }
 1146:     // in with the nuclear
 1147:     for (i=0;i<values.length; i++) {
 1148:         $second.options[i] = new Option(values[i]);
 1149:         $second.options[i].value = values[i];
 1150:         $second.options[i].text = texts[i];
 1151:         if (values[i] == select2def) {
 1152:             $second.options[i].selected = true;
 1153:         }
 1154:     }
 1155: }
 1156: // ]]>
 1157: </script>
 1158: END
 1159:     # output the initial values for the selection lists
 1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1161:     my @order = sort(keys(%{$hashref}));
 1162:     if (ref($menuorder) eq 'ARRAY') {
 1163:         @order = @{$menuorder};
 1164:     }
 1165:     foreach my $value (@order) {
 1166:         $result.="    <option value=\"$value\" ";
 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1169:     }
 1170:     $result .= "</select>\n";
 1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1172:     $result .= $middletext;
 1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1174:     if ($onchangesecond) {
 1175:         $result .= ' onchange="'.$onchangesecond.'"';
 1176:     }
 1177:     $result .= ">\n";
 1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1179:     
 1180:     my @secondorder = sort(keys(%select2));
 1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1183:     }
 1184:     foreach my $value (@secondorder) {
 1185:         $result.="    <option value=\"$value\" ";        
 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1187:         $result.=">".&mt($select2{$value})."</option>\n";
 1188:     }
 1189:     $result .= "</select>\n";
 1190:     #    return $debug;
 1191:     return $result;
 1192: }   #  end of sub linked_select_forms {
 1193: 
 1194: =pod
 1195: 
 1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1197: 
 1198: Returns a string corresponding to an HTML link to the given help
 1199: $topic, where $topic corresponds to the name of a .tex file in
 1200: /home/httpd/html/adm/help/tex, with underscores replaced by
 1201: spaces. 
 1202: 
 1203: $text will optionally be linked to the same topic, allowing you to
 1204: link text in addition to the graphic. If you do not want to link
 1205: text, but wish to specify one of the later parameters, pass an
 1206: empty string. 
 1207: 
 1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1209: the link will not open a new window. If false, the link will open
 1210: a new window using Javascript. (Default is false.) 
 1211: 
 1212: $width and $height are optional numerical parameters that will
 1213: override the width and height of the popped up window, which may
 1214: be useful for certain help topics with big pictures included.
 1215: 
 1216: $imgid is the id of the img tag used for the help icon. This may be
 1217: used in a javascript call to switch the image src.  See 
 1218: lonhtmlcommon::htmlareaselectactive() for an example.
 1219: 
 1220: =cut
 1221: 
 1222: sub help_open_topic {
 1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1224:     $text = "" if (not defined $text);
 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
 1226:     $width = 500 if (not defined $width);
 1227:     $height = 400 if (not defined $height);
 1228:     my $filename = $topic;
 1229:     $filename =~ s/ /_/g;
 1230: 
 1231:     my $template = "";
 1232:     my $link;
 1233:     
 1234:     $topic=~s/\W/\_/g;
 1235: 
 1236:     if (!$stayOnPage) {
 1237: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1238:     } elsif ($stayOnPage eq 'popup') {
 1239:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1240:     } else {
 1241: 	$link = "/adm/help/${filename}.hlp";
 1242:     }
 1243: 
 1244:     # Add the text
 1245:     if ($text ne "") {	
 1246: 	$template.='<span class="LC_help_open_topic">'
 1247:                   .'<a target="_top" href="'.$link.'">'
 1248:                   .$text.'</a>';
 1249:     }
 1250: 
 1251:     # (Always) Add the graphic
 1252:     my $title = &mt('Online Help');
 1253:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1254:     if ($imgid ne '') {
 1255:         $imgid = ' id="'.$imgid.'"';
 1256:     }
 1257:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1258:               .'<img src="'.$helpicon.'" border="0"'
 1259:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1260:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1261:               .' /></a>';
 1262:     if ($text ne "") {	
 1263:         $template.='</span>';
 1264:     }
 1265:     return $template;
 1266: 
 1267: }
 1268: 
 1269: # This is a quicky function for Latex cheatsheet editing, since it 
 1270: # appears in at least four places
 1271: sub helpLatexCheatsheet {
 1272:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1273:     my $out;
 1274:     my $addOther = '';
 1275:     if ($topic) {
 1276: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1277:     }
 1278:     $out = '<span>' # Start cheatsheet
 1279: 	  .$addOther
 1280:           .'<span>'
 1281: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1282: 	  .'</span> <span>'
 1283: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1284: 	  .'</span>';
 1285:     unless ($not_author) {
 1286:         $out .= ' <span>'
 1287: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1288: 	       .'</span>';
 1289:     }
 1290:     $out .= '</span>'; # End cheatsheet
 1291:     return $out;
 1292: }
 1293: 
 1294: sub general_help {
 1295:     my $helptopic='Student_Intro';
 1296:     if ($env{'request.role'}=~/^(ca|au)/) {
 1297: 	$helptopic='Authoring_Intro';
 1298:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1299: 	$helptopic='Course_Coordination_Intro';
 1300:     } elsif ($env{'request.role'}=~/^dc/) {
 1301:         $helptopic='Domain_Coordination_Intro';
 1302:     }
 1303:     return $helptopic;
 1304: }
 1305: 
 1306: sub update_help_link {
 1307:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1308:     my $origurl = $ENV{'REQUEST_URI'};
 1309:     $origurl=~s|^/~|/priv/|;
 1310:     my $timestamp = time;
 1311:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1312:         $$datum = &escape($$datum);
 1313:     }
 1314: 
 1315:     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";
 1316:     my $output .= <<"ENDOUTPUT";
 1317: <script type="text/javascript">
 1318: // <![CDATA[
 1319: banner_link = '$banner_link';
 1320: // ]]>
 1321: </script>
 1322: ENDOUTPUT
 1323:     return $output;
 1324: }
 1325: 
 1326: # now just updates the help link and generates a blue icon
 1327: sub help_open_menu {
 1328:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1329: 	= @_;    
 1330:     $stayOnPage = 1;
 1331:     my $output;
 1332:     if ($component_help) {
 1333: 	if (!$text) {
 1334: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1335: 				       $width,$height);
 1336: 	} else {
 1337: 	    my $help_text;
 1338: 	    $help_text=&unescape($topic);
 1339: 	    $output='<table><tr><td>'.
 1340: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1341: 				 $width,$height).'</td></tr></table>';
 1342: 	}
 1343:     }
 1344:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1345:     return $output.$banner_link;
 1346: }
 1347: 
 1348: sub top_nav_help {
 1349:     my ($text) = @_;
 1350:     $text = &mt($text);
 1351:     my $stay_on_page = 1;
 1352: 
 1353:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1354: 	                     : "javascript:helpMenu('open')";
 1355:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1356: 
 1357:     my $title = &mt('Get help');
 1358: 
 1359:     return <<"END";
 1360: $banner_link
 1361:  <a href="$link" title="$title">$text</a>
 1362: END
 1363: }
 1364: 
 1365: sub help_menu_js {
 1366:     my ($text) = @_;
 1367:     my $stayOnPage = 1;
 1368:     my $width = 620;
 1369:     my $height = 600;
 1370:     my $helptopic=&general_help();
 1371:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1372:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1373:     my $start_page =
 1374:         &Apache::loncommon::start_page('Help Menu', undef,
 1375: 				       {'frameset'    => 1,
 1376: 					'js_ready'    => 1,
 1377: 					'add_entries' => {
 1378: 					    'border' => '0',
 1379: 					    'rows'   => "110,*",},});
 1380:     my $end_page =
 1381:         &Apache::loncommon::end_page({'frameset' => 1,
 1382: 				      'js_ready' => 1,});
 1383: 
 1384:     my $template .= <<"ENDTEMPLATE";
 1385: <script type="text/javascript">
 1386: // <![CDATA[
 1387: // <!-- BEGIN LON-CAPA Internal
 1388: var banner_link = '';
 1389: function helpMenu(target) {
 1390:     var caller = this;
 1391:     if (target == 'open') {
 1392:         var newWindow = null;
 1393:         try {
 1394:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1395:         }
 1396:         catch(error) {
 1397:             writeHelp(caller);
 1398:             return;
 1399:         }
 1400:         if (newWindow) {
 1401:             caller = newWindow;
 1402:         }
 1403:     }
 1404:     writeHelp(caller);
 1405:     return;
 1406: }
 1407: function writeHelp(caller) {
 1408:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1409:     caller.document.close()
 1410:     caller.focus()
 1411: }
 1412: // END LON-CAPA Internal -->
 1413: // ]]>
 1414: </script>
 1415: ENDTEMPLATE
 1416:     return $template;
 1417: }
 1418: 
 1419: sub help_open_bug {
 1420:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1421:     unless ($env{'user.adv'}) { return ''; }
 1422:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1423:     $text = "" if (not defined $text);
 1424: 	$stayOnPage=1;
 1425:     $width = 600 if (not defined $width);
 1426:     $height = 600 if (not defined $height);
 1427: 
 1428:     $topic=~s/\W+/\+/g;
 1429:     my $link='';
 1430:     my $template='';
 1431:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1432: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1433:     if (!$stayOnPage)
 1434:     {
 1435: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1436:     }
 1437:     else
 1438:     {
 1439: 	$link = $url;
 1440:     }
 1441:     # Add the text
 1442:     if ($text ne "")
 1443:     {
 1444: 	$template .= 
 1445:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1446:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1447:     }
 1448: 
 1449:     # Add the graphic
 1450:     my $title = &mt('Report a Bug');
 1451:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1452:     $template .= <<"ENDTEMPLATE";
 1453:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1454: ENDTEMPLATE
 1455:     if ($text ne '') { $template.='</td></tr></table>' };
 1456:     return $template;
 1457: 
 1458: }
 1459: 
 1460: sub help_open_faq {
 1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1462:     unless ($env{'user.adv'}) { return ''; }
 1463:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1464:     $text = "" if (not defined $text);
 1465: 	$stayOnPage=1;
 1466:     $width = 350 if (not defined $width);
 1467:     $height = 400 if (not defined $height);
 1468: 
 1469:     $topic=~s/\W+/\+/g;
 1470:     my $link='';
 1471:     my $template='';
 1472:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1473:     if (!$stayOnPage)
 1474:     {
 1475: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1476:     }
 1477:     else
 1478:     {
 1479: 	$link = $url;
 1480:     }
 1481: 
 1482:     # Add the text
 1483:     if ($text ne "")
 1484:     {
 1485: 	$template .= 
 1486:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1487:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1488:     }
 1489: 
 1490:     # Add the graphic
 1491:     my $title = &mt('View the FAQ');
 1492:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1493:     $template .= <<"ENDTEMPLATE";
 1494:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1495: ENDTEMPLATE
 1496:     if ($text ne '') { $template.='</td></tr></table>' };
 1497:     return $template;
 1498: 
 1499: }
 1500: 
 1501: ###############################################################
 1502: ###############################################################
 1503: 
 1504: =pod
 1505: 
 1506: =item * &change_content_javascript():
 1507: 
 1508: This and the next function allow you to create small sections of an
 1509: otherwise static HTML page that you can update on the fly with
 1510: Javascript, even in Netscape 4.
 1511: 
 1512: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1513: must be written to the HTML page once. It will prove the Javascript
 1514: function "change(name, content)". Calling the change function with the
 1515: name of the section 
 1516: you want to update, matching the name passed to C<changable_area>, and
 1517: the new content you want to put in there, will put the content into
 1518: that area.
 1519: 
 1520: B<Note>: Netscape 4 only reserves enough space for the changable area
 1521: to contain room for the original contents. You need to "make space"
 1522: for whatever changes you wish to make, and be B<sure> to check your
 1523: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1524: it's adequate for updating a one-line status display, but little more.
 1525: This script will set the space to 100% width, so you only need to
 1526: worry about height in Netscape 4.
 1527: 
 1528: Modern browsers are much less limiting, and if you can commit to the
 1529: user not using Netscape 4, this feature may be used freely with
 1530: pretty much any HTML.
 1531: 
 1532: =cut
 1533: 
 1534: sub change_content_javascript {
 1535:     # If we're on Netscape 4, we need to use Layer-based code
 1536:     if ($env{'browser.type'} eq 'netscape' &&
 1537: 	$env{'browser.version'} =~ /^4\./) {
 1538: 	return (<<NETSCAPE4);
 1539: 	function change(name, content) {
 1540: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1541: 	    doc.open();
 1542: 	    doc.write(content);
 1543: 	    doc.close();
 1544: 	}
 1545: NETSCAPE4
 1546:     } else {
 1547: 	# Otherwise, we need to use semi-standards-compliant code
 1548: 	# (technically, "innerHTML" isn't standard but the equivalent
 1549: 	# is really scary, and every useful browser supports it
 1550: 	return (<<DOMBASED);
 1551: 	function change(name, content) {
 1552: 	    element = document.getElementById(name);
 1553: 	    element.innerHTML = content;
 1554: 	}
 1555: DOMBASED
 1556:     }
 1557: }
 1558: 
 1559: =pod
 1560: 
 1561: =item * &changable_area($name,$origContent):
 1562: 
 1563: This provides a "changable area" that can be modified on the fly via
 1564: the Javascript code provided in C<change_content_javascript>. $name is
 1565: the name you will use to reference the area later; do not repeat the
 1566: same name on a given HTML page more then once. $origContent is what
 1567: the area will originally contain, which can be left blank.
 1568: 
 1569: =cut
 1570: 
 1571: sub changable_area {
 1572:     my ($name, $origContent) = @_;
 1573: 
 1574:     if ($env{'browser.type'} eq 'netscape' &&
 1575: 	$env{'browser.version'} =~ /^4\./) {
 1576: 	# If this is netscape 4, we need to use the Layer tag
 1577: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1578:     } else {
 1579: 	return "<span id='$name'>$origContent</span>";
 1580:     }
 1581: }
 1582: 
 1583: =pod
 1584: 
 1585: =item * &viewport_geometry_js 
 1586: 
 1587: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1588: 
 1589: =cut
 1590: 
 1591: 
 1592: sub viewport_geometry_js { 
 1593:     return <<"GEOMETRY";
 1594: var Geometry = {};
 1595: function init_geometry() {
 1596:     if (Geometry.init) { return };
 1597:     Geometry.init=1;
 1598:     if (window.innerHeight) {
 1599:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1600:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1601:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1602:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1603:     }
 1604:     else if (document.documentElement && document.documentElement.clientHeight) {
 1605:         Geometry.getViewportHeight =
 1606:             function() { return document.documentElement.clientHeight; };
 1607:         Geometry.getViewportWidth =
 1608:             function() { return document.documentElement.clientWidth; };
 1609: 
 1610:         Geometry.getHorizontalScroll =
 1611:             function() { return document.documentElement.scrollLeft; };
 1612:         Geometry.getVerticalScroll =
 1613:             function() { return document.documentElement.scrollTop; };
 1614:     }
 1615:     else if (document.body.clientHeight) {
 1616:         Geometry.getViewportHeight =
 1617:             function() { return document.body.clientHeight; };
 1618:         Geometry.getViewportWidth =
 1619:             function() { return document.body.clientWidth; };
 1620:         Geometry.getHorizontalScroll =
 1621:             function() { return document.body.scrollLeft; };
 1622:         Geometry.getVerticalScroll =
 1623:             function() { return document.body.scrollTop; };
 1624:     }
 1625: }
 1626: 
 1627: GEOMETRY
 1628: }
 1629: 
 1630: =pod
 1631: 
 1632: =item * &viewport_size_js()
 1633: 
 1634: 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. 
 1635: 
 1636: =cut
 1637: 
 1638: sub viewport_size_js {
 1639:     my $geometry = &viewport_geometry_js();
 1640:     return <<"DIMS";
 1641: 
 1642: $geometry
 1643: 
 1644: function getViewportDims(width,height) {
 1645:     init_geometry();
 1646:     width.value = Geometry.getViewportWidth();
 1647:     height.value = Geometry.getViewportHeight();
 1648:     return;
 1649: }
 1650: 
 1651: DIMS
 1652: }
 1653: 
 1654: =pod
 1655: 
 1656: =item * &resize_textarea_js()
 1657: 
 1658: emits the needed javascript to resize a textarea to be as big as possible
 1659: 
 1660: creates a function resize_textrea that takes two IDs first should be
 1661: the id of the element to resize, second should be the id of a div that
 1662: surrounds everything that comes after the textarea, this routine needs
 1663: to be attached to the <body> for the onload and onresize events.
 1664: 
 1665: =back
 1666: 
 1667: =cut
 1668: 
 1669: sub resize_textarea_js {
 1670:     my $geometry = &viewport_geometry_js();
 1671:     return <<"RESIZE";
 1672:     <script type="text/javascript">
 1673: // <![CDATA[
 1674: $geometry
 1675: 
 1676: function getX(element) {
 1677:     var x = 0;
 1678:     while (element) {
 1679: 	x += element.offsetLeft;
 1680: 	element = element.offsetParent;
 1681:     }
 1682:     return x;
 1683: }
 1684: function getY(element) {
 1685:     var y = 0;
 1686:     while (element) {
 1687: 	y += element.offsetTop;
 1688: 	element = element.offsetParent;
 1689:     }
 1690:     return y;
 1691: }
 1692: 
 1693: 
 1694: function resize_textarea(textarea_id,bottom_id) {
 1695:     init_geometry();
 1696:     var textarea        = document.getElementById(textarea_id);
 1697:     //alert(textarea);
 1698: 
 1699:     var textarea_top    = getY(textarea);
 1700:     var textarea_height = textarea.offsetHeight;
 1701:     var bottom          = document.getElementById(bottom_id);
 1702:     var bottom_top      = getY(bottom);
 1703:     var bottom_height   = bottom.offsetHeight;
 1704:     var window_height   = Geometry.getViewportHeight();
 1705:     var fudge           = 23;
 1706:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1707:     if (new_height < 300) {
 1708: 	new_height = 300;
 1709:     }
 1710:     textarea.style.height=new_height+'px';
 1711: }
 1712: // ]]>
 1713: </script>
 1714: RESIZE
 1715: 
 1716: }
 1717: 
 1718: =pod
 1719: 
 1720: =head1 Excel and CSV file utility routines
 1721: 
 1722: =over 4
 1723: 
 1724: =cut
 1725: 
 1726: ###############################################################
 1727: ###############################################################
 1728: 
 1729: =pod
 1730: 
 1731: =item * &csv_translate($text) 
 1732: 
 1733: Translate $text to allow it to be output as a 'comma separated values' 
 1734: format.
 1735: 
 1736: =cut
 1737: 
 1738: ###############################################################
 1739: ###############################################################
 1740: sub csv_translate {
 1741:     my $text = shift;
 1742:     $text =~ s/\"/\"\"/g;
 1743:     $text =~ s/\n/ /g;
 1744:     return $text;
 1745: }
 1746: 
 1747: ###############################################################
 1748: ###############################################################
 1749: 
 1750: =pod
 1751: 
 1752: =item * &define_excel_formats()
 1753: 
 1754: Define some commonly used Excel cell formats.
 1755: 
 1756: Currently supported formats:
 1757: 
 1758: =over 4
 1759: 
 1760: =item header
 1761: 
 1762: =item bold
 1763: 
 1764: =item h1
 1765: 
 1766: =item h2
 1767: 
 1768: =item h3
 1769: 
 1770: =item h4
 1771: 
 1772: =item i
 1773: 
 1774: =item date
 1775: 
 1776: =back
 1777: 
 1778: Inputs: $workbook
 1779: 
 1780: Returns: $format, a hash reference.
 1781: 
 1782: 
 1783: =cut
 1784: 
 1785: ###############################################################
 1786: ###############################################################
 1787: sub define_excel_formats {
 1788:     my ($workbook) = @_;
 1789:     my $format;
 1790:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1791:                                                 bottom    => 1,
 1792:                                                 align     => 'center');
 1793:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1794:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1795:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1796:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1797:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1798:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1799:     $format->{'date'} = $workbook->add_format(num_format=>
 1800:                                             'mm/dd/yyyy hh:mm:ss');
 1801:     return $format;
 1802: }
 1803: 
 1804: ###############################################################
 1805: ###############################################################
 1806: 
 1807: =pod
 1808: 
 1809: =item * &create_workbook()
 1810: 
 1811: Create an Excel worksheet.  If it fails, output message on the
 1812: request object and return undefs.
 1813: 
 1814: Inputs: Apache request object
 1815: 
 1816: Returns (undef) on failure, 
 1817:     Excel worksheet object, scalar with filename, and formats 
 1818:     from &Apache::loncommon::define_excel_formats on success
 1819: 
 1820: =cut
 1821: 
 1822: ###############################################################
 1823: ###############################################################
 1824: sub create_workbook {
 1825:     my ($r) = @_;
 1826:         #
 1827:     # Create the excel spreadsheet
 1828:     my $filename = '/prtspool/'.
 1829:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1830:         time.'_'.rand(1000000000).'.xls';
 1831:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1832:     if (! defined($workbook)) {
 1833:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1834:         $r->print(
 1835:             '<p class="LC_error">'
 1836:            .&mt('Problems occurred in creating the new Excel file.')
 1837:            .' '.&mt('This error has been logged.')
 1838:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1839:            .'</p>'
 1840:         );
 1841:         return (undef);
 1842:     }
 1843:     #
 1844:     $workbook->set_tempdir(LONCAPA::tempdir());
 1845:     #
 1846:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1847:     return ($workbook,$filename,$format);
 1848: }
 1849: 
 1850: ###############################################################
 1851: ###############################################################
 1852: 
 1853: =pod
 1854: 
 1855: =item * &create_text_file()
 1856: 
 1857: Create a file to write to and eventually make available to the user.
 1858: If file creation fails, outputs an error message on the request object and 
 1859: return undefs.
 1860: 
 1861: Inputs: Apache request object, and file suffix
 1862: 
 1863: Returns (undef) on failure, 
 1864:     Filehandle and filename on success.
 1865: 
 1866: =cut
 1867: 
 1868: ###############################################################
 1869: ###############################################################
 1870: sub create_text_file {
 1871:     my ($r,$suffix) = @_;
 1872:     if (! defined($suffix)) { $suffix = 'txt'; };
 1873:     my $fh;
 1874:     my $filename = '/prtspool/'.
 1875:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1876:         time.'_'.rand(1000000000).'.'.$suffix;
 1877:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1878:     if (! defined($fh)) {
 1879:         $r->log_error("Couldn't open $filename for output $!");
 1880:         $r->print(
 1881:             '<p class="LC_error">'
 1882:            .&mt('Problems occurred in creating the output file.')
 1883:            .' '.&mt('This error has been logged.')
 1884:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1885:            .'</p>'
 1886:         );
 1887:     }
 1888:     return ($fh,$filename)
 1889: }
 1890: 
 1891: 
 1892: =pod 
 1893: 
 1894: =back
 1895: 
 1896: =cut
 1897: 
 1898: ###############################################################
 1899: ##        Home server <option> list generating code          ##
 1900: ###############################################################
 1901: 
 1902: # ------------------------------------------
 1903: 
 1904: sub domain_select {
 1905:     my ($name,$value,$multiple)=@_;
 1906:     my %domains=map { 
 1907: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1908:     } &Apache::lonnet::all_domains();
 1909:     if ($multiple) {
 1910: 	$domains{''}=&mt('Any domain');
 1911: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1912: 	return &multiple_select_form($name,$value,4,\%domains);
 1913:     } else {
 1914: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1915: 	return &select_form($name,$value,\%domains);
 1916:     }
 1917: }
 1918: 
 1919: #-------------------------------------------
 1920: 
 1921: =pod
 1922: 
 1923: =head1 Routines for form select boxes
 1924: 
 1925: =over 4
 1926: 
 1927: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1928: 
 1929: Returns a string containing a <select> element int multiple mode
 1930: 
 1931: 
 1932: Args:
 1933:   $name - name of the <select> element
 1934:   $value - scalar or array ref of values that should already be selected
 1935:   $size - number of rows long the select element is
 1936:   $hash - the elements should be 'option' => 'shown text'
 1937:           (shown text should already have been &mt())
 1938:   $order - (optional) array ref of the order to show the elements in
 1939: 
 1940: =cut
 1941: 
 1942: #-------------------------------------------
 1943: sub multiple_select_form {
 1944:     my ($name,$value,$size,$hash,$order)=@_;
 1945:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1946:     my $output='';
 1947:     if (! defined($size)) {
 1948:         $size = 4;
 1949:         if (scalar(keys(%$hash))<4) {
 1950:             $size = scalar(keys(%$hash));
 1951:         }
 1952:     }
 1953:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1954:     my @order;
 1955:     if (ref($order) eq 'ARRAY')  {
 1956:         @order = @{$order};
 1957:     } else {
 1958:         @order = sort(keys(%$hash));
 1959:     }
 1960:     if (exists($$hash{'select_form_order'})) {
 1961:         @order = @{$$hash{'select_form_order'}};
 1962:     }
 1963:         
 1964:     foreach my $key (@order) {
 1965:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1966:         $output.='selected="selected" ' if ($selected{$key});
 1967:         $output.='>'.$hash->{$key}."</option>\n";
 1968:     }
 1969:     $output.="</select>\n";
 1970:     return $output;
 1971: }
 1972: 
 1973: #-------------------------------------------
 1974: 
 1975: =pod
 1976: 
 1977: =item * &select_form($defdom,$name,$hashref,$onchange)
 1978: 
 1979: Returns a string containing a <select name='$name' size='1'> form to 
 1980: allow a user to select options from a ref to a hash containing:
 1981: option_name => displayed text. An optional $onchange can include
 1982: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1983: 
 1984: See lonrights.pm for an example invocation and use.
 1985: 
 1986: =cut
 1987: 
 1988: #-------------------------------------------
 1989: sub select_form {
 1990:     my ($def,$name,$hashref,$onchange) = @_;
 1991:     return unless (ref($hashref) eq 'HASH');
 1992:     if ($onchange) {
 1993:         $onchange = ' onchange="'.$onchange.'"';
 1994:     }
 1995:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1996:     my @keys;
 1997:     if (exists($hashref->{'select_form_order'})) {
 1998: 	@keys=@{$hashref->{'select_form_order'}};
 1999:     } else {
 2000: 	@keys=sort(keys(%{$hashref}));
 2001:     }
 2002:     foreach my $key (@keys) {
 2003:         $selectform.=
 2004: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2005:             ($key eq $def ? 'selected="selected" ' : '').
 2006:                 ">".$hashref->{$key}."</option>\n";
 2007:     }
 2008:     $selectform.="</select>";
 2009:     return $selectform;
 2010: }
 2011: 
 2012: # For display filters
 2013: 
 2014: sub display_filter {
 2015:     my ($context) = @_;
 2016:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2017:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2018:     my $phraseinput = 'hidden';
 2019:     my $includeinput = 'hidden';
 2020:     my ($checked,$includetypestext);
 2021:     if ($env{'form.displayfilter'} eq 'containing') {
 2022:         $phraseinput = 'text'; 
 2023:         if ($context eq 'parmslog') {
 2024:             $includeinput = 'checkbox';
 2025:             if ($env{'form.includetypes'}) {
 2026:                 $checked = ' checked="checked"';
 2027:             }
 2028:             $includetypestext = &mt('Include parameter types');
 2029:         }
 2030:     } else {
 2031:         $includetypestext = '&nbsp;';
 2032:     }
 2033:     my ($additional,$secondid,$thirdid);
 2034:     if ($context eq 'parmslog') {
 2035:         $additional = 
 2036:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2037:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2038:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2039:             '</label>';
 2040:         $secondid = 'includetypes';
 2041:         $thirdid = 'includetypestext';
 2042:     }
 2043:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2044:                                                     '$secondid','$thirdid')";
 2045:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2046: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2047: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2048: 	   '</label></span> <span class="LC_nobreak">'.
 2049:            &mt('Filter: [_1]',
 2050: 	   &select_form($env{'form.displayfilter'},
 2051: 			'displayfilter',
 2052: 			{'currentfolder' => 'Current folder/page',
 2053: 			 'containing' => 'Containing phrase',
 2054: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2055: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2056:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2057:                          '" />'.$additional;
 2058: }
 2059: 
 2060: sub display_filter_js {
 2061:     my $includetext = &mt('Include parameter types');
 2062:     return <<"ENDJS";
 2063:   
 2064: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2065:     var firstType = 'hidden';
 2066:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2067:         firstType = 'text';
 2068:     }
 2069:     firstObject = document.getElementById(firstid);
 2070:     if (typeof(firstObject) == 'object') {
 2071:         if (firstObject.type != firstType) {
 2072:             changeInputType(firstObject,firstType);
 2073:         }
 2074:     }
 2075:     if (context == 'parmslog') {
 2076:         var secondType = 'hidden';
 2077:         if (firstType == 'text') {
 2078:             secondType = 'checkbox';
 2079:         }
 2080:         secondObject = document.getElementById(secondid);  
 2081:         if (typeof(secondObject) == 'object') {
 2082:             if (secondObject.type != secondType) {
 2083:                 changeInputType(secondObject,secondType);
 2084:             }
 2085:         }
 2086:         var textItem = document.getElementById(thirdid);
 2087:         var currtext = textItem.innerHTML;
 2088:         var newtext;
 2089:         if (firstType == 'text') {
 2090:             newtext = '$includetext';
 2091:         } else {
 2092:             newtext = '&nbsp;';
 2093:         }
 2094:         if (currtext != newtext) {
 2095:             textItem.innerHTML = newtext;
 2096:         }
 2097:     }
 2098:     return;
 2099: }
 2100: 
 2101: function changeInputType(oldObject,newType) {
 2102:     var newObject = document.createElement('input');
 2103:     newObject.type = newType;
 2104:     if (oldObject.size) {
 2105:         newObject.size = oldObject.size;
 2106:     }
 2107:     if (oldObject.value) {
 2108:         newObject.value = oldObject.value;
 2109:     }
 2110:     if (oldObject.name) {
 2111:         newObject.name = oldObject.name;
 2112:     }
 2113:     if (oldObject.id) {
 2114:         newObject.id = oldObject.id;
 2115:     }
 2116:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2117:     return;
 2118: }
 2119: 
 2120: ENDJS
 2121: }
 2122: 
 2123: sub gradeleveldescription {
 2124:     my $gradelevel=shift;
 2125:     my %gradelevels=(0 => 'Not specified',
 2126: 		     1 => 'Grade 1',
 2127: 		     2 => 'Grade 2',
 2128: 		     3 => 'Grade 3',
 2129: 		     4 => 'Grade 4',
 2130: 		     5 => 'Grade 5',
 2131: 		     6 => 'Grade 6',
 2132: 		     7 => 'Grade 7',
 2133: 		     8 => 'Grade 8',
 2134: 		     9 => 'Grade 9',
 2135: 		     10 => 'Grade 10',
 2136: 		     11 => 'Grade 11',
 2137: 		     12 => 'Grade 12',
 2138: 		     13 => 'Grade 13',
 2139: 		     14 => '100 Level',
 2140: 		     15 => '200 Level',
 2141: 		     16 => '300 Level',
 2142: 		     17 => '400 Level',
 2143: 		     18 => 'Graduate Level');
 2144:     return &mt($gradelevels{$gradelevel});
 2145: }
 2146: 
 2147: sub select_level_form {
 2148:     my ($deflevel,$name)=@_;
 2149:     unless ($deflevel) { $deflevel=0; }
 2150:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2151:     for (my $i=0; $i<=18; $i++) {
 2152:         $selectform.="<option value=\"$i\" ".
 2153:             ($i==$deflevel ? 'selected="selected" ' : '').
 2154:                 ">".&gradeleveldescription($i)."</option>\n";
 2155:     }
 2156:     $selectform.="</select>";
 2157:     return $selectform;
 2158: }
 2159: 
 2160: #-------------------------------------------
 2161: 
 2162: =pod
 2163: 
 2164: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2165: 
 2166: Returns a string containing a <select name='$name' size='1'> form to 
 2167: allow a user to select the domain to preform an operation in.  
 2168: See loncreateuser.pm for an example invocation and use.
 2169: 
 2170: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2171: selected");
 2172: 
 2173: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2174: 
 2175: 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.
 2176: 
 2177: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2178: 
 2179: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2180: 
 2181: =cut
 2182: 
 2183: #-------------------------------------------
 2184: sub select_dom_form {
 2185:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2186:     if ($onchange) {
 2187:         $onchange = ' onchange="'.$onchange.'"';
 2188:     }
 2189:     my (@domains,%exclude);
 2190:     if (ref($incdoms) eq 'ARRAY') {
 2191:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2192:     } else {
 2193:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2194:     }
 2195:     if ($includeempty) { @domains=('',@domains); }
 2196:     if (ref($excdoms) eq 'ARRAY') {
 2197:         map { $exclude{$_} = 1; } @{$excdoms};
 2198:     }
 2199:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2200:     foreach my $dom (@domains) {
 2201:         next if ($exclude{$dom});
 2202:         $selectdomain.="<option value=\"$dom\" ".
 2203:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2204:         if ($showdomdesc) {
 2205:             if ($dom ne '') {
 2206:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2207:                 if ($domdesc ne '') {
 2208:                     $selectdomain .= ' ('.$domdesc.')';
 2209:                 }
 2210:             } 
 2211:         }
 2212:         $selectdomain .= "</option>\n";
 2213:     }
 2214:     $selectdomain.="</select>";
 2215:     return $selectdomain;
 2216: }
 2217: 
 2218: #-------------------------------------------
 2219: 
 2220: =pod
 2221: 
 2222: =item * &home_server_form_item($domain,$name,$defaultflag)
 2223: 
 2224: input: 4 arguments (two required, two optional) - 
 2225:     $domain - domain of new user
 2226:     $name - name of form element
 2227:     $default - Value of 'default' causes a default item to be first 
 2228:                             option, and selected by default. 
 2229:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2230:                             if 1 server found, or default, if 0 found.
 2231: output: returns 2 items: 
 2232: (a) form element which contains either:
 2233:    (i) <select name="$name">
 2234:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2235:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2236:        </select>
 2237:        form item if there are multiple library servers in $domain, or
 2238:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2239:        if there is only one library server in $domain.
 2240: 
 2241: (b) number of library servers found.
 2242: 
 2243: See loncreateuser.pm for example of use.
 2244: 
 2245: =cut
 2246: 
 2247: #-------------------------------------------
 2248: sub home_server_form_item {
 2249:     my ($domain,$name,$default,$hide) = @_;
 2250:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2251:     my $result;
 2252:     my $numlib = keys(%servers);
 2253:     if ($numlib > 1) {
 2254:         $result .= '<select name="'.$name.'" />'."\n";
 2255:         if ($default) {
 2256:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2257:                        '</option>'."\n";
 2258:         }
 2259:         foreach my $hostid (sort(keys(%servers))) {
 2260:             $result.= '<option value="'.$hostid.'">'.
 2261: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2262:         }
 2263:         $result .= '</select>'."\n";
 2264:     } elsif ($numlib == 1) {
 2265:         my $hostid;
 2266:         foreach my $item (keys(%servers)) {
 2267:             $hostid = $item;
 2268:         }
 2269:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2270:                    $hostid.'" />';
 2271:                    if (!$hide) {
 2272:                        $result .= $hostid.' '.$servers{$hostid};
 2273:                    }
 2274:                    $result .= "\n";
 2275:     } elsif ($default) {
 2276:         $result .= '<input type="hidden" name="'.$name.
 2277:                    '" value="default" />';
 2278:                    if (!$hide) {
 2279:                        $result .= &mt('default');
 2280:                    }
 2281:                    $result .= "\n";
 2282:     }
 2283:     return ($result,$numlib);
 2284: }
 2285: 
 2286: =pod
 2287: 
 2288: =back 
 2289: 
 2290: =cut
 2291: 
 2292: ###############################################################
 2293: ##                  Decoding User Agent                      ##
 2294: ###############################################################
 2295: 
 2296: =pod
 2297: 
 2298: =head1 Decoding the User Agent
 2299: 
 2300: =over 4
 2301: 
 2302: =item * &decode_user_agent()
 2303: 
 2304: Inputs: $r
 2305: 
 2306: Outputs:
 2307: 
 2308: =over 4
 2309: 
 2310: =item * $httpbrowser
 2311: 
 2312: =item * $clientbrowser
 2313: 
 2314: =item * $clientversion
 2315: 
 2316: =item * $clientmathml
 2317: 
 2318: =item * $clientunicode
 2319: 
 2320: =item * $clientos
 2321: 
 2322: =item * $clientmobile
 2323: 
 2324: =item * $clientinfo
 2325: 
 2326: =back
 2327: 
 2328: =back 
 2329: 
 2330: =cut
 2331: 
 2332: ###############################################################
 2333: ###############################################################
 2334: sub decode_user_agent {
 2335:     my ($r)=@_;
 2336:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2337:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2338:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2339:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2340:     my $clientbrowser='unknown';
 2341:     my $clientversion='0';
 2342:     my $clientmathml='';
 2343:     my $clientunicode='0';
 2344:     my $clientmobile=0;
 2345:     for (my $i=0;$i<=$#browsertype;$i++) {
 2346:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2347: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2348: 	    $clientbrowser=$bname;
 2349:             $httpbrowser=~/$vreg/i;
 2350: 	    $clientversion=$1;
 2351:             $clientmathml=($clientversion>=$minv);
 2352:             $clientunicode=($clientversion>=$univ);
 2353: 	}
 2354:     }
 2355:     my $clientos='unknown';
 2356:     my $clientinfo;
 2357:     if (($httpbrowser=~/linux/i) ||
 2358:         ($httpbrowser=~/unix/i) ||
 2359:         ($httpbrowser=~/ux/i) ||
 2360:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2361:     if (($httpbrowser=~/vax/i) ||
 2362:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2363:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2364:     if (($httpbrowser=~/mac/i) ||
 2365:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2366:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2367:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2368:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2369:         $clientmobile=lc($1);
 2370:     }
 2371:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2372:         $clientinfo = 'firefox-'.$1;
 2373:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2374:         $clientinfo = 'chromeframe-'.$1;
 2375:     }
 2376:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2377:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2378: }
 2379: 
 2380: ###############################################################
 2381: ##    Authentication changing form generation subroutines    ##
 2382: ###############################################################
 2383: ##
 2384: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2385: ## hash, and have reasonable default values.
 2386: ##
 2387: ##    formname = the name given in the <form> tag.
 2388: #-------------------------------------------
 2389: 
 2390: =pod
 2391: 
 2392: =head1 Authentication Routines
 2393: 
 2394: =over 4
 2395: 
 2396: =item * &authform_xxxxxx()
 2397: 
 2398: The authform_xxxxxx subroutines provide javascript and html forms which 
 2399: handle some of the conveniences required for authentication forms.  
 2400: This is not an optimal method, but it works.  
 2401: 
 2402: =over 4
 2403: 
 2404: =item * authform_header
 2405: 
 2406: =item * authform_authorwarning
 2407: 
 2408: =item * authform_nochange
 2409: 
 2410: =item * authform_kerberos
 2411: 
 2412: =item * authform_internal
 2413: 
 2414: =item * authform_filesystem
 2415: 
 2416: =back
 2417: 
 2418: See loncreateuser.pm for invocation and use examples.
 2419: 
 2420: =cut
 2421: 
 2422: #-------------------------------------------
 2423: sub authform_header{  
 2424:     my %in = (
 2425:         formname => 'cu',
 2426:         kerb_def_dom => '',
 2427:         @_,
 2428:     );
 2429:     $in{'formname'} = 'document.' . $in{'formname'};
 2430:     my $result='';
 2431: 
 2432: #---------------------------------------------- Code for upper case translation
 2433:     my $Javascript_toUpperCase;
 2434:     unless ($in{kerb_def_dom}) {
 2435:         $Javascript_toUpperCase =<<"END";
 2436:         switch (choice) {
 2437:            case 'krb': currentform.elements[choicearg].value =
 2438:                currentform.elements[choicearg].value.toUpperCase();
 2439:                break;
 2440:            default:
 2441:         }
 2442: END
 2443:     } else {
 2444:         $Javascript_toUpperCase = "";
 2445:     }
 2446: 
 2447:     my $radioval = "'nochange'";
 2448:     if (defined($in{'curr_authtype'})) {
 2449:         if ($in{'curr_authtype'} ne '') {
 2450:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2451:         }
 2452:     }
 2453:     my $argfield = 'null';
 2454:     if (defined($in{'mode'})) {
 2455:         if ($in{'mode'} eq 'modifycourse')  {
 2456:             if (defined($in{'curr_autharg'})) {
 2457:                 if ($in{'curr_autharg'} ne '') {
 2458:                     $argfield = "'$in{'curr_autharg'}'";
 2459:                 }
 2460:             }
 2461:         }
 2462:     }
 2463: 
 2464:     $result.=<<"END";
 2465: var current = new Object();
 2466: current.radiovalue = $radioval;
 2467: current.argfield = $argfield;
 2468: 
 2469: function changed_radio(choice,currentform) {
 2470:     var choicearg = choice + 'arg';
 2471:     // If a radio button in changed, we need to change the argfield
 2472:     if (current.radiovalue != choice) {
 2473:         current.radiovalue = choice;
 2474:         if (current.argfield != null) {
 2475:             currentform.elements[current.argfield].value = '';
 2476:         }
 2477:         if (choice == 'nochange') {
 2478:             current.argfield = null;
 2479:         } else {
 2480:             current.argfield = choicearg;
 2481:             switch(choice) {
 2482:                 case 'krb': 
 2483:                     currentform.elements[current.argfield].value = 
 2484:                         "$in{'kerb_def_dom'}";
 2485:                 break;
 2486:               default:
 2487:                 break;
 2488:             }
 2489:         }
 2490:     }
 2491:     return;
 2492: }
 2493: 
 2494: function changed_text(choice,currentform) {
 2495:     var choicearg = choice + 'arg';
 2496:     if (currentform.elements[choicearg].value !='') {
 2497:         $Javascript_toUpperCase
 2498:         // clear old field
 2499:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2500:             currentform.elements[current.argfield].value = '';
 2501:         }
 2502:         current.argfield = choicearg;
 2503:     }
 2504:     set_auth_radio_buttons(choice,currentform);
 2505:     return;
 2506: }
 2507: 
 2508: function set_auth_radio_buttons(newvalue,currentform) {
 2509:     var numauthchoices = currentform.login.length;
 2510:     if (typeof numauthchoices  == "undefined") {
 2511:         return;
 2512:     } 
 2513:     var i=0;
 2514:     while (i < numauthchoices) {
 2515:         if (currentform.login[i].value == newvalue) { break; }
 2516:         i++;
 2517:     }
 2518:     if (i == numauthchoices) {
 2519:         return;
 2520:     }
 2521:     current.radiovalue = newvalue;
 2522:     currentform.login[i].checked = true;
 2523:     return;
 2524: }
 2525: END
 2526:     return $result;
 2527: }
 2528: 
 2529: sub authform_authorwarning {
 2530:     my $result='';
 2531:     $result='<i>'.
 2532:         &mt('As a general rule, only authors or co-authors should be '.
 2533:             'filesystem authenticated '.
 2534:             '(which allows access to the server filesystem).')."</i>\n";
 2535:     return $result;
 2536: }
 2537: 
 2538: sub authform_nochange {
 2539:     my %in = (
 2540:               formname => 'document.cu',
 2541:               kerb_def_dom => 'MSU.EDU',
 2542:               @_,
 2543:           );
 2544:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2545:     my $result;
 2546:     if (!$authnum) {
 2547:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2548:     } else {
 2549:         $result = '<label>'.&mt('[_1] Do not change login data',
 2550:                   '<input type="radio" name="login" value="nochange" '.
 2551:                   'checked="checked" onclick="'.
 2552:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2553: 	    '</label>';
 2554:     }
 2555:     return $result;
 2556: }
 2557: 
 2558: sub authform_kerberos {
 2559:     my %in = (
 2560:               formname => 'document.cu',
 2561:               kerb_def_dom => 'MSU.EDU',
 2562:               kerb_def_auth => 'krb4',
 2563:               @_,
 2564:               );
 2565:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2566:         $autharg,$jscall);
 2567:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2568:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2569:        $check5 = ' checked="checked"';
 2570:     } else {
 2571:        $check4 = ' checked="checked"';
 2572:     }
 2573:     $krbarg = $in{'kerb_def_dom'};
 2574:     if (defined($in{'curr_authtype'})) {
 2575:         if ($in{'curr_authtype'} eq 'krb') {
 2576:             $krbcheck = ' checked="checked"';
 2577:             if (defined($in{'mode'})) {
 2578:                 if ($in{'mode'} eq 'modifyuser') {
 2579:                     $krbcheck = '';
 2580:                 }
 2581:             }
 2582:             if (defined($in{'curr_kerb_ver'})) {
 2583:                 if ($in{'curr_krb_ver'} eq '5') {
 2584:                     $check5 = ' checked="checked"';
 2585:                     $check4 = '';
 2586:                 } else {
 2587:                     $check4 = ' checked="checked"';
 2588:                     $check5 = '';
 2589:                 }
 2590:             }
 2591:             if (defined($in{'curr_autharg'})) {
 2592:                 $krbarg = $in{'curr_autharg'};
 2593:             }
 2594:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2595:                 if (defined($in{'curr_autharg'})) {
 2596:                     $result = 
 2597:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2598:         $in{'curr_autharg'},$krbver);
 2599:                 } else {
 2600:                     $result =
 2601:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2602:                 }
 2603:                 return $result; 
 2604:             }
 2605:         }
 2606:     } else {
 2607:         if ($authnum == 1) {
 2608:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2609:         }
 2610:     }
 2611:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2612:         return;
 2613:     } elsif ($authtype eq '') {
 2614:         if (defined($in{'mode'})) {
 2615:             if ($in{'mode'} eq 'modifycourse') {
 2616:                 if ($authnum == 1) {
 2617:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2618:                 }
 2619:             }
 2620:         }
 2621:     }
 2622:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2623:     if ($authtype eq '') {
 2624:         $authtype = '<input type="radio" name="login" value="krb" '.
 2625:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2626:                     $krbcheck.' />';
 2627:     }
 2628:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2629:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2630:          $in{'curr_authtype'} eq 'krb5') ||
 2631:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2632:          $in{'curr_authtype'} eq 'krb4')) {
 2633:         $result .= &mt
 2634:         ('[_1] Kerberos authenticated with domain [_2] '.
 2635:          '[_3] Version 4 [_4] Version 5 [_5]',
 2636:          '<label>'.$authtype,
 2637:          '</label><input type="text" size="10" name="krbarg" '.
 2638:              'value="'.$krbarg.'" '.
 2639:              'onchange="'.$jscall.'" />',
 2640:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2641:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2642: 	 '</label>');
 2643:     } elsif ($can_assign{'krb4'}) {
 2644:         $result .= &mt
 2645:         ('[_1] Kerberos authenticated with domain [_2] '.
 2646:          '[_3] Version 4 [_4]',
 2647:          '<label>'.$authtype,
 2648:          '</label><input type="text" size="10" name="krbarg" '.
 2649:              'value="'.$krbarg.'" '.
 2650:              'onchange="'.$jscall.'" />',
 2651:          '<label><input type="hidden" name="krbver" value="4" />',
 2652:          '</label>');
 2653:     } elsif ($can_assign{'krb5'}) {
 2654:         $result .= &mt
 2655:         ('[_1] Kerberos authenticated with domain [_2] '.
 2656:          '[_3] Version 5 [_4]',
 2657:          '<label>'.$authtype,
 2658:          '</label><input type="text" size="10" name="krbarg" '.
 2659:              'value="'.$krbarg.'" '.
 2660:              'onchange="'.$jscall.'" />',
 2661:          '<label><input type="hidden" name="krbver" value="5" />',
 2662:          '</label>');
 2663:     }
 2664:     return $result;
 2665: }
 2666: 
 2667: sub authform_internal {
 2668:     my %in = (
 2669:                 formname => 'document.cu',
 2670:                 kerb_def_dom => 'MSU.EDU',
 2671:                 @_,
 2672:                 );
 2673:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2674:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2675:     if (defined($in{'curr_authtype'})) {
 2676:         if ($in{'curr_authtype'} eq 'int') {
 2677:             if ($can_assign{'int'}) {
 2678:                 $intcheck = 'checked="checked" ';
 2679:                 if (defined($in{'mode'})) {
 2680:                     if ($in{'mode'} eq 'modifyuser') {
 2681:                         $intcheck = '';
 2682:                     }
 2683:                 }
 2684:                 if (defined($in{'curr_autharg'})) {
 2685:                     $intarg = $in{'curr_autharg'};
 2686:                 }
 2687:             } else {
 2688:                 $result = &mt('Currently internally authenticated.');
 2689:                 return $result;
 2690:             }
 2691:         }
 2692:     } else {
 2693:         if ($authnum == 1) {
 2694:             $authtype = '<input type="hidden" name="login" value="int" />';
 2695:         }
 2696:     }
 2697:     if (!$can_assign{'int'}) {
 2698:         return;
 2699:     } elsif ($authtype eq '') {
 2700:         if (defined($in{'mode'})) {
 2701:             if ($in{'mode'} eq 'modifycourse') {
 2702:                 if ($authnum == 1) {
 2703:                     $authtype = '<input type="radio" name="login" value="int" />';
 2704:                 }
 2705:             }
 2706:         }
 2707:     }
 2708:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2709:     if ($authtype eq '') {
 2710:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2711:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2712:     }
 2713:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2714:                $intarg.'" onchange="'.$jscall.'" />';
 2715:     $result = &mt
 2716:         ('[_1] Internally authenticated (with initial password [_2])',
 2717:          '<label>'.$authtype,'</label>'.$autharg);
 2718:     $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>';
 2719:     return $result;
 2720: }
 2721: 
 2722: sub authform_local {
 2723:     my %in = (
 2724:               formname => 'document.cu',
 2725:               kerb_def_dom => 'MSU.EDU',
 2726:               @_,
 2727:               );
 2728:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2729:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2730:     if (defined($in{'curr_authtype'})) {
 2731:         if ($in{'curr_authtype'} eq 'loc') {
 2732:             if ($can_assign{'loc'}) {
 2733:                 $loccheck = 'checked="checked" ';
 2734:                 if (defined($in{'mode'})) {
 2735:                     if ($in{'mode'} eq 'modifyuser') {
 2736:                         $loccheck = '';
 2737:                     }
 2738:                 }
 2739:                 if (defined($in{'curr_autharg'})) {
 2740:                     $locarg = $in{'curr_autharg'};
 2741:                 }
 2742:             } else {
 2743:                 $result = &mt('Currently using local (institutional) authentication.');
 2744:                 return $result;
 2745:             }
 2746:         }
 2747:     } else {
 2748:         if ($authnum == 1) {
 2749:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2750:         }
 2751:     }
 2752:     if (!$can_assign{'loc'}) {
 2753:         return;
 2754:     } elsif ($authtype eq '') {
 2755:         if (defined($in{'mode'})) {
 2756:             if ($in{'mode'} eq 'modifycourse') {
 2757:                 if ($authnum == 1) {
 2758:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2759:                 }
 2760:             }
 2761:         }
 2762:     }
 2763:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2764:     if ($authtype eq '') {
 2765:         $authtype = '<input type="radio" name="login" value="loc" '.
 2766:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2767:                     $jscall.'" />';
 2768:     }
 2769:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2770:                $locarg.'" onchange="'.$jscall.'" />';
 2771:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2772:                   '<label>'.$authtype,'</label>'.$autharg);
 2773:     return $result;
 2774: }
 2775: 
 2776: sub authform_filesystem {
 2777:     my %in = (
 2778:               formname => 'document.cu',
 2779:               kerb_def_dom => 'MSU.EDU',
 2780:               @_,
 2781:               );
 2782:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2783:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2784:     if (defined($in{'curr_authtype'})) {
 2785:         if ($in{'curr_authtype'} eq 'fsys') {
 2786:             if ($can_assign{'fsys'}) {
 2787:                 $fsyscheck = 'checked="checked" ';
 2788:                 if (defined($in{'mode'})) {
 2789:                     if ($in{'mode'} eq 'modifyuser') {
 2790:                         $fsyscheck = '';
 2791:                     }
 2792:                 }
 2793:             } else {
 2794:                 $result = &mt('Currently Filesystem Authenticated.');
 2795:                 return $result;
 2796:             }           
 2797:         }
 2798:     } else {
 2799:         if ($authnum == 1) {
 2800:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2801:         }
 2802:     }
 2803:     if (!$can_assign{'fsys'}) {
 2804:         return;
 2805:     } elsif ($authtype eq '') {
 2806:         if (defined($in{'mode'})) {
 2807:             if ($in{'mode'} eq 'modifycourse') {
 2808:                 if ($authnum == 1) {
 2809:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2810:                 }
 2811:             }
 2812:         }
 2813:     }
 2814:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2815:     if ($authtype eq '') {
 2816:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2817:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2818:                     $jscall.'" />';
 2819:     }
 2820:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2821:                ' onchange="'.$jscall.'" />';
 2822:     $result = &mt
 2823:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2824:          '<label><input type="radio" name="login" value="fsys" '.
 2825:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2826:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2827:                   'onchange="'.$jscall.'" />');
 2828:     return $result;
 2829: }
 2830: 
 2831: sub get_assignable_auth {
 2832:     my ($dom) = @_;
 2833:     if ($dom eq '') {
 2834:         $dom = $env{'request.role.domain'};
 2835:     }
 2836:     my %can_assign = (
 2837:                           krb4 => 1,
 2838:                           krb5 => 1,
 2839:                           int  => 1,
 2840:                           loc  => 1,
 2841:                      );
 2842:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2843:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2844:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2845:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2846:             my $context;
 2847:             if ($env{'request.role'} =~ /^au/) {
 2848:                 $context = 'author';
 2849:             } elsif ($env{'request.role'} =~ /^dc/) {
 2850:                 $context = 'domain';
 2851:             } elsif ($env{'request.course.id'}) {
 2852:                 $context = 'course';
 2853:             }
 2854:             if ($context) {
 2855:                 if (ref($authhash->{$context}) eq 'HASH') {
 2856:                    %can_assign = %{$authhash->{$context}}; 
 2857:                 }
 2858:             }
 2859:         }
 2860:     }
 2861:     my $authnum = 0;
 2862:     foreach my $key (keys(%can_assign)) {
 2863:         if ($can_assign{$key}) {
 2864:             $authnum ++;
 2865:         }
 2866:     }
 2867:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2868:         $authnum --;
 2869:     }
 2870:     return ($authnum,%can_assign);
 2871: }
 2872: 
 2873: ###############################################################
 2874: ##    Get Kerberos Defaults for Domain                 ##
 2875: ###############################################################
 2876: ##
 2877: ## Returns default kerberos version and an associated argument
 2878: ## as listed in file domain.tab. If not listed, provides
 2879: ## appropriate default domain and kerberos version.
 2880: ##
 2881: #-------------------------------------------
 2882: 
 2883: =pod
 2884: 
 2885: =item * &get_kerberos_defaults()
 2886: 
 2887: get_kerberos_defaults($target_domain) returns the default kerberos
 2888: version and domain. If not found, it defaults to version 4 and the 
 2889: domain of the server.
 2890: 
 2891: =over 4
 2892: 
 2893: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2894: 
 2895: =back
 2896: 
 2897: =back
 2898: 
 2899: =cut
 2900: 
 2901: #-------------------------------------------
 2902: sub get_kerberos_defaults {
 2903:     my $domain=shift;
 2904:     my ($krbdef,$krbdefdom);
 2905:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2906:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2907:         $krbdef = $domdefaults{'auth_def'};
 2908:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2909:     } else {
 2910:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2911:         my $krbdefdom=$1;
 2912:         $krbdefdom=~tr/a-z/A-Z/;
 2913:         $krbdef = "krb4";
 2914:     }
 2915:     return ($krbdef,$krbdefdom);
 2916: }
 2917: 
 2918: 
 2919: ###############################################################
 2920: ##                Thesaurus Functions                        ##
 2921: ###############################################################
 2922: 
 2923: =pod
 2924: 
 2925: =head1 Thesaurus Functions
 2926: 
 2927: =over 4
 2928: 
 2929: =item * &initialize_keywords()
 2930: 
 2931: Initializes the package variable %Keywords if it is empty.  Uses the
 2932: package variable $thesaurus_db_file.
 2933: 
 2934: =cut
 2935: 
 2936: ###################################################
 2937: 
 2938: sub initialize_keywords {
 2939:     return 1 if (scalar keys(%Keywords));
 2940:     # If we are here, %Keywords is empty, so fill it up
 2941:     #   Make sure the file we need exists...
 2942:     if (! -e $thesaurus_db_file) {
 2943:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2944:                                  " failed because it does not exist");
 2945:         return 0;
 2946:     }
 2947:     #   Set up the hash as a database
 2948:     my %thesaurus_db;
 2949:     if (! tie(%thesaurus_db,'GDBM_File',
 2950:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2951:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2952:                                  $thesaurus_db_file);
 2953:         return 0;
 2954:     } 
 2955:     #  Get the average number of appearances of a word.
 2956:     my $avecount = $thesaurus_db{'average.count'};
 2957:     #  Put keywords (those that appear > average) into %Keywords
 2958:     while (my ($word,$data)=each (%thesaurus_db)) {
 2959:         my ($count,undef) = split /:/,$data;
 2960:         $Keywords{$word}++ if ($count > $avecount);
 2961:     }
 2962:     untie %thesaurus_db;
 2963:     # Remove special values from %Keywords.
 2964:     foreach my $value ('total.count','average.count') {
 2965:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2966:   }
 2967:     return 1;
 2968: }
 2969: 
 2970: ###################################################
 2971: 
 2972: =pod
 2973: 
 2974: =item * &keyword($word)
 2975: 
 2976: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2977: than the average number of times in the thesaurus database.  Calls 
 2978: &initialize_keywords
 2979: 
 2980: =cut
 2981: 
 2982: ###################################################
 2983: 
 2984: sub keyword {
 2985:     return if (!&initialize_keywords());
 2986:     my $word=lc(shift());
 2987:     $word=~s/\W//g;
 2988:     return exists($Keywords{$word});
 2989: }
 2990: 
 2991: ###############################################################
 2992: 
 2993: =pod 
 2994: 
 2995: =item * &get_related_words()
 2996: 
 2997: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2998: an array of words.  If the keyword is not in the thesaurus, an empty array
 2999: will be returned.  The order of the words returned is determined by the
 3000: database which holds them.
 3001: 
 3002: Uses global $thesaurus_db_file.
 3003: 
 3004: 
 3005: =cut
 3006: 
 3007: ###############################################################
 3008: sub get_related_words {
 3009:     my $keyword = shift;
 3010:     my %thesaurus_db;
 3011:     if (! -e $thesaurus_db_file) {
 3012:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3013:                                  "failed because the file does not exist");
 3014:         return ();
 3015:     }
 3016:     if (! tie(%thesaurus_db,'GDBM_File',
 3017:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3018:         return ();
 3019:     } 
 3020:     my @Words=();
 3021:     my $count=0;
 3022:     if (exists($thesaurus_db{$keyword})) {
 3023: 	# The first element is the number of times
 3024: 	# the word appears.  We do not need it now.
 3025: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3026: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3027: 	my $threshold=$mostfrequentcount/10;
 3028:         foreach my $possibleword (@RelatedWords) {
 3029:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3030:             if ($wordcount>$threshold) {
 3031: 		push(@Words,$word);
 3032:                 $count++;
 3033:                 if ($count>10) { last; }
 3034: 	    }
 3035:         }
 3036:     }
 3037:     untie %thesaurus_db;
 3038:     return @Words;
 3039: }
 3040: 
 3041: =pod
 3042: 
 3043: =back
 3044: 
 3045: =cut
 3046: 
 3047: # -------------------------------------------------------------- Plaintext name
 3048: =pod
 3049: 
 3050: =head1 User Name Functions
 3051: 
 3052: =over 4
 3053: 
 3054: =item * &plainname($uname,$udom,$first)
 3055: 
 3056: Takes a users logon name and returns it as a string in
 3057: "first middle last generation" form 
 3058: if $first is set to 'lastname' then it returns it as
 3059: 'lastname generation, firstname middlename' if their is a lastname
 3060: 
 3061: =cut
 3062: 
 3063: 
 3064: ###############################################################
 3065: sub plainname {
 3066:     my ($uname,$udom,$first)=@_;
 3067:     return if (!defined($uname) || !defined($udom));
 3068:     my %names=&getnames($uname,$udom);
 3069:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3070: 					  $names{'middlename'},
 3071: 					  $names{'lastname'},
 3072: 					  $names{'generation'},$first);
 3073:     $name=~s/^\s+//;
 3074:     $name=~s/\s+$//;
 3075:     $name=~s/\s+/ /g;
 3076:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3077:     return $name;
 3078: }
 3079: 
 3080: # -------------------------------------------------------------------- Nickname
 3081: =pod
 3082: 
 3083: =item * &nickname($uname,$udom)
 3084: 
 3085: Gets a users name and returns it as a string as
 3086: 
 3087: "&quot;nickname&quot;"
 3088: 
 3089: if the user has a nickname or
 3090: 
 3091: "first middle last generation"
 3092: 
 3093: if the user does not
 3094: 
 3095: =cut
 3096: 
 3097: sub nickname {
 3098:     my ($uname,$udom)=@_;
 3099:     return if (!defined($uname) || !defined($udom));
 3100:     my %names=&getnames($uname,$udom);
 3101:     my $name=$names{'nickname'};
 3102:     if ($name) {
 3103:        $name='&quot;'.$name.'&quot;'; 
 3104:     } else {
 3105:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3106: 	     $names{'lastname'}.' '.$names{'generation'};
 3107:        $name=~s/\s+$//;
 3108:        $name=~s/\s+/ /g;
 3109:     }
 3110:     return $name;
 3111: }
 3112: 
 3113: sub getnames {
 3114:     my ($uname,$udom)=@_;
 3115:     return if (!defined($uname) || !defined($udom));
 3116:     if ($udom eq 'public' && $uname eq 'public') {
 3117: 	return ('lastname' => &mt('Public'));
 3118:     }
 3119:     my $id=$uname.':'.$udom;
 3120:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3121:     if ($cached) {
 3122: 	return %{$names};
 3123:     } else {
 3124: 	my %loadnames=&Apache::lonnet::get('environment',
 3125:                     ['firstname','middlename','lastname','generation','nickname'],
 3126: 					 $udom,$uname);
 3127: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3128: 	return %loadnames;
 3129:     }
 3130: }
 3131: 
 3132: # -------------------------------------------------------------------- getemails
 3133: 
 3134: =pod
 3135: 
 3136: =item * &getemails($uname,$udom)
 3137: 
 3138: Gets a user's email information and returns it as a hash with keys:
 3139: notification, critnotification, permanentemail
 3140: 
 3141: For notification and critnotification, values are comma-separated lists 
 3142: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3143:  
 3144: 
 3145: =cut
 3146: 
 3147: 
 3148: sub getemails {
 3149:     my ($uname,$udom)=@_;
 3150:     if ($udom eq 'public' && $uname eq 'public') {
 3151: 	return;
 3152:     }
 3153:     if (!$udom) { $udom=$env{'user.domain'}; }
 3154:     if (!$uname) { $uname=$env{'user.name'}; }
 3155:     my $id=$uname.':'.$udom;
 3156:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3157:     if ($cached) {
 3158: 	return %{$names};
 3159:     } else {
 3160: 	my %loadnames=&Apache::lonnet::get('environment',
 3161:                     			   ['notification','critnotification',
 3162: 					    'permanentemail'],
 3163: 					   $udom,$uname);
 3164: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3165: 	return %loadnames;
 3166:     }
 3167: }
 3168: 
 3169: sub flush_email_cache {
 3170:     my ($uname,$udom)=@_;
 3171:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3172:     if (!$uname) { $uname=$env{'user.name'};   }
 3173:     return if ($udom eq 'public' && $uname eq 'public');
 3174:     my $id=$uname.':'.$udom;
 3175:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3176: }
 3177: 
 3178: # -------------------------------------------------------------------- getlangs
 3179: 
 3180: =pod
 3181: 
 3182: =item * &getlangs($uname,$udom)
 3183: 
 3184: Gets a user's language preference and returns it as a hash with key:
 3185: language.
 3186: 
 3187: =cut
 3188: 
 3189: 
 3190: sub getlangs {
 3191:     my ($uname,$udom) = @_;
 3192:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3193:     if (!$uname) { $uname=$env{'user.name'};   }
 3194:     my $id=$uname.':'.$udom;
 3195:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3196:     if ($cached) {
 3197:         return %{$langs};
 3198:     } else {
 3199:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3200:                                            $udom,$uname);
 3201:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3202:         return %loadlangs;
 3203:     }
 3204: }
 3205: 
 3206: sub flush_langs_cache {
 3207:     my ($uname,$udom)=@_;
 3208:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3209:     if (!$uname) { $uname=$env{'user.name'};   }
 3210:     return if ($udom eq 'public' && $uname eq 'public');
 3211:     my $id=$uname.':'.$udom;
 3212:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3213: }
 3214: 
 3215: # ------------------------------------------------------------------ Screenname
 3216: 
 3217: =pod
 3218: 
 3219: =item * &screenname($uname,$udom)
 3220: 
 3221: Gets a users screenname and returns it as a string
 3222: 
 3223: =cut
 3224: 
 3225: sub screenname {
 3226:     my ($uname,$udom)=@_;
 3227:     if ($uname eq $env{'user.name'} &&
 3228: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3229:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3230:     return $names{'screenname'};
 3231: }
 3232: 
 3233: 
 3234: # ------------------------------------------------------------- Confirm Wrapper
 3235: =pod
 3236: 
 3237: =item * &confirmwrapper($message)
 3238: 
 3239: Wrap messages about completion of operation in box
 3240: 
 3241: =cut
 3242: 
 3243: sub confirmwrapper {
 3244:     my ($message)=@_;
 3245:     if ($message) {
 3246:         return "\n".'<div class="LC_confirm_box">'."\n"
 3247:                .$message."\n"
 3248:                .'</div>'."\n";
 3249:     } else {
 3250:         return $message;
 3251:     }
 3252: }
 3253: 
 3254: # ------------------------------------------------------------- Message Wrapper
 3255: 
 3256: sub messagewrapper {
 3257:     my ($link,$username,$domain,$subject,$text)=@_;
 3258:     return 
 3259:         '<a href="/adm/email?compose=individual&amp;'.
 3260:         'recname='.$username.'&amp;recdom='.$domain.
 3261: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3262:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3263: }
 3264: 
 3265: # --------------------------------------------------------------- Notes Wrapper
 3266: 
 3267: sub noteswrapper {
 3268:     my ($link,$un,$do)=@_;
 3269:     return 
 3270: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3271: }
 3272: 
 3273: # ------------------------------------------------------------- Aboutme Wrapper
 3274: 
 3275: sub aboutmewrapper {
 3276:     my ($link,$username,$domain,$target,$class)=@_;
 3277:     if (!defined($username)  && !defined($domain)) {
 3278:         return;
 3279:     }
 3280:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3281: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3282: }
 3283: 
 3284: # ------------------------------------------------------------ Syllabus Wrapper
 3285: 
 3286: sub syllabuswrapper {
 3287:     my ($linktext,$coursedir,$domain)=@_;
 3288:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3289: }
 3290: 
 3291: # -----------------------------------------------------------------------------
 3292: 
 3293: sub track_student_link {
 3294:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3295:     my $link ="/adm/trackstudent?";
 3296:     my $title = 'View recent activity';
 3297:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3298:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3299:         $link .= "selected_student=$sname:$sdom";
 3300:         $title .= ' of this student';
 3301:     } 
 3302:     if (defined($target) && $target !~ /^\s*$/) {
 3303:         $target = qq{target="$target"};
 3304:     } else {
 3305:         $target = '';
 3306:     }
 3307:     if ($start) { $link.='&amp;start='.$start; }
 3308:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3309:     $title = &mt($title);
 3310:     $linktext = &mt($linktext);
 3311:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3312: 	&help_open_topic('View_recent_activity');
 3313: }
 3314: 
 3315: sub slot_reservations_link {
 3316:     my ($linktext,$sname,$sdom,$target) = @_;
 3317:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3318:     my $title = 'View slot reservation history';
 3319:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3320:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3321:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3322:         $title .= ' of this student';
 3323:     }
 3324:     if (defined($target) && $target !~ /^\s*$/) {
 3325:         $target = qq{target="$target"};
 3326:     } else {
 3327:         $target = '';
 3328:     }
 3329:     $title = &mt($title);
 3330:     $linktext = &mt($linktext);
 3331:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3332: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3333: 
 3334: }
 3335: 
 3336: # ===================================================== Display a student photo
 3337: 
 3338: 
 3339: sub student_image_tag {
 3340:     my ($domain,$user)=@_;
 3341:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3342:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3343: 	return '<img src="'.$imgsrc.'" align="right" />';
 3344:     } else {
 3345: 	return '';
 3346:     }
 3347: }
 3348: 
 3349: =pod
 3350: 
 3351: =back
 3352: 
 3353: =head1 Access .tab File Data
 3354: 
 3355: =over 4
 3356: 
 3357: =item * &languageids() 
 3358: 
 3359: returns list of all language ids
 3360: 
 3361: =cut
 3362: 
 3363: sub languageids {
 3364:     return sort(keys(%language));
 3365: }
 3366: 
 3367: =pod
 3368: 
 3369: =item * &languagedescription() 
 3370: 
 3371: returns description of a specified language id
 3372: 
 3373: =cut
 3374: 
 3375: sub languagedescription {
 3376:     my $code=shift;
 3377:     return  ($supported_language{$code}?'* ':'').
 3378:             $language{$code}.
 3379: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3380: }
 3381: 
 3382: =pod
 3383: 
 3384: =item * &plainlanguagedescription
 3385: 
 3386: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3387: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3388: 
 3389: =cut
 3390: 
 3391: sub plainlanguagedescription {
 3392:     my $code=shift;
 3393:     return $language{$code};
 3394: }
 3395: 
 3396: =pod
 3397: 
 3398: =item * &supportedlanguagecode
 3399: 
 3400: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3401: code.
 3402: 
 3403: =cut
 3404: 
 3405: sub supportedlanguagecode {
 3406:     my $code=shift;
 3407:     return $supported_language{$code};
 3408: }
 3409: 
 3410: =pod
 3411: 
 3412: =item * &latexlanguage()
 3413: 
 3414: Given a language key code returns the correspondnig language to use
 3415: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3416: is no supported hyphenation for the language code.
 3417: 
 3418: =cut
 3419: 
 3420: sub latexlanguage {
 3421:     my $code = shift;
 3422:     return $latex_language{$code};
 3423: }
 3424: 
 3425: =pod
 3426: 
 3427: =item * &latexhyphenation()
 3428: 
 3429: Same as above but what's supplied is the language as it might be stored
 3430: in the metadata.
 3431: 
 3432: =cut
 3433: 
 3434: sub latexhyphenation {
 3435:     my $key = shift;
 3436:     return $latex_language_bykey{$key};
 3437: }
 3438: 
 3439: =pod
 3440: 
 3441: =item * &copyrightids() 
 3442: 
 3443: returns list of all copyrights
 3444: 
 3445: =cut
 3446: 
 3447: sub copyrightids {
 3448:     return sort(keys(%cprtag));
 3449: }
 3450: 
 3451: =pod
 3452: 
 3453: =item * &copyrightdescription() 
 3454: 
 3455: returns description of a specified copyright id
 3456: 
 3457: =cut
 3458: 
 3459: sub copyrightdescription {
 3460:     return &mt($cprtag{shift(@_)});
 3461: }
 3462: 
 3463: =pod
 3464: 
 3465: =item * &source_copyrightids() 
 3466: 
 3467: returns list of all source copyrights
 3468: 
 3469: =cut
 3470: 
 3471: sub source_copyrightids {
 3472:     return sort(keys(%scprtag));
 3473: }
 3474: 
 3475: =pod
 3476: 
 3477: =item * &source_copyrightdescription() 
 3478: 
 3479: returns description of a specified source copyright id
 3480: 
 3481: =cut
 3482: 
 3483: sub source_copyrightdescription {
 3484:     return &mt($scprtag{shift(@_)});
 3485: }
 3486: 
 3487: =pod
 3488: 
 3489: =item * &filecategories() 
 3490: 
 3491: returns list of all file categories
 3492: 
 3493: =cut
 3494: 
 3495: sub filecategories {
 3496:     return sort(keys(%category_extensions));
 3497: }
 3498: 
 3499: =pod
 3500: 
 3501: =item * &filecategorytypes() 
 3502: 
 3503: returns list of file types belonging to a given file
 3504: category
 3505: 
 3506: =cut
 3507: 
 3508: sub filecategorytypes {
 3509:     my ($cat) = @_;
 3510:     return @{$category_extensions{lc($cat)}};
 3511: }
 3512: 
 3513: =pod
 3514: 
 3515: =item * &fileembstyle() 
 3516: 
 3517: returns embedding style for a specified file type
 3518: 
 3519: =cut
 3520: 
 3521: sub fileembstyle {
 3522:     return $fe{lc(shift(@_))};
 3523: }
 3524: 
 3525: sub filemimetype {
 3526:     return $fm{lc(shift(@_))};
 3527: }
 3528: 
 3529: 
 3530: sub filecategoryselect {
 3531:     my ($name,$value)=@_;
 3532:     return &select_form($value,$name,
 3533:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3534: }
 3535: 
 3536: =pod
 3537: 
 3538: =item * &filedescription() 
 3539: 
 3540: returns description for a specified file type
 3541: 
 3542: =cut
 3543: 
 3544: sub filedescription {
 3545:     my $file_description = $fd{lc(shift())};
 3546:     $file_description =~ s:([\[\]]):~$1:g;
 3547:     return &mt($file_description);
 3548: }
 3549: 
 3550: =pod
 3551: 
 3552: =item * &filedescriptionex() 
 3553: 
 3554: returns description for a specified file type with
 3555: extra formatting
 3556: 
 3557: =cut
 3558: 
 3559: sub filedescriptionex {
 3560:     my $ex=shift;
 3561:     my $file_description = $fd{lc($ex)};
 3562:     $file_description =~ s:([\[\]]):~$1:g;
 3563:     return '.'.$ex.' '.&mt($file_description);
 3564: }
 3565: 
 3566: # End of .tab access
 3567: =pod
 3568: 
 3569: =back
 3570: 
 3571: =cut
 3572: 
 3573: # ------------------------------------------------------------------ File Types
 3574: sub fileextensions {
 3575:     return sort(keys(%fe));
 3576: }
 3577: 
 3578: # ----------------------------------------------------------- Display Languages
 3579: # returns a hash with all desired display languages
 3580: #
 3581: 
 3582: sub display_languages {
 3583:     my %languages=();
 3584:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3585: 	$languages{$lang}=1;
 3586:     }
 3587:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3588:     if ($env{'form.displaylanguage'}) {
 3589: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3590: 	    $languages{$lang}=1;
 3591:         }
 3592:     }
 3593:     return %languages;
 3594: }
 3595: 
 3596: sub languages {
 3597:     my ($possible_langs) = @_;
 3598:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3599:     if (!ref($possible_langs)) {
 3600: 	if( wantarray ) {
 3601: 	    return @preferred_langs;
 3602: 	} else {
 3603: 	    return $preferred_langs[0];
 3604: 	}
 3605:     }
 3606:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3607:     my @preferred_possibilities;
 3608:     foreach my $preferred_lang (@preferred_langs) {
 3609: 	if (exists($possibilities{$preferred_lang})) {
 3610: 	    push(@preferred_possibilities, $preferred_lang);
 3611: 	}
 3612:     }
 3613:     if( wantarray ) {
 3614: 	return @preferred_possibilities;
 3615:     }
 3616:     return $preferred_possibilities[0];
 3617: }
 3618: 
 3619: sub user_lang {
 3620:     my ($touname,$toudom,$fromcid) = @_;
 3621:     my @userlangs;
 3622:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3623:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3624:                     $env{'course.'.$fromcid.'.languages'}));
 3625:     } else {
 3626:         my %langhash = &getlangs($touname,$toudom);
 3627:         if ($langhash{'languages'} ne '') {
 3628:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3629:         } else {
 3630:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3631:             if ($domdefs{'lang_def'} ne '') {
 3632:                 @userlangs = ($domdefs{'lang_def'});
 3633:             }
 3634:         }
 3635:     }
 3636:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3637:     my $user_lh = Apache::localize->get_handle(@languages);
 3638:     return $user_lh;
 3639: }
 3640: 
 3641: 
 3642: ###############################################################
 3643: ##               Student Answer Attempts                     ##
 3644: ###############################################################
 3645: 
 3646: =pod
 3647: 
 3648: =head1 Alternate Problem Views
 3649: 
 3650: =over 4
 3651: 
 3652: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3653:     $getattempt, $regexp, $gradesub)
 3654: 
 3655: Return string with previous attempt on problem. Arguments:
 3656: 
 3657: =over 4
 3658: 
 3659: =item * $symb: Problem, including path
 3660: 
 3661: =item * $username: username of the desired student
 3662: 
 3663: =item * $domain: domain of the desired student
 3664: 
 3665: =item * $course: Course ID
 3666: 
 3667: =item * $getattempt: Leave blank for all attempts, otherwise put
 3668:     something
 3669: 
 3670: =item * $regexp: if string matches this regexp, the string will be
 3671:     sent to $gradesub
 3672: 
 3673: =item * $gradesub: routine that processes the string if it matches $regexp
 3674: 
 3675: =back
 3676: 
 3677: The output string is a table containing all desired attempts, if any.
 3678: 
 3679: =cut
 3680: 
 3681: sub get_previous_attempt {
 3682:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3683:   my $prevattempts='';
 3684:   no strict 'refs';
 3685:   if ($symb) {
 3686:     my (%returnhash)=
 3687:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3688:     if ($returnhash{'version'}) {
 3689:       my %lasthash=();
 3690:       my $version;
 3691:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3692:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3693: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3694:         }
 3695:       }
 3696:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3697:       $prevattempts.='<th>'.&mt('History').'</th>';
 3698:       my (%typeparts,%lasthidden);
 3699:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3700:       foreach my $key (sort(keys(%lasthash))) {
 3701: 	my ($ign,@parts) = split(/\./,$key);
 3702: 	if ($#parts > 0) {
 3703: 	  my $data=$parts[-1];
 3704:           next if ($data eq 'foilorder');
 3705: 	  pop(@parts);
 3706:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3707:           if ($data eq 'type') {
 3708:               unless ($showsurv) {
 3709:                   my $id = join(',',@parts);
 3710:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3711:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3712:                       $lasthidden{$ign.'.'.$id} = 1;
 3713:                   }
 3714:               }
 3715:           } 
 3716: 	} else {
 3717: 	  if ($#parts == 0) {
 3718: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3719: 	  } else {
 3720: 	    $prevattempts.='<th>'.$ign.'</th>';
 3721: 	  }
 3722: 	}
 3723:       }
 3724:       $prevattempts.=&end_data_table_header_row();
 3725:       if ($getattempt eq '') {
 3726: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3727:             my @hidden;
 3728:             if (%typeparts) {
 3729:                 foreach my $id (keys(%typeparts)) {
 3730:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3731:                         push(@hidden,$id);
 3732:                     }
 3733:                 }
 3734:             }
 3735:             $prevattempts.=&start_data_table_row().
 3736:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3737:             if (@hidden) {
 3738:                 foreach my $key (sort(keys(%lasthash))) {
 3739:                     next if ($key =~ /\.foilorder$/);
 3740:                     my $hide;
 3741:                     foreach my $id (@hidden) {
 3742:                         if ($key =~ /^\Q$id\E/) {
 3743:                             $hide = 1;
 3744:                             last;
 3745:                         }
 3746:                     }
 3747:                     if ($hide) {
 3748:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3749:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3750:                             my $value = &format_previous_attempt_value($key,
 3751:                                              $returnhash{$version.':'.$key});
 3752:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3753:                         } else {
 3754:                             $prevattempts.='<td>&nbsp;</td>';
 3755:                         }
 3756:                     } else {
 3757:                         if ($key =~ /\./) {
 3758:                             my $value = &format_previous_attempt_value($key,
 3759:                                               $returnhash{$version.':'.$key});
 3760:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3761:                         } else {
 3762:                             $prevattempts.='<td>&nbsp;</td>';
 3763:                         }
 3764:                     }
 3765:                 }
 3766:             } else {
 3767: 	        foreach my $key (sort(keys(%lasthash))) {
 3768:                     next if ($key =~ /\.foilorder$/);
 3769: 		    my $value = &format_previous_attempt_value($key,
 3770: 			            $returnhash{$version.':'.$key});
 3771: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3772: 	        }
 3773:             }
 3774: 	    $prevattempts.=&end_data_table_row();
 3775: 	 }
 3776:       }
 3777:       my @currhidden = keys(%lasthidden);
 3778:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3779:       foreach my $key (sort(keys(%lasthash))) {
 3780:           next if ($key =~ /\.foilorder$/);
 3781:           if (%typeparts) {
 3782:               my $hidden;
 3783:               foreach my $id (@currhidden) {
 3784:                   if ($key =~ /^\Q$id\E/) {
 3785:                       $hidden = 1;
 3786:                       last;
 3787:                   }
 3788:               }
 3789:               if ($hidden) {
 3790:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3791:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3792:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3793:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3794:                           $value = &$gradesub($value);
 3795:                       }
 3796:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3797:                   } else {
 3798:                       $prevattempts.='<td>&nbsp;</td>';
 3799:                   }
 3800:               } else {
 3801:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3802:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3803:                       $value = &$gradesub($value);
 3804:                   }
 3805:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3806:               }
 3807:           } else {
 3808: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3809: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3810:                   $value = &$gradesub($value);
 3811:               }
 3812: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3813:           }
 3814:       }
 3815:       $prevattempts.= &end_data_table_row().&end_data_table();
 3816:     } else {
 3817:       $prevattempts=
 3818: 	  &start_data_table().&start_data_table_row().
 3819: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3820: 	  &end_data_table_row().&end_data_table();
 3821:     }
 3822:   } else {
 3823:     $prevattempts=
 3824: 	  &start_data_table().&start_data_table_row().
 3825: 	  '<td>'.&mt('No data.').'</td>'.
 3826: 	  &end_data_table_row().&end_data_table();
 3827:   }
 3828: }
 3829: 
 3830: sub format_previous_attempt_value {
 3831:     my ($key,$value) = @_;
 3832:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3833: 	$value = &Apache::lonlocal::locallocaltime($value);
 3834:     } elsif (ref($value) eq 'ARRAY') {
 3835: 	$value = '('.join(', ', @{ $value }).')';
 3836:     } elsif ($key =~ /answerstring$/) {
 3837:         my %answers = &Apache::lonnet::str2hash($value);
 3838:         my @anskeys = sort(keys(%answers));
 3839:         if (@anskeys == 1) {
 3840:             my $answer = $answers{$anskeys[0]};
 3841:             if ($answer =~ m{\0}) {
 3842:                 $answer =~ s{\0}{,}g;
 3843:             }
 3844:             my $tag_internal_answer_name = 'INTERNAL';
 3845:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3846:                 $value = $answer; 
 3847:             } else {
 3848:                 $value = $anskeys[0].'='.$answer;
 3849:             }
 3850:         } else {
 3851:             foreach my $ans (@anskeys) {
 3852:                 my $answer = $answers{$ans};
 3853:                 if ($answer =~ m{\0}) {
 3854:                     $answer =~ s{\0}{,}g;
 3855:                 }
 3856:                 $value .=  $ans.'='.$answer.'<br />';;
 3857:             } 
 3858:         }
 3859:     } else {
 3860: 	$value = &unescape($value);
 3861:     }
 3862:     return $value;
 3863: }
 3864: 
 3865: 
 3866: sub relative_to_absolute {
 3867:     my ($url,$output)=@_;
 3868:     my $parser=HTML::TokeParser->new(\$output);
 3869:     my $token;
 3870:     my $thisdir=$url;
 3871:     my @rlinks=();
 3872:     while ($token=$parser->get_token) {
 3873: 	if ($token->[0] eq 'S') {
 3874: 	    if ($token->[1] eq 'a') {
 3875: 		if ($token->[2]->{'href'}) {
 3876: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3877: 		}
 3878: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3879: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3880: 	    } elsif ($token->[1] eq 'base') {
 3881: 		$thisdir=$token->[2]->{'href'};
 3882: 	    }
 3883: 	}
 3884:     }
 3885:     $thisdir=~s-/[^/]*$--;
 3886:     foreach my $link (@rlinks) {
 3887: 	unless (($link=~/^https?\:\/\//i) ||
 3888: 		($link=~/^\//) ||
 3889: 		($link=~/^javascript:/i) ||
 3890: 		($link=~/^mailto:/i) ||
 3891: 		($link=~/^\#/)) {
 3892: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3893: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3894: 	}
 3895:     }
 3896: # -------------------------------------------------- Deal with Applet codebases
 3897:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3898:     return $output;
 3899: }
 3900: 
 3901: =pod
 3902: 
 3903: =item * &get_student_view()
 3904: 
 3905: show a snapshot of what student was looking at
 3906: 
 3907: =cut
 3908: 
 3909: sub get_student_view {
 3910:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3911:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3912:   my (%form);
 3913:   my @elements=('symb','courseid','domain','username');
 3914:   foreach my $element (@elements) {
 3915:       $form{'grade_'.$element}=eval '$'.$element #'
 3916:   }
 3917:   if (defined($moreenv)) {
 3918:       %form=(%form,%{$moreenv});
 3919:   }
 3920:   if (defined($target)) { $form{'grade_target'} = $target; }
 3921:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3922:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3923:   $userview=~s/\<body[^\>]*\>//gi;
 3924:   $userview=~s/\<\/body\>//gi;
 3925:   $userview=~s/\<html\>//gi;
 3926:   $userview=~s/\<\/html\>//gi;
 3927:   $userview=~s/\<head\>//gi;
 3928:   $userview=~s/\<\/head\>//gi;
 3929:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3930:   $userview=&relative_to_absolute($feedurl,$userview);
 3931:   if (wantarray) {
 3932:      return ($userview,$response);
 3933:   } else {
 3934:      return $userview;
 3935:   }
 3936: }
 3937: 
 3938: sub get_student_view_with_retries {
 3939:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3940: 
 3941:     my $ok = 0;                 # True if we got a good response.
 3942:     my $content;
 3943:     my $response;
 3944: 
 3945:     # Try to get the student_view done. within the retries count:
 3946:     
 3947:     do {
 3948:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3949:          $ok      = $response->is_success;
 3950:          if (!$ok) {
 3951:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3952:          }
 3953:          $retries--;
 3954:     } while (!$ok && ($retries > 0));
 3955:     
 3956:     if (!$ok) {
 3957:        $content = '';          # On error return an empty content.
 3958:     }
 3959:     if (wantarray) {
 3960:        return ($content, $response);
 3961:     } else {
 3962:        return $content;
 3963:     }
 3964: }
 3965: 
 3966: =pod
 3967: 
 3968: =item * &get_student_answers() 
 3969: 
 3970: show a snapshot of how student was answering problem
 3971: 
 3972: =cut
 3973: 
 3974: sub get_student_answers {
 3975:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3976:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3977:   my (%moreenv);
 3978:   my @elements=('symb','courseid','domain','username');
 3979:   foreach my $element (@elements) {
 3980:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3981:   }
 3982:   $moreenv{'grade_target'}='answer';
 3983:   %moreenv=(%form,%moreenv);
 3984:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3985:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3986:   return $userview;
 3987: }
 3988: 
 3989: =pod
 3990: 
 3991: =item * &submlink()
 3992: 
 3993: Inputs: $text $uname $udom $symb $target
 3994: 
 3995: Returns: A link to grades.pm such as to see the SUBM view of a student
 3996: 
 3997: =cut
 3998: 
 3999: ###############################################
 4000: sub submlink {
 4001:     my ($text,$uname,$udom,$symb,$target)=@_;
 4002:     if (!($uname && $udom)) {
 4003: 	(my $cursymb, my $courseid,$udom,$uname)=
 4004: 	    &Apache::lonnet::whichuser($symb);
 4005: 	if (!$symb) { $symb=$cursymb; }
 4006:     }
 4007:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4008:     $symb=&escape($symb);
 4009:     if ($target) { $target=" target=\"$target\""; }
 4010:     return
 4011:         '<a href="/adm/grades?command=submission'.
 4012:         '&amp;symb='.$symb.
 4013:         '&amp;student='.$uname.
 4014:         '&amp;userdom='.$udom.'"'.
 4015:         $target.'>'.$text.'</a>';
 4016: }
 4017: ##############################################
 4018: 
 4019: =pod
 4020: 
 4021: =item * &pgrdlink()
 4022: 
 4023: Inputs: $text $uname $udom $symb $target
 4024: 
 4025: Returns: A link to grades.pm such as to see the PGRD view of a student
 4026: 
 4027: =cut
 4028: 
 4029: ###############################################
 4030: sub pgrdlink {
 4031:     my $link=&submlink(@_);
 4032:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4033:     return $link;
 4034: }
 4035: ##############################################
 4036: 
 4037: =pod
 4038: 
 4039: =item * &pprmlink()
 4040: 
 4041: Inputs: $text $uname $udom $symb $target
 4042: 
 4043: Returns: A link to parmset.pm such as to see the PPRM view of a
 4044: student and a specific resource
 4045: 
 4046: =cut
 4047: 
 4048: ###############################################
 4049: sub pprmlink {
 4050:     my ($text,$uname,$udom,$symb,$target)=@_;
 4051:     if (!($uname && $udom)) {
 4052: 	(my $cursymb, my $courseid,$udom,$uname)=
 4053: 	    &Apache::lonnet::whichuser($symb);
 4054: 	if (!$symb) { $symb=$cursymb; }
 4055:     }
 4056:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4057:     $symb=&escape($symb);
 4058:     if ($target) { $target="target=\"$target\""; }
 4059:     return '<a href="/adm/parmset?command=set&amp;'.
 4060: 	'symb='.$symb.'&amp;uname='.$uname.
 4061: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4062: }
 4063: ##############################################
 4064: 
 4065: =pod
 4066: 
 4067: =back
 4068: 
 4069: =cut
 4070: 
 4071: ###############################################
 4072: 
 4073: 
 4074: sub timehash {
 4075:     my ($thistime) = @_;
 4076:     my $timezone = &Apache::lonlocal::gettimezone();
 4077:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4078:                      ->set_time_zone($timezone);
 4079:     my $wday = $dt->day_of_week();
 4080:     if ($wday == 7) { $wday = 0; }
 4081:     return ( 'second' => $dt->second(),
 4082:              'minute' => $dt->minute(),
 4083:              'hour'   => $dt->hour(),
 4084:              'day'     => $dt->day_of_month(),
 4085:              'month'   => $dt->month(),
 4086:              'year'    => $dt->year(),
 4087:              'weekday' => $wday,
 4088:              'dayyear' => $dt->day_of_year(),
 4089:              'dlsav'   => $dt->is_dst() );
 4090: }
 4091: 
 4092: sub utc_string {
 4093:     my ($date)=@_;
 4094:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4095: }
 4096: 
 4097: sub maketime {
 4098:     my %th=@_;
 4099:     my ($epoch_time,$timezone,$dt);
 4100:     $timezone = &Apache::lonlocal::gettimezone();
 4101:     eval {
 4102:         $dt = DateTime->new( year   => $th{'year'},
 4103:                              month  => $th{'month'},
 4104:                              day    => $th{'day'},
 4105:                              hour   => $th{'hour'},
 4106:                              minute => $th{'minute'},
 4107:                              second => $th{'second'},
 4108:                              time_zone => $timezone,
 4109:                          );
 4110:     };
 4111:     if (!$@) {
 4112:         $epoch_time = $dt->epoch;
 4113:         if ($epoch_time) {
 4114:             return $epoch_time;
 4115:         }
 4116:     }
 4117:     return POSIX::mktime(
 4118:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4119:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4120: }
 4121: 
 4122: #########################################
 4123: 
 4124: sub findallcourses {
 4125:     my ($roles,$uname,$udom) = @_;
 4126:     my %roles;
 4127:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4128:     my %courses;
 4129:     my $now=time;
 4130:     if (!defined($uname)) {
 4131:         $uname = $env{'user.name'};
 4132:     }
 4133:     if (!defined($udom)) {
 4134:         $udom = $env{'user.domain'};
 4135:     }
 4136:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4137:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4138:         if (!%roles) {
 4139:             %roles = (
 4140:                        cc => 1,
 4141:                        co => 1,
 4142:                        in => 1,
 4143:                        ep => 1,
 4144:                        ta => 1,
 4145:                        cr => 1,
 4146:                        st => 1,
 4147:              );
 4148:         }
 4149:         foreach my $entry (keys(%roleshash)) {
 4150:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4151:             if ($trole =~ /^cr/) { 
 4152:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4153:             } else {
 4154:                 next if (!exists($roles{$trole}));
 4155:             }
 4156:             if ($tend) {
 4157:                 next if ($tend < $now);
 4158:             }
 4159:             if ($tstart) {
 4160:                 next if ($tstart > $now);
 4161:             }
 4162:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4163:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4164:             my $value = $trole.'/'.$cdom.'/';
 4165:             if ($secpart eq '') {
 4166:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4167:                 $sec = 'none';
 4168:                 $value .= $cnum.'/';
 4169:             } else {
 4170:                 $cnum = $cnumpart;
 4171:                 ($sec,$role) = split(/_/,$secpart);
 4172:                 $value .= $cnum.'/'.$sec;
 4173:             }
 4174:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4175:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4176:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4177:                 }
 4178:             } else {
 4179:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4180:             }
 4181:         }
 4182:     } else {
 4183:         foreach my $key (keys(%env)) {
 4184: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4185:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4186: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4187: 	        next if ($role eq 'ca' || $role eq 'aa');
 4188: 	        next if (%roles && !exists($roles{$role}));
 4189: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4190:                 my $active=1;
 4191:                 if ($starttime) {
 4192: 		    if ($now<$starttime) { $active=0; }
 4193:                 }
 4194:                 if ($endtime) {
 4195:                     if ($now>$endtime) { $active=0; }
 4196:                 }
 4197:                 if ($active) {
 4198:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4199:                     if ($sec eq '') {
 4200:                         $sec = 'none';
 4201:                     } else {
 4202:                         $value .= $sec;
 4203:                     }
 4204:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4205:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4206:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4207:                         }
 4208:                     } else {
 4209:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4210:                     }
 4211:                 }
 4212:             }
 4213:         }
 4214:     }
 4215:     return %courses;
 4216: }
 4217: 
 4218: ###############################################
 4219: 
 4220: sub blockcheck {
 4221:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4222: 
 4223:     if (!defined($udom)) {
 4224:         $udom = $env{'user.domain'};
 4225:     }
 4226:     if (!defined($uname)) {
 4227:         $uname = $env{'user.name'};
 4228:     }
 4229: 
 4230:     # If uname and udom are for a course, check for blocks in the course.
 4231: 
 4232:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4233:         my ($startblock,$endblock,$triggerblock) = 
 4234:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4235:         return ($startblock,$endblock,$triggerblock);
 4236:     }
 4237: 
 4238:     my $startblock = 0;
 4239:     my $endblock = 0;
 4240:     my $triggerblock = '';
 4241:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4242: 
 4243:     # If uname is for a user, and activity is course-specific, i.e.,
 4244:     # boards, chat or groups, check for blocking in current course only.
 4245: 
 4246:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4247:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4248:         foreach my $key (keys(%live_courses)) {
 4249:             if ($key ne $env{'request.course.id'}) {
 4250:                 delete($live_courses{$key});
 4251:             }
 4252:         }
 4253:     }
 4254: 
 4255:     my $otheruser = 0;
 4256:     my %own_courses;
 4257:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4258:         # Resource belongs to user other than current user.
 4259:         $otheruser = 1;
 4260:         # Gather courses for current user
 4261:         %own_courses = 
 4262:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4263:     }
 4264: 
 4265:     # Gather active course roles - course coordinator, instructor, 
 4266:     # exam proctor, ta, student, or custom role.
 4267: 
 4268:     foreach my $course (keys(%live_courses)) {
 4269:         my ($cdom,$cnum);
 4270:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4271:             $cdom = $env{'course.'.$course.'.domain'};
 4272:             $cnum = $env{'course.'.$course.'.num'};
 4273:         } else {
 4274:             ($cdom,$cnum) = split(/_/,$course); 
 4275:         }
 4276:         my $no_ownblock = 0;
 4277:         my $no_userblock = 0;
 4278:         if ($otheruser && $activity ne 'com') {
 4279:             # Check if current user has 'evb' priv for this
 4280:             if (defined($own_courses{$course})) {
 4281:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4282:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4283:                     if ($sec ne 'none') {
 4284:                         $checkrole .= '/'.$sec;
 4285:                     }
 4286:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4287:                         $no_ownblock = 1;
 4288:                         last;
 4289:                     }
 4290:                 }
 4291:             }
 4292:             # if they have 'evb' priv and are currently not playing student
 4293:             next if (($no_ownblock) &&
 4294:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4295:         }
 4296:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4297:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4298:             if ($sec ne 'none') {
 4299:                 $checkrole .= '/'.$sec;
 4300:             }
 4301:             if ($otheruser) {
 4302:                 # Resource belongs to user other than current user.
 4303:                 # Assemble privs for that user, and check for 'evb' priv.
 4304:                 my (%allroles,%userroles);
 4305:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4306:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4307:                         my ($trole,$tdom,$tnum,$tsec);
 4308:                         if ($entry =~ /^cr/) {
 4309:                             ($trole,$tdom,$tnum,$tsec) = 
 4310:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4311:                         } else {
 4312:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4313:                         }
 4314:                         my ($spec,$area,$trest);
 4315:                         $area = '/'.$tdom.'/'.$tnum;
 4316:                         $trest = $tnum;
 4317:                         if ($tsec ne '') {
 4318:                             $area .= '/'.$tsec;
 4319:                             $trest .= '/'.$tsec;
 4320:                         }
 4321:                         $spec = $trole.'.'.$area;
 4322:                         if ($trole =~ /^cr/) {
 4323:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4324:                                                               $tdom,$spec,$trest,$area);
 4325:                         } else {
 4326:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4327:                                                                 $tdom,$spec,$trest,$area);
 4328:                         }
 4329:                     }
 4330:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4331:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4332:                         if ($1) {
 4333:                             $no_userblock = 1;
 4334:                             last;
 4335:                         }
 4336:                     }
 4337:                 }
 4338:             } else {
 4339:                 # Resource belongs to current user
 4340:                 # Check for 'evb' priv via lonnet::allowed().
 4341:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4342:                     $no_ownblock = 1;
 4343:                     last;
 4344:                 }
 4345:             }
 4346:         }
 4347:         # if they have the evb priv and are currently not playing student
 4348:         next if (($no_ownblock) &&
 4349:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4350:         next if ($no_userblock);
 4351: 
 4352:         # Retrieve blocking times and identity of locker for course
 4353:         # of specified user, unless user has 'evb' privilege.
 4354:         
 4355:         my ($start,$end,$trigger) = 
 4356:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4357:         if (($start != 0) && 
 4358:             (($startblock == 0) || ($startblock > $start))) {
 4359:             $startblock = $start;
 4360:             if ($trigger ne '') {
 4361:                 $triggerblock = $trigger;
 4362:             }
 4363:         }
 4364:         if (($end != 0)  &&
 4365:             (($endblock == 0) || ($endblock < $end))) {
 4366:             $endblock = $end;
 4367:             if ($trigger ne '') {
 4368:                 $triggerblock = $trigger;
 4369:             }
 4370:         }
 4371:     }
 4372:     return ($startblock,$endblock,$triggerblock);
 4373: }
 4374: 
 4375: sub get_blocks {
 4376:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4377:     my $startblock = 0;
 4378:     my $endblock = 0;
 4379:     my $triggerblock = '';
 4380:     my $course = $cdom.'_'.$cnum;
 4381:     $setters->{$course} = {};
 4382:     $setters->{$course}{'staff'} = [];
 4383:     $setters->{$course}{'times'} = [];
 4384:     $setters->{$course}{'triggers'} = [];
 4385:     my (@blockers,%triggered);
 4386:     my $now = time;
 4387:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4388:     if ($activity eq 'docs') {
 4389:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4390:         foreach my $block (@blockers) {
 4391:             if ($block =~ /^firstaccess____(.+)$/) {
 4392:                 my $item = $1;
 4393:                 my $type = 'map';
 4394:                 my $timersymb = $item;
 4395:                 if ($item eq 'course') {
 4396:                     $type = 'course';
 4397:                 } elsif ($item =~ /___\d+___/) {
 4398:                     $type = 'resource';
 4399:                 } else {
 4400:                     $timersymb = &Apache::lonnet::symbread($item);
 4401:                 }
 4402:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4403:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4404:                 $triggered{$block} = {
 4405:                                        start => $start,
 4406:                                        end   => $end,
 4407:                                        type  => $type,
 4408:                                      };
 4409:             }
 4410:         }
 4411:     } else {
 4412:         foreach my $block (keys(%commblocks)) {
 4413:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4414:                 my ($start,$end) = ($1,$2);
 4415:                 if ($start <= time && $end >= time) {
 4416:                     if (ref($commblocks{$block}) eq 'HASH') {
 4417:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4418:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4419:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4420:                                     push(@blockers,$block);
 4421:                                 }
 4422:                             }
 4423:                         }
 4424:                     }
 4425:                 }
 4426:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4427:                 my $item = $1;
 4428:                 my $timersymb = $item; 
 4429:                 my $type = 'map';
 4430:                 if ($item eq 'course') {
 4431:                     $type = 'course';
 4432:                 } elsif ($item =~ /___\d+___/) {
 4433:                     $type = 'resource';
 4434:                 } else {
 4435:                     $timersymb = &Apache::lonnet::symbread($item);
 4436:                 }
 4437:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4438:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4439:                 if ($start && $end) {
 4440:                     if (($start <= time) && ($end >= time)) {
 4441:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4442:                             push(@blockers,$block);
 4443:                             $triggered{$block} = {
 4444:                                                    start => $start,
 4445:                                                    end   => $end,
 4446:                                                    type  => $type,
 4447:                                                  };
 4448:                         }
 4449:                     }
 4450:                 }
 4451:             }
 4452:         }
 4453:     }
 4454:     foreach my $blocker (@blockers) {
 4455:         my ($staff_name,$staff_dom,$title,$blocks) =
 4456:             &parse_block_record($commblocks{$blocker});
 4457:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4458:         my ($start,$end,$triggertype);
 4459:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4460:             ($start,$end) = ($1,$2);
 4461:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4462:             $start = $triggered{$blocker}{'start'};
 4463:             $end = $triggered{$blocker}{'end'};
 4464:             $triggertype = $triggered{$blocker}{'type'};
 4465:         }
 4466:         if ($start) {
 4467:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4468:             if ($triggertype) {
 4469:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4470:             } else {
 4471:                 push(@{$$setters{$course}{'triggers'}},0);
 4472:             }
 4473:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4474:                 $startblock = $start;
 4475:                 if ($triggertype) {
 4476:                     $triggerblock = $blocker;
 4477:                 }
 4478:             }
 4479:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4480:                $endblock = $end;
 4481:                if ($triggertype) {
 4482:                    $triggerblock = $blocker;
 4483:                }
 4484:             }
 4485:         }
 4486:     }
 4487:     return ($startblock,$endblock,$triggerblock);
 4488: }
 4489: 
 4490: sub parse_block_record {
 4491:     my ($record) = @_;
 4492:     my ($setuname,$setudom,$title,$blocks);
 4493:     if (ref($record) eq 'HASH') {
 4494:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4495:         $title = &unescape($record->{'event'});
 4496:         $blocks = $record->{'blocks'};
 4497:     } else {
 4498:         my @data = split(/:/,$record,3);
 4499:         if (scalar(@data) eq 2) {
 4500:             $title = $data[1];
 4501:             ($setuname,$setudom) = split(/@/,$data[0]);
 4502:         } else {
 4503:             ($setuname,$setudom,$title) = @data;
 4504:         }
 4505:         $blocks = { 'com' => 'on' };
 4506:     }
 4507:     return ($setuname,$setudom,$title,$blocks);
 4508: }
 4509: 
 4510: sub blocking_status {
 4511:     my ($activity,$uname,$udom,$url) = @_;
 4512:     my %setters;
 4513: 
 4514: # check for active blocking
 4515:     my ($startblock,$endblock,$triggerblock) = 
 4516:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4517:     my $blocked = 0;
 4518:     if ($startblock && $endblock) {
 4519:         $blocked = 1;
 4520:     }
 4521: 
 4522: # caller just wants to know whether a block is active
 4523:     if (!wantarray) { return $blocked; }
 4524: 
 4525: # build a link to a popup window containing the details
 4526:     my $querystring  = "?activity=$activity";
 4527: # $uname and $udom decide whose portfolio the user is trying to look at
 4528:     if ($activity eq 'port') {
 4529:         $querystring .= "&amp;udom=$udom"      if $udom;
 4530:         $querystring .= "&amp;uname=$uname"    if $uname;
 4531:     } elsif ($activity eq 'docs') {
 4532:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4533:     }
 4534: 
 4535:     my $output .= <<'END_MYBLOCK';
 4536: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4537:     var options = "width=" + w + ",height=" + h + ",";
 4538:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4539:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4540:     var newWin = window.open(url, wdwName, options);
 4541:     newWin.focus();
 4542: }
 4543: END_MYBLOCK
 4544: 
 4545:     $output = Apache::lonhtmlcommon::scripttag($output);
 4546:   
 4547:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4548:     my $text = &mt('Communication Blocked');
 4549:     if ($activity eq 'docs') {
 4550:         $text = &mt('Content Access Blocked');
 4551:     } elsif ($activity eq 'printout') {
 4552:         $text = &mt('Printing Blocked');
 4553:     }
 4554:     $output .= <<"END_BLOCK";
 4555: <div class='LC_comblock'>
 4556:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4557:   title='$text'>
 4558:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4559:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4560:   title='$text'>$text</a>
 4561: </div>
 4562: 
 4563: END_BLOCK
 4564: 
 4565:     return ($blocked, $output);
 4566: }
 4567: 
 4568: ###############################################
 4569: 
 4570: sub check_ip_acc {
 4571:     my ($acc)=@_;
 4572:     &Apache::lonxml::debug("acc is $acc");
 4573:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4574:         return 1;
 4575:     }
 4576:     my $allowed=0;
 4577:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4578: 
 4579:     my $name;
 4580:     foreach my $pattern (split(',',$acc)) {
 4581:         $pattern =~ s/^\s*//;
 4582:         $pattern =~ s/\s*$//;
 4583:         if ($pattern =~ /\*$/) {
 4584:             #35.8.*
 4585:             $pattern=~s/\*//;
 4586:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4587:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4588:             #35.8.3.[34-56]
 4589:             my $low=$2;
 4590:             my $high=$3;
 4591:             $pattern=$1;
 4592:             if ($ip =~ /^\Q$pattern\E/) {
 4593:                 my $last=(split(/\./,$ip))[3];
 4594:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4595:             }
 4596:         } elsif ($pattern =~ /^\*/) {
 4597:             #*.msu.edu
 4598:             $pattern=~s/\*//;
 4599:             if (!defined($name)) {
 4600:                 use Socket;
 4601:                 my $netaddr=inet_aton($ip);
 4602:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4603:             }
 4604:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4605:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4606:             #127.0.0.1
 4607:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4608:         } else {
 4609:             #some.name.com
 4610:             if (!defined($name)) {
 4611:                 use Socket;
 4612:                 my $netaddr=inet_aton($ip);
 4613:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4614:             }
 4615:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4616:         }
 4617:         if ($allowed) { last; }
 4618:     }
 4619:     return $allowed;
 4620: }
 4621: 
 4622: ###############################################
 4623: 
 4624: =pod
 4625: 
 4626: =head1 Domain Template Functions
 4627: 
 4628: =over 4
 4629: 
 4630: =item * &determinedomain()
 4631: 
 4632: Inputs: $domain (usually will be undef)
 4633: 
 4634: Returns: Determines which domain should be used for designs
 4635: 
 4636: =cut
 4637: 
 4638: ###############################################
 4639: sub determinedomain {
 4640:     my $domain=shift;
 4641:     if (! $domain) {
 4642:         # Determine domain if we have not been given one
 4643:         $domain = &Apache::lonnet::default_login_domain();
 4644:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4645:         if ($env{'request.role.domain'}) { 
 4646:             $domain=$env{'request.role.domain'}; 
 4647:         }
 4648:     }
 4649:     return $domain;
 4650: }
 4651: ###############################################
 4652: 
 4653: sub devalidate_domconfig_cache {
 4654:     my ($udom)=@_;
 4655:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4656: }
 4657: 
 4658: # ---------------------- Get domain configuration for a domain
 4659: sub get_domainconf {
 4660:     my ($udom) = @_;
 4661:     my $cachetime=1800;
 4662:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4663:     if (defined($cached)) { return %{$result}; }
 4664: 
 4665:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4666: 					     ['login','rolecolors','autoenroll'],$udom);
 4667:     my (%designhash,%legacy);
 4668:     if (keys(%domconfig) > 0) {
 4669:         if (ref($domconfig{'login'}) eq 'HASH') {
 4670:             if (keys(%{$domconfig{'login'}})) {
 4671:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4672:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4673:                         if ($key eq 'loginvia') {
 4674:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4675:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4676:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4677:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4678:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4679:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4680:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4681: 
 4682:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4683:                                             } else {
 4684:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4685:                                             }
 4686:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4687:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4688:                                             }
 4689:                                         }
 4690:                                     }
 4691:                                 }
 4692:                             }
 4693:                         } else {
 4694:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4695:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4696:                                     $domconfig{'login'}{$key}{$img};
 4697:                             }
 4698:                         }
 4699:                     } else {
 4700:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4701:                     }
 4702:                 }
 4703:             } else {
 4704:                 $legacy{'login'} = 1;
 4705:             }
 4706:         } else {
 4707:             $legacy{'login'} = 1;
 4708:         }
 4709:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4710:             if (keys(%{$domconfig{'rolecolors'}})) {
 4711:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4712:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4713:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4714:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4715:                         }
 4716:                     }
 4717:                 }
 4718:             } else {
 4719:                 $legacy{'rolecolors'} = 1;
 4720:             }
 4721:         } else {
 4722:             $legacy{'rolecolors'} = 1;
 4723:         }
 4724:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4725:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4726:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4727:             }
 4728:         }
 4729:         if (keys(%legacy) > 0) {
 4730:             my %legacyhash = &get_legacy_domconf($udom);
 4731:             foreach my $item (keys(%legacyhash)) {
 4732:                 if ($item =~ /^\Q$udom\E\.login/) {
 4733:                     if ($legacy{'login'}) { 
 4734:                         $designhash{$item} = $legacyhash{$item};
 4735:                     }
 4736:                 } else {
 4737:                     if ($legacy{'rolecolors'}) {
 4738:                         $designhash{$item} = $legacyhash{$item};
 4739:                     }
 4740:                 }
 4741:             }
 4742:         }
 4743:     } else {
 4744:         %designhash = &get_legacy_domconf($udom); 
 4745:     }
 4746:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4747: 				  $cachetime);
 4748:     return %designhash;
 4749: }
 4750: 
 4751: sub get_legacy_domconf {
 4752:     my ($udom) = @_;
 4753:     my %legacyhash;
 4754:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4755:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4756:     if (-e $designfile) {
 4757:         if ( open (my $fh,"<$designfile") ) {
 4758:             while (my $line = <$fh>) {
 4759:                 next if ($line =~ /^\#/);
 4760:                 chomp($line);
 4761:                 my ($key,$val)=(split(/\=/,$line));
 4762:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4763:             }
 4764:             close($fh);
 4765:         }
 4766:     }
 4767:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4768:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4769:     }
 4770:     return %legacyhash;
 4771: }
 4772: 
 4773: =pod
 4774: 
 4775: =item * &domainlogo()
 4776: 
 4777: Inputs: $domain (usually will be undef)
 4778: 
 4779: Returns: A link to a domain logo, if the domain logo exists.
 4780: If the domain logo does not exist, a description of the domain.
 4781: 
 4782: =cut
 4783: 
 4784: ###############################################
 4785: sub domainlogo {
 4786:     my $domain = &determinedomain(shift);
 4787:     my %designhash = &get_domainconf($domain);    
 4788:     # See if there is a logo
 4789:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4790:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4791:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4792: 	    if ($imgsrc =~ m{^/res/}) {
 4793: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4794: 		&Apache::lonnet::repcopy($local_name);
 4795: 	    }
 4796: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4797:         } 
 4798:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4799:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4800:         return &Apache::lonnet::domain($domain,'description');
 4801:     } else {
 4802:         return '';
 4803:     }
 4804: }
 4805: ##############################################
 4806: 
 4807: =pod
 4808: 
 4809: =item * &designparm()
 4810: 
 4811: Inputs: $which parameter; $domain (usually will be undef)
 4812: 
 4813: Returns: value of designparamter $which
 4814: 
 4815: =cut
 4816: 
 4817: 
 4818: ##############################################
 4819: sub designparm {
 4820:     my ($which,$domain)=@_;
 4821:     if (exists($env{'environment.color.'.$which})) {
 4822:         return $env{'environment.color.'.$which};
 4823:     }
 4824:     $domain=&determinedomain($domain);
 4825:     my %domdesign;
 4826:     unless ($domain eq 'public') {
 4827:         %domdesign = &get_domainconf($domain);
 4828:     }
 4829:     my $output;
 4830:     if ($domdesign{$domain.'.'.$which} ne '') {
 4831:         $output = $domdesign{$domain.'.'.$which};
 4832:     } else {
 4833:         $output = $defaultdesign{$which};
 4834:     }
 4835:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4836:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4837:         if ($output =~ m{^/(adm|res)/}) {
 4838:             if ($output =~ m{^/res/}) {
 4839:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4840:                 &Apache::lonnet::repcopy($local_name);
 4841:             }
 4842:             $output = &lonhttpdurl($output);
 4843:         }
 4844:     }
 4845:     return $output;
 4846: }
 4847: 
 4848: ##############################################
 4849: =pod
 4850: 
 4851: =item * &authorspace()
 4852: 
 4853: Inputs: $url (usually will be undef).
 4854: 
 4855: Returns: Path to Authoring Space containing the resource or 
 4856:          directory being viewed (or for which action is being taken). 
 4857:          If $url is provided, and begins /priv/<domain>/<uname>
 4858:          the path will be that portion of the $context argument.
 4859:          Otherwise the path will be for the author space of the current
 4860:          user when the current role is author, or for that of the 
 4861:          co-author/assistant co-author space when the current role 
 4862:          is co-author or assistant co-author.
 4863: 
 4864: =cut
 4865: 
 4866: sub authorspace {
 4867:     my ($url) = @_;
 4868:     if ($url ne '') {
 4869:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4870:            return $1;
 4871:         }
 4872:     }
 4873:     my $caname = '';
 4874:     my $cadom = '';
 4875:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4876:         ($cadom,$caname) =
 4877:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4878:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4879:         $caname = $env{'user.name'};
 4880:         $cadom = $env{'user.domain'};
 4881:     }
 4882:     if (($caname ne '') && ($cadom ne '')) {
 4883:         return "/priv/$cadom/$caname/";
 4884:     }
 4885:     return;
 4886: }
 4887: 
 4888: ##############################################
 4889: =pod
 4890: 
 4891: =item * &head_subbox()
 4892: 
 4893: Inputs: $content (contains HTML code with page functions, etc.)
 4894: 
 4895: Returns: HTML div with $content
 4896:          To be included in page header
 4897: 
 4898: =cut
 4899: 
 4900: sub head_subbox {
 4901:     my ($content)=@_;
 4902:     my $output =
 4903:         '<div class="LC_head_subbox">'
 4904:        .$content
 4905:        .'</div>'
 4906: }
 4907: 
 4908: ##############################################
 4909: =pod
 4910: 
 4911: =item * &CSTR_pageheader()
 4912: 
 4913: Input: (optional) filename from which breadcrumb trail is built.
 4914:        In most cases no input as needed, as $env{'request.filename'}
 4915:        is appropriate for use in building the breadcrumb trail.
 4916: 
 4917: Returns: HTML div with CSTR path and recent box
 4918:          To be included on Authoring Space pages
 4919: 
 4920: =cut
 4921: 
 4922: sub CSTR_pageheader {
 4923:     my ($trailfile) = @_;
 4924:     if ($trailfile eq '') {
 4925:         $trailfile = $env{'request.filename'};
 4926:     }
 4927: 
 4928: # this is for resources; directories have customtitle, and crumbs
 4929: # and select recent are created in lonpubdir.pm
 4930: 
 4931:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4932:     my ($udom,$uname,$thisdisfn)=
 4933:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 4934:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4935:     $formaction =~ s{/+}{/}g;
 4936: 
 4937:     my $parentpath = '';
 4938:     my $lastitem = '';
 4939:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4940:         $parentpath = $1;
 4941:         $lastitem = $2;
 4942:     } else {
 4943:         $lastitem = $thisdisfn;
 4944:     }
 4945: 
 4946:     my $output =
 4947:          '<div>'
 4948:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4949:         .'<b>'.&mt('Authoring Space:').'</b> '
 4950:         .'<form name="dirs" method="post" action="'.$formaction
 4951:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4952:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4953: 
 4954:     if ($lastitem) {
 4955:         $output .=
 4956:              '<span class="LC_filename">'
 4957:             .$lastitem
 4958:             .'</span>';
 4959:     }
 4960:     $output .=
 4961:          '<br />'
 4962:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4963:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4964:         .'</form>'
 4965:         .&Apache::lonmenu::constspaceform()
 4966:         .'</div>';
 4967: 
 4968:     return $output;
 4969: }
 4970: 
 4971: ###############################################
 4972: ###############################################
 4973: 
 4974: =pod
 4975: 
 4976: =back
 4977: 
 4978: =head1 HTML Helpers
 4979: 
 4980: =over 4
 4981: 
 4982: =item * &bodytag()
 4983: 
 4984: Returns a uniform header for LON-CAPA web pages.
 4985: 
 4986: Inputs: 
 4987: 
 4988: =over 4
 4989: 
 4990: =item * $title, A title to be displayed on the page.
 4991: 
 4992: =item * $function, the current role (can be undef).
 4993: 
 4994: =item * $addentries, extra parameters for the <body> tag.
 4995: 
 4996: =item * $bodyonly, if defined, only return the <body> tag.
 4997: 
 4998: =item * $domain, if defined, force a given domain.
 4999: 
 5000: =item * $forcereg, if page should register as content page (relevant for 
 5001:             text interface only)
 5002: 
 5003: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5004:                      navigational links
 5005: 
 5006: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5007: 
 5008: =item * $no_inline_link, if true and in remote mode, don't show the
 5009:          'Switch To Inline Menu' link
 5010: 
 5011: =item * $args, optional argument valid values are
 5012:             no_auto_mt_title -> prevents &mt()ing the title arg
 5013:             inherit_jsmath -> when creating popup window in a page,
 5014:                               should it have jsmath forced on by the
 5015:                               current page
 5016: 
 5017: =item * $advtoolsref, optional argument, ref to an array containing
 5018:             inlineremote items to be added in "Functions" menu below
 5019:             breadcrumbs.
 5020: 
 5021: =back
 5022: 
 5023: Returns: A uniform header for LON-CAPA web pages.  
 5024: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5025: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5026: other decorations will be returned.
 5027: 
 5028: =cut
 5029: 
 5030: sub bodytag {
 5031:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5032:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5033: 
 5034:     my $public;
 5035:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5036:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5037:         $public = 1;
 5038:     }
 5039:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5040: 
 5041:     $function = &get_users_function() if (!$function);
 5042:     my $img =    &designparm($function.'.img',$domain);
 5043:     my $font =   &designparm($function.'.font',$domain);
 5044:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5045: 
 5046:     my %design = ( 'style'   => 'margin-top: 0',
 5047: 		   'bgcolor' => $pgbg,
 5048: 		   'text'    => $font,
 5049:                    'alink'   => &designparm($function.'.alink',$domain),
 5050: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5051: 		   'link'    => &designparm($function.'.link',$domain),);
 5052:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5053: 
 5054:  # role and realm
 5055:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5056:     if ($role  eq 'ca') {
 5057:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5058:         $realm = &plainname($rname,$rdom);
 5059:     } 
 5060: # realm
 5061:     if ($env{'request.course.id'}) {
 5062:         if ($env{'request.role'} !~ /^cr/) {
 5063:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5064:         }
 5065:         if ($env{'request.course.sec'}) {
 5066:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5067:         }   
 5068: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5069:     } else {
 5070:         $role = &Apache::lonnet::plaintext($role);
 5071:     }
 5072: 
 5073:     if (!$realm) { $realm='&nbsp;'; }
 5074: 
 5075:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5076: 
 5077: # construct main body tag
 5078:     my $bodytag = "<body $extra_body_attr>".
 5079: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5080: 
 5081:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5082: 
 5083:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5084:         return $bodytag;
 5085:     }
 5086: 
 5087:     if ($public) {
 5088: 	undef($role);
 5089:     }
 5090:     
 5091:     my $titleinfo = '<h1>'.$title.'</h1>';
 5092:     #
 5093:     # Extra info if you are the DC
 5094:     my $dc_info = '';
 5095:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5096:                         $env{'course.'.$env{'request.course.id'}.
 5097:                                  '.domain'}.'/'})) {
 5098:         my $cid = $env{'request.course.id'};
 5099:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5100:         $dc_info =~ s/\s+$//;
 5101:     }
 5102: 
 5103:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5104: 
 5105:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5106: 
 5107: 
 5108: 
 5109:     my $funclist;
 5110:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5111:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions(), 'start')."\n".
 5112:                     Apache::lonmenu::serverform();
 5113:         my $forbodytag;
 5114:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5115:                                             $forcereg,$args->{'group'},
 5116:                                             $args->{'bread_crumbs'},
 5117:                                             $advtoolsref,'',\$forbodytag);
 5118:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5119:             $funclist = $forbodytag;
 5120:         }
 5121:     } else {
 5122: 
 5123:         #    if ($env{'request.state'} eq 'construct') {
 5124:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5125:         #    }
 5126: 
 5127:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5128:             Apache::lonmenu::utilityfunctions(), 'start');
 5129: 
 5130:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5131: 
 5132:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5133:             if ($dc_info) {
 5134:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5135:             }
 5136:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5137:                            <em>$realm</em> $dc_info</div>|;
 5138:             return $bodytag;
 5139:         }
 5140: 
 5141:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5142:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5143:         }
 5144: 
 5145:         $bodytag .= $right;
 5146: 
 5147:         if ($dc_info) {
 5148:             $dc_info = &dc_courseid_toggle($dc_info);
 5149:         }
 5150:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5151: 
 5152:         #don't show menus for public users
 5153:         if (!$public){
 5154:             $bodytag .= Apache::lonmenu::secondary_menu();
 5155:             $bodytag .= Apache::lonmenu::serverform();
 5156:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5157:             if ($env{'request.state'} eq 'construct') {
 5158:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5159:                                 $args->{'bread_crumbs'});
 5160:             } elsif ($forcereg) { 
 5161:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5162:                                                             $args->{'group'});
 5163:             } else {
 5164:                 my $forbodytag;
 5165:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5166:                                                     $forcereg,$args->{'group'},
 5167:                                                     $args->{'bread_crumbs'},
 5168:                                                     $advtoolsref,'',\$forbodytag);
 5169:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5170:                     $bodytag .= $forbodytag;
 5171:                 }
 5172:             }
 5173:         }else{
 5174:             # this is to seperate menu from content when there's no secondary
 5175:             # menu. Especially needed for public accessible ressources.
 5176:             $bodytag .= '<hr style="clear:both" />';
 5177:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5178:         }
 5179: 
 5180:         return $bodytag;
 5181:     }
 5182: 
 5183: #
 5184: # Top frame rendering, Remote is up
 5185: #
 5186: 
 5187:     my $imgsrc = $img;
 5188:     if ($img =~ /^\/adm/) {
 5189:         $imgsrc = &lonhttpdurl($img);
 5190:     }
 5191:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5192: 
 5193:     # Explicit link to get inline menu
 5194:     my $menu= ($no_inline_link?''
 5195:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5196: 
 5197:     if ($dc_info) {
 5198:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5199:     }
 5200: 
 5201:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5202:     unless ($public) {
 5203:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5204:                                 undef,'LC_menubuttons_link');
 5205:     }
 5206: 
 5207:     unless ($env{'form.inhibitmenu'}) {
 5208:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5209:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5210:                        <li>$menu</li>
 5211:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5212:     }
 5213:     if ($env{'request.state'} eq 'construct') {
 5214:         if (!$public){
 5215:             if ($env{'request.state'} eq 'construct') {
 5216:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5217:                                 &Apache::lonmenu::utilityfunctions(), 'start').
 5218:                             &Apache::lonhtmlcommon::scripttag('','end').
 5219:                             &Apache::lonmenu::innerregister($forcereg,
 5220:                                                             $args->{'bread_crumbs'});
 5221:             }
 5222:         }
 5223:     }
 5224:     return $bodytag."\n".$funclist;
 5225: }
 5226: 
 5227: sub dc_courseid_toggle {
 5228:     my ($dc_info) = @_;
 5229:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5230:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5231:            &mt('(More ...)').'</a></span>'.
 5232:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5233: }
 5234: 
 5235: sub make_attr_string {
 5236:     my ($register,$attr_ref) = @_;
 5237: 
 5238:     if ($attr_ref && !ref($attr_ref)) {
 5239: 	die("addentries Must be a hash ref ".
 5240: 	    join(':',caller(1))." ".
 5241: 	    join(':',caller(0))." ");
 5242:     }
 5243: 
 5244:     if ($register) {
 5245: 	my ($on_load,$on_unload);
 5246: 	foreach my $key (keys(%{$attr_ref})) {
 5247: 	    if      (lc($key) eq 'onload') {
 5248: 		$on_load.=$attr_ref->{$key}.';';
 5249: 		delete($attr_ref->{$key});
 5250: 
 5251: 	    } elsif (lc($key) eq 'onunload') {
 5252: 		$on_unload.=$attr_ref->{$key}.';';
 5253: 		delete($attr_ref->{$key});
 5254: 	    }
 5255: 	}
 5256:         if ($env{'environment.remote'} eq 'on') {
 5257:             $attr_ref->{'onload'}  =
 5258:                 &Apache::lonmenu::loadevents().  $on_load;
 5259:             $attr_ref->{'onunload'}=
 5260:                 &Apache::lonmenu::unloadevents().$on_unload;
 5261:         } else {  
 5262: 	    $attr_ref->{'onload'}  = $on_load;
 5263: 	    $attr_ref->{'onunload'}= $on_unload;
 5264:         }
 5265:     }
 5266: 
 5267:     my $attr_string;
 5268:     foreach my $attr (keys(%$attr_ref)) {
 5269: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5270:     }
 5271:     return $attr_string;
 5272: }
 5273: 
 5274: 
 5275: ###############################################
 5276: ###############################################
 5277: 
 5278: =pod
 5279: 
 5280: =item * &endbodytag()
 5281: 
 5282: Returns a uniform footer for LON-CAPA web pages.
 5283: 
 5284: Inputs: 1 - optional reference to an args hash
 5285: If in the hash, key for noredirectlink has a value which evaluates to true,
 5286: a 'Continue' link is not displayed if the page contains an
 5287: internal redirect in the <head></head> section,
 5288: i.e., $env{'internal.head.redirect'} exists   
 5289: 
 5290: =cut
 5291: 
 5292: sub endbodytag {
 5293:     my ($args) = @_;
 5294:     my $endbodytag;
 5295:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5296:         $endbodytag='</body>';
 5297:     }
 5298:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5299:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5300:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5301: 	    $endbodytag=
 5302: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5303: 	        &mt('Continue').'</a>'.
 5304: 	        $endbodytag;
 5305:         }
 5306:     }
 5307:     return $endbodytag;
 5308: }
 5309: 
 5310: =pod
 5311: 
 5312: =item * &standard_css()
 5313: 
 5314: Returns a style sheet
 5315: 
 5316: Inputs: (all optional)
 5317:             domain         -> force to color decorate a page for a specific
 5318:                                domain
 5319:             function       -> force usage of a specific rolish color scheme
 5320:             bgcolor        -> override the default page bgcolor
 5321: 
 5322: =cut
 5323: 
 5324: sub standard_css {
 5325:     my ($function,$domain,$bgcolor) = @_;
 5326:     $function  = &get_users_function() if (!$function);
 5327:     my $img    = &designparm($function.'.img',   $domain);
 5328:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5329:     my $font   = &designparm($function.'.font',  $domain);
 5330:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5331: #second colour for later usage
 5332:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5333:     my $pgbg_or_bgcolor =
 5334: 	         $bgcolor ||
 5335: 	         &designparm($function.'.pgbg',  $domain);
 5336:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5337:     my $alink  = &designparm($function.'.alink', $domain);
 5338:     my $vlink  = &designparm($function.'.vlink', $domain);
 5339:     my $link   = &designparm($function.'.link',  $domain);
 5340: 
 5341:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5342:     my $mono                 = 'monospace';
 5343:     my $data_table_head      = $sidebg;
 5344:     my $data_table_light     = '#FAFAFA';
 5345:     my $data_table_dark      = '#E0E0E0';
 5346:     my $data_table_darker    = '#CCCCCC';
 5347:     my $data_table_highlight = '#FFFF00';
 5348:     my $mail_new             = '#FFBB77';
 5349:     my $mail_new_hover       = '#DD9955';
 5350:     my $mail_read            = '#BBBB77';
 5351:     my $mail_read_hover      = '#999944';
 5352:     my $mail_replied         = '#AAAA88';
 5353:     my $mail_replied_hover   = '#888855';
 5354:     my $mail_other           = '#99BBBB';
 5355:     my $mail_other_hover     = '#669999';
 5356:     my $table_header         = '#DDDDDD';
 5357:     my $feedback_link_bg     = '#BBBBBB';
 5358:     my $lg_border_color      = '#C8C8C8';
 5359:     my $button_hover         = '#BF2317';
 5360: 
 5361:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5362:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5363:                                              : '0 3px 0 4px';
 5364: 
 5365: 
 5366:     return <<END;
 5367: 
 5368: /* needed for iframe to allow 100% height in FF */
 5369: body, html { 
 5370:     margin: 0;
 5371:     padding: 0 0.5%;
 5372:     height: 99%; /* to avoid scrollbars */
 5373: }
 5374: 
 5375: body {
 5376:   font-family: $sans;
 5377:   line-height:130%;
 5378:   font-size:0.83em;
 5379:   color:$font;
 5380: }
 5381: 
 5382: a:focus,
 5383: a:focus img {
 5384:   color: red;
 5385: }
 5386: 
 5387: form, .inline {
 5388:   display: inline;
 5389: }
 5390: 
 5391: .LC_right {
 5392:   text-align:right;
 5393: }
 5394: 
 5395: .LC_middle {
 5396:   vertical-align:middle;
 5397: }
 5398: 
 5399: .LC_floatleft {
 5400:   float: left;
 5401: }
 5402: 
 5403: .LC_floatright {
 5404:   float: right;
 5405: }
 5406: 
 5407: .LC_400Box {
 5408:   width:400px;
 5409: }
 5410: 
 5411: .LC_iframecontainer {
 5412:     width: 98%;
 5413:     margin: 0;
 5414:     position: fixed;
 5415:     top: 8.5em;
 5416:     bottom: 0;
 5417: }
 5418: 
 5419: .LC_iframecontainer iframe{
 5420:     border: none;
 5421:     width: 100%;
 5422:     height: 100%;
 5423: }
 5424: 
 5425: .LC_filename {
 5426:   font-family: $mono;
 5427:   white-space:pre;
 5428:   font-size: 120%;
 5429: }
 5430: 
 5431: .LC_fileicon {
 5432:   border: none;
 5433:   height: 1.3em;
 5434:   vertical-align: text-bottom;
 5435:   margin-right: 0.3em;
 5436:   text-decoration:none;
 5437: }
 5438: 
 5439: .LC_setting {
 5440:   text-decoration:underline;
 5441: }
 5442: 
 5443: .LC_error {
 5444:   color: red;
 5445: }
 5446: 
 5447: .LC_warning {
 5448:   color: darkorange;
 5449: }
 5450: 
 5451: .LC_diff_removed {
 5452:   color: red;
 5453: }
 5454: 
 5455: .LC_info,
 5456: .LC_success,
 5457: .LC_diff_added {
 5458:   color: green;
 5459: }
 5460: 
 5461: div.LC_confirm_box {
 5462:   background-color: #FAFAFA;
 5463:   border: 1px solid $lg_border_color;
 5464:   margin-right: 0;
 5465:   padding: 5px;
 5466: }
 5467: 
 5468: div.LC_confirm_box .LC_error img,
 5469: div.LC_confirm_box .LC_success img {
 5470:   vertical-align: middle;
 5471: }
 5472: 
 5473: .LC_icon {
 5474:   border: none;
 5475:   vertical-align: middle;
 5476: }
 5477: 
 5478: .LC_docs_spacer {
 5479:   width: 25px;
 5480:   height: 1px;
 5481:   border: none;
 5482: }
 5483: 
 5484: .LC_internal_info {
 5485:   color: #999999;
 5486: }
 5487: 
 5488: .LC_discussion {
 5489:   background: $data_table_dark;
 5490:   border: 1px solid black;
 5491:   margin: 2px;
 5492: }
 5493: 
 5494: .LC_disc_action_left {
 5495:   background: $sidebg;
 5496:   text-align: left;
 5497:   padding: 4px;
 5498:   margin: 2px;
 5499: }
 5500: 
 5501: .LC_disc_action_right {
 5502:   background: $sidebg;
 5503:   text-align: right;
 5504:   padding: 4px;
 5505:   margin: 2px;
 5506: }
 5507: 
 5508: .LC_disc_new_item {
 5509:   background: white;
 5510:   border: 2px solid red;
 5511:   margin: 4px;
 5512:   padding: 4px;
 5513: }
 5514: 
 5515: .LC_disc_old_item {
 5516:   background: white;
 5517:   margin: 4px;
 5518:   padding: 4px;
 5519: }
 5520: 
 5521: table.LC_pastsubmission {
 5522:   border: 1px solid black;
 5523:   margin: 2px;
 5524: }
 5525: 
 5526: table#LC_menubuttons {
 5527:   width: 100%;
 5528:   background: $pgbg;
 5529:   border: 2px;
 5530:   border-collapse: separate;
 5531:   padding: 0;
 5532: }
 5533: 
 5534: table#LC_title_bar a {
 5535:   color: $fontmenu;
 5536: }
 5537: 
 5538: table#LC_title_bar {
 5539:   clear: both;
 5540:   display: none;
 5541: }
 5542: 
 5543: table#LC_title_bar,
 5544: table.LC_breadcrumbs, /* obsolete? */
 5545: table#LC_title_bar.LC_with_remote {
 5546:   width: 100%;
 5547:   border-color: $pgbg;
 5548:   border-style: solid;
 5549:   border-width: $border;
 5550:   background: $pgbg;
 5551:   color: $fontmenu;
 5552:   border-collapse: collapse;
 5553:   padding: 0;
 5554:   margin: 0;
 5555: }
 5556: 
 5557: ul.LC_breadcrumb_tools_outerlist {
 5558:     margin: 0;
 5559:     padding: 0;
 5560:     position: relative;
 5561:     list-style: none;
 5562: }
 5563: ul.LC_breadcrumb_tools_outerlist li {
 5564:     display: inline;
 5565: }
 5566: 
 5567: .LC_breadcrumb_tools_navigation {
 5568:     padding: 0;
 5569:     margin: 0;
 5570:     float: left;
 5571: }
 5572: .LC_breadcrumb_tools_tools {
 5573:     padding: 0;
 5574:     margin: 0;
 5575:     float: right;
 5576: }
 5577: 
 5578: table#LC_title_bar td {
 5579:   background: $tabbg;
 5580: }
 5581: 
 5582: table#LC_menubuttons img {
 5583:   border: none;
 5584: }
 5585: 
 5586: .LC_breadcrumbs_component {
 5587:   float: right;
 5588:   margin: 0 1em;
 5589: }
 5590: .LC_breadcrumbs_component img {
 5591:   vertical-align: middle;
 5592: }
 5593: 
 5594: td.LC_table_cell_checkbox {
 5595:   text-align: center;
 5596: }
 5597: 
 5598: .LC_fontsize_small {
 5599:   font-size: 70%;
 5600: }
 5601: 
 5602: #LC_breadcrumbs {
 5603:   clear:both;
 5604:   background: $sidebg;
 5605:   border-bottom: 1px solid $lg_border_color;
 5606:   line-height: 2.5em;
 5607:   overflow: hidden;
 5608:   margin: 0;
 5609:   padding: 0;
 5610:   text-align: left;
 5611: }
 5612: 
 5613: .LC_head_subbox, .LC_actionbox {
 5614:   clear:both;
 5615:   background: #F8F8F8; /* $sidebg; */
 5616:   border: 1px solid $sidebg;
 5617:   margin: 0 0 10px 0;
 5618:   padding: 3px;
 5619:   text-align: left;
 5620: }
 5621: 
 5622: .LC_fontsize_medium {
 5623:   font-size: 85%;
 5624: }
 5625: 
 5626: .LC_fontsize_large {
 5627:   font-size: 120%;
 5628: }
 5629: 
 5630: .LC_menubuttons_inline_text {
 5631:   color: $font;
 5632:   font-size: 90%;
 5633:   padding-left:3px;
 5634: }
 5635: 
 5636: .LC_menubuttons_inline_text img{
 5637:   vertical-align: middle;
 5638: }
 5639: 
 5640: li.LC_menubuttons_inline_text img {
 5641:   cursor:pointer;
 5642:   text-decoration: none;
 5643: }
 5644: 
 5645: .LC_menubuttons_link {
 5646:   text-decoration: none;
 5647: }
 5648: 
 5649: .LC_menubuttons_category {
 5650:   color: $font;
 5651:   background: $pgbg;
 5652:   font-size: larger;
 5653:   font-weight: bold;
 5654: }
 5655: 
 5656: td.LC_menubuttons_text {
 5657:   color: $font;
 5658: }
 5659: 
 5660: .LC_current_location {
 5661:   background: $tabbg;
 5662: }
 5663: 
 5664: table.LC_data_table {
 5665:   border: 1px solid #000000;
 5666:   border-collapse: separate;
 5667:   border-spacing: 1px;
 5668:   background: $pgbg;
 5669: }
 5670: 
 5671: .LC_data_table_dense {
 5672:   font-size: small;
 5673: }
 5674: 
 5675: table.LC_nested_outer {
 5676:   border: 1px solid #000000;
 5677:   border-collapse: collapse;
 5678:   border-spacing: 0;
 5679:   width: 100%;
 5680: }
 5681: 
 5682: table.LC_innerpickbox,
 5683: table.LC_nested {
 5684:   border: none;
 5685:   border-collapse: collapse;
 5686:   border-spacing: 0;
 5687:   width: 100%;
 5688: }
 5689: 
 5690: table.LC_data_table tr th,
 5691: table.LC_calendar tr th,
 5692: table.LC_prior_tries tr th,
 5693: table.LC_innerpickbox tr th {
 5694:   font-weight: bold;
 5695:   background-color: $data_table_head;
 5696:   color:$fontmenu;
 5697:   font-size:90%;
 5698: }
 5699: 
 5700: table.LC_innerpickbox tr th,
 5701: table.LC_innerpickbox tr td {
 5702:   vertical-align: top;
 5703: }
 5704: 
 5705: table.LC_data_table tr.LC_info_row > td {
 5706:   background-color: #CCCCCC;
 5707:   font-weight: bold;
 5708:   text-align: left;
 5709: }
 5710: 
 5711: table.LC_data_table tr.LC_odd_row > td {
 5712:   background-color: $data_table_light;
 5713:   padding: 2px;
 5714:   vertical-align: top;
 5715: }
 5716: 
 5717: table.LC_pick_box tr > td.LC_odd_row {
 5718:   background-color: $data_table_light;
 5719:   vertical-align: top;
 5720: }
 5721: 
 5722: table.LC_data_table tr.LC_even_row > td {
 5723:   background-color: $data_table_dark;
 5724:   padding: 2px;
 5725:   vertical-align: top;
 5726: }
 5727: 
 5728: table.LC_pick_box tr > td.LC_even_row {
 5729:   background-color: $data_table_dark;
 5730:   vertical-align: top;
 5731: }
 5732: 
 5733: table.LC_data_table tr.LC_data_table_highlight td {
 5734:   background-color: $data_table_darker;
 5735: }
 5736: 
 5737: table.LC_data_table tr td.LC_leftcol_header {
 5738:   background-color: $data_table_head;
 5739:   font-weight: bold;
 5740: }
 5741: 
 5742: table.LC_data_table tr.LC_empty_row td,
 5743: table.LC_nested tr.LC_empty_row td {
 5744:   font-weight: bold;
 5745:   font-style: italic;
 5746:   text-align: center;
 5747:   padding: 8px;
 5748: }
 5749: 
 5750: table.LC_data_table tr.LC_empty_row td,
 5751: table.LC_data_table tr.LC_footer_row td {
 5752:   background-color: $sidebg;
 5753: }
 5754: 
 5755: table.LC_nested tr.LC_empty_row td {
 5756:   background-color: #FFFFFF;
 5757: }
 5758: 
 5759: table.LC_caption {
 5760: }
 5761: 
 5762: table.LC_nested tr.LC_empty_row td {
 5763:   padding: 4ex
 5764: }
 5765: 
 5766: table.LC_nested_outer tr th {
 5767:   font-weight: bold;
 5768:   color:$fontmenu;
 5769:   background-color: $data_table_head;
 5770:   font-size: small;
 5771:   border-bottom: 1px solid #000000;
 5772: }
 5773: 
 5774: table.LC_nested_outer tr td.LC_subheader {
 5775:   background-color: $data_table_head;
 5776:   font-weight: bold;
 5777:   font-size: small;
 5778:   border-bottom: 1px solid #000000;
 5779:   text-align: right;
 5780: }
 5781: 
 5782: table.LC_nested tr.LC_info_row td {
 5783:   background-color: #CCCCCC;
 5784:   font-weight: bold;
 5785:   font-size: small;
 5786:   text-align: center;
 5787: }
 5788: 
 5789: table.LC_nested tr.LC_info_row td.LC_left_item,
 5790: table.LC_nested_outer tr th.LC_left_item {
 5791:   text-align: left;
 5792: }
 5793: 
 5794: table.LC_nested td {
 5795:   background-color: #FFFFFF;
 5796:   font-size: small;
 5797: }
 5798: 
 5799: table.LC_nested_outer tr th.LC_right_item,
 5800: table.LC_nested tr.LC_info_row td.LC_right_item,
 5801: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5802: table.LC_nested tr td.LC_right_item {
 5803:   text-align: right;
 5804: }
 5805: 
 5806: table.LC_nested tr.LC_odd_row td {
 5807:   background-color: #EEEEEE;
 5808: }
 5809: 
 5810: table.LC_createuser {
 5811: }
 5812: 
 5813: table.LC_createuser tr.LC_section_row td {
 5814:   font-size: small;
 5815: }
 5816: 
 5817: table.LC_createuser tr.LC_info_row td  {
 5818:   background-color: #CCCCCC;
 5819:   font-weight: bold;
 5820:   text-align: center;
 5821: }
 5822: 
 5823: table.LC_calendar {
 5824:   border: 1px solid #000000;
 5825:   border-collapse: collapse;
 5826:   width: 98%;
 5827: }
 5828: 
 5829: table.LC_calendar_pickdate {
 5830:   font-size: xx-small;
 5831: }
 5832: 
 5833: table.LC_calendar tr td {
 5834:   border: 1px solid #000000;
 5835:   vertical-align: top;
 5836:   width: 14%;
 5837: }
 5838: 
 5839: table.LC_calendar tr td.LC_calendar_day_empty {
 5840:   background-color: $data_table_dark;
 5841: }
 5842: 
 5843: table.LC_calendar tr td.LC_calendar_day_current {
 5844:   background-color: $data_table_highlight;
 5845: }
 5846: 
 5847: table.LC_data_table tr td.LC_mail_new {
 5848:   background-color: $mail_new;
 5849: }
 5850: 
 5851: table.LC_data_table tr.LC_mail_new:hover {
 5852:   background-color: $mail_new_hover;
 5853: }
 5854: 
 5855: table.LC_data_table tr td.LC_mail_read {
 5856:   background-color: $mail_read;
 5857: }
 5858: 
 5859: /*
 5860: table.LC_data_table tr.LC_mail_read:hover {
 5861:   background-color: $mail_read_hover;
 5862: }
 5863: */
 5864: 
 5865: table.LC_data_table tr td.LC_mail_replied {
 5866:   background-color: $mail_replied;
 5867: }
 5868: 
 5869: /*
 5870: table.LC_data_table tr.LC_mail_replied:hover {
 5871:   background-color: $mail_replied_hover;
 5872: }
 5873: */
 5874: 
 5875: table.LC_data_table tr td.LC_mail_other {
 5876:   background-color: $mail_other;
 5877: }
 5878: 
 5879: /*
 5880: table.LC_data_table tr.LC_mail_other:hover {
 5881:   background-color: $mail_other_hover;
 5882: }
 5883: */
 5884: 
 5885: table.LC_data_table tr > td.LC_browser_file,
 5886: table.LC_data_table tr > td.LC_browser_file_published {
 5887:   background: #AAEE77;
 5888: }
 5889: 
 5890: table.LC_data_table tr > td.LC_browser_file_locked,
 5891: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5892:   background: #FFAA99;
 5893: }
 5894: 
 5895: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5896:   background: #888888;
 5897: }
 5898: 
 5899: table.LC_data_table tr > td.LC_browser_file_modified,
 5900: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5901:   background: #F8F866;
 5902: }
 5903: 
 5904: table.LC_data_table tr.LC_browser_folder > td {
 5905:   background: #E0E8FF;
 5906: }
 5907: 
 5908: table.LC_data_table tr > td.LC_roles_is {
 5909:   /* background: #77FF77; */
 5910: }
 5911: 
 5912: table.LC_data_table tr > td.LC_roles_future {
 5913:   border-right: 8px solid #FFFF77;
 5914: }
 5915: 
 5916: table.LC_data_table tr > td.LC_roles_will {
 5917:   border-right: 8px solid #FFAA77;
 5918: }
 5919: 
 5920: table.LC_data_table tr > td.LC_roles_expired {
 5921:   border-right: 8px solid #FF7777;
 5922: }
 5923: 
 5924: table.LC_data_table tr > td.LC_roles_will_not {
 5925:   border-right: 8px solid #AAFF77;
 5926: }
 5927: 
 5928: table.LC_data_table tr > td.LC_roles_selected {
 5929:   border-right: 8px solid #11CC55;
 5930: }
 5931: 
 5932: span.LC_current_location {
 5933:   font-size:larger;
 5934:   background: $pgbg;
 5935: }
 5936: 
 5937: span.LC_current_nav_location {
 5938:   font-weight:bold;
 5939:   background: $sidebg;
 5940: }
 5941: 
 5942: span.LC_parm_menu_item {
 5943:   font-size: larger;
 5944: }
 5945: 
 5946: span.LC_parm_scope_all {
 5947:   color: red;
 5948: }
 5949: 
 5950: span.LC_parm_scope_folder {
 5951:   color: green;
 5952: }
 5953: 
 5954: span.LC_parm_scope_resource {
 5955:   color: orange;
 5956: }
 5957: 
 5958: span.LC_parm_part {
 5959:   color: blue;
 5960: }
 5961: 
 5962: span.LC_parm_folder,
 5963: span.LC_parm_symb {
 5964:   font-size: x-small;
 5965:   font-family: $mono;
 5966:   color: #AAAAAA;
 5967: }
 5968: 
 5969: ul.LC_parm_parmlist li {
 5970:   display: inline-block;
 5971:   padding: 0.3em 0.8em;
 5972:   vertical-align: top;
 5973:   width: 150px;
 5974:   border-top:1px solid $lg_border_color;
 5975: }
 5976: 
 5977: td.LC_parm_overview_level_menu,
 5978: td.LC_parm_overview_map_menu,
 5979: td.LC_parm_overview_parm_selectors,
 5980: td.LC_parm_overview_restrictions  {
 5981:   border: 1px solid black;
 5982:   border-collapse: collapse;
 5983: }
 5984: 
 5985: table.LC_parm_overview_restrictions td {
 5986:   border-width: 1px 4px 1px 4px;
 5987:   border-style: solid;
 5988:   border-color: $pgbg;
 5989:   text-align: center;
 5990: }
 5991: 
 5992: table.LC_parm_overview_restrictions th {
 5993:   background: $tabbg;
 5994:   border-width: 1px 4px 1px 4px;
 5995:   border-style: solid;
 5996:   border-color: $pgbg;
 5997: }
 5998: 
 5999: table#LC_helpmenu {
 6000:   border: none;
 6001:   height: 55px;
 6002:   border-spacing: 0;
 6003: }
 6004: 
 6005: table#LC_helpmenu fieldset legend {
 6006:   font-size: larger;
 6007: }
 6008: 
 6009: table#LC_helpmenu_links {
 6010:   width: 100%;
 6011:   border: 1px solid black;
 6012:   background: $pgbg;
 6013:   padding: 0;
 6014:   border-spacing: 1px;
 6015: }
 6016: 
 6017: table#LC_helpmenu_links tr td {
 6018:   padding: 1px;
 6019:   background: $tabbg;
 6020:   text-align: center;
 6021:   font-weight: bold;
 6022: }
 6023: 
 6024: table#LC_helpmenu_links a:link,
 6025: table#LC_helpmenu_links a:visited,
 6026: table#LC_helpmenu_links a:active {
 6027:   text-decoration: none;
 6028:   color: $font;
 6029: }
 6030: 
 6031: table#LC_helpmenu_links a:hover {
 6032:   text-decoration: underline;
 6033:   color: $vlink;
 6034: }
 6035: 
 6036: .LC_chrt_popup_exists {
 6037:   border: 1px solid #339933;
 6038:   margin: -1px;
 6039: }
 6040: 
 6041: .LC_chrt_popup_up {
 6042:   border: 1px solid yellow;
 6043:   margin: -1px;
 6044: }
 6045: 
 6046: .LC_chrt_popup {
 6047:   border: 1px solid #8888FF;
 6048:   background: #CCCCFF;
 6049: }
 6050: 
 6051: table.LC_pick_box {
 6052:   border-collapse: separate;
 6053:   background: white;
 6054:   border: 1px solid black;
 6055:   border-spacing: 1px;
 6056: }
 6057: 
 6058: table.LC_pick_box td.LC_pick_box_title {
 6059:   background: $sidebg;
 6060:   font-weight: bold;
 6061:   text-align: left;
 6062:   vertical-align: top;
 6063:   width: 184px;
 6064:   padding: 8px;
 6065: }
 6066: 
 6067: table.LC_pick_box td.LC_pick_box_value {
 6068:   text-align: left;
 6069:   padding: 8px;
 6070: }
 6071: 
 6072: table.LC_pick_box td.LC_pick_box_select {
 6073:   text-align: left;
 6074:   padding: 8px;
 6075: }
 6076: 
 6077: table.LC_pick_box td.LC_pick_box_separator {
 6078:   padding: 0;
 6079:   height: 1px;
 6080:   background: black;
 6081: }
 6082: 
 6083: table.LC_pick_box td.LC_pick_box_submit {
 6084:   text-align: right;
 6085: }
 6086: 
 6087: table.LC_pick_box td.LC_evenrow_value {
 6088:   text-align: left;
 6089:   padding: 8px;
 6090:   background-color: $data_table_light;
 6091: }
 6092: 
 6093: table.LC_pick_box td.LC_oddrow_value {
 6094:   text-align: left;
 6095:   padding: 8px;
 6096:   background-color: $data_table_light;
 6097: }
 6098: 
 6099: span.LC_helpform_receipt_cat {
 6100:   font-weight: bold;
 6101: }
 6102: 
 6103: table.LC_group_priv_box {
 6104:   background: white;
 6105:   border: 1px solid black;
 6106:   border-spacing: 1px;
 6107: }
 6108: 
 6109: table.LC_group_priv_box td.LC_pick_box_title {
 6110:   background: $tabbg;
 6111:   font-weight: bold;
 6112:   text-align: right;
 6113:   width: 184px;
 6114: }
 6115: 
 6116: table.LC_group_priv_box td.LC_groups_fixed {
 6117:   background: $data_table_light;
 6118:   text-align: center;
 6119: }
 6120: 
 6121: table.LC_group_priv_box td.LC_groups_optional {
 6122:   background: $data_table_dark;
 6123:   text-align: center;
 6124: }
 6125: 
 6126: table.LC_group_priv_box td.LC_groups_functionality {
 6127:   background: $data_table_darker;
 6128:   text-align: center;
 6129:   font-weight: bold;
 6130: }
 6131: 
 6132: table.LC_group_priv td {
 6133:   text-align: left;
 6134:   padding: 0;
 6135: }
 6136: 
 6137: .LC_navbuttons {
 6138:   margin: 2ex 0ex 2ex 0ex;
 6139: }
 6140: 
 6141: .LC_topic_bar {
 6142:   font-weight: bold;
 6143:   background: $tabbg;
 6144:   margin: 1em 0em 1em 2em;
 6145:   padding: 3px;
 6146:   font-size: 1.2em;
 6147: }
 6148: 
 6149: .LC_topic_bar span {
 6150:   left: 0.5em;
 6151:   position: absolute;
 6152:   vertical-align: middle;
 6153:   font-size: 1.2em;
 6154: }
 6155: 
 6156: table.LC_course_group_status {
 6157:   margin: 20px;
 6158: }
 6159: 
 6160: table.LC_status_selector td {
 6161:   vertical-align: top;
 6162:   text-align: center;
 6163:   padding: 4px;
 6164: }
 6165: 
 6166: div.LC_feedback_link {
 6167:   clear: both;
 6168:   background: $sidebg;
 6169:   width: 100%;
 6170:   padding-bottom: 10px;
 6171:   border: 1px $tabbg solid;
 6172:   height: 22px;
 6173:   line-height: 22px;
 6174:   padding-top: 5px;
 6175: }
 6176: 
 6177: div.LC_feedback_link img {
 6178:   height: 22px;
 6179:   vertical-align:middle;
 6180: }
 6181: 
 6182: div.LC_feedback_link a {
 6183:   text-decoration: none;
 6184: }
 6185: 
 6186: div.LC_comblock {
 6187:   display:inline;
 6188:   color:$font;
 6189:   font-size:90%;
 6190: }
 6191: 
 6192: div.LC_feedback_link div.LC_comblock {
 6193:   padding-left:5px;
 6194: }
 6195: 
 6196: div.LC_feedback_link div.LC_comblock a {
 6197:   color:$font;
 6198: }
 6199: 
 6200: span.LC_feedback_link {
 6201:   /* background: $feedback_link_bg; */
 6202:   font-size: larger;
 6203: }
 6204: 
 6205: span.LC_message_link {
 6206:   /* background: $feedback_link_bg; */
 6207:   font-size: larger;
 6208:   position: absolute;
 6209:   right: 1em;
 6210: }
 6211: 
 6212: table.LC_prior_tries {
 6213:   border: 1px solid #000000;
 6214:   border-collapse: separate;
 6215:   border-spacing: 1px;
 6216: }
 6217: 
 6218: table.LC_prior_tries td {
 6219:   padding: 2px;
 6220: }
 6221: 
 6222: .LC_answer_correct {
 6223:   background: lightgreen;
 6224:   color: darkgreen;
 6225:   padding: 6px;
 6226: }
 6227: 
 6228: .LC_answer_charged_try {
 6229:   background: #FFAAAA;
 6230:   color: darkred;
 6231:   padding: 6px;
 6232: }
 6233: 
 6234: .LC_answer_not_charged_try,
 6235: .LC_answer_no_grade,
 6236: .LC_answer_late {
 6237:   background: lightyellow;
 6238:   color: black;
 6239:   padding: 6px;
 6240: }
 6241: 
 6242: .LC_answer_previous {
 6243:   background: lightblue;
 6244:   color: darkblue;
 6245:   padding: 6px;
 6246: }
 6247: 
 6248: .LC_answer_no_message {
 6249:   background: #FFFFFF;
 6250:   color: black;
 6251:   padding: 6px;
 6252: }
 6253: 
 6254: .LC_answer_unknown {
 6255:   background: orange;
 6256:   color: black;
 6257:   padding: 6px;
 6258: }
 6259: 
 6260: span.LC_prior_numerical,
 6261: span.LC_prior_string,
 6262: span.LC_prior_custom,
 6263: span.LC_prior_reaction,
 6264: span.LC_prior_math {
 6265:   font-family: $mono;
 6266:   white-space: pre;
 6267: }
 6268: 
 6269: span.LC_prior_string {
 6270:   font-family: $mono;
 6271:   white-space: pre;
 6272: }
 6273: 
 6274: table.LC_prior_option {
 6275:   width: 100%;
 6276:   border-collapse: collapse;
 6277: }
 6278: 
 6279: table.LC_prior_rank,
 6280: table.LC_prior_match {
 6281:   border-collapse: collapse;
 6282: }
 6283: 
 6284: table.LC_prior_option tr td,
 6285: table.LC_prior_rank tr td,
 6286: table.LC_prior_match tr td {
 6287:   border: 1px solid #000000;
 6288: }
 6289: 
 6290: .LC_nobreak {
 6291:   white-space: nowrap;
 6292: }
 6293: 
 6294: span.LC_cusr_emph {
 6295:   font-style: italic;
 6296: }
 6297: 
 6298: span.LC_cusr_subheading {
 6299:   font-weight: normal;
 6300:   font-size: 85%;
 6301: }
 6302: 
 6303: div.LC_docs_entry_move {
 6304:   border: 1px solid #BBBBBB;
 6305:   background: #DDDDDD;
 6306:   width: 22px;
 6307:   padding: 1px;
 6308:   margin: 0;
 6309: }
 6310: 
 6311: table.LC_data_table tr > td.LC_docs_entry_commands,
 6312: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6313:   font-size: x-small;
 6314: }
 6315: 
 6316: .LC_docs_entry_parameter {
 6317:   white-space: nowrap;
 6318: }
 6319: 
 6320: .LC_docs_copy {
 6321:   color: #000099;
 6322: }
 6323: 
 6324: .LC_docs_cut {
 6325:   color: #550044;
 6326: }
 6327: 
 6328: .LC_docs_rename {
 6329:   color: #009900;
 6330: }
 6331: 
 6332: .LC_docs_remove {
 6333:   color: #990000;
 6334: }
 6335: 
 6336: .LC_docs_reinit_warn,
 6337: .LC_docs_ext_edit {
 6338:   font-size: x-small;
 6339: }
 6340: 
 6341: table.LC_docs_adddocs td,
 6342: table.LC_docs_adddocs th {
 6343:   border: 1px solid #BBBBBB;
 6344:   padding: 4px;
 6345:   background: #DDDDDD;
 6346: }
 6347: 
 6348: table.LC_sty_begin {
 6349:   background: #BBFFBB;
 6350: }
 6351: 
 6352: table.LC_sty_end {
 6353:   background: #FFBBBB;
 6354: }
 6355: 
 6356: table.LC_double_column {
 6357:   border-width: 0;
 6358:   border-collapse: collapse;
 6359:   width: 100%;
 6360:   padding: 2px;
 6361: }
 6362: 
 6363: table.LC_double_column tr td.LC_left_col {
 6364:   top: 2px;
 6365:   left: 2px;
 6366:   width: 47%;
 6367:   vertical-align: top;
 6368: }
 6369: 
 6370: table.LC_double_column tr td.LC_right_col {
 6371:   top: 2px;
 6372:   right: 2px;
 6373:   width: 47%;
 6374:   vertical-align: top;
 6375: }
 6376: 
 6377: div.LC_left_float {
 6378:   float: left;
 6379:   padding-right: 5%;
 6380:   padding-bottom: 4px;
 6381: }
 6382: 
 6383: div.LC_clear_float_header {
 6384:   padding-bottom: 2px;
 6385: }
 6386: 
 6387: div.LC_clear_float_footer {
 6388:   padding-top: 10px;
 6389:   clear: both;
 6390: }
 6391: 
 6392: div.LC_grade_show_user {
 6393: /*  border-left: 5px solid $sidebg; */
 6394:   border-top: 5px solid #000000;
 6395:   margin: 50px 0 0 0;
 6396:   padding: 15px 0 5px 10px;
 6397: }
 6398: 
 6399: div.LC_grade_show_user_odd_row {
 6400: /*  border-left: 5px solid #000000; */
 6401: }
 6402: 
 6403: div.LC_grade_show_user div.LC_Box {
 6404:   margin-right: 50px;
 6405: }
 6406: 
 6407: div.LC_grade_submissions,
 6408: div.LC_grade_message_center,
 6409: div.LC_grade_info_links {
 6410:   margin: 5px;
 6411:   width: 99%;
 6412:   background: #FFFFFF;
 6413: }
 6414: 
 6415: div.LC_grade_submissions_header,
 6416: div.LC_grade_message_center_header {
 6417:   font-weight: bold;
 6418:   font-size: large;
 6419: }
 6420: 
 6421: div.LC_grade_submissions_body,
 6422: div.LC_grade_message_center_body {
 6423:   border: 1px solid black;
 6424:   width: 99%;
 6425:   background: #FFFFFF;
 6426: }
 6427: 
 6428: table.LC_scantron_action {
 6429:   width: 100%;
 6430: }
 6431: 
 6432: table.LC_scantron_action tr th {
 6433:   font-weight:bold;
 6434:   font-style:normal;
 6435: }
 6436: 
 6437: .LC_edit_problem_header,
 6438: div.LC_edit_problem_footer {
 6439:   font-weight: normal;
 6440:   font-size:  medium;
 6441:   margin: 2px;
 6442:   background-color: $sidebg;
 6443: }
 6444: 
 6445: div.LC_edit_problem_header,
 6446: div.LC_edit_problem_header div,
 6447: div.LC_edit_problem_footer,
 6448: div.LC_edit_problem_footer div,
 6449: div.LC_edit_problem_editxml_header,
 6450: div.LC_edit_problem_editxml_header div {
 6451:   margin-top: 5px;
 6452: }
 6453: 
 6454: div.LC_edit_problem_header_title {
 6455:   font-weight: bold;
 6456:   font-size: larger;
 6457:   background: $tabbg;
 6458:   padding: 3px;
 6459:   margin: 0 0 5px 0;
 6460: }
 6461: 
 6462: table.LC_edit_problem_header_title {
 6463:   width: 100%;
 6464:   background: $tabbg;
 6465: }
 6466: 
 6467: div.LC_edit_problem_discards {
 6468:   float: left;
 6469:   padding-bottom: 5px;
 6470: }
 6471: 
 6472: div.LC_edit_problem_saves {
 6473:   float: right;
 6474:   padding-bottom: 5px;
 6475: }
 6476: 
 6477: .LC_edit_opt {
 6478:   padding-left: 1em;
 6479:   white-space: nowrap;
 6480: }
 6481: 
 6482: img.stift {
 6483:   border-width: 0;
 6484:   vertical-align: middle;
 6485: }
 6486: 
 6487: table td.LC_mainmenu_col_fieldset {
 6488:   vertical-align: top;
 6489: }
 6490: 
 6491: div.LC_createcourse {
 6492:   margin: 10px 10px 10px 10px;
 6493: }
 6494: 
 6495: .LC_dccid {
 6496:   float: right;
 6497:   margin: 0.2em 0 0 0;
 6498:   padding: 0;
 6499:   font-size: 90%;
 6500:   display:none;
 6501: }
 6502: 
 6503: ol.LC_primary_menu a:hover,
 6504: ol#LC_MenuBreadcrumbs a:hover,
 6505: ol#LC_PathBreadcrumbs a:hover,
 6506: ul#LC_secondary_menu a:hover,
 6507: .LC_FormSectionClearButton input:hover
 6508: ul.LC_TabContent   li:hover a {
 6509:   color:$button_hover;
 6510:   text-decoration:none;
 6511: }
 6512: 
 6513: h1 {
 6514:   padding: 0;
 6515:   line-height:130%;
 6516: }
 6517: 
 6518: h2,
 6519: h3,
 6520: h4,
 6521: h5,
 6522: h6 {
 6523:   margin: 5px 0 5px 0;
 6524:   padding: 0;
 6525:   line-height:130%;
 6526: }
 6527: 
 6528: .LC_hcell {
 6529:   padding:3px 15px 3px 15px;
 6530:   margin: 0;
 6531:   background-color:$tabbg;
 6532:   color:$fontmenu;
 6533:   border-bottom:solid 1px $lg_border_color;
 6534: }
 6535: 
 6536: .LC_Box > .LC_hcell {
 6537:   margin: 0 -10px 10px -10px;
 6538: }
 6539: 
 6540: .LC_noBorder {
 6541:   border: 0;
 6542: }
 6543: 
 6544: .LC_FormSectionClearButton input {
 6545:   background-color:transparent;
 6546:   border: none;
 6547:   cursor:pointer;
 6548:   text-decoration:underline;
 6549: }
 6550: 
 6551: .LC_help_open_topic {
 6552:   color: #FFFFFF;
 6553:   background-color: #EEEEFF;
 6554:   margin: 1px;
 6555:   padding: 4px;
 6556:   border: 1px solid #000033;
 6557:   white-space: nowrap;
 6558:   /* vertical-align: middle; */
 6559: }
 6560: 
 6561: dl,
 6562: ul,
 6563: div,
 6564: fieldset {
 6565:   margin: 10px 10px 10px 0;
 6566:   /* overflow: hidden; */
 6567: }
 6568: 
 6569: fieldset > legend {
 6570:   font-weight: bold;
 6571:   padding: 0 5px 0 5px;
 6572: }
 6573: 
 6574: #LC_nav_bar {
 6575:   float: left;
 6576:   background-color: $pgbg_or_bgcolor;
 6577:   margin: 0 0 2px 0;
 6578: }
 6579: 
 6580: #LC_realm {
 6581:   margin: 0.2em 0 0 0;
 6582:   padding: 0;
 6583:   font-weight: bold;
 6584:   text-align: center;
 6585:   background-color: $pgbg_or_bgcolor;
 6586: }
 6587: 
 6588: #LC_nav_bar em {
 6589:   font-weight: bold;
 6590:   font-style: normal;
 6591: }
 6592: 
 6593: ol.LC_primary_menu {
 6594:   margin: 0;
 6595:   padding: 0;
 6596:   background-color: $pgbg_or_bgcolor;
 6597: }
 6598: 
 6599: ol#LC_PathBreadcrumbs {
 6600:   margin: 0;
 6601: }
 6602: 
 6603: ol.LC_primary_menu li {
 6604:   color: RGB(80, 80, 80);
 6605:   vertical-align: middle;
 6606:   text-align: left;
 6607:   list-style: none;
 6608:   float: left;
 6609: }
 6610: 
 6611: ol.LC_primary_menu li a {
 6612:   display: block;
 6613:   margin: 0;
 6614:   padding: 0 5px 0 10px;
 6615:   text-decoration: none;
 6616: }
 6617: 
 6618: ol.LC_primary_menu li ul {
 6619:   display: none;
 6620:   width: 10em;
 6621:   background-color: $data_table_light;
 6622: }
 6623: 
 6624: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6625:   display: block;
 6626:   position: absolute;
 6627:   margin: 0;
 6628:   padding: 0;
 6629:   z-index: 2;
 6630: }
 6631: 
 6632: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6633:   font-size: 90%;
 6634:   vertical-align: top;
 6635:   float: none;
 6636:   border-left: 1px solid black;
 6637:   border-right: 1px solid black;
 6638: }
 6639: 
 6640: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6641:   background-color:$data_table_light;
 6642: }
 6643: 
 6644: ol.LC_primary_menu li li a:hover {
 6645:    color:$button_hover;
 6646:    background-color:$data_table_dark;
 6647: }
 6648: 
 6649: ol.LC_primary_menu li img {
 6650:   vertical-align: bottom;
 6651:   height: 1.1em;
 6652:   margin: 0.2em 0 0 0;
 6653: }
 6654: 
 6655: ol.LC_primary_menu a {
 6656:   color: RGB(80, 80, 80);
 6657:   text-decoration: none;
 6658: }
 6659: 
 6660: ol.LC_primary_menu a.LC_new_message {
 6661:   font-weight:bold;
 6662:   color: darkred;
 6663: }
 6664: 
 6665: ol.LC_docs_parameters {
 6666:   margin-left: 0;
 6667:   padding: 0;
 6668:   list-style: none;
 6669: }
 6670: 
 6671: ol.LC_docs_parameters li {
 6672:   margin: 0;
 6673:   padding-right: 20px;
 6674:   display: inline;
 6675: }
 6676: 
 6677: ol.LC_docs_parameters li:before {
 6678:   content: "\\002022 \\0020";
 6679: }
 6680: 
 6681: li.LC_docs_parameters_title {
 6682:   font-weight: bold;
 6683: }
 6684: 
 6685: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6686:   content: "";
 6687: }
 6688: 
 6689: ul#LC_secondary_menu {
 6690:   clear: right;
 6691:   color: $fontmenu;
 6692:   background: $tabbg;
 6693:   list-style: none;
 6694:   padding: 0;
 6695:   margin: 0;
 6696:   width: 100%;
 6697:   text-align: left;
 6698:   float: left;
 6699: }
 6700: 
 6701: ul#LC_secondary_menu li {
 6702:   font-weight: bold;
 6703:   line-height: 1.8em;
 6704:   border-right: 1px solid black;
 6705:   vertical-align: middle;
 6706:   float: left;
 6707: }
 6708: 
 6709: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6710:   background-color: $data_table_light;
 6711: }
 6712: 
 6713: ul#LC_secondary_menu li a {
 6714:   padding: 0 0.8em;
 6715: }
 6716: 
 6717: ul#LC_secondary_menu li ul {
 6718:   display: none;
 6719: }
 6720: 
 6721: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6722:   display: block;
 6723:   position: absolute;
 6724:   margin: 0;
 6725:   padding: 0;
 6726:   list-style:none;
 6727:   float: none;
 6728:   background-color: $data_table_light;
 6729:   z-index: 2;
 6730:   margin-left: -1px;
 6731: }
 6732: 
 6733: ul#LC_secondary_menu li ul li {
 6734:   font-size: 90%;
 6735:   vertical-align: top;
 6736:   border-left: 1px solid black;
 6737:   border-right: 1px solid black;
 6738:   background-color: $data_table_light;
 6739:   list-style:none;
 6740:   float: none;
 6741: }
 6742: 
 6743: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6744:   background-color: $data_table_dark;
 6745: }
 6746: 
 6747: ul.LC_TabContent {
 6748:   display:block;
 6749:   background: $sidebg;
 6750:   border-bottom: solid 1px $lg_border_color;
 6751:   list-style:none;
 6752:   margin: -1px -10px 0 -10px;
 6753:   padding: 0;
 6754: }
 6755: 
 6756: ul.LC_TabContent li,
 6757: ul.LC_TabContentBigger li {
 6758:   float:left;
 6759: }
 6760: 
 6761: ul#LC_secondary_menu li a {
 6762:   color: $fontmenu;
 6763:   text-decoration: none;
 6764: }
 6765: 
 6766: ul.LC_TabContent {
 6767:   min-height:20px;
 6768: }
 6769: 
 6770: ul.LC_TabContent li {
 6771:   vertical-align:middle;
 6772:   padding: 0 16px 0 10px;
 6773:   background-color:$tabbg;
 6774:   border-bottom:solid 1px $lg_border_color;
 6775:   border-left: solid 1px $font;
 6776: }
 6777: 
 6778: ul.LC_TabContent .right {
 6779:   float:right;
 6780: }
 6781: 
 6782: ul.LC_TabContent li a,
 6783: ul.LC_TabContent li {
 6784:   color:rgb(47,47,47);
 6785:   text-decoration:none;
 6786:   font-size:95%;
 6787:   font-weight:bold;
 6788:   min-height:20px;
 6789: }
 6790: 
 6791: ul.LC_TabContent li a:hover,
 6792: ul.LC_TabContent li a:focus {
 6793:   color: $button_hover;
 6794:   background:none;
 6795:   outline:none;
 6796: }
 6797: 
 6798: ul.LC_TabContent li:hover {
 6799:   color: $button_hover;
 6800:   cursor:pointer;
 6801: }
 6802: 
 6803: ul.LC_TabContent li.active {
 6804:   color: $font;
 6805:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6806:   border-bottom:solid 1px #FFFFFF;
 6807:   cursor: default;
 6808: }
 6809: 
 6810: ul.LC_TabContent li.active a {
 6811:   color:$font;
 6812:   background:#FFFFFF;
 6813:   outline: none;
 6814: }
 6815: 
 6816: ul.LC_TabContent li.goback {
 6817:   float: left;
 6818:   border-left: none;
 6819: }
 6820: 
 6821: #maincoursedoc {
 6822:   clear:both;
 6823: }
 6824: 
 6825: ul.LC_TabContentBigger {
 6826:   display:block;
 6827:   list-style:none;
 6828:   padding: 0;
 6829: }
 6830: 
 6831: ul.LC_TabContentBigger li {
 6832:   vertical-align:bottom;
 6833:   height: 30px;
 6834:   font-size:110%;
 6835:   font-weight:bold;
 6836:   color: #737373;
 6837: }
 6838: 
 6839: ul.LC_TabContentBigger li.active {
 6840:   position: relative;
 6841:   top: 1px;
 6842: }
 6843: 
 6844: ul.LC_TabContentBigger li a {
 6845:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6846:   height: 30px;
 6847:   line-height: 30px;
 6848:   text-align: center;
 6849:   display: block;
 6850:   text-decoration: none;
 6851:   outline: none;  
 6852: }
 6853: 
 6854: ul.LC_TabContentBigger li.active a {
 6855:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6856:   color:$font;
 6857: }
 6858: 
 6859: ul.LC_TabContentBigger li b {
 6860:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6861:   display: block;
 6862:   float: left;
 6863:   padding: 0 30px;
 6864:   border-bottom: 1px solid $lg_border_color;
 6865: }
 6866: 
 6867: ul.LC_TabContentBigger li:hover b {
 6868:   color:$button_hover;
 6869: }
 6870: 
 6871: ul.LC_TabContentBigger li.active b {
 6872:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6873:   color:$font;
 6874:   border: 0;
 6875: }
 6876: 
 6877: 
 6878: ul.LC_CourseBreadcrumbs {
 6879:   background: $sidebg;
 6880:   height: 2em;
 6881:   padding-left: 10px;
 6882:   margin: 0;
 6883:   list-style-position: inside;
 6884: }
 6885: 
 6886: ol#LC_MenuBreadcrumbs,
 6887: ol#LC_PathBreadcrumbs {
 6888:   padding-left: 10px;
 6889:   margin: 0;
 6890:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6891: }
 6892: 
 6893: ol#LC_MenuBreadcrumbs li,
 6894: ol#LC_PathBreadcrumbs li,
 6895: ul.LC_CourseBreadcrumbs li {
 6896:   display: inline;
 6897:   white-space: normal;  
 6898: }
 6899: 
 6900: ol#LC_MenuBreadcrumbs li a,
 6901: ul.LC_CourseBreadcrumbs li a {
 6902:   text-decoration: none;
 6903:   font-size:90%;
 6904: }
 6905: 
 6906: ol#LC_MenuBreadcrumbs h1 {
 6907:   display: inline;
 6908:   font-size: 90%;
 6909:   line-height: 2.5em;
 6910:   margin: 0;
 6911:   padding: 0;
 6912: }
 6913: 
 6914: ol#LC_PathBreadcrumbs li a {
 6915:   text-decoration:none;
 6916:   font-size:100%;
 6917:   font-weight:bold;
 6918: }
 6919: 
 6920: .LC_Box {
 6921:   border: solid 1px $lg_border_color;
 6922:   padding: 0 10px 10px 10px;
 6923: }
 6924: 
 6925: .LC_DocsBox {
 6926:   border: solid 1px $lg_border_color;
 6927:   padding: 0 0 10px 10px;
 6928: }
 6929: 
 6930: .LC_AboutMe_Image {
 6931:   float:left;
 6932:   margin-right:10px;
 6933: }
 6934: 
 6935: .LC_Clear_AboutMe_Image {
 6936:   clear:left;
 6937: }
 6938: 
 6939: dl.LC_ListStyleClean dt {
 6940:   padding-right: 5px;
 6941:   display: table-header-group;
 6942: }
 6943: 
 6944: dl.LC_ListStyleClean dd {
 6945:   display: table-row;
 6946: }
 6947: 
 6948: .LC_ListStyleClean,
 6949: .LC_ListStyleSimple,
 6950: .LC_ListStyleNormal,
 6951: .LC_ListStyleSpecial {
 6952:   /* display:block; */
 6953:   list-style-position: inside;
 6954:   list-style-type: none;
 6955:   overflow: hidden;
 6956:   padding: 0;
 6957: }
 6958: 
 6959: .LC_ListStyleSimple li,
 6960: .LC_ListStyleSimple dd,
 6961: .LC_ListStyleNormal li,
 6962: .LC_ListStyleNormal dd,
 6963: .LC_ListStyleSpecial li,
 6964: .LC_ListStyleSpecial dd {
 6965:   margin: 0;
 6966:   padding: 5px 5px 5px 10px;
 6967:   clear: both;
 6968: }
 6969: 
 6970: .LC_ListStyleClean li,
 6971: .LC_ListStyleClean dd {
 6972:   padding-top: 0;
 6973:   padding-bottom: 0;
 6974: }
 6975: 
 6976: .LC_ListStyleSimple dd,
 6977: .LC_ListStyleSimple li {
 6978:   border-bottom: solid 1px $lg_border_color;
 6979: }
 6980: 
 6981: .LC_ListStyleSpecial li,
 6982: .LC_ListStyleSpecial dd {
 6983:   list-style-type: none;
 6984:   background-color: RGB(220, 220, 220);
 6985:   margin-bottom: 4px;
 6986: }
 6987: 
 6988: table.LC_SimpleTable {
 6989:   margin:5px;
 6990:   border:solid 1px $lg_border_color;
 6991: }
 6992: 
 6993: table.LC_SimpleTable tr {
 6994:   padding: 0;
 6995:   border:solid 1px $lg_border_color;
 6996: }
 6997: 
 6998: table.LC_SimpleTable thead {
 6999:   background:rgb(220,220,220);
 7000: }
 7001: 
 7002: div.LC_columnSection {
 7003:   display: block;
 7004:   clear: both;
 7005:   overflow: hidden;
 7006:   margin: 0;
 7007: }
 7008: 
 7009: div.LC_columnSection>* {
 7010:   float: left;
 7011:   margin: 10px 20px 10px 0;
 7012:   overflow:hidden;
 7013: }
 7014: 
 7015: table em {
 7016:   font-weight: bold;
 7017:   font-style: normal;
 7018: }
 7019: 
 7020: table.LC_tableBrowseRes,
 7021: table.LC_tableOfContent {
 7022:   border:none;
 7023:   border-spacing: 1px;
 7024:   padding: 3px;
 7025:   background-color: #FFFFFF;
 7026:   font-size: 90%;
 7027: }
 7028: 
 7029: table.LC_tableOfContent {
 7030:   border-collapse: collapse;
 7031: }
 7032: 
 7033: table.LC_tableBrowseRes a,
 7034: table.LC_tableOfContent a {
 7035:   background-color: transparent;
 7036:   text-decoration: none;
 7037: }
 7038: 
 7039: table.LC_tableOfContent img {
 7040:   border: none;
 7041:   height: 1.3em;
 7042:   vertical-align: text-bottom;
 7043:   margin-right: 0.3em;
 7044: }
 7045: 
 7046: a#LC_content_toolbar_firsthomework {
 7047:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7048: }
 7049: 
 7050: a#LC_content_toolbar_everything {
 7051:   background-image:url(/res/adm/pages/show-all.gif);
 7052: }
 7053: 
 7054: a#LC_content_toolbar_uncompleted {
 7055:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7056: }
 7057: 
 7058: #LC_content_toolbar_clearbubbles {
 7059:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7060: }
 7061: 
 7062: a#LC_content_toolbar_changefolder {
 7063:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7064: }
 7065: 
 7066: a#LC_content_toolbar_changefolder_toggled {
 7067:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7068: }
 7069: 
 7070: a#LC_content_toolbar_edittoplevel {
 7071:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7072: }
 7073: 
 7074: ul#LC_toolbar li a:hover {
 7075:   background-position: bottom center;
 7076: }
 7077: 
 7078: ul#LC_toolbar {
 7079:   padding: 0;
 7080:   margin: 2px;
 7081:   list-style:none;
 7082:   position:relative;
 7083:   background-color:white;
 7084:   overflow: auto;
 7085: }
 7086: 
 7087: ul#LC_toolbar li {
 7088:   border:1px solid white;
 7089:   padding: 0;
 7090:   margin: 0;
 7091:   float: left;
 7092:   display:inline;
 7093:   vertical-align:middle;
 7094:   white-space: nowrap;
 7095: }
 7096: 
 7097: 
 7098: a.LC_toolbarItem {
 7099:   display:block;
 7100:   padding: 0;
 7101:   margin: 0;
 7102:   height: 32px;
 7103:   width: 32px;
 7104:   color:white;
 7105:   border: none;
 7106:   background-repeat:no-repeat;
 7107:   background-color:transparent;
 7108: }
 7109: 
 7110: ul.LC_funclist {
 7111:     margin: 0;
 7112:     padding: 0.5em 1em 0.5em 0;
 7113: }
 7114: 
 7115: ul.LC_funclist > li:first-child {
 7116:     font-weight:bold; 
 7117:     margin-left:0.8em;
 7118: }
 7119: 
 7120: ul.LC_funclist + ul.LC_funclist {
 7121:     /* 
 7122:        left border as a seperator if we have more than
 7123:        one list 
 7124:     */
 7125:     border-left: 1px solid $sidebg;
 7126:     /* 
 7127:        this hides the left border behind the border of the 
 7128:        outer box if element is wrapped to the next 'line' 
 7129:     */
 7130:     margin-left: -1px;
 7131: }
 7132: 
 7133: ul.LC_funclist li {
 7134:   display: inline;
 7135:   white-space: nowrap;
 7136:   margin: 0 0 0 25px;
 7137:   line-height: 150%;
 7138: }
 7139: 
 7140: .LC_hidden {
 7141:   display: none;
 7142: }
 7143: 
 7144: .LCmodal-overlay {
 7145: 		position:fixed;
 7146: 		top:0;
 7147: 		right:0;
 7148: 		bottom:0;
 7149: 		left:0;
 7150: 		height:100%;
 7151: 		width:100%;
 7152: 		margin:0;
 7153: 		padding:0;
 7154: 		background:#999;
 7155: 		opacity:.75;
 7156: 		filter: alpha(opacity=75);
 7157: 		-moz-opacity: 0.75;
 7158: 		z-index:101;
 7159: }
 7160: 
 7161: * html .LCmodal-overlay {   
 7162: 		position: absolute;
 7163: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7164: }
 7165: 
 7166: .LCmodal-window {
 7167: 		position:fixed;
 7168: 		top:50%;
 7169: 		left:50%;
 7170: 		margin:0;
 7171: 		padding:0;
 7172: 		z-index:102;
 7173: 	}
 7174: 
 7175: * html .LCmodal-window {
 7176: 		position:absolute;
 7177: }
 7178: 
 7179: .LCclose-window {
 7180: 		position:absolute;
 7181: 		width:32px;
 7182: 		height:32px;
 7183: 		right:8px;
 7184: 		top:8px;
 7185: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7186: 		text-indent:-99999px;
 7187: 		overflow:hidden;
 7188: 		cursor:pointer;
 7189: }
 7190: 
 7191: /*
 7192:   styles used by TTH when "Default set of options to pass to tth/m
 7193:   when converting TeX" in course settings has been set
 7194: 
 7195:   option passed: -t
 7196: 
 7197: */
 7198: 
 7199: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7200: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7201: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7202: td div.norm {line-height:normal;}
 7203: 
 7204: /*
 7205:   option passed -y3
 7206: */
 7207: 
 7208: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7209: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7210: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7211: 
 7212: END
 7213: }
 7214: 
 7215: =pod
 7216: 
 7217: =item * &headtag()
 7218: 
 7219: Returns a uniform footer for LON-CAPA web pages.
 7220: 
 7221: Inputs: $title - optional title for the head
 7222:         $head_extra - optional extra HTML to put inside the <head>
 7223:         $args - optional arguments
 7224:             force_register - if is true call registerurl so the remote is 
 7225:                              informed
 7226:             redirect       -> array ref of
 7227:                                    1- seconds before redirect occurs
 7228:                                    2- url to redirect to
 7229:                                    3- whether the side effect should occur
 7230:                            (side effect of setting 
 7231:                                $env{'internal.head.redirect'} to the url 
 7232:                                redirected too)
 7233:             domain         -> force to color decorate a page for a specific
 7234:                                domain
 7235:             function       -> force usage of a specific rolish color scheme
 7236:             bgcolor        -> override the default page bgcolor
 7237:             no_auto_mt_title
 7238:                            -> prevent &mt()ing the title arg
 7239: 
 7240: =cut
 7241: 
 7242: sub headtag {
 7243:     my ($title,$head_extra,$args) = @_;
 7244:     
 7245:     my $function = $args->{'function'} || &get_users_function();
 7246:     my $domain   = $args->{'domain'}   || &determinedomain();
 7247:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7248:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7249: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7250: 		   #time(),
 7251: 		   $env{'environment.color.timestamp'},
 7252: 		   $function,$domain,$bgcolor);
 7253: 
 7254:     $url = '/adm/css/'.&escape($url).'.css';
 7255: 
 7256:     my $result =
 7257: 	'<head>'.
 7258: 	&font_settings();
 7259: 
 7260:     my $inhibitprint = &print_suppression();
 7261: 
 7262:     if (!$args->{'frameset'}) {
 7263: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7264:     }
 7265:     if ($args->{'force_register'}) {
 7266:         $result .= &Apache::lonmenu::registerurl(1);
 7267:     }
 7268:     if (!$args->{'no_nav_bar'} 
 7269: 	&& !$args->{'only_body'}
 7270: 	&& !$args->{'frameset'}) {
 7271: 	$result .= &help_menu_js();
 7272:         $result.=&modal_window();
 7273:         $result.=&togglebox_script();
 7274:         $result.=&wishlist_window();
 7275:         $result.=&LCprogressbarUpdate_script();
 7276:     } else {
 7277:         if ($args->{'add_modal'}) {
 7278:            $result.=&modal_window();
 7279:         }
 7280:         if ($args->{'add_wishlist'}) {
 7281:            $result.=&wishlist_window();
 7282:         }
 7283:         if ($args->{'add_togglebox'}) {
 7284:            $result.=&togglebox_script();
 7285:         }
 7286:         if ($args->{'add_progressbar'}) {
 7287:            $result.=&LCprogressbarUpdate_script();
 7288:         }
 7289:     }
 7290:     if (ref($args->{'redirect'})) {
 7291: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7292: 	$url = &Apache::lonenc::check_encrypt($url);
 7293: 	if (!$inhibit_continue) {
 7294: 	    $env{'internal.head.redirect'} = $url;
 7295: 	}
 7296: 	$result.=<<ADDMETA
 7297: <meta http-equiv="pragma" content="no-cache" />
 7298: <meta http-equiv="Refresh" content="$time; url=$url" />
 7299: ADDMETA
 7300:     }
 7301:     if (!defined($title)) {
 7302: 	$title = 'The LearningOnline Network with CAPA';
 7303:     }
 7304:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7305:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7306: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7307:         .$inhibitprint
 7308: 	.$head_extra;
 7309:     if ($env{'browser.mobile'}) {
 7310:         $result .= '
 7311: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7312: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7313:     }
 7314:     return $result.'</head>';
 7315: }
 7316: 
 7317: =pod
 7318: 
 7319: =item * &font_settings()
 7320: 
 7321: Returns neccessary <meta> to set the proper encoding
 7322: 
 7323: Inputs: none
 7324: 
 7325: =cut
 7326: 
 7327: sub font_settings {
 7328:     my $headerstring='';
 7329:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7330: 	$headerstring.=
 7331: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7332:     }
 7333:     return $headerstring;
 7334: }
 7335: 
 7336: =pod
 7337: 
 7338: =item * &print_suppression()
 7339: 
 7340: In course context returns css which causes the body to be blank when media="print",
 7341: if printout generation is unavailable for the current resource.
 7342: 
 7343: This could be because:
 7344: 
 7345: (a) printstartdate is in the future
 7346: 
 7347: (b) printenddate is in the past
 7348: 
 7349: (c) there is an active exam block with "printout"
 7350: functionality blocked
 7351: 
 7352: Users with pav, pfo or evb privileges are exempt.
 7353: 
 7354: Inputs: none
 7355: 
 7356: =cut
 7357: 
 7358: 
 7359: sub print_suppression {
 7360:     my $noprint;
 7361:     if ($env{'request.course.id'}) {
 7362:         my $scope = $env{'request.course.id'};
 7363:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7364:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7365:             return;
 7366:         }
 7367:         if ($env{'request.course.sec'} ne '') {
 7368:             $scope .= "/$env{'request.course.sec'}";
 7369:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7370:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7371:                 return;
 7372:             }
 7373:         }
 7374:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7375:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7376:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7377:         if ($blocked) {
 7378:             my $checkrole = "cm./$cdom/$cnum";
 7379:             if ($env{'request.course.sec'} ne '') {
 7380:                 $checkrole .= "/$env{'request.course.sec'}";
 7381:             }
 7382:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7383:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7384:                 $noprint = 1;
 7385:             }
 7386:         }
 7387:         unless ($noprint) {
 7388:             my $symb = &Apache::lonnet::symbread();
 7389:             if ($symb ne '') {
 7390:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7391:                 if (ref($navmap)) {
 7392:                     my $res = $navmap->getBySymb($symb);
 7393:                     if (ref($res)) {
 7394:                         if (!$res->resprintable()) {
 7395:                             $noprint = 1;
 7396:                         }
 7397:                     }
 7398:                 }
 7399:             }
 7400:         }
 7401:         if ($noprint) {
 7402:             return <<"ENDSTYLE";
 7403: <style type="text/css" media="print">
 7404:     body { display:none }
 7405: </style>
 7406: ENDSTYLE
 7407:         }
 7408:     }
 7409:     return;
 7410: }
 7411: 
 7412: =pod
 7413: 
 7414: =item * &xml_begin()
 7415: 
 7416: Returns the needed doctype and <html>
 7417: 
 7418: Inputs: none
 7419: 
 7420: =cut
 7421: 
 7422: sub xml_begin {
 7423:     my $output='';
 7424: 
 7425:     if ($env{'browser.mathml'}) {
 7426: 	$output='<?xml version="1.0"?>'
 7427:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7428: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7429:             
 7430: #	    .'<!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">] >'
 7431: 	    .'<!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">'
 7432:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7433: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7434:     } else {
 7435: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7436:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7437:     }
 7438:     return $output;
 7439: }
 7440: 
 7441: =pod
 7442: 
 7443: =item * &start_page()
 7444: 
 7445: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7446: 
 7447: Inputs:
 7448: 
 7449: =over 4
 7450: 
 7451: $title - optional title for the page
 7452: 
 7453: $head_extra - optional extra HTML to incude inside the <head>
 7454: 
 7455: $args - additional optional args supported are:
 7456: 
 7457: =over 8
 7458: 
 7459:              only_body      -> is true will set &bodytag() onlybodytag
 7460:                                     arg on
 7461:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7462:              add_entries    -> additional attributes to add to the  <body>
 7463:              domain         -> force to color decorate a page for a 
 7464:                                     specific domain
 7465:              function       -> force usage of a specific rolish color
 7466:                                     scheme
 7467:              redirect       -> see &headtag()
 7468:              bgcolor        -> override the default page bg color
 7469:              js_ready       -> return a string ready for being used in 
 7470:                                     a javascript writeln
 7471:              html_encode    -> return a string ready for being used in 
 7472:                                     a html attribute
 7473:              force_register -> if is true will turn on the &bodytag()
 7474:                                     $forcereg arg
 7475:              frameset       -> if true will start with a <frameset>
 7476:                                     rather than <body>
 7477:              skip_phases    -> hash ref of 
 7478:                                     head -> skip the <html><head> generation
 7479:                                     body -> skip all <body> generation
 7480:              no_inline_link -> if true and in remote mode, don't show the
 7481:                                     'Switch To Inline Menu' link
 7482:              no_auto_mt_title -> prevent &mt()ing the title arg
 7483:              inherit_jsmath -> when creating popup window in a page,
 7484:                                     should it have jsmath forced on by the
 7485:                                     current page
 7486:              bread_crumbs ->             Array containing breadcrumbs
 7487:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7488:              group          -> includes the current group, if page is for a
 7489:                                specific group
 7490: 
 7491: =back
 7492: 
 7493: =back
 7494: 
 7495: =cut
 7496: 
 7497: sub start_page {
 7498:     my ($title,$head_extra,$args) = @_;
 7499:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7500: 
 7501:     $env{'internal.start_page'}++;
 7502:     my ($result,@advtools);
 7503: 
 7504:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7505:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7506:     }
 7507:     
 7508:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7509: 	if ($args->{'frameset'}) {
 7510: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7511: 						$args->{'add_entries'});
 7512: 	    $result .= "\n<frameset $attr_string>\n";
 7513:         } else {
 7514:             $result .=
 7515:                 &bodytag($title, 
 7516:                          $args->{'function'},       $args->{'add_entries'},
 7517:                          $args->{'only_body'},      $args->{'domain'},
 7518:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7519:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7520:                          $args,                     \@advtools);
 7521:         }
 7522:     }
 7523: 
 7524:     if ($args->{'js_ready'}) {
 7525: 		$result = &js_ready($result);
 7526:     }
 7527:     if ($args->{'html_encode'}) {
 7528: 		$result = &html_encode($result);
 7529:     }
 7530: 
 7531:     # Preparation for new and consistent functionlist at top of screen
 7532:     # if ($args->{'functionlist'}) {
 7533:     #            $result .= &build_functionlist();
 7534:     #}
 7535: 
 7536:     # Don't add anything more if only_body wanted or in const space
 7537:     return $result if    $args->{'only_body'} 
 7538:                       || $env{'request.state'} eq 'construct';
 7539: 
 7540:     #Breadcrumbs
 7541:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7542: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7543: 		#if any br links exists, add them to the breadcrumbs
 7544: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7545: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7546: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7547: 			}
 7548: 		}
 7549:                 # if @advtools array contains items add then to the breadcrumbs
 7550:                 if (@advtools > 0) {
 7551:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7552:                 }
 7553: 
 7554: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7555: 		if(exists($args->{'bread_crumbs_component'})){
 7556: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7557: 		}else{
 7558: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7559: 		}
 7560:     } elsif (($env{'environment.remote'} eq 'on') &&
 7561:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7562:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7563:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7564:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7565:     }
 7566:     return $result;
 7567: }
 7568: 
 7569: sub end_page {
 7570:     my ($args) = @_;
 7571:     $env{'internal.end_page'}++;
 7572:     my $result;
 7573:     if ($args->{'discussion'}) {
 7574: 	my ($target,$parser);
 7575: 	if (ref($args->{'discussion'})) {
 7576: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7577: 				$args->{'discussion'}{'parser'});
 7578: 	}
 7579: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7580:     }
 7581:     if ($args->{'frameset'}) {
 7582: 	$result .= '</frameset>';
 7583:     } else {
 7584: 	$result .= &endbodytag($args);
 7585:     }
 7586:     unless ($args->{'notbody'}) {
 7587:         $result .= "\n</html>";
 7588:     }
 7589: 
 7590:     if ($args->{'js_ready'}) {
 7591: 	$result = &js_ready($result);
 7592:     }
 7593: 
 7594:     if ($args->{'html_encode'}) {
 7595: 	$result = &html_encode($result);
 7596:     }
 7597: 
 7598:     return $result;
 7599: }
 7600: 
 7601: sub wishlist_window {
 7602:     return(<<'ENDWISHLIST');
 7603: <script type="text/javascript">
 7604: // <![CDATA[
 7605: // <!-- BEGIN LON-CAPA Internal
 7606: function set_wishlistlink(title, path) {
 7607:     if (!title) {
 7608:         title = document.title;
 7609:         title = title.replace(/^LON-CAPA /,'');
 7610:     }
 7611:     if (!path) {
 7612:         path = location.pathname;
 7613:     }
 7614:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7615:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7616: }
 7617: // END LON-CAPA Internal -->
 7618: // ]]>
 7619: </script>
 7620: ENDWISHLIST
 7621: }
 7622: 
 7623: sub modal_window {
 7624:     return(<<'ENDMODAL');
 7625: <script type="text/javascript">
 7626: // <![CDATA[
 7627: // <!-- BEGIN LON-CAPA Internal
 7628: var modalWindow = {
 7629: 	parent:"body",
 7630: 	windowId:null,
 7631: 	content:null,
 7632: 	width:null,
 7633: 	height:null,
 7634: 	close:function()
 7635: 	{
 7636: 	        $(".LCmodal-window").remove();
 7637: 	        $(".LCmodal-overlay").remove();
 7638: 	},
 7639: 	open:function()
 7640: 	{
 7641: 		var modal = "";
 7642: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7643: 		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;\">";
 7644: 		modal += this.content;
 7645: 		modal += "</div>";	
 7646: 
 7647: 		$(this.parent).append(modal);
 7648: 
 7649: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7650: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7651: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7652: 	}
 7653: };
 7654: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7655: 	{
 7656: 		modalWindow.windowId = "myModal";
 7657: 		modalWindow.width = width;
 7658: 		modalWindow.height = height;
 7659: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7660: 		modalWindow.open();
 7661: 	};	
 7662: // END LON-CAPA Internal -->
 7663: // ]]>
 7664: </script>
 7665: ENDMODAL
 7666: }
 7667: 
 7668: sub modal_link {
 7669:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7670:     unless ($width) { $width=480; }
 7671:     unless ($height) { $height=400; }
 7672:     unless ($scrolling) { $scrolling='yes'; }
 7673:     unless ($transparency) { $transparency='true'; }
 7674: 
 7675:     my $target_attr;
 7676:     if (defined($target)) {
 7677:         $target_attr = 'target="'.$target.'"';
 7678:     }
 7679:     return <<"ENDLINK";
 7680: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7681:            $linktext</a>
 7682: ENDLINK
 7683: }
 7684: 
 7685: sub modal_adhoc_script {
 7686:     my ($funcname,$width,$height,$content)=@_;
 7687:     return (<<ENDADHOC);
 7688: <script type="text/javascript">
 7689: // <![CDATA[
 7690:         var $funcname = function()
 7691:         {
 7692:                 modalWindow.windowId = "myModal";
 7693:                 modalWindow.width = $width;
 7694:                 modalWindow.height = $height;
 7695:                 modalWindow.content = '$content';
 7696:                 modalWindow.open();
 7697:         };  
 7698: // ]]>
 7699: </script>
 7700: ENDADHOC
 7701: }
 7702: 
 7703: sub modal_adhoc_inner {
 7704:     my ($funcname,$width,$height,$content)=@_;
 7705:     my $innerwidth=$width-20;
 7706:     $content=&js_ready(
 7707:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7708:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7709:                  $content.
 7710:                  &end_scrollbox().
 7711:                  &end_page()
 7712:              );
 7713:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7714: }
 7715: 
 7716: sub modal_adhoc_window {
 7717:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7718:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7719:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7720: }
 7721: 
 7722: sub modal_adhoc_launch {
 7723:     my ($funcname,$width,$height,$content)=@_;
 7724:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7725: <script type="text/javascript">
 7726: // <![CDATA[
 7727: $funcname();
 7728: // ]]>
 7729: </script>
 7730: ENDLAUNCH
 7731: }
 7732: 
 7733: sub modal_adhoc_close {
 7734:     return (<<ENDCLOSE);
 7735: <script type="text/javascript">
 7736: // <![CDATA[
 7737: modalWindow.close();
 7738: // ]]>
 7739: </script>
 7740: ENDCLOSE
 7741: }
 7742: 
 7743: sub togglebox_script {
 7744:    return(<<ENDTOGGLE);
 7745: <script type="text/javascript"> 
 7746: // <![CDATA[
 7747: function LCtoggleDisplay(id,hidetext,showtext) {
 7748:    link = document.getElementById(id + "link").childNodes[0];
 7749:    with (document.getElementById(id).style) {
 7750:       if (display == "none" ) {
 7751:           display = "inline";
 7752:           link.nodeValue = hidetext;
 7753:         } else {
 7754:           display = "none";
 7755:           link.nodeValue = showtext;
 7756:        }
 7757:    }
 7758: }
 7759: // ]]>
 7760: </script>
 7761: ENDTOGGLE
 7762: }
 7763: 
 7764: sub start_togglebox {
 7765:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7766:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7767:     unless ($showtext) { $showtext=&mt('show'); }
 7768:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7769:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7770:     return &start_data_table().
 7771:            &start_data_table_header_row().
 7772:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7773:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7774:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7775:            &end_data_table_header_row().
 7776:            '<tr id="'.$id.'" style="display:none""><td>';
 7777: }
 7778: 
 7779: sub end_togglebox {
 7780:     return '</td></tr>'.&end_data_table();
 7781: }
 7782: 
 7783: sub LCprogressbar_script {
 7784:    my ($id)=@_;
 7785:    return(<<ENDPROGRESS);
 7786: <script type="text/javascript">
 7787: // <![CDATA[
 7788: \$('#progressbar$id').progressbar({
 7789:   value: 0,
 7790:   change: function(event, ui) {
 7791:     var newVal = \$(this).progressbar('option', 'value');
 7792:     \$('.pblabel', this).text(LCprogressTxt);
 7793:   }
 7794: });
 7795: // ]]>
 7796: </script>
 7797: ENDPROGRESS
 7798: }
 7799: 
 7800: sub LCprogressbarUpdate_script {
 7801:    return(<<ENDPROGRESSUPDATE);
 7802: <style type="text/css">
 7803: .ui-progressbar { position:relative; }
 7804: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7805: </style>
 7806: <script type="text/javascript">
 7807: // <![CDATA[
 7808: var LCprogressTxt='---';
 7809: 
 7810: function LCupdateProgress(percent,progresstext,id) {
 7811:    LCprogressTxt=progresstext;
 7812:    \$('#progressbar'+id).progressbar('value',percent);
 7813: }
 7814: // ]]>
 7815: </script>
 7816: ENDPROGRESSUPDATE
 7817: }
 7818: 
 7819: my $LClastpercent;
 7820: my $LCidcnt;
 7821: my $LCcurrentid;
 7822: 
 7823: sub LCprogressbar {
 7824:     my ($r)=(@_);
 7825:     $LClastpercent=0;
 7826:     $LCidcnt++;
 7827:     $LCcurrentid=$$.'_'.$LCidcnt;
 7828:     my $starting=&mt('Starting');
 7829:     my $content=(<<ENDPROGBAR);
 7830:   <div id="progressbar$LCcurrentid">
 7831:     <span class="pblabel">$starting</span>
 7832:   </div>
 7833: ENDPROGBAR
 7834:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7835: }
 7836: 
 7837: sub LCprogressbarUpdate {
 7838:     my ($r,$val,$text)=@_;
 7839:     unless ($val) { 
 7840:        if ($LClastpercent) {
 7841:            $val=$LClastpercent;
 7842:        } else {
 7843:            $val=0;
 7844:        }
 7845:     }
 7846:     if ($val<0) { $val=0; }
 7847:     if ($val>100) { $val=0; }
 7848:     $LClastpercent=$val;
 7849:     unless ($text) { $text=$val.'%'; }
 7850:     $text=&js_ready($text);
 7851:     &r_print($r,<<ENDUPDATE);
 7852: <script type="text/javascript">
 7853: // <![CDATA[
 7854: LCupdateProgress($val,'$text','$LCcurrentid');
 7855: // ]]>
 7856: </script>
 7857: ENDUPDATE
 7858: }
 7859: 
 7860: sub LCprogressbarClose {
 7861:     my ($r)=@_;
 7862:     $LClastpercent=0;
 7863:     &r_print($r,<<ENDCLOSE);
 7864: <script type="text/javascript">
 7865: // <![CDATA[
 7866: \$("#progressbar$LCcurrentid").hide('slow'); 
 7867: // ]]>
 7868: </script>
 7869: ENDCLOSE
 7870: }
 7871: 
 7872: sub r_print {
 7873:     my ($r,$to_print)=@_;
 7874:     if ($r) {
 7875:       $r->print($to_print);
 7876:       $r->rflush();
 7877:     } else {
 7878:       print($to_print);
 7879:     }
 7880: }
 7881: 
 7882: sub html_encode {
 7883:     my ($result) = @_;
 7884: 
 7885:     $result = &HTML::Entities::encode($result,'<>&"');
 7886:     
 7887:     return $result;
 7888: }
 7889: 
 7890: sub js_ready {
 7891:     my ($result) = @_;
 7892: 
 7893:     $result =~ s/[\n\r]/ /xmsg;
 7894:     $result =~ s/\\/\\\\/xmsg;
 7895:     $result =~ s/'/\\'/xmsg;
 7896:     $result =~ s{</}{<\\/}xmsg;
 7897:     
 7898:     return $result;
 7899: }
 7900: 
 7901: sub validate_page {
 7902:     if (  exists($env{'internal.start_page'})
 7903: 	  &&     $env{'internal.start_page'} > 1) {
 7904: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7905: 				 $env{'internal.start_page'}.' '.
 7906: 				 $ENV{'request.filename'});
 7907:     }
 7908:     if (  exists($env{'internal.end_page'})
 7909: 	  &&     $env{'internal.end_page'} > 1) {
 7910: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7911: 				 $env{'internal.end_page'}.' '.
 7912: 				 $env{'request.filename'});
 7913:     }
 7914:     if (     exists($env{'internal.start_page'})
 7915: 	&& ! exists($env{'internal.end_page'})) {
 7916: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7917: 				 $env{'request.filename'});
 7918:     }
 7919:     if (   ! exists($env{'internal.start_page'})
 7920: 	&&   exists($env{'internal.end_page'})) {
 7921: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7922: 				 $env{'request.filename'});
 7923:     }
 7924: }
 7925: 
 7926: 
 7927: sub start_scrollbox {
 7928:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready)=@_;
 7929:     unless ($outerwidth) { $outerwidth='520px'; }
 7930:     unless ($width) { $width='500px'; }
 7931:     unless ($height) { $height='200px'; }
 7932:     my ($table_id,$div_id,$tdcol);
 7933:     if ($id ne '') {
 7934:         $table_id = ' id="table_'.$id.'"';
 7935:         $div_id = ' id="div_'.$id.'"';
 7936:     }
 7937:     if ($bgcolor ne '') {
 7938:         $tdcol = "background-color: $bgcolor;";
 7939:     }
 7940:     my $nicescroll_js;
 7941:     if ($env{'browser.mobile'}) {
 7942:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 7943:     }
 7944:     return <<"END";
 7945: $nicescroll_js
 7946: 
 7947: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 7948: <div style="overflow:auto; width:$width; height: $height;"$div_id>
 7949: END
 7950: }
 7951: 
 7952: sub end_scrollbox {
 7953:     return '</div></td></tr></table>';
 7954: }
 7955: 
 7956: sub nicescroll_javascript {
 7957:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 7958:     my %options;
 7959:     if (ref($cursor) eq 'HASH') {
 7960:         %options = %{$cursor};
 7961:     }
 7962:     unless ($options{'railalign'} =~ /^left|right$/) {
 7963:         $options{'railalign'} = 'left';
 7964:     }
 7965:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7966:         my $function  = &get_users_function();
 7967:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 7968:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7969:             $options{'cursorcolor'} = '#00F';
 7970:         }
 7971:     }
 7972:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 7973:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 7974:             $options{'cursoropacity'}='1.0';
 7975:         }
 7976:     } else {
 7977:         $options{'cursoropacity'}='1.0';
 7978:     }
 7979:     if ($options{'cursorfixedheight'} eq 'none') {
 7980:         delete($options{'cursorfixedheight'});
 7981:     } else {
 7982:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 7983:     }
 7984:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 7985:         delete($options{'railoffset'});
 7986:     }
 7987:     my @niceoptions;
 7988:     while (my($key,$value) = each(%options)) {
 7989:         if ($value =~ /^\{.+\}$/) {
 7990:             push(@niceoptions,$key.':'.$value);
 7991:         } else {
 7992:             push(@niceoptions,$key.':"'.$value.'"');
 7993:         }
 7994:     }
 7995:     my $nicescroll_js = '
 7996: $(document).ready(
 7997:       function() {
 7998:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 7999:       }
 8000: );
 8001: ';
 8002:     if ($framecheck) {
 8003:         $nicescroll_js .= '
 8004: function expand_div(caller) {
 8005:     if (top === self) {
 8006:         document.getElementById("'.$id.'").style.width = "auto";
 8007:         document.getElementById("'.$id.'").style.height = "auto";
 8008:     } else {
 8009:         try {
 8010:             if (parent.frames) {
 8011:                 if (parent.frames.length > 1) {
 8012:                     var framesrc = parent.frames[1].location.href;
 8013:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8014:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8015:                         document.getElementById("'.$id.'").style.width = "auto";
 8016:                         document.getElementById("'.$id.'").style.height = "auto";
 8017:                     }
 8018:                 }
 8019:             }
 8020:         } catch (e) {
 8021:             return;
 8022:         }
 8023:     }
 8024:     return;
 8025: }
 8026: ';
 8027:     }
 8028:     if ($needjsready) {
 8029:         $nicescroll_js = '
 8030: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8031:     } else {
 8032:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8033:     }
 8034:     return $nicescroll_js;
 8035: }
 8036: 
 8037: sub simple_error_page {
 8038:     my ($r,$title,$msg) = @_;
 8039:     my $page =
 8040: 	&Apache::loncommon::start_page($title).
 8041: 	'<p class="LC_error">'.&mt($msg).'</p>'.
 8042: 	&Apache::loncommon::end_page();
 8043:     if (ref($r)) {
 8044: 	$r->print($page);
 8045: 	return;
 8046:     }
 8047:     return $page;
 8048: }
 8049: 
 8050: {
 8051:     my @row_count;
 8052: 
 8053:     sub start_data_table_count {
 8054:         unshift(@row_count, 0);
 8055:         return;
 8056:     }
 8057: 
 8058:     sub end_data_table_count {
 8059:         shift(@row_count);
 8060:         return;
 8061:     }
 8062: 
 8063:     sub start_data_table {
 8064: 	my ($add_class,$id) = @_;
 8065: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8066:         my $table_id;
 8067:         if (defined($id)) {
 8068:             $table_id = ' id="'.$id.'"';
 8069:         }
 8070: 	&start_data_table_count();
 8071: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8072:     }
 8073: 
 8074:     sub end_data_table {
 8075: 	&end_data_table_count();
 8076: 	return '</table>'."\n";;
 8077:     }
 8078: 
 8079:     sub start_data_table_row {
 8080: 	my ($add_class, $id) = @_;
 8081: 	$row_count[0]++;
 8082: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8083: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8084:         $id = (' id="'.$id.'"') unless ($id eq '');
 8085:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8086:     }
 8087:     
 8088:     sub continue_data_table_row {
 8089: 	my ($add_class, $id) = @_;
 8090: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8091: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8092:         $id = (' id="'.$id.'"') unless ($id eq '');
 8093:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8094:     }
 8095: 
 8096:     sub end_data_table_row {
 8097: 	return '</tr>'."\n";;
 8098:     }
 8099: 
 8100:     sub start_data_table_empty_row {
 8101: #	$row_count[0]++;
 8102: 	return  '<tr class="LC_empty_row" >'."\n";;
 8103:     }
 8104: 
 8105:     sub end_data_table_empty_row {
 8106: 	return '</tr>'."\n";;
 8107:     }
 8108: 
 8109:     sub start_data_table_header_row {
 8110: 	return  '<tr class="LC_header_row">'."\n";;
 8111:     }
 8112: 
 8113:     sub end_data_table_header_row {
 8114: 	return '</tr>'."\n";;
 8115:     }
 8116: 
 8117:     sub data_table_caption {
 8118:         my $caption = shift;
 8119:         return "<caption class=\"LC_caption\">$caption</caption>";
 8120:     }
 8121: }
 8122: 
 8123: =pod
 8124: 
 8125: =item * &inhibit_menu_check($arg)
 8126: 
 8127: Checks for a inhibitmenu state and generates output to preserve it
 8128: 
 8129: Inputs:         $arg - can be any of
 8130:                      - undef - in which case the return value is a string 
 8131:                                to add  into arguments list of a uri
 8132:                      - 'input' - in which case the return value is a HTML
 8133:                                  <form> <input> field of type hidden to
 8134:                                  preserve the value
 8135:                      - a url - in which case the return value is the url with
 8136:                                the neccesary cgi args added to preserve the
 8137:                                inhibitmenu state
 8138:                      - a ref to a url - no return value, but the string is
 8139:                                         updated to include the neccessary cgi
 8140:                                         args to preserve the inhibitmenu state
 8141: 
 8142: =cut
 8143: 
 8144: sub inhibit_menu_check {
 8145:     my ($arg) = @_;
 8146:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8147:     if ($arg eq 'input') {
 8148: 	if ($env{'form.inhibitmenu'}) {
 8149: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8150: 	} else {
 8151: 	    return
 8152: 	}
 8153:     }
 8154:     if ($env{'form.inhibitmenu'}) {
 8155: 	if (ref($arg)) {
 8156: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8157: 	} elsif ($arg eq '') {
 8158: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8159: 	} else {
 8160: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8161: 	}
 8162:     }
 8163:     if (!ref($arg)) {
 8164: 	return $arg;
 8165:     }
 8166: }
 8167: 
 8168: ###############################################
 8169: 
 8170: =pod
 8171: 
 8172: =back
 8173: 
 8174: =head1 User Information Routines
 8175: 
 8176: =over 4
 8177: 
 8178: =item * &get_users_function()
 8179: 
 8180: Used by &bodytag to determine the current users primary role.
 8181: Returns either 'student','coordinator','admin', or 'author'.
 8182: 
 8183: =cut
 8184: 
 8185: ###############################################
 8186: sub get_users_function {
 8187:     my $function = 'norole';
 8188:     if ($env{'request.role'}=~/^(st)/) {
 8189:         $function='student';
 8190:     }
 8191:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8192:         $function='coordinator';
 8193:     }
 8194:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8195:         $function='admin';
 8196:     }
 8197:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8198:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8199:         $function='author';
 8200:     }
 8201:     return $function;
 8202: }
 8203: 
 8204: ###############################################
 8205: 
 8206: =pod
 8207: 
 8208: =item * &show_course()
 8209: 
 8210: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8211: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8212: 
 8213: Inputs:
 8214: None
 8215: 
 8216: Outputs:
 8217: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8218: 
 8219: =cut
 8220: 
 8221: ###############################################
 8222: sub show_course {
 8223:     my $course = !$env{'user.adv'};
 8224:     if (!$env{'user.adv'}) {
 8225:         foreach my $env (keys(%env)) {
 8226:             next if ($env !~ m/^user\.priv\./);
 8227:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8228:                 $course = 0;
 8229:                 last;
 8230:             }
 8231:         }
 8232:     }
 8233:     return $course;
 8234: }
 8235: 
 8236: ###############################################
 8237: 
 8238: =pod
 8239: 
 8240: =item * &check_user_status()
 8241: 
 8242: Determines current status of supplied role for a
 8243: specific user. Roles can be active, previous or future.
 8244: 
 8245: Inputs: 
 8246: user's domain, user's username, course's domain,
 8247: course's number, optional section ID.
 8248: 
 8249: Outputs:
 8250: role status: active, previous or future. 
 8251: 
 8252: =cut
 8253: 
 8254: sub check_user_status {
 8255:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8256:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8257:     my @uroles = keys %userinfo;
 8258:     my $srchstr;
 8259:     my $active_chk = 'none';
 8260:     my $now = time;
 8261:     if (@uroles > 0) {
 8262:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8263:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8264:         } else {
 8265:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8266:         }
 8267:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8268:             my $role_end = 0;
 8269:             my $role_start = 0;
 8270:             $active_chk = 'active';
 8271:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8272:                 $role_end = $1;
 8273:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8274:                     $role_start = $1;
 8275:                 }
 8276:             }
 8277:             if ($role_start > 0) {
 8278:                 if ($now < $role_start) {
 8279:                     $active_chk = 'future';
 8280:                 }
 8281:             }
 8282:             if ($role_end > 0) {
 8283:                 if ($now > $role_end) {
 8284:                     $active_chk = 'previous';
 8285:                 }
 8286:             }
 8287:         }
 8288:     }
 8289:     return $active_chk;
 8290: }
 8291: 
 8292: ###############################################
 8293: 
 8294: =pod
 8295: 
 8296: =item * &get_sections()
 8297: 
 8298: Determines all the sections for a course including
 8299: sections with students and sections containing other roles.
 8300: Incoming parameters: 
 8301: 
 8302: 1. domain
 8303: 2. course number 
 8304: 3. reference to array containing roles for which sections should 
 8305: be gathered (optional).
 8306: 4. reference to array containing status types for which sections 
 8307: should be gathered (optional).
 8308: 
 8309: If the third argument is undefined, sections are gathered for any role. 
 8310: If the fourth argument is undefined, sections are gathered for any status.
 8311: Permissible values are 'active' or 'future' or 'previous'.
 8312:  
 8313: Returns section hash (keys are section IDs, values are
 8314: number of users in each section), subject to the
 8315: optional roles filter, optional status filter 
 8316: 
 8317: =cut
 8318: 
 8319: ###############################################
 8320: sub get_sections {
 8321:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8322:     if (!defined($cdom) || !defined($cnum)) {
 8323:         my $cid =  $env{'request.course.id'};
 8324: 
 8325: 	return if (!defined($cid));
 8326: 
 8327:         $cdom = $env{'course.'.$cid.'.domain'};
 8328:         $cnum = $env{'course.'.$cid.'.num'};
 8329:     }
 8330: 
 8331:     my %sectioncount;
 8332:     my $now = time;
 8333: 
 8334:     my $check_students = 1;
 8335:     my $only_students = 0;
 8336:     if (ref($possible_roles) eq 'ARRAY') {
 8337:         if (grep(/^st$/,@{$possible_roles})) {
 8338:             if (@{$possible_roles} == 1) {
 8339:                 $only_students = 1;
 8340:             }
 8341:         } else {
 8342:             $check_students = 0;
 8343:         }
 8344:     }
 8345: 
 8346:     if ($check_students) {
 8347: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8348: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8349: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8350:         my $start_index = &Apache::loncoursedata::CL_START();
 8351:         my $end_index = &Apache::loncoursedata::CL_END();
 8352:         my $status;
 8353: 	while (my ($student,$data) = each(%$classlist)) {
 8354: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8355: 				                     $data->[$status_index],
 8356:                                                      $data->[$start_index],
 8357:                                                      $data->[$end_index]);
 8358:             if ($stu_status eq 'Active') {
 8359:                 $status = 'active';
 8360:             } elsif ($end < $now) {
 8361:                 $status = 'previous';
 8362:             } elsif ($start > $now) {
 8363:                 $status = 'future';
 8364:             } 
 8365: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8366:                 if ((!defined($possible_status)) || (($status ne '') && 
 8367:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8368: 		    $sectioncount{$section}++;
 8369:                 }
 8370: 	    }
 8371: 	}
 8372:     }
 8373:     if ($only_students) {
 8374:         return %sectioncount;
 8375:     }
 8376:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8377:     foreach my $user (sort(keys(%courseroles))) {
 8378: 	if ($user !~ /^(\w{2})/) { next; }
 8379: 	my ($role) = ($user =~ /^(\w{2})/);
 8380: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8381: 	my ($section,$status);
 8382: 	if ($role eq 'cr' &&
 8383: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8384: 	    $section=$1;
 8385: 	}
 8386: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8387: 	if (!defined($section) || $section eq '-1') { next; }
 8388:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8389:         if ($end == -1 && $start == -1) {
 8390:             next; #deleted role
 8391:         }
 8392:         if (!defined($possible_status)) { 
 8393:             $sectioncount{$section}++;
 8394:         } else {
 8395:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8396:                 $status = 'active';
 8397:             } elsif ($end < $now) {
 8398:                 $status = 'future';
 8399:             } elsif ($start > $now) {
 8400:                 $status = 'previous';
 8401:             }
 8402:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8403:                 $sectioncount{$section}++;
 8404:             }
 8405:         }
 8406:     }
 8407:     return %sectioncount;
 8408: }
 8409: 
 8410: ###############################################
 8411: 
 8412: =pod
 8413: 
 8414: =item * &get_course_users()
 8415: 
 8416: Retrieves usernames:domains for users in the specified course
 8417: with specific role(s), and access status. 
 8418: 
 8419: Incoming parameters:
 8420: 1. course domain
 8421: 2. course number
 8422: 3. access status: users must have - either active, 
 8423: previous, future, or all.
 8424: 4. reference to array of permissible roles
 8425: 5. reference to array of section restrictions (optional)
 8426: 6. reference to results object (hash of hashes).
 8427: 7. reference to optional userdata hash
 8428: 8. reference to optional statushash
 8429: 9. flag if privileged users (except those set to unhide in
 8430:    course settings) should be excluded    
 8431: Keys of top level results hash are roles.
 8432: Keys of inner hashes are username:domain, with 
 8433: values set to access type.
 8434: Optional userdata hash returns an array with arguments in the 
 8435: same order as loncoursedata::get_classlist() for student data.
 8436: 
 8437: Optional statushash returns
 8438: 
 8439: Entries for end, start, section and status are blank because
 8440: of the possibility of multiple values for non-student roles.
 8441: 
 8442: =cut
 8443: 
 8444: ###############################################
 8445: 
 8446: sub get_course_users {
 8447:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8448:     my %idx = ();
 8449:     my %seclists;
 8450: 
 8451:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8452:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8453:     $idx{end} = &Apache::loncoursedata::CL_END();
 8454:     $idx{start} = &Apache::loncoursedata::CL_START();
 8455:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8456:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8457:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8458:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8459: 
 8460:     if (grep(/^st$/,@{$roles})) {
 8461:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8462:         my $now = time;
 8463:         foreach my $student (keys(%{$classlist})) {
 8464:             my $match = 0;
 8465:             my $secmatch = 0;
 8466:             my $section = $$classlist{$student}[$idx{section}];
 8467:             my $status = $$classlist{$student}[$idx{status}];
 8468:             if ($section eq '') {
 8469:                 $section = 'none';
 8470:             }
 8471:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8472:                 if (grep(/^all$/,@{$sections})) {
 8473:                     $secmatch = 1;
 8474:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8475:                     if (grep(/^none$/,@{$sections})) {
 8476:                         $secmatch = 1;
 8477:                     }
 8478:                 } else {  
 8479: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8480: 		        $secmatch = 1;
 8481:                     }
 8482: 		}
 8483:                 if (!$secmatch) {
 8484:                     next;
 8485:                 }
 8486:             }
 8487:             if (defined($$types{'active'})) {
 8488:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8489:                     push(@{$$users{st}{$student}},'active');
 8490:                     $match = 1;
 8491:                 }
 8492:             }
 8493:             if (defined($$types{'previous'})) {
 8494:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8495:                     push(@{$$users{st}{$student}},'previous');
 8496:                     $match = 1;
 8497:                 }
 8498:             }
 8499:             if (defined($$types{'future'})) {
 8500:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8501:                     push(@{$$users{st}{$student}},'future');
 8502:                     $match = 1;
 8503:                 }
 8504:             }
 8505:             if ($match) {
 8506:                 push(@{$seclists{$student}},$section);
 8507:                 if (ref($userdata) eq 'HASH') {
 8508:                     $$userdata{$student} = $$classlist{$student};
 8509:                 }
 8510:                 if (ref($statushash) eq 'HASH') {
 8511:                     $statushash->{$student}{'st'}{$section} = $status;
 8512:                 }
 8513:             }
 8514:         }
 8515:     }
 8516:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8517:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8518:         my $now = time;
 8519:         my %displaystatus = ( previous => 'Expired',
 8520:                               active   => 'Active',
 8521:                               future   => 'Future',
 8522:                             );
 8523:         my (%nothide,@possdoms);
 8524:         if ($hidepriv) {
 8525:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8526:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8527:                 if ($user !~ /:/) {
 8528:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8529:                 } else {
 8530:                     $nothide{$user} = 1;
 8531:                 }
 8532:             }
 8533:             my @possdoms = ($cdom);
 8534:             if ($coursehash{'checkforpriv'}) {
 8535:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8536:             }
 8537:         }
 8538:         foreach my $person (sort(keys(%coursepersonnel))) {
 8539:             my $match = 0;
 8540:             my $secmatch = 0;
 8541:             my $status;
 8542:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8543:             $user =~ s/:$//;
 8544:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8545:             if ($end == -1 || $start == -1) {
 8546:                 next;
 8547:             }
 8548:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8549:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8550:                 my ($uname,$udom) = split(/:/,$user);
 8551:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8552:                     if (grep(/^all$/,@{$sections})) {
 8553:                         $secmatch = 1;
 8554:                     } elsif ($usec eq '') {
 8555:                         if (grep(/^none$/,@{$sections})) {
 8556:                             $secmatch = 1;
 8557:                         }
 8558:                     } else {
 8559:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8560:                             $secmatch = 1;
 8561:                         }
 8562:                     }
 8563:                     if (!$secmatch) {
 8564:                         next;
 8565:                     }
 8566:                 }
 8567:                 if ($usec eq '') {
 8568:                     $usec = 'none';
 8569:                 }
 8570:                 if ($uname ne '' && $udom ne '') {
 8571:                     if ($hidepriv) {
 8572:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8573:                             (!$nothide{$uname.':'.$udom})) {
 8574:                             next;
 8575:                         }
 8576:                     }
 8577:                     if ($end > 0 && $end < $now) {
 8578:                         $status = 'previous';
 8579:                     } elsif ($start > $now) {
 8580:                         $status = 'future';
 8581:                     } else {
 8582:                         $status = 'active';
 8583:                     }
 8584:                     foreach my $type (keys(%{$types})) { 
 8585:                         if ($status eq $type) {
 8586:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8587:                                 push(@{$$users{$role}{$user}},$type);
 8588:                             }
 8589:                             $match = 1;
 8590:                         }
 8591:                     }
 8592:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8593:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8594: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8595:                         }
 8596:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8597:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8598:                         }
 8599:                         if (ref($statushash) eq 'HASH') {
 8600:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8601:                         }
 8602:                     }
 8603:                 }
 8604:             }
 8605:         }
 8606:         if (grep(/^ow$/,@{$roles})) {
 8607:             if ((defined($cdom)) && (defined($cnum))) {
 8608:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8609:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8610:                     my $owner = $csettings{'internal.courseowner'};
 8611:                     next if ($owner eq '');
 8612:                     my ($ownername,$ownerdom);
 8613:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8614:                         $ownername = $1;
 8615:                         $ownerdom = $2;
 8616:                     } else {
 8617:                         $ownername = $owner;
 8618:                         $ownerdom = $cdom;
 8619:                         $owner = $ownername.':'.$ownerdom;
 8620:                     }
 8621:                     @{$$users{'ow'}{$owner}} = 'any';
 8622:                     if (defined($userdata) && 
 8623: 			!exists($$userdata{$owner})) {
 8624: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8625:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8626:                             push(@{$seclists{$owner}},'none');
 8627:                         }
 8628:                         if (ref($statushash) eq 'HASH') {
 8629:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8630:                         }
 8631: 		    }
 8632:                 }
 8633:             }
 8634:         }
 8635:         foreach my $user (keys(%seclists)) {
 8636:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8637:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8638:         }
 8639:     }
 8640:     return;
 8641: }
 8642: 
 8643: sub get_user_info {
 8644:     my ($udom,$uname,$idx,$userdata) = @_;
 8645:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8646: 	&plainname($uname,$udom,'lastname');
 8647:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8648:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8649:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8650:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8651:     return;
 8652: }
 8653: 
 8654: ###############################################
 8655: 
 8656: =pod
 8657: 
 8658: =item * &get_user_quota()
 8659: 
 8660: Retrieves quota assigned for storage of user files.
 8661: Default is to report quota for portfolio files.
 8662: 
 8663: Incoming parameters:
 8664: 1. user's username
 8665: 2. user's domain
 8666: 3. quota name - portfolio, author, or course
 8667:    (if no quota name provided, defaults to portfolio).
 8668: 4. crstype - official, unofficial or community, if quota name is
 8669:    course
 8670: 
 8671: Returns:
 8672: 1. Disk quota (in Mb) assigned to student.
 8673: 2. (Optional) Type of setting: custom or default
 8674:    (individually assigned or default for user's 
 8675:    institutional status).
 8676: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8677:    or student - types as defined in localenroll::inst_usertypes 
 8678:    for user's domain, which determines default quota for user.
 8679: 4. (Optional) - Default quota which would apply to the user.
 8680: 
 8681: If a value has been stored in the user's environment, 
 8682: it will return that, otherwise it returns the maximal default
 8683: defined for the user's institutional status(es) in the domain.
 8684: 
 8685: =cut
 8686: 
 8687: ###############################################
 8688: 
 8689: 
 8690: sub get_user_quota {
 8691:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8692:     my ($quota,$quotatype,$settingstatus,$defquota);
 8693:     if (!defined($udom)) {
 8694:         $udom = $env{'user.domain'};
 8695:     }
 8696:     if (!defined($uname)) {
 8697:         $uname = $env{'user.name'};
 8698:     }
 8699:     if (($udom eq '' || $uname eq '') ||
 8700:         ($udom eq 'public') && ($uname eq 'public')) {
 8701:         $quota = 0;
 8702:         $quotatype = 'default';
 8703:         $defquota = 0; 
 8704:     } else {
 8705:         my $inststatus;
 8706:         if ($quotaname eq 'course') {
 8707:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8708:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8709:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8710:             } else {
 8711:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8712:                 $quota = $cenv{'internal.uploadquota'};
 8713:             }
 8714:         } else {
 8715:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8716:                 if ($quotaname eq 'author') {
 8717:                     $quota = $env{'environment.authorquota'};
 8718:                 } else {
 8719:                     $quota = $env{'environment.portfolioquota'};
 8720:                 }
 8721:                 $inststatus = $env{'environment.inststatus'};
 8722:             } else {
 8723:                 my %userenv = 
 8724:                     &Apache::lonnet::get('environment',['portfolioquota',
 8725:                                          'authorquota','inststatus'],$udom,$uname);
 8726:                 my ($tmp) = keys(%userenv);
 8727:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8728:                     if ($quotaname eq 'author') {
 8729:                         $quota = $userenv{'authorquota'};
 8730:                     } else {
 8731:                         $quota = $userenv{'portfolioquota'};
 8732:                     }
 8733:                     $inststatus = $userenv{'inststatus'};
 8734:                 } else {
 8735:                     undef(%userenv);
 8736:                 }
 8737:             }
 8738:         }
 8739:         if ($quota eq '' || wantarray) {
 8740:             if ($quotaname eq 'course') {
 8741:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8742:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || ($crstype eq 'community')) {
 8743:                     $defquota = $domdefs{$crstype.'quota'};
 8744:                 }
 8745:                 if ($defquota eq '') {
 8746:                     $defquota = 500;
 8747:                 }
 8748:             } else {
 8749:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8750:             }
 8751:             if ($quota eq '') {
 8752:                 $quota = $defquota;
 8753:                 $quotatype = 'default';
 8754:             } else {
 8755:                 $quotatype = 'custom';
 8756:             }
 8757:         }
 8758:     }
 8759:     if (wantarray) {
 8760:         return ($quota,$quotatype,$settingstatus,$defquota);
 8761:     } else {
 8762:         return $quota;
 8763:     }
 8764: }
 8765: 
 8766: ###############################################
 8767: 
 8768: =pod
 8769: 
 8770: =item * &default_quota()
 8771: 
 8772: Retrieves default quota assigned for storage of user portfolio files,
 8773: given an (optional) user's institutional status.
 8774: 
 8775: Incoming parameters:
 8776: 
 8777: 1. domain
 8778: 2. (Optional) institutional status(es).  This is a : separated list of 
 8779:    status types (e.g., faculty, staff, student etc.)
 8780:    which apply to the user for whom the default is being retrieved.
 8781:    If the institutional status string in undefined, the domain
 8782:    default quota will be returned.
 8783: 3.  quota name - portfolio, author, or course
 8784:    (if no quota name provided, defaults to portfolio).
 8785: 
 8786: Returns:
 8787: 
 8788: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8789: 2. (Optional) institutional type which determined the value of the
 8790:    default quota.
 8791: 
 8792: If a value has been stored in the domain's configuration db,
 8793: it will return that, otherwise it returns 20 (for backwards 
 8794: compatibility with domains which have not set up a configuration
 8795: db file; the original statically defined portfolio quota was 20 Mb). 
 8796: 
 8797: If the user's status includes multiple types (e.g., staff and student),
 8798: the largest default quota which applies to the user determines the
 8799: default quota returned.
 8800: 
 8801: =cut
 8802: 
 8803: ###############################################
 8804: 
 8805: 
 8806: sub default_quota {
 8807:     my ($udom,$inststatus,$quotaname) = @_;
 8808:     my ($defquota,$settingstatus);
 8809:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8810:                                             ['quotas'],$udom);
 8811:     my $key = 'defaultquota';
 8812:     if ($quotaname eq 'author') {
 8813:         $key = 'authorquota';
 8814:     }
 8815:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8816:         if ($inststatus ne '') {
 8817:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8818:             foreach my $item (@statuses) {
 8819:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8820:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8821:                         if ($defquota eq '') {
 8822:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8823:                             $settingstatus = $item;
 8824:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8825:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8826:                             $settingstatus = $item;
 8827:                         }
 8828:                     }
 8829:                 } elsif ($key eq 'defaultquota') {
 8830:                     if ($quotahash{'quotas'}{$item} ne '') {
 8831:                         if ($defquota eq '') {
 8832:                             $defquota = $quotahash{'quotas'}{$item};
 8833:                             $settingstatus = $item;
 8834:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8835:                             $defquota = $quotahash{'quotas'}{$item};
 8836:                             $settingstatus = $item;
 8837:                         }
 8838:                     }
 8839:                 }
 8840:             }
 8841:         }
 8842:         if ($defquota eq '') {
 8843:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8844:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8845:             } elsif ($key eq 'defaultquota') {
 8846:                 $defquota = $quotahash{'quotas'}{'default'};
 8847:             }
 8848:             $settingstatus = 'default';
 8849:             if ($defquota eq '') {
 8850:                 if ($quotaname eq 'author') {
 8851:                     $defquota = 500;
 8852:                 }
 8853:             }
 8854:         }
 8855:     } else {
 8856:         $settingstatus = 'default';
 8857:         if ($quotaname eq 'author') {
 8858:             $defquota = 500;
 8859:         } else {
 8860:             $defquota = 20;
 8861:         }
 8862:     }
 8863:     if (wantarray) {
 8864:         return ($defquota,$settingstatus);
 8865:     } else {
 8866:         return $defquota;
 8867:     }
 8868: }
 8869: 
 8870: ###############################################
 8871: 
 8872: =pod
 8873: 
 8874: =item * &excess_filesize_warning()
 8875: 
 8876: Returns warning message if upload of file to authoring space, or copying
 8877: of existing file within authoring space will cause quota for the authoring
 8878: space to be exceeded.
 8879: 
 8880: Same, if upload of a file directly to a course/community via Course Editor
 8881: will cause quota for uploaded content for the course to be exceeded.
 8882: 
 8883: Inputs: 6
 8884: 1. username or coursenum
 8885: 2. domain
 8886: 3. context ('author' or 'course')
 8887: 4. filename of file for which action is being requested
 8888: 5. filesize (kB) of file
 8889: 6. action being taken: copy or upload.
 8890: 
 8891: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8892:          otherwise return null.
 8893: 
 8894: =back
 8895: 
 8896: =cut
 8897: 
 8898: sub excess_filesize_warning {
 8899:     my ($uname,$udom,$context,$filename,$filesize,$action) = @_;
 8900:     my $current_disk_usage = 0;
 8901:     my $disk_quota = &get_user_quota($uname,$udom,$context); #expressed in MB
 8902:     if ($context eq 'author') {
 8903:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8904:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8905:     } else {
 8906:         foreach my $subdir ('docs','supplemental') {
 8907:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8908:         }
 8909:     }
 8910:     $disk_quota = int($disk_quota * 1000);
 8911:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8912:         return '<p><span class="LC_warning">'.
 8913:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8914:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
 8915:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8916:                             $disk_quota,$current_disk_usage).
 8917:                '</p>';
 8918:     }
 8919:     return;
 8920: }
 8921: 
 8922: ###############################################
 8923: 
 8924: 
 8925: sub get_secgrprole_info {
 8926:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8927:     my %sections_count = &get_sections($cdom,$cnum);
 8928:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8929:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8930:     my @groups = sort(keys(%curr_groups));
 8931:     my $allroles = [];
 8932:     my $rolehash;
 8933:     my $accesshash = {
 8934:                      active => 'Currently has access',
 8935:                      future => 'Will have future access',
 8936:                      previous => 'Previously had access',
 8937:                   };
 8938:     if ($needroles) {
 8939:         $rolehash = {'all' => 'all'};
 8940:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8941: 	if (&Apache::lonnet::error(%user_roles)) {
 8942: 	    undef(%user_roles);
 8943: 	}
 8944:         foreach my $item (keys(%user_roles)) {
 8945:             my ($role)=split(/\:/,$item,2);
 8946:             if ($role eq 'cr') { next; }
 8947:             if ($role =~ /^cr/) {
 8948:                 $$rolehash{$role} = (split('/',$role))[3];
 8949:             } else {
 8950:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8951:             }
 8952:         }
 8953:         foreach my $key (sort(keys(%{$rolehash}))) {
 8954:             push(@{$allroles},$key);
 8955:         }
 8956:         push (@{$allroles},'st');
 8957:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8958:     }
 8959:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8960: }
 8961: 
 8962: sub user_picker {
 8963:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8964:     my $currdom = $dom;
 8965:     my %curr_selected = (
 8966:                         srchin => 'dom',
 8967:                         srchby => 'lastname',
 8968:                       );
 8969:     my $srchterm;
 8970:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8971:         if ($srch->{'srchby'} ne '') {
 8972:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8973:         }
 8974:         if ($srch->{'srchin'} ne '') {
 8975:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8976:         }
 8977:         if ($srch->{'srchtype'} ne '') {
 8978:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8979:         }
 8980:         if ($srch->{'srchdomain'} ne '') {
 8981:             $currdom = $srch->{'srchdomain'};
 8982:         }
 8983:         $srchterm = $srch->{'srchterm'};
 8984:     }
 8985:     my %lt=&Apache::lonlocal::texthash(
 8986:                     'usr'       => 'Search criteria',
 8987:                     'doma'      => 'Domain/institution to search',
 8988:                     'uname'     => 'username',
 8989:                     'lastname'  => 'last name',
 8990:                     'lastfirst' => 'last name, first name',
 8991:                     'crs'       => 'in this course',
 8992:                     'dom'       => 'in selected LON-CAPA domain', 
 8993:                     'alc'       => 'all LON-CAPA',
 8994:                     'instd'     => 'in institutional directory for selected domain',
 8995:                     'exact'     => 'is',
 8996:                     'contains'  => 'contains',
 8997:                     'begins'    => 'begins with',
 8998:                     'youm'      => "You must include some text to search for.",
 8999:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9000:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9001:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9002:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9003:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9004:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9005:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9006:                                        );
 9007:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9008:     my $srchinsel = ' <select name="srchin">';
 9009: 
 9010:     my @srchins = ('crs','dom','alc','instd');
 9011: 
 9012:     foreach my $option (@srchins) {
 9013:         # FIXME 'alc' option unavailable until 
 9014:         #       loncreateuser::print_user_query_page()
 9015:         #       has been completed.
 9016:         next if ($option eq 'alc');
 9017:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9018:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9019:         if ($curr_selected{'srchin'} eq $option) {
 9020:             $srchinsel .= ' 
 9021:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9022:         } else {
 9023:             $srchinsel .= '
 9024:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9025:         }
 9026:     }
 9027:     $srchinsel .= "\n  </select>\n";
 9028: 
 9029:     my $srchbysel =  ' <select name="srchby">';
 9030:     foreach my $option ('lastname','lastfirst','uname') {
 9031:         if ($curr_selected{'srchby'} eq $option) {
 9032:             $srchbysel .= '
 9033:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9034:         } else {
 9035:             $srchbysel .= '
 9036:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9037:          }
 9038:     }
 9039:     $srchbysel .= "\n  </select>\n";
 9040: 
 9041:     my $srchtypesel = ' <select name="srchtype">';
 9042:     foreach my $option ('begins','contains','exact') {
 9043:         if ($curr_selected{'srchtype'} eq $option) {
 9044:             $srchtypesel .= '
 9045:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9046:         } else {
 9047:             $srchtypesel .= '
 9048:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9049:         }
 9050:     }
 9051:     $srchtypesel .= "\n  </select>\n";
 9052: 
 9053:     my ($newuserscript,$new_user_create);
 9054:     my $context_dom = $env{'request.role.domain'};
 9055:     if ($context eq 'requestcrs') {
 9056:         if ($env{'form.coursedom'} ne '') { 
 9057:             $context_dom = $env{'form.coursedom'};
 9058:         }
 9059:     }
 9060:     if ($forcenewuser) {
 9061:         if (ref($srch) eq 'HASH') {
 9062:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9063:                 if ($cancreate) {
 9064:                     $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>';
 9065:                 } else {
 9066:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9067:                     my %usertypetext = (
 9068:                         official   => 'institutional',
 9069:                         unofficial => 'non-institutional',
 9070:                     );
 9071:                     $new_user_create = '<p class="LC_warning">'
 9072:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9073:                                       .' '
 9074:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9075:                                           ,'<a href="'.$helplink.'">','</a>')
 9076:                                       .'</p><br />';
 9077:                 }
 9078:             }
 9079:         }
 9080: 
 9081:         $newuserscript = <<"ENDSCRIPT";
 9082: 
 9083: function setSearch(createnew,callingForm) {
 9084:     if (createnew == 1) {
 9085:         for (var i=0; i<callingForm.srchby.length; i++) {
 9086:             if (callingForm.srchby.options[i].value == 'uname') {
 9087:                 callingForm.srchby.selectedIndex = i;
 9088:             }
 9089:         }
 9090:         for (var i=0; i<callingForm.srchin.length; i++) {
 9091:             if ( callingForm.srchin.options[i].value == 'dom') {
 9092: 		callingForm.srchin.selectedIndex = i;
 9093:             }
 9094:         }
 9095:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9096:             if (callingForm.srchtype.options[i].value == 'exact') {
 9097:                 callingForm.srchtype.selectedIndex = i;
 9098:             }
 9099:         }
 9100:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9101:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9102:                 callingForm.srchdomain.selectedIndex = i;
 9103:             }
 9104:         }
 9105:     }
 9106: }
 9107: ENDSCRIPT
 9108: 
 9109:     }
 9110: 
 9111:     my $output = <<"END_BLOCK";
 9112: <script type="text/javascript">
 9113: // <![CDATA[
 9114: function validateEntry(callingForm) {
 9115: 
 9116:     var checkok = 1;
 9117:     var srchin;
 9118:     for (var i=0; i<callingForm.srchin.length; i++) {
 9119: 	if ( callingForm.srchin[i].checked ) {
 9120: 	    srchin = callingForm.srchin[i].value;
 9121: 	}
 9122:     }
 9123: 
 9124:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9125:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9126:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9127:     var srchterm =  callingForm.srchterm.value;
 9128:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9129:     var msg = "";
 9130: 
 9131:     if (srchterm == "") {
 9132:         checkok = 0;
 9133:         msg += "$lt{'youm'}\\n";
 9134:     }
 9135: 
 9136:     if (srchtype== 'begins') {
 9137:         if (srchterm.length < 2) {
 9138:             checkok = 0;
 9139:             msg += "$lt{'thte'}\\n";
 9140:         }
 9141:     }
 9142: 
 9143:     if (srchtype== 'contains') {
 9144:         if (srchterm.length < 3) {
 9145:             checkok = 0;
 9146:             msg += "$lt{'thet'}\\n";
 9147:         }
 9148:     }
 9149:     if (srchin == 'instd') {
 9150:         if (srchdomain == '') {
 9151:             checkok = 0;
 9152:             msg += "$lt{'yomc'}\\n";
 9153:         }
 9154:     }
 9155:     if (srchin == 'dom') {
 9156:         if (srchdomain == '') {
 9157:             checkok = 0;
 9158:             msg += "$lt{'ymcd'}\\n";
 9159:         }
 9160:     }
 9161:     if (srchby == 'lastfirst') {
 9162:         if (srchterm.indexOf(",") == -1) {
 9163:             checkok = 0;
 9164:             msg += "$lt{'whus'}\\n";
 9165:         }
 9166:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9167:             checkok = 0;
 9168:             msg += "$lt{'whse'}\\n";
 9169:         }
 9170:     }
 9171:     if (checkok == 0) {
 9172:         alert("$lt{'thfo'}\\n"+msg);
 9173:         return;
 9174:     }
 9175:     if (checkok == 1) {
 9176:         callingForm.submit();
 9177:     }
 9178: }
 9179: 
 9180: $newuserscript
 9181: 
 9182: // ]]>
 9183: </script>
 9184: 
 9185: $new_user_create
 9186: 
 9187: END_BLOCK
 9188: 
 9189:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9190:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9191:                $domform.
 9192:                &Apache::lonhtmlcommon::row_closure().
 9193:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9194:                $srchbysel.
 9195:                $srchtypesel. 
 9196:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9197:                $srchinsel.
 9198:                &Apache::lonhtmlcommon::row_closure(1). 
 9199:                &Apache::lonhtmlcommon::end_pick_box().
 9200:                '<br />';
 9201:     return $output;
 9202: }
 9203: 
 9204: sub user_rule_check {
 9205:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9206:     my $response;
 9207:     if (ref($usershash) eq 'HASH') {
 9208:         foreach my $user (keys(%{$usershash})) {
 9209:             my ($uname,$udom) = split(/:/,$user);
 9210:             next if ($udom eq '' || $uname eq '');
 9211:             my ($id,$newuser);
 9212:             if (ref($usershash->{$user}) eq 'HASH') {
 9213:                 $newuser = $usershash->{$user}->{'newuser'};
 9214:                 $id = $usershash->{$user}->{'id'};
 9215:             }
 9216:             my $inst_response;
 9217:             if (ref($checks) eq 'HASH') {
 9218:                 if (defined($checks->{'username'})) {
 9219:                     ($inst_response,%{$inst_results->{$user}}) = 
 9220:                         &Apache::lonnet::get_instuser($udom,$uname);
 9221:                 } elsif (defined($checks->{'id'})) {
 9222:                     ($inst_response,%{$inst_results->{$user}}) =
 9223:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9224:                 }
 9225:             } else {
 9226:                 ($inst_response,%{$inst_results->{$user}}) =
 9227:                     &Apache::lonnet::get_instuser($udom,$uname);
 9228:                 return;
 9229:             }
 9230:             if (!$got_rules->{$udom}) {
 9231:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9232:                                                   ['usercreation'],$udom);
 9233:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9234:                     foreach my $item ('username','id') {
 9235:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9236:                             $$curr_rules{$udom}{$item} = 
 9237:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9238:                         }
 9239:                     }
 9240:                 }
 9241:                 $got_rules->{$udom} = 1;  
 9242:             }
 9243:             foreach my $item (keys(%{$checks})) {
 9244:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9245:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9246:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9247:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9248:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9249:                                 if ($rule_check{$rule}) {
 9250:                                     $$rulematch{$user}{$item} = $rule;
 9251:                                     if ($inst_response eq 'ok') {
 9252:                                         if (ref($inst_results) eq 'HASH') {
 9253:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9254:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9255:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9256:                                                 }
 9257:                                             }
 9258:                                         }
 9259:                                     }
 9260:                                     last;
 9261:                                 }
 9262:                             }
 9263:                         }
 9264:                     }
 9265:                 }
 9266:             }
 9267:         }
 9268:     }
 9269:     return;
 9270: }
 9271: 
 9272: sub user_rule_formats {
 9273:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9274:     my %text = ( 
 9275:                  'username' => 'Usernames',
 9276:                  'id'       => 'IDs',
 9277:                );
 9278:     my $output;
 9279:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9280:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9281:         if (@{$ruleorder} > 0) {
 9282:             $output = '<br />'.
 9283:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9284:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9285:                       ' <ul>';
 9286:             foreach my $rule (@{$ruleorder}) {
 9287:                 if (ref($curr_rules) eq 'ARRAY') {
 9288:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9289:                         if (ref($rules->{$rule}) eq 'HASH') {
 9290:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9291:                                         $rules->{$rule}{'desc'}.'</li>';
 9292:                         }
 9293:                     }
 9294:                 }
 9295:             }
 9296:             $output .= '</ul>';
 9297:         }
 9298:     }
 9299:     return $output;
 9300: }
 9301: 
 9302: sub instrule_disallow_msg {
 9303:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9304:     my $response;
 9305:     my %text = (
 9306:                   item   => 'username',
 9307:                   items  => 'usernames',
 9308:                   match  => 'matches',
 9309:                   do     => 'does',
 9310:                   action => 'a username',
 9311:                   one    => 'one',
 9312:                );
 9313:     if ($count > 1) {
 9314:         $text{'item'} = 'usernames';
 9315:         $text{'match'} ='match';
 9316:         $text{'do'} = 'do';
 9317:         $text{'action'} = 'usernames',
 9318:         $text{'one'} = 'ones';
 9319:     }
 9320:     if ($checkitem eq 'id') {
 9321:         $text{'items'} = 'IDs';
 9322:         $text{'item'} = 'ID';
 9323:         $text{'action'} = 'an ID';
 9324:         if ($count > 1) {
 9325:             $text{'item'} = 'IDs';
 9326:             $text{'action'} = 'IDs';
 9327:         }
 9328:     }
 9329:     $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 />';
 9330:     if ($mode eq 'upload') {
 9331:         if ($checkitem eq 'username') {
 9332:             $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'}.");
 9333:         } elsif ($checkitem eq 'id') {
 9334:             $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.");
 9335:         }
 9336:     } elsif ($mode eq 'selfcreate') {
 9337:         if ($checkitem eq 'id') {
 9338:             $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.");
 9339:         }
 9340:     } else {
 9341:         if ($checkitem eq 'username') {
 9342:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9343:         } elsif ($checkitem eq 'id') {
 9344:             $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.");
 9345:         }
 9346:     }
 9347:     return $response;
 9348: }
 9349: 
 9350: sub personal_data_fieldtitles {
 9351:     my %fieldtitles = &Apache::lonlocal::texthash (
 9352:                         id => 'Student/Employee ID',
 9353:                         permanentemail => 'E-mail address',
 9354:                         lastname => 'Last Name',
 9355:                         firstname => 'First Name',
 9356:                         middlename => 'Middle Name',
 9357:                         generation => 'Generation',
 9358:                         gen => 'Generation',
 9359:                         inststatus => 'Affiliation',
 9360:                    );
 9361:     return %fieldtitles;
 9362: }
 9363: 
 9364: sub sorted_inst_types {
 9365:     my ($dom) = @_;
 9366:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9367:     my $othertitle = &mt('All users');
 9368:     if ($env{'request.course.id'}) {
 9369:         $othertitle  = &mt('Any users');
 9370:     }
 9371:     my @types;
 9372:     if (ref($order) eq 'ARRAY') {
 9373:         @types = @{$order};
 9374:     }
 9375:     if (@types == 0) {
 9376:         if (ref($usertypes) eq 'HASH') {
 9377:             @types = sort(keys(%{$usertypes}));
 9378:         }
 9379:     }
 9380:     if (keys(%{$usertypes}) > 0) {
 9381:         $othertitle = &mt('Other users');
 9382:     }
 9383:     return ($othertitle,$usertypes,\@types);
 9384: }
 9385: 
 9386: sub get_institutional_codes {
 9387:     my ($settings,$allcourses,$LC_code) = @_;
 9388: # Get complete list of course sections to update
 9389:     my @currsections = ();
 9390:     my @currxlists = ();
 9391:     my $coursecode = $$settings{'internal.coursecode'};
 9392: 
 9393:     if ($$settings{'internal.sectionnums'} ne '') {
 9394:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9395:     }
 9396: 
 9397:     if ($$settings{'internal.crosslistings'} ne '') {
 9398:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9399:     }
 9400: 
 9401:     if (@currxlists > 0) {
 9402:         foreach (@currxlists) {
 9403:             if (m/^([^:]+):(\w*)$/) {
 9404:                 unless (grep/^$1$/,@{$allcourses}) {
 9405:                     push @{$allcourses},$1;
 9406:                     $$LC_code{$1} = $2;
 9407:                 }
 9408:             }
 9409:         }
 9410:     }
 9411:  
 9412:     if (@currsections > 0) {
 9413:         foreach (@currsections) {
 9414:             if (m/^(\w+):(\w*)$/) {
 9415:                 my $sec = $coursecode.$1;
 9416:                 my $lc_sec = $2;
 9417:                 unless (grep/^$sec$/,@{$allcourses}) {
 9418:                     push @{$allcourses},$sec;
 9419:                     $$LC_code{$sec} = $lc_sec;
 9420:                 }
 9421:             }
 9422:         }
 9423:     }
 9424:     return;
 9425: }
 9426: 
 9427: sub get_standard_codeitems {
 9428:     return ('Year','Semester','Department','Number','Section');
 9429: }
 9430: 
 9431: =pod
 9432: 
 9433: =head1 Slot Helpers
 9434: 
 9435: =over 4
 9436: 
 9437: =item * sorted_slots()
 9438: 
 9439: Sorts an array of slot names in order of an optional sort key,
 9440: default sort is by slot start time (earliest first). 
 9441: 
 9442: Inputs:
 9443: 
 9444: =over 4
 9445: 
 9446: slotsarr  - Reference to array of unsorted slot names.
 9447: 
 9448: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9449: 
 9450: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9451: 
 9452: =back
 9453: 
 9454: Returns:
 9455: 
 9456: =over 4
 9457: 
 9458: sorted   - An array of slot names sorted by a specified sort key 
 9459:            (default sort key is start time of the slot).
 9460: 
 9461: =back
 9462: 
 9463: =cut
 9464: 
 9465: 
 9466: sub sorted_slots {
 9467:     my ($slotsarr,$slots,$sortkey) = @_;
 9468:     if ($sortkey eq '') {
 9469:         $sortkey = 'starttime';
 9470:     }
 9471:     my @sorted;
 9472:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9473:         @sorted =
 9474:             sort {
 9475:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9476:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9477:                      }
 9478:                      if (ref($slots->{$a})) { return -1;}
 9479:                      if (ref($slots->{$b})) { return 1;}
 9480:                      return 0;
 9481:                  } @{$slotsarr};
 9482:     }
 9483:     return @sorted;
 9484: }
 9485: 
 9486: =pod
 9487: 
 9488: =item * get_future_slots()
 9489: 
 9490: Inputs:
 9491: 
 9492: =over 4
 9493: 
 9494: cnum - course number
 9495: 
 9496: cdom - course domain
 9497: 
 9498: now - current UNIX time
 9499: 
 9500: symb - optional symb
 9501: 
 9502: =back
 9503: 
 9504: Returns:
 9505: 
 9506: =over 4
 9507: 
 9508: sorted_reservable - ref to array of student_schedulable slots currently 
 9509:                     reservable, ordered by end date of reservation period.
 9510: 
 9511: reservable_now - ref to hash of student_schedulable slots currently
 9512:                  reservable.
 9513: 
 9514:     Keys in inner hash are:
 9515:     (a) symb: either blank or symb to which slot use is restricted.
 9516:     (b) endreserve: end date of reservation period. 
 9517: 
 9518: sorted_future - ref to array of student_schedulable slots reservable in
 9519:                 the future, ordered by start date of reservation period.
 9520: 
 9521: future_reservable - ref to hash of student_schedulable slots reservable
 9522:                     in the future.
 9523: 
 9524:     Keys in inner hash are:
 9525:     (a) symb: either blank or symb to which slot use is restricted.
 9526:     (b) startreserve:  start date of reservation period.
 9527: 
 9528: =back
 9529: 
 9530: =cut
 9531: 
 9532: sub get_future_slots {
 9533:     my ($cnum,$cdom,$now,$symb) = @_;
 9534:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9535:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9536:     foreach my $slot (keys(%slots)) {
 9537:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9538:         if ($symb) {
 9539:             next if (($slots{$slot}->{'symb'} ne '') && 
 9540:                      ($slots{$slot}->{'symb'} ne $symb));
 9541:         }
 9542:         if (($slots{$slot}->{'starttime'} > $now) &&
 9543:             ($slots{$slot}->{'endtime'} > $now)) {
 9544:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9545:                 my $userallowed = 0;
 9546:                 if ($slots{$slot}->{'allowedsections'}) {
 9547:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9548:                     if (!defined($env{'request.role.sec'})
 9549:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9550:                         $userallowed=1;
 9551:                     } else {
 9552:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9553:                             $userallowed=1;
 9554:                         }
 9555:                     }
 9556:                     unless ($userallowed) {
 9557:                         if (defined($env{'request.course.groups'})) {
 9558:                             my @groups = split(/:/,$env{'request.course.groups'});
 9559:                             foreach my $group (@groups) {
 9560:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9561:                                     $userallowed=1;
 9562:                                     last;
 9563:                                 }
 9564:                             }
 9565:                         }
 9566:                     }
 9567:                 }
 9568:                 if ($slots{$slot}->{'allowedusers'}) {
 9569:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9570:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9571:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9572:                         $userallowed = 1;
 9573:                     }
 9574:                 }
 9575:                 next unless($userallowed);
 9576:             }
 9577:             my $startreserve = $slots{$slot}->{'startreserve'};
 9578:             my $endreserve = $slots{$slot}->{'endreserve'};
 9579:             my $symb = $slots{$slot}->{'symb'};
 9580:             if (($startreserve < $now) &&
 9581:                 (!$endreserve || $endreserve > $now)) {
 9582:                 my $lastres = $endreserve;
 9583:                 if (!$lastres) {
 9584:                     $lastres = $slots{$slot}->{'starttime'};
 9585:                 }
 9586:                 $reservable_now{$slot} = {
 9587:                                            symb       => $symb,
 9588:                                            endreserve => $lastres
 9589:                                          };
 9590:             } elsif (($startreserve > $now) &&
 9591:                      (!$endreserve || $endreserve > $startreserve)) {
 9592:                 $future_reservable{$slot} = {
 9593:                                               symb         => $symb,
 9594:                                               startreserve => $startreserve
 9595:                                             };
 9596:             }
 9597:         }
 9598:     }
 9599:     my @unsorted_reservable = keys(%reservable_now);
 9600:     if (@unsorted_reservable > 0) {
 9601:         @sorted_reservable = 
 9602:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9603:     }
 9604:     my @unsorted_future = keys(%future_reservable);
 9605:     if (@unsorted_future > 0) {
 9606:         @sorted_future =
 9607:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9608:     }
 9609:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9610: }
 9611: 
 9612: =pod
 9613: 
 9614: =back
 9615: 
 9616: =head1 HTTP Helpers
 9617: 
 9618: =over 4
 9619: 
 9620: =item * &get_unprocessed_cgi($query,$possible_names)
 9621: 
 9622: Modify the %env hash to contain unprocessed CGI form parameters held in
 9623: $query.  The parameters listed in $possible_names (an array reference),
 9624: will be set in $env{'form.name'} if they do not already exist.
 9625: 
 9626: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9627: $possible_names is an ref to an array of form element names.  As an example:
 9628: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9629: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9630: 
 9631: =cut
 9632: 
 9633: sub get_unprocessed_cgi {
 9634:   my ($query,$possible_names)= @_;
 9635:   # $Apache::lonxml::debug=1;
 9636:   foreach my $pair (split(/&/,$query)) {
 9637:     my ($name, $value) = split(/=/,$pair);
 9638:     $name = &unescape($name);
 9639:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9640:       $value =~ tr/+/ /;
 9641:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9642:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9643:     }
 9644:   }
 9645: }
 9646: 
 9647: =pod
 9648: 
 9649: =item * &cacheheader() 
 9650: 
 9651: returns cache-controlling header code
 9652: 
 9653: =cut
 9654: 
 9655: sub cacheheader {
 9656:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9657:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9658:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9659:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9660:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9661:     return $output;
 9662: }
 9663: 
 9664: =pod
 9665: 
 9666: =item * &no_cache($r) 
 9667: 
 9668: specifies header code to not have cache
 9669: 
 9670: =cut
 9671: 
 9672: sub no_cache {
 9673:     my ($r) = @_;
 9674:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9675: 	$env{'request.method'} ne 'GET') { return ''; }
 9676:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9677:     $r->no_cache(1);
 9678:     $r->header_out("Expires" => $date);
 9679:     $r->header_out("Pragma" => "no-cache");
 9680: }
 9681: 
 9682: sub content_type {
 9683:     my ($r,$type,$charset) = @_;
 9684:     if ($r) {
 9685: 	#  Note that printout.pl calls this with undef for $r.
 9686: 	&no_cache($r);
 9687:     }
 9688:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9689:     unless ($charset) {
 9690: 	$charset=&Apache::lonlocal::current_encoding;
 9691:     }
 9692:     if ($charset) { $type.='; charset='.$charset; }
 9693:     if ($r) {
 9694: 	$r->content_type($type);
 9695:     } else {
 9696: 	print("Content-type: $type\n\n");
 9697:     }
 9698: }
 9699: 
 9700: =pod
 9701: 
 9702: =item * &add_to_env($name,$value) 
 9703: 
 9704: adds $name to the %env hash with value
 9705: $value, if $name already exists, the entry is converted to an array
 9706: reference and $value is added to the array.
 9707: 
 9708: =cut
 9709: 
 9710: sub add_to_env {
 9711:   my ($name,$value)=@_;
 9712:   if (defined($env{$name})) {
 9713:     if (ref($env{$name})) {
 9714:       #already have multiple values
 9715:       push(@{ $env{$name} },$value);
 9716:     } else {
 9717:       #first time seeing multiple values, convert hash entry to an arrayref
 9718:       my $first=$env{$name};
 9719:       undef($env{$name});
 9720:       push(@{ $env{$name} },$first,$value);
 9721:     }
 9722:   } else {
 9723:     $env{$name}=$value;
 9724:   }
 9725: }
 9726: 
 9727: =pod
 9728: 
 9729: =item * &get_env_multiple($name) 
 9730: 
 9731: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9732: values may be defined and end up as an array ref.
 9733: 
 9734: returns an array of values
 9735: 
 9736: =cut
 9737: 
 9738: sub get_env_multiple {
 9739:     my ($name) = @_;
 9740:     my @values;
 9741:     if (defined($env{$name})) {
 9742:         # exists is it an array
 9743:         if (ref($env{$name})) {
 9744:             @values=@{ $env{$name} };
 9745:         } else {
 9746:             $values[0]=$env{$name};
 9747:         }
 9748:     }
 9749:     return(@values);
 9750: }
 9751: 
 9752: sub ask_for_embedded_content {
 9753:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9754:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9755:         %currsubfile,%unused,$rem);
 9756:     my $counter = 0;
 9757:     my $numnew = 0;
 9758:     my $numremref = 0;
 9759:     my $numinvalid = 0;
 9760:     my $numpathchg = 0;
 9761:     my $numexisting = 0;
 9762:     my $numunused = 0;
 9763:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9764:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9765:     my $heading = &mt('Upload embedded files');
 9766:     my $buttontext = &mt('Upload');
 9767: 
 9768:     my ($navmap,$cdom,$cnum);
 9769:     if ($env{'request.course.id'}) {
 9770:         if ($actionurl eq '/adm/dependencies') {
 9771:             $navmap = Apache::lonnavmaps::navmap->new();
 9772:         }
 9773:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9774:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9775:     }
 9776:     if (($actionurl eq '/adm/portfolio') ||
 9777:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9778:         my $current_path='/';
 9779:         if ($env{'form.currentpath'}) {
 9780:             $current_path = $env{'form.currentpath'};
 9781:         }
 9782:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9783:             $udom = $cdom;
 9784:             $uname = $cnum;
 9785:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9786:         } else {
 9787:             $udom = $env{'user.domain'};
 9788:             $uname = $env{'user.name'};
 9789:             $url = '/userfiles/portfolio';
 9790:         }
 9791:         $toplevel = $url.'/';
 9792:         $url .= $current_path;
 9793:         $getpropath = 1;
 9794:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9795:              ($actionurl eq '/adm/imsimport')) { 
 9796:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9797:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9798:         $toplevel = $url;
 9799:         if ($rest ne '') {
 9800:             $url .= $rest;
 9801:         }
 9802:     } elsif ($actionurl eq '/adm/coursedocs') {
 9803:         if (ref($args) eq 'HASH') {
 9804:             $url = $args->{'docs_url'};
 9805:             $toplevel = $url;
 9806:             if ($args->{'context'} eq 'paste') {
 9807:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9808:                 ($path) =
 9809:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9810:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9811:                 $fileloc =~ s{^/}{};
 9812:             }
 9813:         }
 9814:     } elsif ($actionurl eq '/adm/dependencies') {
 9815:         if ($env{'request.course.id'} ne '') {
 9816:             if (ref($args) eq 'HASH') {
 9817:                 $url = $args->{'docs_url'};
 9818:                 $title = $args->{'docs_title'};
 9819:                 $toplevel = $url;
 9820:                 unless ($toplevel =~ m{^/}) {
 9821:                     $toplevel = "/$url";
 9822:                 }
 9823:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9824:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9825:                     $path = $1;
 9826:                 } else {
 9827:                     ($path) =
 9828:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9829:                 }
 9830:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9831:                 $fileloc =~ s{^/}{};
 9832:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9833:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9834:             }
 9835:         }
 9836:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9837:         $udom = $cdom;
 9838:         $uname = $cnum;
 9839:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9840:         $toplevel = $url;
 9841:         $path = $url;
 9842:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9843:         $fileloc =~ s{^/}{};
 9844:     }
 9845:     foreach my $file (keys(%{$allfiles})) {
 9846:         my $embed_file;
 9847:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9848:             $embed_file = $1;
 9849:         } else {
 9850:             $embed_file = $file;
 9851:         }
 9852:         my $absolutepath;
 9853:         if ($embed_file =~ m{^\w+://}) {
 9854:             $newfiles{$embed_file} = 1;
 9855:             $mapping{$embed_file} = $embed_file;
 9856:         } else {
 9857:             if ($embed_file =~ m{^/}) {
 9858:                 $absolutepath = $embed_file;
 9859:                 $embed_file =~ s{^(/+)}{};
 9860:             }
 9861:             if ($embed_file =~ m{/}) {
 9862:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9863:                 $path = &check_for_traversal($path,$url,$toplevel);
 9864:                 my $item = $fname;
 9865:                 if ($path ne '') {
 9866:                     $item = $path.'/'.$fname;
 9867:                     $subdependencies{$path}{$fname} = 1;
 9868:                 } else {
 9869:                     $dependencies{$item} = 1;
 9870:                 }
 9871:                 if ($absolutepath) {
 9872:                     $mapping{$item} = $absolutepath;
 9873:                 } else {
 9874:                     $mapping{$item} = $embed_file;
 9875:                 }
 9876:             } else {
 9877:                 $dependencies{$embed_file} = 1;
 9878:                 if ($absolutepath) {
 9879:                     $mapping{$embed_file} = $absolutepath;
 9880:                 } else {
 9881:                     $mapping{$embed_file} = $embed_file;
 9882:                 }
 9883:             }
 9884:         }
 9885:     }
 9886:     my $dirptr = 16384;
 9887:     foreach my $path (keys(%subdependencies)) {
 9888:         $currsubfile{$path} = {};
 9889:         if (($actionurl eq '/adm/portfolio') ||
 9890:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9891:             my ($sublistref,$listerror) =
 9892:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9893:             if (ref($sublistref) eq 'ARRAY') {
 9894:                 foreach my $line (@{$sublistref}) {
 9895:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9896:                     $currsubfile{$path}{$file_name} = 1;
 9897:                 }
 9898:             }
 9899:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9900:             if (opendir(my $dir,$url.'/'.$path)) {
 9901:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9902:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9903:             }
 9904:         } elsif (($actionurl eq '/adm/dependencies') ||
 9905:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9906:                   ($args->{'context'} eq 'paste')) ||
 9907:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9908:             if ($env{'request.course.id'} ne '') {
 9909:                 my $dir;
 9910:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9911:                     $dir = $fileloc;
 9912:                 } else {
 9913:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9914:                 }
 9915:                 if ($dir ne '') {
 9916:                     my ($sublistref,$listerror) =
 9917:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9918:                     if (ref($sublistref) eq 'ARRAY') {
 9919:                         foreach my $line (@{$sublistref}) {
 9920:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9921:                                 undef,$mtime)=split(/\&/,$line,12);
 9922:                             unless (($testdir&$dirptr) ||
 9923:                                     ($file_name =~ /^\.\.?$/)) {
 9924:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9925:                             }
 9926:                         }
 9927:                     }
 9928:                 }
 9929:             }
 9930:         }
 9931:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9932:             if (exists($currsubfile{$path}{$file})) {
 9933:                 my $item = $path.'/'.$file;
 9934:                 unless ($mapping{$item} eq $item) {
 9935:                     $pathchanges{$item} = 1;
 9936:                 }
 9937:                 $existing{$item} = 1;
 9938:                 $numexisting ++;
 9939:             } else {
 9940:                 $newfiles{$path.'/'.$file} = 1;
 9941:             }
 9942:         }
 9943:         if ($actionurl eq '/adm/dependencies') {
 9944:             foreach my $path (keys(%currsubfile)) {
 9945:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9946:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9947:                          unless ($subdependencies{$path}{$file}) {
 9948:                              next if (($rem ne '') &&
 9949:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9950:                                        (ref($navmap) &&
 9951:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9952:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9953:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9954:                              $unused{$path.'/'.$file} = 1; 
 9955:                          }
 9956:                     }
 9957:                 }
 9958:             }
 9959:         }
 9960:     }
 9961:     my %currfile;
 9962:     if (($actionurl eq '/adm/portfolio') ||
 9963:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9964:         my ($dirlistref,$listerror) =
 9965:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9966:         if (ref($dirlistref) eq 'ARRAY') {
 9967:             foreach my $line (@{$dirlistref}) {
 9968:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9969:                 $currfile{$file_name} = 1;
 9970:             }
 9971:         }
 9972:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9973:         if (opendir(my $dir,$url)) {
 9974:             my @dir_list = grep(!/^\./,readdir($dir));
 9975:             map {$currfile{$_} = 1;} @dir_list;
 9976:         }
 9977:     } elsif (($actionurl eq '/adm/dependencies') ||
 9978:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9979:               ($args->{'context'} eq 'paste')) ||
 9980:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9981:         if ($env{'request.course.id'} ne '') {
 9982:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9983:             if ($dir ne '') {
 9984:                 my ($dirlistref,$listerror) =
 9985:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9986:                 if (ref($dirlistref) eq 'ARRAY') {
 9987:                     foreach my $line (@{$dirlistref}) {
 9988:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9989:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9990:                         unless (($testdir&$dirptr) ||
 9991:                                 ($file_name =~ /^\.\.?$/)) {
 9992:                             $currfile{$file_name} = [$size,$mtime];
 9993:                         }
 9994:                     }
 9995:                 }
 9996:             }
 9997:         }
 9998:     }
 9999:     foreach my $file (keys(%dependencies)) {
10000:         if (exists($currfile{$file})) {
10001:             unless ($mapping{$file} eq $file) {
10002:                 $pathchanges{$file} = 1;
10003:             }
10004:             $existing{$file} = 1;
10005:             $numexisting ++;
10006:         } else {
10007:             $newfiles{$file} = 1;
10008:         }
10009:     }
10010:     foreach my $file (keys(%currfile)) {
10011:         unless (($file eq $filename) ||
10012:                 ($file eq $filename.'.bak') ||
10013:                 ($dependencies{$file})) {
10014:             if ($actionurl eq '/adm/dependencies') {
10015:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10016:                     next if (($rem ne '') &&
10017:                              (($env{"httpref.$rem".$file} ne '') ||
10018:                               (ref($navmap) &&
10019:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10020:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10021:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10022:                 }
10023:             }
10024:             $unused{$file} = 1;
10025:         }
10026:     }
10027:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10028:         ($args->{'context'} eq 'paste')) {
10029:         $counter = scalar(keys(%existing));
10030:         $numpathchg = scalar(keys(%pathchanges));
10031:         return ($output,$counter,$numpathchg,\%existing);
10032:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10033:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10034:         $counter = scalar(keys(%existing));
10035:         $numpathchg = scalar(keys(%pathchanges));
10036:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10037:     }
10038:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10039:         if ($actionurl eq '/adm/dependencies') {
10040:             next if ($embed_file =~ m{^\w+://});
10041:         }
10042:         $upload_output .= &start_data_table_row().
10043:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10044:                           '<span class="LC_filename">'.$embed_file.'</span>';
10045:         unless ($mapping{$embed_file} eq $embed_file) {
10046:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10047:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10048:         }
10049:         $upload_output .= '</td>';
10050:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10051:             $upload_output.='<td align="right">'.
10052:                             '<span class="LC_info LC_fontsize_medium">'.
10053:                             &mt("URL points to web address").'</span>';
10054:             $numremref++;
10055:         } elsif ($args->{'error_on_invalid_names'}
10056:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10057:             $upload_output.='<td align="right"><span class="LC_warning">'.
10058:                             &mt('Invalid characters').'</span>';
10059:             $numinvalid++;
10060:         } else {
10061:             $upload_output .= '<td>'.
10062:                               &embedded_file_element('upload_embedded',$counter,
10063:                                                      $embed_file,\%mapping,
10064:                                                      $allfiles,$codebase,'upload');
10065:             $counter ++;
10066:             $numnew ++;
10067:         }
10068:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10069:     }
10070:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10071:         if ($actionurl eq '/adm/dependencies') {
10072:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10073:             $modify_output .= &start_data_table_row().
10074:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10075:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10076:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10077:                               '<td>'.$size.'</td>'.
10078:                               '<td>'.$mtime.'</td>'.
10079:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10080:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10081:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10082:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10083:                               &embedded_file_element('upload_embedded',$counter,
10084:                                                      $embed_file,\%mapping,
10085:                                                      $allfiles,$codebase,'modify').
10086:                               '</div></td>'.
10087:                               &end_data_table_row()."\n";
10088:             $counter ++;
10089:         } else {
10090:             $upload_output .= &start_data_table_row().
10091:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10092:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10093:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10094:                               &Apache::loncommon::end_data_table_row()."\n";
10095:         }
10096:     }
10097:     my $delidx = $counter;
10098:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10099:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10100:         $delete_output .= &start_data_table_row().
10101:                           '<td><img src="'.&icon($oldfile).'" />'.
10102:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10103:                           '<td>'.$size.'</td>'.
10104:                           '<td>'.$mtime.'</td>'.
10105:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10106:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10107:                           &embedded_file_element('upload_embedded',$delidx,
10108:                                                  $oldfile,\%mapping,$allfiles,
10109:                                                  $codebase,'delete').'</td>'.
10110:                           &end_data_table_row()."\n"; 
10111:         $numunused ++;
10112:         $delidx ++;
10113:     }
10114:     if ($upload_output) {
10115:         $upload_output = &start_data_table().
10116:                          $upload_output.
10117:                          &end_data_table()."\n";
10118:     }
10119:     if ($modify_output) {
10120:         $modify_output = &start_data_table().
10121:                          &start_data_table_header_row().
10122:                          '<th>'.&mt('File').'</th>'.
10123:                          '<th>'.&mt('Size (KB)').'</th>'.
10124:                          '<th>'.&mt('Modified').'</th>'.
10125:                          '<th>'.&mt('Upload replacement?').'</th>'.
10126:                          &end_data_table_header_row().
10127:                          $modify_output.
10128:                          &end_data_table()."\n";
10129:     }
10130:     if ($delete_output) {
10131:         $delete_output = &start_data_table().
10132:                          &start_data_table_header_row().
10133:                          '<th>'.&mt('File').'</th>'.
10134:                          '<th>'.&mt('Size (KB)').'</th>'.
10135:                          '<th>'.&mt('Modified').'</th>'.
10136:                          '<th>'.&mt('Delete?').'</th>'.
10137:                          &end_data_table_header_row().
10138:                          $delete_output.
10139:                          &end_data_table()."\n";
10140:     }
10141:     my $applies = 0;
10142:     if ($numremref) {
10143:         $applies ++;
10144:     }
10145:     if ($numinvalid) {
10146:         $applies ++;
10147:     }
10148:     if ($numexisting) {
10149:         $applies ++;
10150:     }
10151:     if ($counter || $numunused) {
10152:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10153:                   ' method="post" enctype="multipart/form-data">'."\n".
10154:                   $state.'<h3>'.$heading.'</h3>'; 
10155:         if ($actionurl eq '/adm/dependencies') {
10156:             if ($numnew) {
10157:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10158:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10159:                            $upload_output.'<br />'."\n";
10160:             }
10161:             if ($numexisting) {
10162:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10163:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10164:                            $modify_output.'<br />'."\n";
10165:                            $buttontext = &mt('Save changes');
10166:             }
10167:             if ($numunused) {
10168:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10169:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10170:                            $delete_output.'<br />'."\n";
10171:                            $buttontext = &mt('Save changes');
10172:             }
10173:         } else {
10174:             $output .= $upload_output.'<br />'."\n";
10175:         }
10176:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10177:                    $counter.'" />'."\n";
10178:         if ($actionurl eq '/adm/dependencies') { 
10179:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10180:                        $numnew.'" />'."\n";
10181:         } elsif ($actionurl eq '') {
10182:             $output .=  '<input type="hidden" name="phase" value="three" />';
10183:         }
10184:     } elsif ($applies) {
10185:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10186:         if ($applies > 1) {
10187:             $output .=  
10188:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10189:             if ($numremref) {
10190:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10191:             }
10192:             if ($numinvalid) {
10193:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10194:             }
10195:             if ($numexisting) {
10196:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10197:             }
10198:             $output .= '</ul><br />';
10199:         } elsif ($numremref) {
10200:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10201:         } elsif ($numinvalid) {
10202:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10203:         } elsif ($numexisting) {
10204:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10205:         }
10206:         $output .= $upload_output.'<br />';
10207:     }
10208:     my ($pathchange_output,$chgcount);
10209:     $chgcount = $counter;
10210:     if (keys(%pathchanges) > 0) {
10211:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10212:             if ($counter) {
10213:                 $output .= &embedded_file_element('pathchange',$chgcount,
10214:                                                   $embed_file,\%mapping,
10215:                                                   $allfiles,$codebase,'change');
10216:             } else {
10217:                 $pathchange_output .= 
10218:                     &start_data_table_row().
10219:                     '<td><input type ="checkbox" name="namechange" value="'.
10220:                     $chgcount.'" checked="checked" /></td>'.
10221:                     '<td>'.$mapping{$embed_file}.'</td>'.
10222:                     '<td>'.$embed_file.
10223:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10224:                                            \%mapping,$allfiles,$codebase,'change').
10225:                     '</td>'.&end_data_table_row();
10226:             }
10227:             $numpathchg ++;
10228:             $chgcount ++;
10229:         }
10230:     }
10231:     if (($counter) || ($numunused)) {
10232:         if ($numpathchg) {
10233:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10234:                        $numpathchg.'" />'."\n";
10235:         }
10236:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10237:             ($actionurl eq '/adm/imsimport')) {
10238:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10239:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10240:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10241:         } elsif ($actionurl eq '/adm/dependencies') {
10242:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10243:         }
10244:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10245:     } elsif ($numpathchg) {
10246:         my %pathchange = ();
10247:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10248:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10249:             $output .= '<p>'.&mt('or').'</p>'; 
10250:         }
10251:     }
10252:     return ($output,$counter,$numpathchg);
10253: }
10254: 
10255: sub embedded_file_element {
10256:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10257:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10258:                    (ref($codebase) eq 'HASH'));
10259:     my $output;
10260:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10261:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10262:     }
10263:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10264:                &escape($embed_file).'" />';
10265:     unless (($context eq 'upload_embedded') && 
10266:             ($mapping->{$embed_file} eq $embed_file)) {
10267:         $output .='
10268:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10269:     }
10270:     my $attrib;
10271:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10272:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10273:     }
10274:     $output .=
10275:         "\n\t\t".
10276:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10277:         $attrib.'" />';
10278:     if (exists($codebase->{$mapping->{$embed_file}})) {
10279:         $output .=
10280:             "\n\t\t".
10281:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10282:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10283:     }
10284:     return $output;
10285: }
10286: 
10287: sub get_dependency_details {
10288:     my ($currfile,$currsubfile,$embed_file) = @_;
10289:     my ($size,$mtime,$showsize,$showmtime);
10290:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10291:         if ($embed_file =~ m{/}) {
10292:             my ($path,$fname) = split(/\//,$embed_file);
10293:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10294:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10295:             }
10296:         } else {
10297:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10298:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10299:             }
10300:         }
10301:         $showsize = $size/1024.0;
10302:         $showsize = sprintf("%.1f",$showsize);
10303:         if ($mtime > 0) {
10304:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10305:         }
10306:     }
10307:     return ($showsize,$showmtime);
10308: }
10309: 
10310: sub ask_embedded_js {
10311:     return <<"END";
10312: <script type="text/javascript"">
10313: // <![CDATA[
10314: function toggleBrowse(counter) {
10315:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10316:     var fileid = document.getElementById('embedded_item_'+counter);
10317:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10318:     if (chkboxid.checked == true) {
10319:         uploaddivid.style.display='block';
10320:     } else {
10321:         uploaddivid.style.display='none';
10322:         fileid.value = '';
10323:     }
10324: }
10325: // ]]>
10326: </script>
10327: 
10328: END
10329: }
10330: 
10331: sub upload_embedded {
10332:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10333:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10334:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10335:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10336:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10337:         my $orig_uploaded_filename =
10338:             $env{'form.embedded_item_'.$i.'.filename'};
10339:         foreach my $type ('orig','ref','attrib','codebase') {
10340:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10341:                 $env{'form.embedded_'.$type.'_'.$i} =
10342:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10343:             }
10344:         }
10345:         my ($path,$fname) =
10346:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10347:         # no path, whole string is fname
10348:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10349:         $fname = &Apache::lonnet::clean_filename($fname);
10350:         # See if there is anything left
10351:         next if ($fname eq '');
10352: 
10353:         # Check if file already exists as a file or directory.
10354:         my ($state,$msg);
10355:         if ($context eq 'portfolio') {
10356:             my $port_path = $dirpath;
10357:             if ($group ne '') {
10358:                 $port_path = "groups/$group/$port_path";
10359:             }
10360:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10361:                                               $fname,$group,'embedded_item_'.$i,
10362:                                               $dir_root,$port_path,$disk_quota,
10363:                                               $current_disk_usage,$uname,$udom);
10364:             if ($state eq 'will_exceed_quota'
10365:                 || $state eq 'file_locked') {
10366:                 $output .= $msg;
10367:                 next;
10368:             }
10369:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10370:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10371:             if ($state eq 'exists') {
10372:                 $output .= $msg;
10373:                 next;
10374:             }
10375:         }
10376:         # Check if extension is valid
10377:         if (($fname =~ /\.(\w+)$/) &&
10378:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10379:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10380:             next;
10381:         } elsif (($fname =~ /\.(\w+)$/) &&
10382:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10383:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10384:             next;
10385:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10386:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10387:             next;
10388:         }
10389:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10390:         my $subdir = $path;
10391:         $subdir =~ s{/+$}{};
10392:         if ($context eq 'portfolio') {
10393:             my $result;
10394:             if ($state eq 'existingfile') {
10395:                 $result=
10396:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10397:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10398:             } else {
10399:                 $result=
10400:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10401:                                                     $dirpath.
10402:                                                     $env{'form.currentpath'}.$subdir);
10403:                 if ($result !~ m|^/uploaded/|) {
10404:                     $output .= '<span class="LC_error">'
10405:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10406:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10407:                                .'</span><br />';
10408:                     next;
10409:                 } else {
10410:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10411:                                $path.$fname.'</span>').'<br />';     
10412:                 }
10413:             }
10414:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10415:             my $extendedsubdir = $dirpath.'/'.$subdir;
10416:             $extendedsubdir =~ s{/+$}{};
10417:             my $result =
10418:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10419:             if ($result !~ m|^/uploaded/|) {
10420:                 $output .= '<span class="LC_error">'
10421:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10422:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10423:                            .'</span><br />';
10424:                     next;
10425:             } else {
10426:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10427:                            $path.$fname.'</span>').'<br />';
10428:                 if ($context eq 'syllabus') {
10429:                     &Apache::lonnet::make_public_indefinitely($result);
10430:                 }
10431:             }
10432:         } else {
10433: # Save the file
10434:             my $target = $env{'form.embedded_item_'.$i};
10435:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10436:             my $dest = $fullpath.$fname;
10437:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10438:             my @parts=split(/\//,"$dirpath/$path");
10439:             my $count;
10440:             my $filepath = $dir_root;
10441:             foreach my $subdir (@parts) {
10442:                 $filepath .= "/$subdir";
10443:                 if (!-e $filepath) {
10444:                     mkdir($filepath,0770);
10445:                 }
10446:             }
10447:             my $fh;
10448:             if (!open($fh,'>'.$dest)) {
10449:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10450:                 $output .= '<span class="LC_error">'.
10451:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10452:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10453:                            '</span><br />';
10454:             } else {
10455:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10456:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10457:                     $output .= '<span class="LC_error">'.
10458:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10459:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10460:                               '</span><br />';
10461:                 } else {
10462:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10463:                                $url.'</span>').'<br />';
10464:                     unless ($context eq 'testbank') {
10465:                         $footer .= &mt('View embedded file: [_1]',
10466:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10467:                     }
10468:                 }
10469:                 close($fh);
10470:             }
10471:         }
10472:         if ($env{'form.embedded_ref_'.$i}) {
10473:             $pathchange{$i} = 1;
10474:         }
10475:     }
10476:     if ($output) {
10477:         $output = '<p>'.$output.'</p>';
10478:     }
10479:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10480:     $returnflag = 'ok';
10481:     my $numpathchgs = scalar(keys(%pathchange));
10482:     if ($numpathchgs > 0) {
10483:         if ($context eq 'portfolio') {
10484:             $output .= '<p>'.&mt('or').'</p>';
10485:         } elsif ($context eq 'testbank') {
10486:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10487:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10488:             $returnflag = 'modify_orightml';
10489:         }
10490:     }
10491:     return ($output.$footer,$returnflag,$numpathchgs);
10492: }
10493: 
10494: sub modify_html_form {
10495:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10496:     my $end = 0;
10497:     my $modifyform;
10498:     if ($context eq 'upload_embedded') {
10499:         return unless (ref($pathchange) eq 'HASH');
10500:         if ($env{'form.number_embedded_items'}) {
10501:             $end += $env{'form.number_embedded_items'};
10502:         }
10503:         if ($env{'form.number_pathchange_items'}) {
10504:             $end += $env{'form.number_pathchange_items'};
10505:         }
10506:         if ($end) {
10507:             for (my $i=0; $i<$end; $i++) {
10508:                 if ($i < $env{'form.number_embedded_items'}) {
10509:                     next unless($pathchange->{$i});
10510:                 }
10511:                 $modifyform .=
10512:                     &start_data_table_row().
10513:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10514:                     'checked="checked" /></td>'.
10515:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10516:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10517:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10518:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10519:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10520:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10521:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10522:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10523:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10524:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10525:                     &end_data_table_row();
10526:             }
10527:         }
10528:     } else {
10529:         $modifyform = $pathchgtable;
10530:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10531:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10532:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10533:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10534:         }
10535:     }
10536:     if ($modifyform) {
10537:         if ($actionurl eq '/adm/dependencies') {
10538:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10539:         }
10540:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10541:                '<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".
10542:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10543:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10544:                '</ol></p>'."\n".'<p>'.
10545:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10546:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10547:                &start_data_table()."\n".
10548:                &start_data_table_header_row().
10549:                '<th>'.&mt('Change?').'</th>'.
10550:                '<th>'.&mt('Current reference').'</th>'.
10551:                '<th>'.&mt('Required reference').'</th>'.
10552:                &end_data_table_header_row()."\n".
10553:                $modifyform.
10554:                &end_data_table().'<br />'."\n".$hiddenstate.
10555:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10556:                '</form>'."\n";
10557:     }
10558:     return;
10559: }
10560: 
10561: sub modify_html_refs {
10562:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10563:     my $container;
10564:     if ($context eq 'portfolio') {
10565:         $container = $env{'form.container'};
10566:     } elsif ($context eq 'coursedoc') {
10567:         $container = $env{'form.primaryurl'};
10568:     } elsif ($context eq 'manage_dependencies') {
10569:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10570:         $container = "/$container";
10571:     } elsif ($context eq 'syllabus') {
10572:         $container = $url;
10573:     } else {
10574:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10575:     }
10576:     my (%allfiles,%codebase,$output,$content);
10577:     my @changes = &get_env_multiple('form.namechange');
10578:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10579:         if (wantarray) {
10580:             return ('',0,0); 
10581:         } else {
10582:             return;
10583:         }
10584:     }
10585:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10586:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10587:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10588:             if (wantarray) {
10589:                 return ('',0,0);
10590:             } else {
10591:                 return;
10592:             }
10593:         } 
10594:         $content = &Apache::lonnet::getfile($container);
10595:         if ($content eq '-1') {
10596:             if (wantarray) {
10597:                 return ('',0,0);
10598:             } else {
10599:                 return;
10600:             }
10601:         }
10602:     } else {
10603:         unless ($container =~ /^\Q$dir_root\E/) {
10604:             if (wantarray) {
10605:                 return ('',0,0);
10606:             } else {
10607:                 return;
10608:             }
10609:         } 
10610:         if (open(my $fh,"<$container")) {
10611:             $content = join('', <$fh>);
10612:             close($fh);
10613:         } else {
10614:             if (wantarray) {
10615:                 return ('',0,0);
10616:             } else {
10617:                 return;
10618:             }
10619:         }
10620:     }
10621:     my ($count,$codebasecount) = (0,0);
10622:     my $mm = new File::MMagic;
10623:     my $mime_type = $mm->checktype_contents($content);
10624:     if ($mime_type eq 'text/html') {
10625:         my $parse_result = 
10626:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10627:                                                     \%codebase,\$content);
10628:         if ($parse_result eq 'ok') {
10629:             foreach my $i (@changes) {
10630:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10631:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10632:                 if ($allfiles{$ref}) {
10633:                     my $newname =  $orig;
10634:                     my ($attrib_regexp,$codebase);
10635:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10636:                     if ($attrib_regexp =~ /:/) {
10637:                         $attrib_regexp =~ s/\:/|/g;
10638:                     }
10639:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10640:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10641:                         $count += $numchg;
10642:                         $allfiles{$newname} = $allfiles{$ref};
10643:                     }
10644:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10645:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10646:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10647:                         $codebasecount ++;
10648:                     }
10649:                 }
10650:             }
10651:             my $skiprewrites;
10652:             if ($count || $codebasecount) {
10653:                 my $saveresult;
10654:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10655:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10656:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10657:                     if ($url eq $container) {
10658:                         my ($fname) = ($container =~ m{/([^/]+)$});
10659:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10660:                                             $count,'<span class="LC_filename">'.
10661:                                             $fname.'</span>').'</p>';
10662:                     } else {
10663:                          $output = '<p class="LC_error">'.
10664:                                    &mt('Error: update failed for: [_1].',
10665:                                    '<span class="LC_filename">'.
10666:                                    $container.'</span>').'</p>';
10667:                     }
10668:                     if ($context eq 'syllabus') {
10669:                         unless ($saveresult eq 'ok') {
10670:                             $skiprewrites = 1;
10671:                         }
10672:                     }
10673:                 } else {
10674:                     if (open(my $fh,">$container")) {
10675:                         print $fh $content;
10676:                         close($fh);
10677:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10678:                                   $count,'<span class="LC_filename">'.
10679:                                   $container.'</span>').'</p>';
10680:                     } else {
10681:                          $output = '<p class="LC_error">'.
10682:                                    &mt('Error: could not update [_1].',
10683:                                    '<span class="LC_filename">'.
10684:                                    $container.'</span>').'</p>';
10685:                     }
10686:                 }
10687:             }
10688:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10689:                 my ($actionurl,$state);
10690:                 $actionurl = "/public/$udom/$uname/syllabus";
10691:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10692:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10693:                                               \%codebase,
10694:                                               {'context' => 'rewrites',
10695:                                                'ignore_remote_references' => 1,});
10696:                 if (ref($mapping) eq 'HASH') {
10697:                     my $rewrites = 0;
10698:                     foreach my $key (keys(%{$mapping})) {
10699:                         next if ($key =~ m{^https?://});
10700:                         my $ref = $mapping->{$key};
10701:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10702:                         my $attrib;
10703:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10704:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10705:                         }
10706:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10707:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10708:                             $rewrites += $numchg;
10709:                         }
10710:                     }
10711:                     if ($rewrites) {
10712:                         my $saveresult;
10713:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10714:                         if ($url eq $container) {
10715:                             my ($fname) = ($container =~ m{/([^/]+)$});
10716:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10717:                                             $count,'<span class="LC_filename">'.
10718:                                             $fname.'</span>').'</p>';
10719:                         } else {
10720:                             $output .= '<p class="LC_error">'.
10721:                                        &mt('Error: could not update links in [_1].',
10722:                                        '<span class="LC_filename">'.
10723:                                        $container.'</span>').'</p>';
10724: 
10725:                         }
10726:                     }
10727:                 }
10728:             }
10729:         } else {
10730:             &logthis('Failed to parse '.$container.
10731:                      ' to modify references: '.$parse_result);
10732:         }
10733:     }
10734:     if (wantarray) {
10735:         return ($output,$count,$codebasecount);
10736:     } else {
10737:         return $output;
10738:     }
10739: }
10740: 
10741: sub check_for_existing {
10742:     my ($path,$fname,$element) = @_;
10743:     my ($state,$msg);
10744:     if (-d $path.'/'.$fname) {
10745:         $state = 'exists';
10746:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10747:     } elsif (-e $path.'/'.$fname) {
10748:         $state = 'exists';
10749:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10750:     }
10751:     if ($state eq 'exists') {
10752:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10753:     }
10754:     return ($state,$msg);
10755: }
10756: 
10757: sub check_for_upload {
10758:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10759:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10760:     my $filesize = length($env{'form.'.$element});
10761:     if (!$filesize) {
10762:         my $msg = '<span class="LC_error">'.
10763:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10764:                       '<span class="LC_filename">'.$fname.'</span>',
10765:                       $filesize).'<br />'.
10766:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10767:                   '</span>';
10768:         return ('zero_bytes',$msg);
10769:     }
10770:     $filesize =  $filesize/1000; #express in k (1024?)
10771:     my $getpropath = 1;
10772:     my ($dirlistref,$listerror) =
10773:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10774:     my $found_file = 0;
10775:     my $locked_file = 0;
10776:     my @lockers;
10777:     my $navmap;
10778:     if ($env{'request.course.id'}) {
10779:         $navmap = Apache::lonnavmaps::navmap->new();
10780:     }
10781:     if (ref($dirlistref) eq 'ARRAY') {
10782:         foreach my $line (@{$dirlistref}) {
10783:             my ($file_name,$rest)=split(/\&/,$line,2);
10784:             if ($file_name eq $fname){
10785:                 $file_name = $path.$file_name;
10786:                 if ($group ne '') {
10787:                     $file_name = $group.$file_name;
10788:                 }
10789:                 $found_file = 1;
10790:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10791:                     foreach my $lock (@lockers) {
10792:                         if (ref($lock) eq 'ARRAY') {
10793:                             my ($symb,$crsid) = @{$lock};
10794:                             if ($crsid eq $env{'request.course.id'}) {
10795:                                 if (ref($navmap)) {
10796:                                     my $res = $navmap->getBySymb($symb);
10797:                                     foreach my $part (@{$res->parts()}) { 
10798:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10799:                                         unless (($slot_status == $res->RESERVED) ||
10800:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10801:                                             $locked_file = 1;
10802:                                         }
10803:                                     }
10804:                                 } else {
10805:                                     $locked_file = 1;
10806:                                 }
10807:                             } else {
10808:                                 $locked_file = 1;
10809:                             }
10810:                         }
10811:                    }
10812:                 } else {
10813:                     my @info = split(/\&/,$rest);
10814:                     my $currsize = $info[6]/1000;
10815:                     if ($currsize < $filesize) {
10816:                         my $extra = $filesize - $currsize;
10817:                         if (($current_disk_usage + $extra) > $disk_quota) {
10818:                             my $msg = '<span class="LC_error">'.
10819:                                       &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.',
10820:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10821:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10822:                                                    $disk_quota,$current_disk_usage);
10823:                             return ('will_exceed_quota',$msg);
10824:                         }
10825:                     }
10826:                 }
10827:             }
10828:         }
10829:     }
10830:     if (($current_disk_usage + $filesize) > $disk_quota){
10831:         my $msg = '<span class="LC_error">'.
10832:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10833:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10834:         return ('will_exceed_quota',$msg);
10835:     } elsif ($found_file) {
10836:         if ($locked_file) {
10837:             my $msg = '<span class="LC_error">';
10838:             $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>');
10839:             $msg .= '</span><br />';
10840:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10841:             return ('file_locked',$msg);
10842:         } else {
10843:             my $msg = '<span class="LC_error">';
10844:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10845:             $msg .= '</span>';
10846:             return ('existingfile',$msg);
10847:         }
10848:     }
10849: }
10850: 
10851: sub check_for_traversal {
10852:     my ($path,$url,$toplevel) = @_;
10853:     my @parts=split(/\//,$path);
10854:     my $cleanpath;
10855:     my $fullpath = $url;
10856:     for (my $i=0;$i<@parts;$i++) {
10857:         next if ($parts[$i] eq '.');
10858:         if ($parts[$i] eq '..') {
10859:             $fullpath =~ s{([^/]+/)$}{};
10860:         } else {
10861:             $fullpath .= $parts[$i].'/';
10862:         }
10863:     }
10864:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10865:         $cleanpath = $1;
10866:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10867:         my $curr_toprel = $1;
10868:         my @parts = split(/\//,$curr_toprel);
10869:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10870:         my @urlparts = split(/\//,$url_toprel);
10871:         my $doubledots;
10872:         my $startdiff = -1;
10873:         for (my $i=0; $i<@urlparts; $i++) {
10874:             if ($startdiff == -1) {
10875:                 unless ($urlparts[$i] eq $parts[$i]) {
10876:                     $startdiff = $i;
10877:                     $doubledots .= '../';
10878:                 }
10879:             } else {
10880:                 $doubledots .= '../';
10881:             }
10882:         }
10883:         if ($startdiff > -1) {
10884:             $cleanpath = $doubledots;
10885:             for (my $i=$startdiff; $i<@parts; $i++) {
10886:                 $cleanpath .= $parts[$i].'/';
10887:             }
10888:         }
10889:     }
10890:     $cleanpath =~ s{(/)$}{};
10891:     return $cleanpath;
10892: }
10893: 
10894: sub is_archive_file {
10895:     my ($mimetype) = @_;
10896:     if (($mimetype eq 'application/octet-stream') ||
10897:         ($mimetype eq 'application/x-stuffit') ||
10898:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10899:         return 1;
10900:     }
10901:     return;
10902: }
10903: 
10904: sub decompress_form {
10905:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10906:     my %lt = &Apache::lonlocal::texthash (
10907:         this => 'This file is an archive file.',
10908:         camt => 'This file is a Camtasia archive file.',
10909:         itsc => 'Its contents are as follows:',
10910:         youm => 'You may wish to extract its contents.',
10911:         extr => 'Extract contents',
10912:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10913:         proa => 'Process automatically?',
10914:         yes  => 'Yes',
10915:         no   => 'No',
10916:         fold => 'Title for folder containing movie',
10917:         movi => 'Title for page containing embedded movie', 
10918:     );
10919:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10920:     my ($is_camtasia,$topdir,%toplevel,@paths);
10921:     my $info = &list_archive_contents($fileloc,\@paths);
10922:     if (@paths) {
10923:         foreach my $path (@paths) {
10924:             $path =~ s{^/}{};
10925:             if ($path =~ m{^([^/]+)/$}) {
10926:                 $topdir = $1;
10927:             }
10928:             if ($path =~ m{^([^/]+)/}) {
10929:                 $toplevel{$1} = $path;
10930:             } else {
10931:                 $toplevel{$path} = $path;
10932:             }
10933:         }
10934:     }
10935:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10936:         my @camtasia = ("$topdir/","$topdir/index.html",
10937:                         "$topdir/media/",
10938:                         "$topdir/media/$topdir.mp4",
10939:                         "$topdir/media/FirstFrame.png",
10940:                         "$topdir/media/player.swf",
10941:                         "$topdir/media/swfobject.js",
10942:                         "$topdir/media/expressInstall.swf");
10943:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10944:         if (@diffs == 0) {
10945:             $is_camtasia = 1;
10946:         }
10947:     }
10948:     my $output;
10949:     if ($is_camtasia) {
10950:         $output = <<"ENDCAM";
10951: <script type="text/javascript" language="Javascript">
10952: // <![CDATA[
10953: 
10954: function camtasiaToggle() {
10955:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10956:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10957:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10958: 
10959:                 document.getElementById('camtasia_titles').style.display='block';
10960:             } else {
10961:                 document.getElementById('camtasia_titles').style.display='none';
10962:             }
10963:         }
10964:     }
10965:     return;
10966: }
10967: 
10968: // ]]>
10969: </script>
10970: <p>$lt{'camt'}</p>
10971: ENDCAM
10972:     } else {
10973:         $output = '<p>'.$lt{'this'};
10974:         if ($info eq '') {
10975:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10976:         } else {
10977:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10978:                        '<div><pre>'.$info.'</pre></div>';
10979:         }
10980:     }
10981:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10982:     my $duplicates;
10983:     my $num = 0;
10984:     if (ref($dirlist) eq 'ARRAY') {
10985:         foreach my $item (@{$dirlist}) {
10986:             if (ref($item) eq 'ARRAY') {
10987:                 if (exists($toplevel{$item->[0]})) {
10988:                     $duplicates .= 
10989:                         &start_data_table_row().
10990:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10991:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10992:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10993:                         'value="1" />'.&mt('Yes').'</label>'.
10994:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10995:                         '<td>'.$item->[0].'</td>';
10996:                     if ($item->[2]) {
10997:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10998:                     } else {
10999:                         $duplicates .= '<td>'.&mt('File').'</td>';
11000:                     }
11001:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11002:                                    '<td>'.
11003:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11004:                                    '</td>'.
11005:                                    &end_data_table_row();
11006:                     $num ++;
11007:                 }
11008:             }
11009:         }
11010:     }
11011:     my $itemcount;
11012:     if (@paths > 0) {
11013:         $itemcount = scalar(@paths);
11014:     } else {
11015:         $itemcount = 1;
11016:     }
11017:     if ($is_camtasia) {
11018:         $output .= $lt{'auto'}.'<br />'.
11019:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11020:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11021:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11022:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11023:                    $lt{'no'}.'</label></span><br />'.
11024:                    '<div id="camtasia_titles" style="display:block">'.
11025:                    &Apache::lonhtmlcommon::start_pick_box().
11026:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11027:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11028:                    &Apache::lonhtmlcommon::row_closure().
11029:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11030:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11031:                    &Apache::lonhtmlcommon::row_closure(1).
11032:                    &Apache::lonhtmlcommon::end_pick_box().
11033:                    '</div>';
11034:     }
11035:     $output .= 
11036:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11037:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11038:         "\n";
11039:     if ($duplicates ne '') {
11040:         $output .= '<p><span class="LC_warning">'.
11041:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11042:                    &start_data_table().
11043:                    &start_data_table_header_row().
11044:                    '<th>'.&mt('Overwrite?').'</th>'.
11045:                    '<th>'.&mt('Name').'</th>'.
11046:                    '<th>'.&mt('Type').'</th>'.
11047:                    '<th>'.&mt('Size').'</th>'.
11048:                    '<th>'.&mt('Last modified').'</th>'.
11049:                    &end_data_table_header_row().
11050:                    $duplicates.
11051:                    &end_data_table().
11052:                    '</p>';
11053:     }
11054:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11055:     if (ref($hiddenelements) eq 'HASH') {
11056:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11057:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11058:         }
11059:     }
11060:     $output .= <<"END";
11061: <br />
11062: <input type="submit" name="decompress" value="$lt{'extr'}" />
11063: </form>
11064: $noextract
11065: END
11066:     return $output;
11067: }
11068: 
11069: sub decompression_utility {
11070:     my ($program) = @_;
11071:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11072:     my $location;
11073:     if (grep(/^\Q$program\E$/,@utilities)) { 
11074:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11075:                          '/usr/sbin/') {
11076:             if (-x $dir.$program) {
11077:                 $location = $dir.$program;
11078:                 last;
11079:             }
11080:         }
11081:     }
11082:     return $location;
11083: }
11084: 
11085: sub list_archive_contents {
11086:     my ($file,$pathsref) = @_;
11087:     my (@cmd,$output);
11088:     my $needsregexp;
11089:     if ($file =~ /\.zip$/) {
11090:         @cmd = (&decompression_utility('unzip'),"-l");
11091:         $needsregexp = 1;
11092:     } elsif (($file =~ m/\.tar\.gz$/) ||
11093:              ($file =~ /\.tgz$/)) {
11094:         @cmd = (&decompression_utility('tar'),"-ztf");
11095:     } elsif ($file =~ /\.tar\.bz2$/) {
11096:         @cmd = (&decompression_utility('tar'),"-jtf");
11097:     } elsif ($file =~ m|\.tar$|) {
11098:         @cmd = (&decompression_utility('tar'),"-tf");
11099:     }
11100:     if (@cmd) {
11101:         undef($!);
11102:         undef($@);
11103:         if (open(my $fh,"-|", @cmd, $file)) {
11104:             while (my $line = <$fh>) {
11105:                 $output .= $line;
11106:                 chomp($line);
11107:                 my $item;
11108:                 if ($needsregexp) {
11109:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11110:                 } else {
11111:                     $item = $line;
11112:                 }
11113:                 if ($item ne '') {
11114:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11115:                         push(@{$pathsref},$item);
11116:                     } 
11117:                 }
11118:             }
11119:             close($fh);
11120:         }
11121:     }
11122:     return $output;
11123: }
11124: 
11125: sub decompress_uploaded_file {
11126:     my ($file,$dir) = @_;
11127:     &Apache::lonnet::appenv({'cgi.file' => $file});
11128:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11129:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11130:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11131:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11132:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11133:     my $decompressed = $env{'cgi.decompressed'};
11134:     &Apache::lonnet::delenv('cgi.file');
11135:     &Apache::lonnet::delenv('cgi.dir');
11136:     &Apache::lonnet::delenv('cgi.decompressed');
11137:     return ($decompressed,$result);
11138: }
11139: 
11140: sub process_decompression {
11141:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11142:     my ($dir,$error,$warning,$output);
11143:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11144:         $error = &mt('Filename not a supported archive file type.').
11145:                  '<br />'.&mt('Filename should end with one of: [_1].',
11146:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11147:     } else {
11148:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11149:         if ($docuhome eq 'no_host') {
11150:             $error = &mt('Could not determine home server for course.');
11151:         } else {
11152:             my @ids=&Apache::lonnet::current_machine_ids();
11153:             my $currdir = "$dir_root/$destination";
11154:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11155:                 $dir = &LONCAPA::propath($docudom,$docuname).
11156:                        "$dir_root/$destination";
11157:             } else {
11158:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11159:                        "$dir_root/$docudom/$docuname/$destination";
11160:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11161:                     $error = &mt('Archive file not found.');
11162:                 }
11163:             }
11164:             my (@to_overwrite,@to_skip);
11165:             if ($env{'form.archive_overwrite_total'} > 0) {
11166:                 my $total = $env{'form.archive_overwrite_total'};
11167:                 for (my $i=0; $i<$total; $i++) {
11168:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11169:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11170:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11171:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11172:                     }
11173:                 }
11174:             }
11175:             my $numskip = scalar(@to_skip);
11176:             if (($numskip > 0) && 
11177:                 ($numskip == $env{'form.archive_itemcount'})) {
11178:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11179:             } elsif ($dir eq '') {
11180:                 $error = &mt('Directory containing archive file unavailable.');
11181:             } elsif (!$error) {
11182:                 my ($decompressed,$display);
11183:                 if ($numskip > 0) {
11184:                     my $tempdir = time.'_'.$$.int(rand(10000));
11185:                     mkdir("$dir/$tempdir",0755);
11186:                     system("mv $dir/$file $dir/$tempdir/$file");
11187:                     ($decompressed,$display) = 
11188:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11189:                     foreach my $item (@to_skip) {
11190:                         if (($item ne '') && ($item !~ /\.\./)) {
11191:                             if (-f "$dir/$tempdir/$item") { 
11192:                                 unlink("$dir/$tempdir/$item");
11193:                             } elsif (-d "$dir/$tempdir/$item") {
11194:                                 system("rm -rf $dir/$tempdir/$item");
11195:                             }
11196:                         }
11197:                     }
11198:                     system("mv $dir/$tempdir/* $dir");
11199:                     rmdir("$dir/$tempdir");   
11200:                 } else {
11201:                     ($decompressed,$display) = 
11202:                         &decompress_uploaded_file($file,$dir);
11203:                 }
11204:                 if ($decompressed eq 'ok') {
11205:                     $output = '<p class="LC_info">'.
11206:                               &mt('Files extracted successfully from archive.').
11207:                               '</p>'."\n";
11208:                     my ($warning,$result,@contents);
11209:                     my ($newdirlistref,$newlisterror) =
11210:                         &Apache::lonnet::dirlist($currdir,$docudom,
11211:                                                  $docuname,1);
11212:                     my (%is_dir,%changes,@newitems);
11213:                     my $dirptr = 16384;
11214:                     if (ref($newdirlistref) eq 'ARRAY') {
11215:                         foreach my $dir_line (@{$newdirlistref}) {
11216:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11217:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11218:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11219:                                 push(@newitems,$item);
11220:                                 if ($dirptr&$testdir) {
11221:                                     $is_dir{$item} = 1;
11222:                                 }
11223:                                 $changes{$item} = 1;
11224:                             }
11225:                         }
11226:                     }
11227:                     if (keys(%changes) > 0) {
11228:                         foreach my $item (sort(@newitems)) {
11229:                             if ($changes{$item}) {
11230:                                 push(@contents,$item);
11231:                             }
11232:                         }
11233:                     }
11234:                     if (@contents > 0) {
11235:                         my $wantform;
11236:                         unless ($env{'form.autoextract_camtasia'}) {
11237:                             $wantform = 1;
11238:                         }
11239:                         my (%children,%parent,%dirorder,%titles);
11240:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11241:                                                                 $currdir,\%is_dir,
11242:                                                                 \%children,\%parent,
11243:                                                                 \@contents,\%dirorder,
11244:                                                                 \%titles,$wantform);
11245:                         if ($datatable ne '') {
11246:                             $output .= &archive_options_form('decompressed',$datatable,
11247:                                                              $count,$hiddenelem);
11248:                             my $startcount = 6;
11249:                             $output .= &archive_javascript($startcount,$count,
11250:                                                            \%titles,\%children);
11251:                         }
11252:                         if ($env{'form.autoextract_camtasia'}) {
11253:                             my %displayed;
11254:                             my $total = 1;
11255:                             $env{'form.archive_directory'} = [];
11256:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11257:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11258:                                 $path =~ s{/$}{};
11259:                                 my $item;
11260:                                 if ($path ne '') {
11261:                                     $item = "$path/$titles{$i}";
11262:                                 } else {
11263:                                     $item = $titles{$i};
11264:                                 }
11265:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11266:                                 if ($item eq $contents[0]) {
11267:                                     push(@{$env{'form.archive_directory'}},$i);
11268:                                     $env{'form.archive_'.$i} = 'display';
11269:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11270:                                     $displayed{'folder'} = $i;
11271:                                 } elsif ($item eq "$contents[0]/index.html") {
11272:                                     $env{'form.archive_'.$i} = 'display';
11273:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11274:                                     $displayed{'web'} = $i;
11275:                                 } else {
11276:                                     if ($item eq "$contents[0]/media") {
11277:                                         push(@{$env{'form.archive_directory'}},$i);
11278:                                     }
11279:                                     $env{'form.archive_'.$i} = 'dependency';
11280:                                 }
11281:                                 $total ++;
11282:                             }
11283:                             for (my $i=1; $i<$total; $i++) {
11284:                                 next if ($i == $displayed{'web'});
11285:                                 next if ($i == $displayed{'folder'});
11286:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11287:                             }
11288:                             $env{'form.phase'} = 'decompress_cleanup';
11289:                             $env{'form.archivedelete'} = 1;
11290:                             $env{'form.archive_count'} = $total-1;
11291:                             $output .=
11292:                                 &process_extracted_files('coursedocs',$docudom,
11293:                                                          $docuname,$destination,
11294:                                                          $dir_root,$hiddenelem);
11295:                         }
11296:                     } else {
11297:                         $warning = &mt('No new items extracted from archive file.');
11298:                     }
11299:                 } else {
11300:                     $output = $display;
11301:                     $error = &mt('An error occurred during extraction from the archive file.');
11302:                 }
11303:             }
11304:         }
11305:     }
11306:     if ($error) {
11307:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11308:                    $error.'</p>'."\n";
11309:     }
11310:     if ($warning) {
11311:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11312:     }
11313:     return $output;
11314: }
11315: 
11316: sub get_extracted {
11317:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11318:         $titles,$wantform) = @_;
11319:     my $count = 0;
11320:     my $depth = 0;
11321:     my $datatable;
11322:     my @hierarchy;
11323:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11324:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11325:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11326:     foreach my $item (@{$contents}) {
11327:         $count ++;
11328:         @{$dirorder->{$count}} = @hierarchy;
11329:         $titles->{$count} = $item;
11330:         &archive_hierarchy($depth,$count,$parent,$children);
11331:         if ($wantform) {
11332:             $datatable .= &archive_row($is_dir->{$item},$item,
11333:                                        $currdir,$depth,$count);
11334:         }
11335:         if ($is_dir->{$item}) {
11336:             $depth ++;
11337:             push(@hierarchy,$count);
11338:             $parent->{$depth} = $count;
11339:             $datatable .=
11340:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11341:                                            \$depth,\$count,\@hierarchy,$dirorder,
11342:                                            $children,$parent,$titles,$wantform);
11343:             $depth --;
11344:             pop(@hierarchy);
11345:         }
11346:     }
11347:     return ($count,$datatable);
11348: }
11349: 
11350: sub recurse_extracted_archive {
11351:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11352:         $children,$parent,$titles,$wantform) = @_;
11353:     my $result='';
11354:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11355:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11356:             (ref($dirorder) eq 'HASH')) {
11357:         return $result;
11358:     }
11359:     my $dirptr = 16384;
11360:     my ($newdirlistref,$newlisterror) =
11361:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11362:     if (ref($newdirlistref) eq 'ARRAY') {
11363:         foreach my $dir_line (@{$newdirlistref}) {
11364:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11365:             unless ($item =~ /^\.+$/) {
11366:                 $$count ++;
11367:                 @{$dirorder->{$$count}} = @{$hierarchy};
11368:                 $titles->{$$count} = $item;
11369:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11370: 
11371:                 my $is_dir;
11372:                 if ($dirptr&$testdir) {
11373:                     $is_dir = 1;
11374:                 }
11375:                 if ($wantform) {
11376:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11377:                 }
11378:                 if ($is_dir) {
11379:                     $$depth ++;
11380:                     push(@{$hierarchy},$$count);
11381:                     $parent->{$$depth} = $$count;
11382:                     $result .=
11383:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11384:                                                    $docuname,$depth,$count,
11385:                                                    $hierarchy,$dirorder,$children,
11386:                                                    $parent,$titles,$wantform);
11387:                     $$depth --;
11388:                     pop(@{$hierarchy});
11389:                 }
11390:             }
11391:         }
11392:     }
11393:     return $result;
11394: }
11395: 
11396: sub archive_hierarchy {
11397:     my ($depth,$count,$parent,$children) =@_;
11398:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11399:         if (exists($parent->{$depth})) {
11400:              $children->{$parent->{$depth}} .= $count.':';
11401:         }
11402:     }
11403:     return;
11404: }
11405: 
11406: sub archive_row {
11407:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11408:     my ($name) = ($item =~ m{([^/]+)$});
11409:     my %choices = &Apache::lonlocal::texthash (
11410:                                        'display'    => 'Add as file',
11411:                                        'dependency' => 'Include as dependency',
11412:                                        'discard'    => 'Discard',
11413:                                       );
11414:     if ($is_dir) {
11415:         $choices{'display'} = &mt('Add as folder'); 
11416:     }
11417:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11418:     my $offset = 0;
11419:     foreach my $action ('display','dependency','discard') {
11420:         $offset ++;
11421:         if ($action ne 'display') {
11422:             $offset ++;
11423:         }  
11424:         $output .= '<td><span class="LC_nobreak">'.
11425:                    '<label><input type="radio" name="archive_'.$count.
11426:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11427:         my $text = $choices{$action};
11428:         if ($is_dir) {
11429:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11430:             if ($action eq 'display') {
11431:                 $text = &mt('Add as folder');
11432:             }
11433:         } else {
11434:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11435: 
11436:         }
11437:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11438:         if ($action eq 'dependency') {
11439:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11440:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11441:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11442:                        '<option value=""></option>'."\n".
11443:                        '</select>'."\n".
11444:                        '</div>';
11445:         } elsif ($action eq 'display') {
11446:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11447:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11448:                        '</div>';
11449:         }
11450:         $output .= '</td>';
11451:     }
11452:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11453:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11454:     for (my $i=0; $i<$depth; $i++) {
11455:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11456:     }
11457:     if ($is_dir) {
11458:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11459:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11460:     } else {
11461:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11462:     }
11463:     $output .= '&nbsp;'.$name.'</td>'."\n".
11464:                &end_data_table_row();
11465:     return $output;
11466: }
11467: 
11468: sub archive_options_form {
11469:     my ($form,$display,$count,$hiddenelem) = @_;
11470:     my %lt = &Apache::lonlocal::texthash(
11471:                perm => 'Permanently remove archive file?',
11472:                hows => 'How should each extracted item be incorporated in the course?',
11473:                cont => 'Content actions for all',
11474:                addf => 'Add as folder/file',
11475:                incd => 'Include as dependency for a displayed file',
11476:                disc => 'Discard',
11477:                no   => 'No',
11478:                yes  => 'Yes',
11479:                save => 'Save',
11480:     );
11481:     my $output = <<"END";
11482: <form name="$form" method="post" action="">
11483: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11484: <label>
11485:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11486: </label>
11487: &nbsp;
11488: <label>
11489:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11490: </span>
11491: </p>
11492: <input type="hidden" name="phase" value="decompress_cleanup" />
11493: <br />$lt{'hows'}
11494: <div class="LC_columnSection">
11495:   <fieldset>
11496:     <legend>$lt{'cont'}</legend>
11497:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11498:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11499:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11500:   </fieldset>
11501: </div>
11502: END
11503:     return $output.
11504:            &start_data_table()."\n".
11505:            $display."\n".
11506:            &end_data_table()."\n".
11507:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11508:            $hiddenelem.
11509:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11510:            '</form>';
11511: }
11512: 
11513: sub archive_javascript {
11514:     my ($startcount,$numitems,$titles,$children) = @_;
11515:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11516:     my $maintitle = $env{'form.comment'};
11517:     my $scripttag = <<START;
11518: <script type="text/javascript">
11519: // <![CDATA[
11520: 
11521: function checkAll(form,prefix) {
11522:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11523:     for (var i=0; i < form.elements.length; i++) {
11524:         var id = form.elements[i].id;
11525:         if ((id != '') && (id != undefined)) {
11526:             if (idstr.test(id)) {
11527:                 if (form.elements[i].type == 'radio') {
11528:                     form.elements[i].checked = true;
11529:                     var nostart = i-$startcount;
11530:                     var offset = nostart%7;
11531:                     var count = (nostart-offset)/7;    
11532:                     dependencyCheck(form,count,offset);
11533:                 }
11534:             }
11535:         }
11536:     }
11537: }
11538: 
11539: function propagateCheck(form,count) {
11540:     if (count > 0) {
11541:         var startelement = $startcount + ((count-1) * 7);
11542:         for (var j=1; j<6; j++) {
11543:             if ((j != 2) && (j != 4)) {
11544:                 var item = startelement + j; 
11545:                 if (form.elements[item].type == 'radio') {
11546:                     if (form.elements[item].checked) {
11547:                         containerCheck(form,count,j);
11548:                         break;
11549:                     }
11550:                 }
11551:             }
11552:         }
11553:     }
11554: }
11555: 
11556: numitems = $numitems
11557: var titles = new Array(numitems);
11558: var parents = new Array(numitems);
11559: for (var i=0; i<numitems; i++) {
11560:     parents[i] = new Array;
11561: }
11562: var maintitle = '$maintitle';
11563: 
11564: START
11565: 
11566:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11567:         my @contents = split(/:/,$children->{$container});
11568:         for (my $i=0; $i<@contents; $i ++) {
11569:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11570:         }
11571:     }
11572: 
11573:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11574:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11575:     }
11576: 
11577:     $scripttag .= <<END;
11578: 
11579: function containerCheck(form,count,offset) {
11580:     if (count > 0) {
11581:         dependencyCheck(form,count,offset);
11582:         var item = (offset+$startcount)+7*(count-1);
11583:         form.elements[item].checked = true;
11584:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11585:             if (parents[count].length > 0) {
11586:                 for (var j=0; j<parents[count].length; j++) {
11587:                     containerCheck(form,parents[count][j],offset);
11588:                 }
11589:             }
11590:         }
11591:     }
11592: }
11593: 
11594: function dependencyCheck(form,count,offset) {
11595:     if (count > 0) {
11596:         var chosen = (offset+$startcount)+7*(count-1);
11597:         var depitem = $startcount + ((count-1) * 7) + 4;
11598:         var currtype = form.elements[depitem].type;
11599:         if (form.elements[chosen].value == 'dependency') {
11600:             document.getElementById('arc_depon_'+count).style.display='block'; 
11601:             form.elements[depitem].options.length = 0;
11602:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11603:             for (var i=1; i<=numitems; i++) {
11604:                 if (i == count) {
11605:                     continue;
11606:                 }
11607:                 var startelement = $startcount + (i-1) * 7;
11608:                 for (var j=1; j<6; j++) {
11609:                     if ((j != 2) && (j!= 4)) {
11610:                         var item = startelement + j;
11611:                         if (form.elements[item].type == 'radio') {
11612:                             if (form.elements[item].checked) {
11613:                                 if (form.elements[item].value == 'display') {
11614:                                     var n = form.elements[depitem].options.length;
11615:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11616:                                 }
11617:                             }
11618:                         }
11619:                     }
11620:                 }
11621:             }
11622:         } else {
11623:             document.getElementById('arc_depon_'+count).style.display='none';
11624:             form.elements[depitem].options.length = 0;
11625:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11626:         }
11627:         titleCheck(form,count,offset);
11628:     }
11629: }
11630: 
11631: function propagateSelect(form,count,offset) {
11632:     if (count > 0) {
11633:         var item = (1+offset+$startcount)+7*(count-1);
11634:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11635:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11636:             if (parents[count].length > 0) {
11637:                 for (var j=0; j<parents[count].length; j++) {
11638:                     containerSelect(form,parents[count][j],offset,picked);
11639:                 }
11640:             }
11641:         }
11642:     }
11643: }
11644: 
11645: function containerSelect(form,count,offset,picked) {
11646:     if (count > 0) {
11647:         var item = (offset+$startcount)+7*(count-1);
11648:         if (form.elements[item].type == 'radio') {
11649:             if (form.elements[item].value == 'dependency') {
11650:                 if (form.elements[item+1].type == 'select-one') {
11651:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11652:                         if (form.elements[item+1].options[i].value == picked) {
11653:                             form.elements[item+1].selectedIndex = i;
11654:                             break;
11655:                         }
11656:                     }
11657:                 }
11658:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11659:                     if (parents[count].length > 0) {
11660:                         for (var j=0; j<parents[count].length; j++) {
11661:                             containerSelect(form,parents[count][j],offset,picked);
11662:                         }
11663:                     }
11664:                 }
11665:             }
11666:         }
11667:     }
11668: }
11669: 
11670: function titleCheck(form,count,offset) {
11671:     if (count > 0) {
11672:         var chosen = (offset+$startcount)+7*(count-1);
11673:         var depitem = $startcount + ((count-1) * 7) + 2;
11674:         var currtype = form.elements[depitem].type;
11675:         if (form.elements[chosen].value == 'display') {
11676:             document.getElementById('arc_title_'+count).style.display='block';
11677:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11678:                 document.getElementById('archive_title_'+count).value=maintitle;
11679:             }
11680:         } else {
11681:             document.getElementById('arc_title_'+count).style.display='none';
11682:             if (currtype == 'text') { 
11683:                 document.getElementById('archive_title_'+count).value='';
11684:             }
11685:         }
11686:     }
11687:     return;
11688: }
11689: 
11690: // ]]>
11691: </script>
11692: END
11693:     return $scripttag;
11694: }
11695: 
11696: sub process_extracted_files {
11697:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11698:     my $numitems = $env{'form.archive_count'};
11699:     return unless ($numitems);
11700:     my @ids=&Apache::lonnet::current_machine_ids();
11701:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11702:         %folders,%containers,%mapinner,%prompttofetch);
11703:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11704:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11705:         $prefix = &LONCAPA::propath($docudom,$docuname);
11706:         $pathtocheck = "$dir_root/$destination";
11707:         $dir = $dir_root;
11708:         $ishome = 1;
11709:     } else {
11710:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11711:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11712:         $dir = "$dir_root/$docudom/$docuname";    
11713:     }
11714:     my $currdir = "$dir_root/$destination";
11715:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11716:     if ($env{'form.folderpath'}) {
11717:         my @items = split('&',$env{'form.folderpath'});
11718:         $folders{'0'} = $items[-2];
11719:         if ($env{'form.folderpath'} =~ /\:1$/) {
11720:             $containers{'0'}='page';
11721:         } else {
11722:             $containers{'0'}='sequence';
11723:         }
11724:     }
11725:     my @archdirs = &get_env_multiple('form.archive_directory');
11726:     if ($numitems) {
11727:         for (my $i=1; $i<=$numitems; $i++) {
11728:             my $path = $env{'form.archive_content_'.$i};
11729:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11730:                 my $item = $1;
11731:                 $toplevelitems{$item} = $i;
11732:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11733:                     $is_dir{$item} = 1;
11734:                 }
11735:             }
11736:         }
11737:     }
11738:     my ($output,%children,%parent,%titles,%dirorder,$result);
11739:     if (keys(%toplevelitems) > 0) {
11740:         my @contents = sort(keys(%toplevelitems));
11741:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11742:                                            \%parent,\@contents,\%dirorder,\%titles);
11743:     }
11744:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11745:     if ($numitems) {
11746:         for (my $i=1; $i<=$numitems; $i++) {
11747:             next if ($env{'form.archive_'.$i} eq 'dependency');
11748:             my $path = $env{'form.archive_content_'.$i};
11749:             if ($path =~ /^\Q$pathtocheck\E/) {
11750:                 if ($env{'form.archive_'.$i} eq 'discard') {
11751:                     if ($prefix ne '' && $path ne '') {
11752:                         if (-e $prefix.$path) {
11753:                             if ((@archdirs > 0) && 
11754:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11755:                                 $todeletedir{$prefix.$path} = 1;
11756:                             } else {
11757:                                 $todelete{$prefix.$path} = 1;
11758:                             }
11759:                         }
11760:                     }
11761:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11762:                     my ($docstitle,$title,$url,$outer);
11763:                     ($title) = ($path =~ m{/([^/]+)$});
11764:                     $docstitle = $env{'form.archive_title_'.$i};
11765:                     if ($docstitle eq '') {
11766:                         $docstitle = $title;
11767:                     }
11768:                     $outer = 0;
11769:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11770:                         if (@{$dirorder{$i}} > 0) {
11771:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11772:                                 if ($env{'form.archive_'.$item} eq 'display') {
11773:                                     $outer = $item;
11774:                                     last;
11775:                                 }
11776:                             }
11777:                         }
11778:                     }
11779:                     my ($errtext,$fatal) = 
11780:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11781:                                                '/'.$folders{$outer}.'.'.
11782:                                                $containers{$outer});
11783:                     next if ($fatal);
11784:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11785:                         if ($context eq 'coursedocs') {
11786:                             $mapinner{$i} = time;
11787:                             $folders{$i} = 'default_'.$mapinner{$i};
11788:                             $containers{$i} = 'sequence';
11789:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11790:                                       $folders{$i}.'.'.$containers{$i};
11791:                             my $newidx = &LONCAPA::map::getresidx();
11792:                             $LONCAPA::map::resources[$newidx]=
11793:                                 $docstitle.':'.$url.':false:normal:res';
11794:                             push(@LONCAPA::map::order,$newidx);
11795:                             my ($outtext,$errtext) =
11796:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11797:                                                         $docuname.'/'.$folders{$outer}.
11798:                                                         '.'.$containers{$outer},1,1);
11799:                             $newseqid{$i} = $newidx;
11800:                             unless ($errtext) {
11801:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11802:                             }
11803:                         }
11804:                     } else {
11805:                         if ($context eq 'coursedocs') {
11806:                             my $newidx=&LONCAPA::map::getresidx();
11807:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11808:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11809:                                       $title;
11810:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11811:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11812:                             }
11813:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11814:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11815:                             }
11816:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11817:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11818:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11819:                                 unless ($ishome) {
11820:                                     my $fetch = "$newdest{$i}/$title";
11821:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11822:                                     $prompttofetch{$fetch} = 1;
11823:                                 }
11824:                             }
11825:                             $LONCAPA::map::resources[$newidx]=
11826:                                 $docstitle.':'.$url.':false:normal:res';
11827:                             push(@LONCAPA::map::order, $newidx);
11828:                             my ($outtext,$errtext)=
11829:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11830:                                                         $docuname.'/'.$folders{$outer}.
11831:                                                         '.'.$containers{$outer},1,1);
11832:                             unless ($errtext) {
11833:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11834:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11835:                                 }
11836:                             }
11837:                         }
11838:                     }
11839:                 }
11840:             } else {
11841:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11842:             }
11843:         }
11844:         for (my $i=1; $i<=$numitems; $i++) {
11845:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11846:             my $path = $env{'form.archive_content_'.$i};
11847:             if ($path =~ /^\Q$pathtocheck\E/) {
11848:                 my ($title) = ($path =~ m{/([^/]+)$});
11849:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11850:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11851:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11852:                         my ($itemidx,$fullpath,$relpath);
11853:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11854:                             my $container = $dirorder{$referrer{$i}}->[-1];
11855:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11856:                                 if ($dirorder{$i}->[$j] eq $container) {
11857:                                     $itemidx = $j;
11858:                                 }
11859:                             }
11860:                         }
11861:                         if ($itemidx eq '') {
11862:                             $itemidx =  0;
11863:                         }
11864:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11865:                             if ($mapinner{$referrer{$i}}) {
11866:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11867:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11868:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11869:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11870:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11871:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11872:                                             if (!-e $fullpath) {
11873:                                                 mkdir($fullpath,0755);
11874:                                             }
11875:                                         }
11876:                                     } else {
11877:                                         last;
11878:                                     }
11879:                                 }
11880:                             }
11881:                         } elsif ($newdest{$referrer{$i}}) {
11882:                             $fullpath = $newdest{$referrer{$i}};
11883:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11884:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11885:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11886:                                     last;
11887:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11888:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11889:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11890:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11891:                                         if (!-e $fullpath) {
11892:                                             mkdir($fullpath,0755);
11893:                                         }
11894:                                     }
11895:                                 } else {
11896:                                     last;
11897:                                 }
11898:                             }
11899:                         }
11900:                         if ($fullpath ne '') {
11901:                             if (-e "$prefix$path") {
11902:                                 system("mv $prefix$path $fullpath/$title");
11903:                             }
11904:                             if (-e "$fullpath/$title") {
11905:                                 my $showpath;
11906:                                 if ($relpath ne '') {
11907:                                     $showpath = "$relpath/$title";
11908:                                 } else {
11909:                                     $showpath = "/$title";
11910:                                 }
11911:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11912:                             }
11913:                             unless ($ishome) {
11914:                                 my $fetch = "$fullpath/$title";
11915:                                 $fetch =~ s/^\Q$prefix$dir\E//;
11916:                                 $prompttofetch{$fetch} = 1;
11917:                             }
11918:                         }
11919:                     }
11920:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11921:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11922:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11923:                 }
11924:             } else {
11925:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11926:             }
11927:         }
11928:         if (keys(%todelete)) {
11929:             foreach my $key (keys(%todelete)) {
11930:                 unlink($key);
11931:             }
11932:         }
11933:         if (keys(%todeletedir)) {
11934:             foreach my $key (keys(%todeletedir)) {
11935:                 rmdir($key);
11936:             }
11937:         }
11938:         foreach my $dir (sort(keys(%is_dir))) {
11939:             if (($pathtocheck ne '') && ($dir ne ''))  {
11940:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11941:             }
11942:         }
11943:         if ($result ne '') {
11944:             $output .= '<ul>'."\n".
11945:                        $result."\n".
11946:                        '</ul>';
11947:         }
11948:         unless ($ishome) {
11949:             my $replicationfail;
11950:             foreach my $item (keys(%prompttofetch)) {
11951:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11952:                 unless ($fetchresult eq 'ok') {
11953:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11954:                 }
11955:             }
11956:             if ($replicationfail) {
11957:                 $output .= '<p class="LC_error">'.
11958:                            &mt('Course home server failed to retrieve:').'<ul>'.
11959:                            $replicationfail.
11960:                            '</ul></p>';
11961:             }
11962:         }
11963:     } else {
11964:         $warning = &mt('No items found in archive.');
11965:     }
11966:     if ($error) {
11967:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11968:                    $error.'</p>'."\n";
11969:     }
11970:     if ($warning) {
11971:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11972:     }
11973:     return $output;
11974: }
11975: 
11976: sub cleanup_empty_dirs {
11977:     my ($path) = @_;
11978:     if (($path ne '') && (-d $path)) {
11979:         if (opendir(my $dirh,$path)) {
11980:             my @dircontents = grep(!/^\./,readdir($dirh));
11981:             my $numitems = 0;
11982:             foreach my $item (@dircontents) {
11983:                 if (-d "$path/$item") {
11984:                     &cleanup_empty_dirs("$path/$item");
11985:                     if (-e "$path/$item") {
11986:                         $numitems ++;
11987:                     }
11988:                 } else {
11989:                     $numitems ++;
11990:                 }
11991:             }
11992:             if ($numitems == 0) {
11993:                 rmdir($path);
11994:             }
11995:             closedir($dirh);
11996:         }
11997:     }
11998:     return;
11999: }
12000: 
12001: =pod
12002: 
12003: =item &get_folder_hierarchy()
12004: 
12005: Provides hierarchy of names of folders/sub-folders containing the current
12006: item,
12007: 
12008: Inputs: 3
12009:      - $navmap - navmaps object
12010: 
12011:      - $map - url for map (either the trigger itself, or map containing
12012:                            the resource, which is the trigger).
12013: 
12014:      - $showitem - 1 => show title for map itself; 0 => do not show.
12015: 
12016: Outputs: 1 @pathitems - array of folder/subfolder names.
12017: 
12018: =cut
12019: 
12020: sub get_folder_hierarchy {
12021:     my ($navmap,$map,$showitem) = @_;
12022:     my @pathitems;
12023:     if (ref($navmap)) {
12024:         my $mapres = $navmap->getResourceByUrl($map);
12025:         if (ref($mapres)) {
12026:             my $pcslist = $mapres->map_hierarchy();
12027:             if ($pcslist ne '') {
12028:                 my @pcs = split(/,/,$pcslist);
12029:                 foreach my $pc (@pcs) {
12030:                     if ($pc == 1) {
12031:                         push(@pathitems,&mt('Main Content'));
12032:                     } else {
12033:                         my $res = $navmap->getByMapPc($pc);
12034:                         if (ref($res)) {
12035:                             my $title = $res->compTitle();
12036:                             $title =~ s/\W+/_/g;
12037:                             if ($title ne '') {
12038:                                 push(@pathitems,$title);
12039:                             }
12040:                         }
12041:                     }
12042:                 }
12043:             }
12044:             if ($showitem) {
12045:                 if ($mapres->{ID} eq '0.0') {
12046:                     push(@pathitems,&mt('Main Content'));
12047:                 } else {
12048:                     my $maptitle = $mapres->compTitle();
12049:                     $maptitle =~ s/\W+/_/g;
12050:                     if ($maptitle ne '') {
12051:                         push(@pathitems,$maptitle);
12052:                     }
12053:                 }
12054:             }
12055:         }
12056:     }
12057:     return @pathitems;
12058: }
12059: 
12060: =pod
12061: 
12062: =item * &get_turnedin_filepath()
12063: 
12064: Determines path in a user's portfolio file for storage of files uploaded
12065: to a specific essayresponse or dropbox item.
12066: 
12067: Inputs: 3 required + 1 optional.
12068: $symb is symb for resource, $uname and $udom are for current user (required).
12069: $caller is optional (can be "submission", if routine is called when storing
12070: an upoaded file when "Submit Answer" button was pressed).
12071: 
12072: Returns array containing $path and $multiresp. 
12073: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12074: than one file upload item.  Callers of routine should append partid as a 
12075: subdirectory to $path in cases where $multiresp is 1.
12076: 
12077: Called by: homework/essayresponse.pm and homework/structuretags.pm
12078: 
12079: =cut
12080: 
12081: sub get_turnedin_filepath {
12082:     my ($symb,$uname,$udom,$caller) = @_;
12083:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12084:     my $turnindir;
12085:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12086:     $turnindir = $userhash{'turnindir'};
12087:     my ($path,$multiresp);
12088:     if ($turnindir eq '') {
12089:         if ($caller eq 'submission') {
12090:             $turnindir = &mt('turned in');
12091:             $turnindir =~ s/\W+/_/g;
12092:             my %newhash = (
12093:                             'turnindir' => $turnindir,
12094:                           );
12095:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12096:         }
12097:     }
12098:     if ($turnindir ne '') {
12099:         $path = '/'.$turnindir.'/';
12100:         my ($multipart,$turnin,@pathitems);
12101:         my $navmap = Apache::lonnavmaps::navmap->new();
12102:         if (defined($navmap)) {
12103:             my $mapres = $navmap->getResourceByUrl($map);
12104:             if (ref($mapres)) {
12105:                 my $pcslist = $mapres->map_hierarchy();
12106:                 if ($pcslist ne '') {
12107:                     foreach my $pc (split(/,/,$pcslist)) {
12108:                         my $res = $navmap->getByMapPc($pc);
12109:                         if (ref($res)) {
12110:                             my $title = $res->compTitle();
12111:                             $title =~ s/\W+/_/g;
12112:                             if ($title ne '') {
12113:                                 push(@pathitems,$title);
12114:                             }
12115:                         }
12116:                     }
12117:                 }
12118:                 my $maptitle = $mapres->compTitle();
12119:                 $maptitle =~ s/\W+/_/g;
12120:                 if ($maptitle ne '') {
12121:                     push(@pathitems,$maptitle);
12122:                 }
12123:                 unless ($env{'request.state'} eq 'construct') {
12124:                     my $res = $navmap->getBySymb($symb);
12125:                     if (ref($res)) {
12126:                         my $partlist = $res->parts();
12127:                         my $totaluploads = 0;
12128:                         if (ref($partlist) eq 'ARRAY') {
12129:                             foreach my $part (@{$partlist}) {
12130:                                 my @types = $res->responseType($part);
12131:                                 my @ids = $res->responseIds($part);
12132:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12133:                                     if ($types[$i] eq 'essay') {
12134:                                         my $partid = $part.'_'.$ids[$i];
12135:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12136:                                             $totaluploads ++;
12137:                                         }
12138:                                     }
12139:                                 }
12140:                             }
12141:                             if ($totaluploads > 1) {
12142:                                 $multiresp = 1;
12143:                             }
12144:                         }
12145:                     }
12146:                 }
12147:             } else {
12148:                 return;
12149:             }
12150:         } else {
12151:             return;
12152:         }
12153:         my $restitle=&Apache::lonnet::gettitle($symb);
12154:         $restitle =~ s/\W+/_/g;
12155:         if ($restitle eq '') {
12156:             $restitle = ($resurl =~ m{/[^/]+$});
12157:             if ($restitle eq '') {
12158:                 $restitle = time;
12159:             }
12160:         }
12161:         push(@pathitems,$restitle);
12162:         $path .= join('/',@pathitems);
12163:     }
12164:     return ($path,$multiresp);
12165: }
12166: 
12167: =pod
12168: 
12169: =back
12170: 
12171: =head1 CSV Upload/Handling functions
12172: 
12173: =over 4
12174: 
12175: =item * &upfile_store($r)
12176: 
12177: Store uploaded file, $r should be the HTTP Request object,
12178: needs $env{'form.upfile'}
12179: returns $datatoken to be put into hidden field
12180: 
12181: =cut
12182: 
12183: sub upfile_store {
12184:     my $r=shift;
12185:     $env{'form.upfile'}=~s/\r/\n/gs;
12186:     $env{'form.upfile'}=~s/\f/\n/gs;
12187:     $env{'form.upfile'}=~s/\n+/\n/gs;
12188:     $env{'form.upfile'}=~s/\n+$//gs;
12189: 
12190:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12191: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12192:     {
12193:         my $datafile = $r->dir_config('lonDaemons').
12194:                            '/tmp/'.$datatoken.'.tmp';
12195:         if ( open(my $fh,">$datafile") ) {
12196:             print $fh $env{'form.upfile'};
12197:             close($fh);
12198:         }
12199:     }
12200:     return $datatoken;
12201: }
12202: 
12203: =pod
12204: 
12205: =item * &load_tmp_file($r)
12206: 
12207: Load uploaded file from tmp, $r should be the HTTP Request object,
12208: needs $env{'form.datatoken'},
12209: sets $env{'form.upfile'} to the contents of the file
12210: 
12211: =cut
12212: 
12213: sub load_tmp_file {
12214:     my $r=shift;
12215:     my @studentdata=();
12216:     {
12217:         my $studentfile = $r->dir_config('lonDaemons').
12218:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12219:         if ( open(my $fh,"<$studentfile") ) {
12220:             @studentdata=<$fh>;
12221:             close($fh);
12222:         }
12223:     }
12224:     $env{'form.upfile'}=join('',@studentdata);
12225: }
12226: 
12227: =pod
12228: 
12229: =item * &upfile_record_sep()
12230: 
12231: Separate uploaded file into records
12232: returns array of records,
12233: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12234: 
12235: =cut
12236: 
12237: sub upfile_record_sep {
12238:     if ($env{'form.upfiletype'} eq 'xml') {
12239:     } else {
12240: 	my @records;
12241: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12242: 	    if ($line=~/^\s*$/) { next; }
12243: 	    push(@records,$line);
12244: 	}
12245: 	return @records;
12246:     }
12247: }
12248: 
12249: =pod
12250: 
12251: =item * &record_sep($record)
12252: 
12253: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12254: 
12255: =cut
12256: 
12257: sub takeleft {
12258:     my $index=shift;
12259:     return substr('0000'.$index,-4,4);
12260: }
12261: 
12262: sub record_sep {
12263:     my $record=shift;
12264:     my %components=();
12265:     if ($env{'form.upfiletype'} eq 'xml') {
12266:     } elsif ($env{'form.upfiletype'} eq 'space') {
12267:         my $i=0;
12268:         foreach my $field (split(/\s+/,$record)) {
12269:             $field=~s/^(\"|\')//;
12270:             $field=~s/(\"|\')$//;
12271:             $components{&takeleft($i)}=$field;
12272:             $i++;
12273:         }
12274:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12275:         my $i=0;
12276:         foreach my $field (split(/\t/,$record)) {
12277:             $field=~s/^(\"|\')//;
12278:             $field=~s/(\"|\')$//;
12279:             $components{&takeleft($i)}=$field;
12280:             $i++;
12281:         }
12282:     } else {
12283:         my $separator=',';
12284:         if ($env{'form.upfiletype'} eq 'semisv') {
12285:             $separator=';';
12286:         }
12287:         my $i=0;
12288: # the character we are looking for to indicate the end of a quote or a record 
12289:         my $looking_for=$separator;
12290: # do not add the characters to the fields
12291:         my $ignore=0;
12292: # we just encountered a separator (or the beginning of the record)
12293:         my $just_found_separator=1;
12294: # store the field we are working on here
12295:         my $field='';
12296: # work our way through all characters in record
12297:         foreach my $character ($record=~/(.)/g) {
12298:             if ($character eq $looking_for) {
12299:                if ($character ne $separator) {
12300: # Found the end of a quote, again looking for separator
12301:                   $looking_for=$separator;
12302:                   $ignore=1;
12303:                } else {
12304: # Found a separator, store away what we got
12305:                   $components{&takeleft($i)}=$field;
12306: 	          $i++;
12307:                   $just_found_separator=1;
12308:                   $ignore=0;
12309:                   $field='';
12310:                }
12311:                next;
12312:             }
12313: # single or double quotation marks after a separator indicate beginning of a quote
12314: # we are now looking for the end of the quote and need to ignore separators
12315:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12316:                $looking_for=$character;
12317:                next;
12318:             }
12319: # ignore would be true after we reached the end of a quote
12320:             if ($ignore) { next; }
12321:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12322:             $field.=$character;
12323:             $just_found_separator=0; 
12324:         }
12325: # catch the very last entry, since we never encountered the separator
12326:         $components{&takeleft($i)}=$field;
12327:     }
12328:     return %components;
12329: }
12330: 
12331: ######################################################
12332: ######################################################
12333: 
12334: =pod
12335: 
12336: =item * &upfile_select_html()
12337: 
12338: Return HTML code to select a file from the users machine and specify 
12339: the file type.
12340: 
12341: =cut
12342: 
12343: ######################################################
12344: ######################################################
12345: sub upfile_select_html {
12346:     my %Types = (
12347:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12348:                  semisv => &mt('Semicolon separated values'),
12349:                  space => &mt('Space separated'),
12350:                  tab   => &mt('Tabulator separated'),
12351: #                 xml   => &mt('HTML/XML'),
12352:                  );
12353:     my $Str = '<input type="file" name="upfile" size="50" />'.
12354:         '<br />'.&mt('Type').': <select name="upfiletype">';
12355:     foreach my $type (sort(keys(%Types))) {
12356:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12357:     }
12358:     $Str .= "</select>\n";
12359:     return $Str;
12360: }
12361: 
12362: sub get_samples {
12363:     my ($records,$toget) = @_;
12364:     my @samples=({});
12365:     my $got=0;
12366:     foreach my $rec (@$records) {
12367: 	my %temp = &record_sep($rec);
12368: 	if (! grep(/\S/, values(%temp))) { next; }
12369: 	if (%temp) {
12370: 	    $samples[$got]=\%temp;
12371: 	    $got++;
12372: 	    if ($got == $toget) { last; }
12373: 	}
12374:     }
12375:     return \@samples;
12376: }
12377: 
12378: ######################################################
12379: ######################################################
12380: 
12381: =pod
12382: 
12383: =item * &csv_print_samples($r,$records)
12384: 
12385: Prints a table of sample values from each column uploaded $r is an
12386: Apache Request ref, $records is an arrayref from
12387: &Apache::loncommon::upfile_record_sep
12388: 
12389: =cut
12390: 
12391: ######################################################
12392: ######################################################
12393: sub csv_print_samples {
12394:     my ($r,$records) = @_;
12395:     my $samples = &get_samples($records,5);
12396: 
12397:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12398:               &start_data_table_header_row());
12399:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12400:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12401:     $r->print(&end_data_table_header_row());
12402:     foreach my $hash (@$samples) {
12403: 	$r->print(&start_data_table_row());
12404: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12405: 	    $r->print('<td>');
12406: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12407: 	    $r->print('</td>');
12408: 	}
12409: 	$r->print(&end_data_table_row());
12410:     }
12411:     $r->print(&end_data_table().'<br />'."\n");
12412: }
12413: 
12414: ######################################################
12415: ######################################################
12416: 
12417: =pod
12418: 
12419: =item * &csv_print_select_table($r,$records,$d)
12420: 
12421: Prints a table to create associations between values and table columns.
12422: 
12423: $r is an Apache Request ref,
12424: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12425: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12426: 
12427: =cut
12428: 
12429: ######################################################
12430: ######################################################
12431: sub csv_print_select_table {
12432:     my ($r,$records,$d) = @_;
12433:     my $i=0;
12434:     my $samples = &get_samples($records,1);
12435:     $r->print(&mt('Associate columns with student attributes.')."\n".
12436: 	      &start_data_table().&start_data_table_header_row().
12437:               '<th>'.&mt('Attribute').'</th>'.
12438:               '<th>'.&mt('Column').'</th>'.
12439:               &end_data_table_header_row()."\n");
12440:     foreach my $array_ref (@$d) {
12441: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12442: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12443: 
12444: 	$r->print('<td><select name="f'.$i.'"'.
12445: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12446: 	$r->print('<option value="none"></option>');
12447: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12448: 	    $r->print('<option value="'.$sample.'"'.
12449:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12450:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12451: 	}
12452: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12453: 	$i++;
12454:     }
12455:     $r->print(&end_data_table());
12456:     $i--;
12457:     return $i;
12458: }
12459: 
12460: ######################################################
12461: ######################################################
12462: 
12463: =pod
12464: 
12465: =item * &csv_samples_select_table($r,$records,$d)
12466: 
12467: Prints a table of sample values from the upload and can make associate samples to internal names.
12468: 
12469: $r is an Apache Request ref,
12470: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12471: $d is an array of 2 element arrays (internal name, displayed name)
12472: 
12473: =cut
12474: 
12475: ######################################################
12476: ######################################################
12477: sub csv_samples_select_table {
12478:     my ($r,$records,$d) = @_;
12479:     my $i=0;
12480:     #
12481:     my $max_samples = 5;
12482:     my $samples = &get_samples($records,$max_samples);
12483:     $r->print(&start_data_table().
12484:               &start_data_table_header_row().'<th>'.
12485:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12486:               &end_data_table_header_row());
12487: 
12488:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12489: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12490: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12491: 	foreach my $option (@$d) {
12492: 	    my ($value,$display,$defaultcol)=@{ $option };
12493: 	    $r->print('<option value="'.$value.'"'.
12494:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12495:                       $display.'</option>');
12496: 	}
12497: 	$r->print('</select></td><td>');
12498: 	foreach my $line (0..($max_samples-1)) {
12499: 	    if (defined($samples->[$line]{$key})) { 
12500: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12501: 	    }
12502: 	}
12503: 	$r->print('</td>'.&end_data_table_row());
12504: 	$i++;
12505:     }
12506:     $r->print(&end_data_table());
12507:     $i--;
12508:     return($i);
12509: }
12510: 
12511: ######################################################
12512: ######################################################
12513: 
12514: =pod
12515: 
12516: =item * &clean_excel_name($name)
12517: 
12518: Returns a replacement for $name which does not contain any illegal characters.
12519: 
12520: =cut
12521: 
12522: ######################################################
12523: ######################################################
12524: sub clean_excel_name {
12525:     my ($name) = @_;
12526:     $name =~ s/[:\*\?\/\\]//g;
12527:     if (length($name) > 31) {
12528:         $name = substr($name,0,31);
12529:     }
12530:     return $name;
12531: }
12532: 
12533: =pod
12534: 
12535: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12536: 
12537: Returns either 1 or undef
12538: 
12539: 1 if the part is to be hidden, undef if it is to be shown
12540: 
12541: Arguments are:
12542: 
12543: $id the id of the part to be checked
12544: $symb, optional the symb of the resource to check
12545: $udom, optional the domain of the user to check for
12546: $uname, optional the username of the user to check for
12547: 
12548: =cut
12549: 
12550: sub check_if_partid_hidden {
12551:     my ($id,$symb,$udom,$uname) = @_;
12552:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12553: 					 $symb,$udom,$uname);
12554:     my $truth=1;
12555:     #if the string starts with !, then the list is the list to show not hide
12556:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12557:     my @hiddenlist=split(/,/,$hiddenparts);
12558:     foreach my $checkid (@hiddenlist) {
12559: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12560:     }
12561:     return !$truth;
12562: }
12563: 
12564: 
12565: ############################################################
12566: ############################################################
12567: 
12568: =pod
12569: 
12570: =back 
12571: 
12572: =head1 cgi-bin script and graphing routines
12573: 
12574: =over 4
12575: 
12576: =item * &get_cgi_id()
12577: 
12578: Inputs: none
12579: 
12580: Returns an id which can be used to pass environment variables
12581: to various cgi-bin scripts.  These environment variables will
12582: be removed from the users environment after a given time by
12583: the routine &Apache::lonnet::transfer_profile_to_env.
12584: 
12585: =cut
12586: 
12587: ############################################################
12588: ############################################################
12589: my $uniq=0;
12590: sub get_cgi_id {
12591:     $uniq=($uniq+1)%100000;
12592:     return (time.'_'.$$.'_'.$uniq);
12593: }
12594: 
12595: ############################################################
12596: ############################################################
12597: 
12598: =pod
12599: 
12600: =item * &DrawBarGraph()
12601: 
12602: Facilitates the plotting of data in a (stacked) bar graph.
12603: Puts plot definition data into the users environment in order for 
12604: graph.png to plot it.  Returns an <img> tag for the plot.
12605: The bars on the plot are labeled '1','2',...,'n'.
12606: 
12607: Inputs:
12608: 
12609: =over 4
12610: 
12611: =item $Title: string, the title of the plot
12612: 
12613: =item $xlabel: string, text describing the X-axis of the plot
12614: 
12615: =item $ylabel: string, text describing the Y-axis of the plot
12616: 
12617: =item $Max: scalar, the maximum Y value to use in the plot
12618: If $Max is < any data point, the graph will not be rendered.
12619: 
12620: =item $colors: array ref holding the colors to be used for the data sets when
12621: they are plotted.  If undefined, default values will be used.
12622: 
12623: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12624: 
12625: =item @Values: An array of array references.  Each array reference holds data
12626: to be plotted in a stacked bar chart.
12627: 
12628: =item If the final element of @Values is a hash reference the key/value
12629: pairs will be added to the graph definition.
12630: 
12631: =back
12632: 
12633: Returns:
12634: 
12635: An <img> tag which references graph.png and the appropriate identifying
12636: information for the plot.
12637: 
12638: =cut
12639: 
12640: ############################################################
12641: ############################################################
12642: sub DrawBarGraph {
12643:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12644:     #
12645:     if (! defined($colors)) {
12646:         $colors = ['#33ff00', 
12647:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12648:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12649:                   ]; 
12650:     }
12651:     my $extra_settings = {};
12652:     if (ref($Values[-1]) eq 'HASH') {
12653:         $extra_settings = pop(@Values);
12654:     }
12655:     #
12656:     my $identifier = &get_cgi_id();
12657:     my $id = 'cgi.'.$identifier;        
12658:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12659:         return '';
12660:     }
12661:     #
12662:     my @Labels;
12663:     if (defined($labels)) {
12664:         @Labels = @$labels;
12665:     } else {
12666:         for (my $i=0;$i<@{$Values[0]};$i++) {
12667:             push (@Labels,$i+1);
12668:         }
12669:     }
12670:     #
12671:     my $NumBars = scalar(@{$Values[0]});
12672:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12673:     my %ValuesHash;
12674:     my $NumSets=1;
12675:     foreach my $array (@Values) {
12676:         next if (! ref($array));
12677:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12678:             join(',',@$array);
12679:     }
12680:     #
12681:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12682:     if ($NumBars < 3) {
12683:         $width = 120+$NumBars*32;
12684:         $xskip = 1;
12685:         $bar_width = 30;
12686:     } elsif ($NumBars < 5) {
12687:         $width = 120+$NumBars*20;
12688:         $xskip = 1;
12689:         $bar_width = 20;
12690:     } elsif ($NumBars < 10) {
12691:         $width = 120+$NumBars*15;
12692:         $xskip = 1;
12693:         $bar_width = 15;
12694:     } elsif ($NumBars <= 25) {
12695:         $width = 120+$NumBars*11;
12696:         $xskip = 5;
12697:         $bar_width = 8;
12698:     } elsif ($NumBars <= 50) {
12699:         $width = 120+$NumBars*8;
12700:         $xskip = 5;
12701:         $bar_width = 4;
12702:     } else {
12703:         $width = 120+$NumBars*8;
12704:         $xskip = 5;
12705:         $bar_width = 4;
12706:     }
12707:     #
12708:     $Max = 1 if ($Max < 1);
12709:     if ( int($Max) < $Max ) {
12710:         $Max++;
12711:         $Max = int($Max);
12712:     }
12713:     $Title  = '' if (! defined($Title));
12714:     $xlabel = '' if (! defined($xlabel));
12715:     $ylabel = '' if (! defined($ylabel));
12716:     $ValuesHash{$id.'.title'}    = &escape($Title);
12717:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12718:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12719:     $ValuesHash{$id.'.y_max_value'} = $Max;
12720:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12721:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12722:     $ValuesHash{$id.'.PlotType'} = 'bar';
12723:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12724:     $ValuesHash{$id.'.height'}   = $height;
12725:     $ValuesHash{$id.'.width'}    = $width;
12726:     $ValuesHash{$id.'.xskip'}    = $xskip;
12727:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12728:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12729:     #
12730:     # Deal with other parameters
12731:     while (my ($key,$value) = each(%$extra_settings)) {
12732:         $ValuesHash{$id.'.'.$key} = $value;
12733:     }
12734:     #
12735:     &Apache::lonnet::appenv(\%ValuesHash);
12736:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12737: }
12738: 
12739: ############################################################
12740: ############################################################
12741: 
12742: =pod
12743: 
12744: =item * &DrawXYGraph()
12745: 
12746: Facilitates the plotting of data in an XY graph.
12747: Puts plot definition data into the users environment in order for 
12748: graph.png to plot it.  Returns an <img> tag for the plot.
12749: 
12750: Inputs:
12751: 
12752: =over 4
12753: 
12754: =item $Title: string, the title of the plot
12755: 
12756: =item $xlabel: string, text describing the X-axis of the plot
12757: 
12758: =item $ylabel: string, text describing the Y-axis of the plot
12759: 
12760: =item $Max: scalar, the maximum Y value to use in the plot
12761: If $Max is < any data point, the graph will not be rendered.
12762: 
12763: =item $colors: Array ref containing the hex color codes for the data to be 
12764: plotted in.  If undefined, default values will be used.
12765: 
12766: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12767: 
12768: =item $Ydata: Array ref containing Array refs.  
12769: Each of the contained arrays will be plotted as a separate curve.
12770: 
12771: =item %Values: hash indicating or overriding any default values which are 
12772: passed to graph.png.  
12773: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12774: 
12775: =back
12776: 
12777: Returns:
12778: 
12779: An <img> tag which references graph.png and the appropriate identifying
12780: information for the plot.
12781: 
12782: =cut
12783: 
12784: ############################################################
12785: ############################################################
12786: sub DrawXYGraph {
12787:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12788:     #
12789:     # Create the identifier for the graph
12790:     my $identifier = &get_cgi_id();
12791:     my $id = 'cgi.'.$identifier;
12792:     #
12793:     $Title  = '' if (! defined($Title));
12794:     $xlabel = '' if (! defined($xlabel));
12795:     $ylabel = '' if (! defined($ylabel));
12796:     my %ValuesHash = 
12797:         (
12798:          $id.'.title'  => &escape($Title),
12799:          $id.'.xlabel' => &escape($xlabel),
12800:          $id.'.ylabel' => &escape($ylabel),
12801:          $id.'.y_max_value'=> $Max,
12802:          $id.'.labels'     => join(',',@$Xlabels),
12803:          $id.'.PlotType'   => 'XY',
12804:          );
12805:     #
12806:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12807:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12808:     }
12809:     #
12810:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12811:         return '';
12812:     }
12813:     my $NumSets=1;
12814:     foreach my $array (@{$Ydata}){
12815:         next if (! ref($array));
12816:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12817:     }
12818:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12819:     #
12820:     # Deal with other parameters
12821:     while (my ($key,$value) = each(%Values)) {
12822:         $ValuesHash{$id.'.'.$key} = $value;
12823:     }
12824:     #
12825:     &Apache::lonnet::appenv(\%ValuesHash);
12826:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12827: }
12828: 
12829: ############################################################
12830: ############################################################
12831: 
12832: =pod
12833: 
12834: =item * &DrawXYYGraph()
12835: 
12836: Facilitates the plotting of data in an XY graph with two Y axes.
12837: Puts plot definition data into the users environment in order for 
12838: graph.png to plot it.  Returns an <img> tag for the plot.
12839: 
12840: Inputs:
12841: 
12842: =over 4
12843: 
12844: =item $Title: string, the title of the plot
12845: 
12846: =item $xlabel: string, text describing the X-axis of the plot
12847: 
12848: =item $ylabel: string, text describing the Y-axis of the plot
12849: 
12850: =item $colors: Array ref containing the hex color codes for the data to be 
12851: plotted in.  If undefined, default values will be used.
12852: 
12853: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12854: 
12855: =item $Ydata1: The first data set
12856: 
12857: =item $Min1: The minimum value of the left Y-axis
12858: 
12859: =item $Max1: The maximum value of the left Y-axis
12860: 
12861: =item $Ydata2: The second data set
12862: 
12863: =item $Min2: The minimum value of the right Y-axis
12864: 
12865: =item $Max2: The maximum value of the left Y-axis
12866: 
12867: =item %Values: hash indicating or overriding any default values which are 
12868: passed to graph.png.  
12869: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12870: 
12871: =back
12872: 
12873: Returns:
12874: 
12875: An <img> tag which references graph.png and the appropriate identifying
12876: information for the plot.
12877: 
12878: =cut
12879: 
12880: ############################################################
12881: ############################################################
12882: sub DrawXYYGraph {
12883:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12884:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12885:     #
12886:     # Create the identifier for the graph
12887:     my $identifier = &get_cgi_id();
12888:     my $id = 'cgi.'.$identifier;
12889:     #
12890:     $Title  = '' if (! defined($Title));
12891:     $xlabel = '' if (! defined($xlabel));
12892:     $ylabel = '' if (! defined($ylabel));
12893:     my %ValuesHash = 
12894:         (
12895:          $id.'.title'  => &escape($Title),
12896:          $id.'.xlabel' => &escape($xlabel),
12897:          $id.'.ylabel' => &escape($ylabel),
12898:          $id.'.labels' => join(',',@$Xlabels),
12899:          $id.'.PlotType' => 'XY',
12900:          $id.'.NumSets' => 2,
12901:          $id.'.two_axes' => 1,
12902:          $id.'.y1_max_value' => $Max1,
12903:          $id.'.y1_min_value' => $Min1,
12904:          $id.'.y2_max_value' => $Max2,
12905:          $id.'.y2_min_value' => $Min2,
12906:          );
12907:     #
12908:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12909:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12910:     }
12911:     #
12912:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12913:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12914:         return '';
12915:     }
12916:     my $NumSets=1;
12917:     foreach my $array ($Ydata1,$Ydata2){
12918:         next if (! ref($array));
12919:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12920:     }
12921:     #
12922:     # Deal with other parameters
12923:     while (my ($key,$value) = each(%Values)) {
12924:         $ValuesHash{$id.'.'.$key} = $value;
12925:     }
12926:     #
12927:     &Apache::lonnet::appenv(\%ValuesHash);
12928:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12929: }
12930: 
12931: ############################################################
12932: ############################################################
12933: 
12934: =pod
12935: 
12936: =back 
12937: 
12938: =head1 Statistics helper routines?  
12939: 
12940: Bad place for them but what the hell.
12941: 
12942: =over 4
12943: 
12944: =item * &chartlink()
12945: 
12946: Returns a link to the chart for a specific student.  
12947: 
12948: Inputs:
12949: 
12950: =over 4
12951: 
12952: =item $linktext: The text of the link
12953: 
12954: =item $sname: The students username
12955: 
12956: =item $sdomain: The students domain
12957: 
12958: =back
12959: 
12960: =back
12961: 
12962: =cut
12963: 
12964: ############################################################
12965: ############################################################
12966: sub chartlink {
12967:     my ($linktext, $sname, $sdomain) = @_;
12968:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12969:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12970:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12971:        '">'.$linktext.'</a>';
12972: }
12973: 
12974: #######################################################
12975: #######################################################
12976: 
12977: =pod
12978: 
12979: =head1 Course Environment Routines
12980: 
12981: =over 4
12982: 
12983: =item * &restore_course_settings()
12984: 
12985: =item * &store_course_settings()
12986: 
12987: Restores/Store indicated form parameters from the course environment.
12988: Will not overwrite existing values of the form parameters.
12989: 
12990: Inputs: 
12991: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12992: 
12993: a hash ref describing the data to be stored.  For example:
12994:    
12995: %Save_Parameters = ('Status' => 'scalar',
12996:     'chartoutputmode' => 'scalar',
12997:     'chartoutputdata' => 'scalar',
12998:     'Section' => 'array',
12999:     'Group' => 'array',
13000:     'StudentData' => 'array',
13001:     'Maps' => 'array');
13002: 
13003: Returns: both routines return nothing
13004: 
13005: =back
13006: 
13007: =cut
13008: 
13009: #######################################################
13010: #######################################################
13011: sub store_course_settings {
13012:     return &store_settings($env{'request.course.id'},@_);
13013: }
13014: 
13015: sub store_settings {
13016:     # save to the environment
13017:     # appenv the same items, just to be safe
13018:     my $udom  = $env{'user.domain'};
13019:     my $uname = $env{'user.name'};
13020:     my ($context,$prefix,$Settings) = @_;
13021:     my %SaveHash;
13022:     my %AppHash;
13023:     while (my ($setting,$type) = each(%$Settings)) {
13024:         my $basename = join('.','internal',$context,$prefix,$setting);
13025:         my $envname = 'environment.'.$basename;
13026:         if (exists($env{'form.'.$setting})) {
13027:             # Save this value away
13028:             if ($type eq 'scalar' &&
13029:                 (! exists($env{$envname}) || 
13030:                  $env{$envname} ne $env{'form.'.$setting})) {
13031:                 $SaveHash{$basename} = $env{'form.'.$setting};
13032:                 $AppHash{$envname}   = $env{'form.'.$setting};
13033:             } elsif ($type eq 'array') {
13034:                 my $stored_form;
13035:                 if (ref($env{'form.'.$setting})) {
13036:                     $stored_form = join(',',
13037:                                         map {
13038:                                             &escape($_);
13039:                                         } sort(@{$env{'form.'.$setting}}));
13040:                 } else {
13041:                     $stored_form = 
13042:                         &escape($env{'form.'.$setting});
13043:                 }
13044:                 # Determine if the array contents are the same.
13045:                 if ($stored_form ne $env{$envname}) {
13046:                     $SaveHash{$basename} = $stored_form;
13047:                     $AppHash{$envname}   = $stored_form;
13048:                 }
13049:             }
13050:         }
13051:     }
13052:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13053:                                           $udom,$uname);
13054:     if ($put_result !~ /^(ok|delayed)/) {
13055:         &Apache::lonnet::logthis('unable to save form parameters, '.
13056:                                  'got error:'.$put_result);
13057:     }
13058:     # Make sure these settings stick around in this session, too
13059:     &Apache::lonnet::appenv(\%AppHash);
13060:     return;
13061: }
13062: 
13063: sub restore_course_settings {
13064:     return &restore_settings($env{'request.course.id'},@_);
13065: }
13066: 
13067: sub restore_settings {
13068:     my ($context,$prefix,$Settings) = @_;
13069:     while (my ($setting,$type) = each(%$Settings)) {
13070:         next if (exists($env{'form.'.$setting}));
13071:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13072:             '.'.$setting;
13073:         if (exists($env{$envname})) {
13074:             if ($type eq 'scalar') {
13075:                 $env{'form.'.$setting} = $env{$envname};
13076:             } elsif ($type eq 'array') {
13077:                 $env{'form.'.$setting} = [ 
13078:                                            map { 
13079:                                                &unescape($_); 
13080:                                            } split(',',$env{$envname})
13081:                                            ];
13082:             }
13083:         }
13084:     }
13085: }
13086: 
13087: #######################################################
13088: #######################################################
13089: 
13090: =pod
13091: 
13092: =head1 Domain E-mail Routines  
13093: 
13094: =over 4
13095: 
13096: =item * &build_recipient_list()
13097: 
13098: Build recipient lists for following types of e-mail:
13099: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13100: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13101: module change checking, student/employee ID conflict checks, as
13102: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13103: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13104: 
13105: Inputs:
13106: defmail (scalar - email address of default recipient),
13107: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13108: requestsmail, updatesmail, or idconflictsmail).
13109: 
13110: defdom (domain for which to retrieve configuration settings),
13111: 
13112: origmail (scalar - email address of recipient from loncapa.conf,
13113: i.e., predates configuration by DC via domainprefs.pm
13114: 
13115: Returns: comma separated list of addresses to which to send e-mail.
13116: 
13117: =back
13118: 
13119: =cut
13120: 
13121: ############################################################
13122: ############################################################
13123: sub build_recipient_list {
13124:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13125:     my @recipients;
13126:     my $otheremails;
13127:     my %domconfig =
13128:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13129:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13130:         if (exists($domconfig{'contacts'}{$mailing})) {
13131:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13132:                 my @contacts = ('adminemail','supportemail');
13133:                 foreach my $item (@contacts) {
13134:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13135:                         my $addr = $domconfig{'contacts'}{$item}; 
13136:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13137:                             push(@recipients,$addr);
13138:                         }
13139:                     }
13140:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13141:                 }
13142:             }
13143:         } elsif ($origmail ne '') {
13144:             push(@recipients,$origmail);
13145:         }
13146:     } elsif ($origmail ne '') {
13147:         push(@recipients,$origmail);
13148:     }
13149:     if (defined($defmail)) {
13150:         if ($defmail ne '') {
13151:             push(@recipients,$defmail);
13152:         }
13153:     }
13154:     if ($otheremails) {
13155:         my @others;
13156:         if ($otheremails =~ /,/) {
13157:             @others = split(/,/,$otheremails);
13158:         } else {
13159:             push(@others,$otheremails);
13160:         }
13161:         foreach my $addr (@others) {
13162:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13163:                 push(@recipients,$addr);
13164:             }
13165:         }
13166:     }
13167:     my $recipientlist = join(',',@recipients); 
13168:     return $recipientlist;
13169: }
13170: 
13171: ############################################################
13172: ############################################################
13173: 
13174: =pod
13175: 
13176: =head1 Course Catalog Routines
13177: 
13178: =over 4
13179: 
13180: =item * &gather_categories()
13181: 
13182: Converts category definitions - keys of categories hash stored in  
13183: coursecategories in configuration.db on the primary library server in a 
13184: domain - to an array.  Also generates javascript and idx hash used to 
13185: generate Domain Coordinator interface for editing Course Categories.
13186: 
13187: Inputs:
13188: 
13189: categories (reference to hash of category definitions).
13190: 
13191: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13192:       categories and subcategories).
13193: 
13194: idx (reference to hash of counters used in Domain Coordinator interface for 
13195:       editing Course Categories).
13196: 
13197: jsarray (reference to array of categories used to create Javascript arrays for
13198:          Domain Coordinator interface for editing Course Categories).
13199: 
13200: Returns: nothing
13201: 
13202: Side effects: populates cats, idx and jsarray. 
13203: 
13204: =cut
13205: 
13206: sub gather_categories {
13207:     my ($categories,$cats,$idx,$jsarray) = @_;
13208:     my %counters;
13209:     my $num = 0;
13210:     foreach my $item (keys(%{$categories})) {
13211:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13212:         if ($container eq '' && $depth == 0) {
13213:             $cats->[$depth][$categories->{$item}] = $cat;
13214:         } else {
13215:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13216:         }
13217:         my ($escitem,$tail) = split(/:/,$item,2);
13218:         if ($counters{$tail} eq '') {
13219:             $counters{$tail} = $num;
13220:             $num ++;
13221:         }
13222:         if (ref($idx) eq 'HASH') {
13223:             $idx->{$item} = $counters{$tail};
13224:         }
13225:         if (ref($jsarray) eq 'ARRAY') {
13226:             push(@{$jsarray->[$counters{$tail}]},$item);
13227:         }
13228:     }
13229:     return;
13230: }
13231: 
13232: =pod
13233: 
13234: =item * &extract_categories()
13235: 
13236: Used to generate breadcrumb trails for course categories.
13237: 
13238: Inputs:
13239: 
13240: categories (reference to hash of category definitions).
13241: 
13242: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13243:       categories and subcategories).
13244: 
13245: trails (reference to array of breacrumb trails for each category).
13246: 
13247: allitems (reference to hash - key is category key 
13248:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13249: 
13250: idx (reference to hash of counters used in Domain Coordinator interface for
13251:       editing Course Categories).
13252: 
13253: jsarray (reference to array of categories used to create Javascript arrays for
13254:          Domain Coordinator interface for editing Course Categories).
13255: 
13256: subcats (reference to hash of arrays containing all subcategories within each 
13257:          category, -recursive)
13258: 
13259: Returns: nothing
13260: 
13261: Side effects: populates trails and allitems hash references.
13262: 
13263: =cut
13264: 
13265: sub extract_categories {
13266:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13267:     if (ref($categories) eq 'HASH') {
13268:         &gather_categories($categories,$cats,$idx,$jsarray);
13269:         if (ref($cats->[0]) eq 'ARRAY') {
13270:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13271:                 my $name = $cats->[0][$i];
13272:                 my $item = &escape($name).'::0';
13273:                 my $trailstr;
13274:                 if ($name eq 'instcode') {
13275:                     $trailstr = &mt('Official courses (with institutional codes)');
13276:                 } elsif ($name eq 'communities') {
13277:                     $trailstr = &mt('Communities');
13278:                 } else {
13279:                     $trailstr = $name;
13280:                 }
13281:                 if ($allitems->{$item} eq '') {
13282:                     push(@{$trails},$trailstr);
13283:                     $allitems->{$item} = scalar(@{$trails})-1;
13284:                 }
13285:                 my @parents = ($name);
13286:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13287:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13288:                         my $category = $cats->[1]{$name}[$j];
13289:                         if (ref($subcats) eq 'HASH') {
13290:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13291:                         }
13292:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13293:                     }
13294:                 } else {
13295:                     if (ref($subcats) eq 'HASH') {
13296:                         $subcats->{$item} = [];
13297:                     }
13298:                 }
13299:             }
13300:         }
13301:     }
13302:     return;
13303: }
13304: 
13305: =pod
13306: 
13307: =item *&recurse_categories()
13308: 
13309: Recursively used to generate breadcrumb trails for course categories.
13310: 
13311: Inputs:
13312: 
13313: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13314:       categories and subcategories).
13315: 
13316: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13317: 
13318: category (current course category, for which breadcrumb trail is being generated).
13319: 
13320: trails (reference to array of breadcrumb trails for each category).
13321: 
13322: allitems (reference to hash - key is category key
13323:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13324: 
13325: parents (array containing containers directories for current category, 
13326:          back to top level). 
13327: 
13328: Returns: nothing
13329: 
13330: Side effects: populates trails and allitems hash references
13331: 
13332: =cut
13333: 
13334: sub recurse_categories {
13335:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13336:     my $shallower = $depth - 1;
13337:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13338:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13339:             my $name = $cats->[$depth]{$category}[$k];
13340:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13341:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13342:             if ($allitems->{$item} eq '') {
13343:                 push(@{$trails},$trailstr);
13344:                 $allitems->{$item} = scalar(@{$trails})-1;
13345:             }
13346:             my $deeper = $depth+1;
13347:             push(@{$parents},$category);
13348:             if (ref($subcats) eq 'HASH') {
13349:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13350:                 for (my $j=@{$parents}; $j>=0; $j--) {
13351:                     my $higher;
13352:                     if ($j > 0) {
13353:                         $higher = &escape($parents->[$j]).':'.
13354:                                   &escape($parents->[$j-1]).':'.$j;
13355:                     } else {
13356:                         $higher = &escape($parents->[$j]).'::'.$j;
13357:                     }
13358:                     push(@{$subcats->{$higher}},$subcat);
13359:                 }
13360:             }
13361:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13362:                                 $subcats);
13363:             pop(@{$parents});
13364:         }
13365:     } else {
13366:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13367:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13368:         if ($allitems->{$item} eq '') {
13369:             push(@{$trails},$trailstr);
13370:             $allitems->{$item} = scalar(@{$trails})-1;
13371:         }
13372:     }
13373:     return;
13374: }
13375: 
13376: =pod
13377: 
13378: =item *&assign_categories_table()
13379: 
13380: Create a datatable for display of hierarchical categories in a domain,
13381: with checkboxes to allow a course to be categorized. 
13382: 
13383: Inputs:
13384: 
13385: cathash - reference to hash of categories defined for the domain (from
13386:           configuration.db)
13387: 
13388: currcat - scalar with an & separated list of categories assigned to a course. 
13389: 
13390: type    - scalar contains course type (Course or Community).
13391: 
13392: Returns: $output (markup to be displayed) 
13393: 
13394: =cut
13395: 
13396: sub assign_categories_table {
13397:     my ($cathash,$currcat,$type) = @_;
13398:     my $output;
13399:     if (ref($cathash) eq 'HASH') {
13400:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13401:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13402:         $maxdepth = scalar(@cats);
13403:         if (@cats > 0) {
13404:             my $itemcount = 0;
13405:             if (ref($cats[0]) eq 'ARRAY') {
13406:                 my @currcategories;
13407:                 if ($currcat ne '') {
13408:                     @currcategories = split('&',$currcat);
13409:                 }
13410:                 my $table;
13411:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13412:                     my $parent = $cats[0][$i];
13413:                     next if ($parent eq 'instcode');
13414:                     if ($type eq 'Community') {
13415:                         next unless ($parent eq 'communities');
13416:                     } else {
13417:                         next if ($parent eq 'communities');
13418:                     }
13419:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13420:                     my $item = &escape($parent).'::0';
13421:                     my $checked = '';
13422:                     if (@currcategories > 0) {
13423:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13424:                             $checked = ' checked="checked"';
13425:                         }
13426:                     }
13427:                     my $parent_title = $parent;
13428:                     if ($parent eq 'communities') {
13429:                         $parent_title = &mt('Communities');
13430:                     }
13431:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13432:                               '<input type="checkbox" name="usecategory" value="'.
13433:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13434:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13435:                     my $depth = 1;
13436:                     push(@path,$parent);
13437:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13438:                     pop(@path);
13439:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13440:                     $itemcount ++;
13441:                 }
13442:                 if ($itemcount) {
13443:                     $output = &Apache::loncommon::start_data_table().
13444:                               $table.
13445:                               &Apache::loncommon::end_data_table();
13446:                 }
13447:             }
13448:         }
13449:     }
13450:     return $output;
13451: }
13452: 
13453: =pod
13454: 
13455: =item *&assign_category_rows()
13456: 
13457: Create a datatable row for display of nested categories in a domain,
13458: with checkboxes to allow a course to be categorized,called recursively.
13459: 
13460: Inputs:
13461: 
13462: itemcount - track row number for alternating colors
13463: 
13464: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13465:       categories and subcategories.
13466: 
13467: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13468: 
13469: parent - parent of current category item
13470: 
13471: path - Array containing all categories back up through the hierarchy from the
13472:        current category to the top level.
13473: 
13474: currcategories - reference to array of current categories assigned to the course
13475: 
13476: Returns: $output (markup to be displayed).
13477: 
13478: =cut
13479: 
13480: sub assign_category_rows {
13481:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13482:     my ($text,$name,$item,$chgstr);
13483:     if (ref($cats) eq 'ARRAY') {
13484:         my $maxdepth = scalar(@{$cats});
13485:         if (ref($cats->[$depth]) eq 'HASH') {
13486:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13487:                 my $numchildren = @{$cats->[$depth]{$parent}};
13488:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13489:                 $text .= '<td><table class="LC_data_table">';
13490:                 for (my $j=0; $j<$numchildren; $j++) {
13491:                     $name = $cats->[$depth]{$parent}[$j];
13492:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13493:                     my $deeper = $depth+1;
13494:                     my $checked = '';
13495:                     if (ref($currcategories) eq 'ARRAY') {
13496:                         if (@{$currcategories} > 0) {
13497:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13498:                                 $checked = ' checked="checked"';
13499:                             }
13500:                         }
13501:                     }
13502:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13503:                              '<input type="checkbox" name="usecategory" value="'.
13504:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13505:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13506:                              '</td><td>';
13507:                     if (ref($path) eq 'ARRAY') {
13508:                         push(@{$path},$name);
13509:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13510:                         pop(@{$path});
13511:                     }
13512:                     $text .= '</td></tr>';
13513:                 }
13514:                 $text .= '</table></td>';
13515:             }
13516:         }
13517:     }
13518:     return $text;
13519: }
13520: 
13521: ############################################################
13522: ############################################################
13523: 
13524: 
13525: sub commit_customrole {
13526:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13527:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13528:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13529:                          ($end?', ending '.localtime($end):'').': <b>'.
13530:               &Apache::lonnet::assigncustomrole(
13531:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13532:                  '</b><br />';
13533:     return $output;
13534: }
13535: 
13536: sub commit_standardrole {
13537:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13538:     my ($output,$logmsg,$linefeed);
13539:     if ($context eq 'auto') {
13540:         $linefeed = "\n";
13541:     } else {
13542:         $linefeed = "<br />\n";
13543:     }  
13544:     if ($three eq 'st') {
13545:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13546:                                          $one,$two,$sec,$context,$credits);
13547:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13548:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13549:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13550:         } else {
13551:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13552:                ($start?', '.&mt('starting').' '.localtime($start):'').
13553:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13554:             if ($context eq 'auto') {
13555:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13556:             } else {
13557:                $output .= '<b>'.$result.'</b>'.$linefeed.
13558:                &mt('Add to classlist').': <b>ok</b>';
13559:             }
13560:             $output .= $linefeed;
13561:         }
13562:     } else {
13563:         $output = &mt('Assigning').' '.$three.' in '.$url.
13564:                ($start?', '.&mt('starting').' '.localtime($start):'').
13565:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13566:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13567:         if ($context eq 'auto') {
13568:             $output .= $result.$linefeed;
13569:         } else {
13570:             $output .= '<b>'.$result.'</b>'.$linefeed;
13571:         }
13572:     }
13573:     return $output;
13574: }
13575: 
13576: sub commit_studentrole {
13577:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13578:         $credits) = @_;
13579:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13580:     if ($context eq 'auto') {
13581:         $linefeed = "\n";
13582:     } else {
13583:         $linefeed = '<br />'."\n";
13584:     }
13585:     if (defined($one) && defined($two)) {
13586:         my $cid=$one.'_'.$two;
13587:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13588:         my $secchange = 0;
13589:         my $expire_role_result;
13590:         my $modify_section_result;
13591:         if ($oldsec ne '-1') { 
13592:             if ($oldsec ne $sec) {
13593:                 $secchange = 1;
13594:                 my $now = time;
13595:                 my $uurl='/'.$cid;
13596:                 $uurl=~s/\_/\//g;
13597:                 if ($oldsec) {
13598:                     $uurl.='/'.$oldsec;
13599:                 }
13600:                 $oldsecurl = $uurl;
13601:                 $expire_role_result = 
13602:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13603:                 if ($env{'request.course.sec'} ne '') { 
13604:                     if ($expire_role_result eq 'refused') {
13605:                         my @roles = ('st');
13606:                         my @statuses = ('previous');
13607:                         my @roledoms = ($one);
13608:                         my $withsec = 1;
13609:                         my %roleshash = 
13610:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13611:                                               \@statuses,\@roles,\@roledoms,$withsec);
13612:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13613:                             my ($oldstart,$oldend) = 
13614:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13615:                             if ($oldend > 0 && $oldend <= $now) {
13616:                                 $expire_role_result = 'ok';
13617:                             }
13618:                         }
13619:                     }
13620:                 }
13621:                 $result = $expire_role_result;
13622:             }
13623:         }
13624:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13625:             $modify_section_result = 
13626:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13627:                                                            undef,undef,undef,$sec,
13628:                                                            $end,$start,'','',$cid,
13629:                                                            '',$context,$credits);
13630:             if ($modify_section_result =~ /^ok/) {
13631:                 if ($secchange == 1) {
13632:                     if ($sec eq '') {
13633:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13634:                     } else {
13635:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13636:                     }
13637:                 } elsif ($oldsec eq '-1') {
13638:                     if ($sec eq '') {
13639:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13640:                     } else {
13641:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13642:                     }
13643:                 } else {
13644:                     if ($sec eq '') {
13645:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13646:                     } else {
13647:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13648:                     }
13649:                 }
13650:             } else {
13651:                 if ($secchange) {       
13652:                     $$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;
13653:                 } else {
13654:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13655:                 }
13656:             }
13657:             $result = $modify_section_result;
13658:         } elsif ($secchange == 1) {
13659:             if ($oldsec eq '') {
13660:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13661:             } else {
13662:                 $$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;
13663:             }
13664:             if ($expire_role_result eq 'refused') {
13665:                 my $newsecurl = '/'.$cid;
13666:                 $newsecurl =~ s/\_/\//g;
13667:                 if ($sec ne '') {
13668:                     $newsecurl.='/'.$sec;
13669:                 }
13670:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13671:                     if ($sec eq '') {
13672:                         $$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;
13673:                     } else {
13674:                         $$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;
13675:                     }
13676:                 }
13677:             }
13678:         }
13679:     } else {
13680:         $$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;
13681:         $result = "error: incomplete course id\n";
13682:     }
13683:     return $result;
13684: }
13685: 
13686: sub show_role_extent {
13687:     my ($scope,$context,$role) = @_;
13688:     $scope =~ s{^/}{};
13689:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13690:     push(@courseroles,'co');
13691:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13692:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13693:         $scope =~ s{/}{_};
13694:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13695:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13696:         my ($audom,$auname) = split(/\//,$scope);
13697:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13698:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13699:     } else {
13700:         $scope =~ s{/$}{};
13701:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13702:                    &Apache::lonnet::domain($scope,'description').'</span>');
13703:     }
13704: }
13705: 
13706: ############################################################
13707: ############################################################
13708: 
13709: sub check_clone {
13710:     my ($args,$linefeed) = @_;
13711:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13712:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13713:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13714:     my $clonemsg;
13715:     my $can_clone = 0;
13716:     my $lctype = lc($args->{'crstype'});
13717:     if ($lctype ne 'community') {
13718:         $lctype = 'course';
13719:     }
13720:     if ($clonehome eq 'no_host') {
13721:         if ($args->{'crstype'} eq 'Community') {
13722:             $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'});
13723:         } else {
13724:             $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'});
13725:         }     
13726:     } else {
13727: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13728:         if ($args->{'crstype'} eq 'Community') {
13729:             if ($clonedesc{'type'} ne 'Community') {
13730:                  $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'});
13731:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13732:             }
13733:         }
13734: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13735:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13736: 	    $can_clone = 1;
13737: 	} else {
13738: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13739: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13740: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13741:             if (grep(/^\*$/,@cloners)) {
13742:                 $can_clone = 1;
13743:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13744:                 $can_clone = 1;
13745:             } else {
13746:                 my $ccrole = 'cc';
13747:                 if ($args->{'crstype'} eq 'Community') {
13748:                     $ccrole = 'co';
13749:                 }
13750: 	        my %roleshash =
13751: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13752: 					 $args->{'ccdomain'},
13753:                                          'userroles',['active'],[$ccrole],
13754: 					 [$args->{'clonedomain'}]);
13755: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13756:                     $can_clone = 1;
13757:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13758:                     $can_clone = 1;
13759:                 } else {
13760:                     if ($args->{'crstype'} eq 'Community') {
13761:                         $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'});
13762:                     } else {
13763:                         $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'});
13764:                     }
13765: 	        }
13766: 	    }
13767:         }
13768:     }
13769:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13770: }
13771: 
13772: sub construct_course {
13773:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13774:     my $outcome;
13775:     my $linefeed =  '<br />'."\n";
13776:     if ($context eq 'auto') {
13777:         $linefeed = "\n";
13778:     }
13779: 
13780: #
13781: # Are we cloning?
13782: #
13783:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13784:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13785: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13786: 	if ($context ne 'auto') {
13787:             if ($clonemsg ne '') {
13788: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13789:             }
13790: 	}
13791: 	$outcome .= $clonemsg.$linefeed;
13792: 
13793:         if (!$can_clone) {
13794: 	    return (0,$outcome);
13795: 	}
13796:     }
13797: 
13798: #
13799: # Open course
13800: #
13801:     my $crstype = lc($args->{'crstype'});
13802:     my %cenv=();
13803:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13804:                                              $args->{'cdescr'},
13805:                                              $args->{'curl'},
13806:                                              $args->{'course_home'},
13807:                                              $args->{'nonstandard'},
13808:                                              $args->{'crscode'},
13809:                                              $args->{'ccuname'}.':'.
13810:                                              $args->{'ccdomain'},
13811:                                              $args->{'crstype'},
13812:                                              $cnum,$context,$category);
13813: 
13814:     # Note: The testing routines depend on this being output; see 
13815:     # Utils::Course. This needs to at least be output as a comment
13816:     # if anyone ever decides to not show this, and Utils::Course::new
13817:     # will need to be suitably modified.
13818:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13819:     if ($$courseid =~ /^error:/) {
13820:         return (0,$outcome);
13821:     }
13822: 
13823: #
13824: # Check if created correctly
13825: #
13826:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13827:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13828:     if ($crsuhome eq 'no_host') {
13829:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13830:         return (0,$outcome);
13831:     }
13832:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13833: 
13834: #
13835: # Do the cloning
13836: #   
13837:     if ($can_clone && $cloneid) {
13838: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13839: 	if ($context ne 'auto') {
13840: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13841: 	}
13842: 	$outcome .= $clonemsg.$linefeed;
13843: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13844: # Copy all files
13845: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13846: # Restore URL
13847: 	$cenv{'url'}=$oldcenv{'url'};
13848: # Restore title
13849: 	$cenv{'description'}=$oldcenv{'description'};
13850: # Restore creation date, creator and creation context.
13851:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13852:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13853:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13854: # Mark as cloned
13855: 	$cenv{'clonedfrom'}=$cloneid;
13856: # Need to clone grading mode
13857:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13858:         $cenv{'grading'}=$newenv{'grading'};
13859: # Do not clone these environment entries
13860:         &Apache::lonnet::del('environment',
13861:                   ['default_enrollment_start_date',
13862:                    'default_enrollment_end_date',
13863:                    'question.email',
13864:                    'policy.email',
13865:                    'comment.email',
13866:                    'pch.users.denied',
13867:                    'plc.users.denied',
13868:                    'hidefromcat',
13869:                    'checkforpriv',
13870:                    'categories'],
13871:                    $$crsudom,$$crsunum);
13872:     }
13873: 
13874: #
13875: # Set environment (will override cloned, if existing)
13876: #
13877:     my @sections = ();
13878:     my @xlists = ();
13879:     if ($args->{'crstype'}) {
13880:         $cenv{'type'}=$args->{'crstype'};
13881:     }
13882:     if ($args->{'crsid'}) {
13883:         $cenv{'courseid'}=$args->{'crsid'};
13884:     }
13885:     if ($args->{'crscode'}) {
13886:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13887:     }
13888:     if ($args->{'crsquota'} ne '') {
13889:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13890:     } else {
13891:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13892:     }
13893:     if ($args->{'ccuname'}) {
13894:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13895:                                         ':'.$args->{'ccdomain'};
13896:     } else {
13897:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13898:     }
13899:     if ($args->{'defaultcredits'}) {
13900:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
13901:     }
13902:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13903:     if ($args->{'crssections'}) {
13904:         $cenv{'internal.sectionnums'} = '';
13905:         if ($args->{'crssections'} =~ m/,/) {
13906:             @sections = split/,/,$args->{'crssections'};
13907:         } else {
13908:             $sections[0] = $args->{'crssections'};
13909:         }
13910:         if (@sections > 0) {
13911:             foreach my $item (@sections) {
13912:                 my ($sec,$gp) = split/:/,$item;
13913:                 my $class = $args->{'crscode'}.$sec;
13914:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13915:                 $cenv{'internal.sectionnums'} .= $item.',';
13916:                 unless ($addcheck eq 'ok') {
13917:                     push @badclasses, $class;
13918:                 }
13919:             }
13920:             $cenv{'internal.sectionnums'} =~ s/,$//;
13921:         }
13922:     }
13923: # do not hide course coordinator from staff listing, 
13924: # even if privileged
13925:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13926: # add course coordinator's domain to domains to check for privileged users
13927: # if different to course domain
13928:     if ($$crsudom ne $args->{'ccdomain'}) {
13929:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
13930:     }
13931: # add crosslistings
13932:     if ($args->{'crsxlist'}) {
13933:         $cenv{'internal.crosslistings'}='';
13934:         if ($args->{'crsxlist'} =~ m/,/) {
13935:             @xlists = split/,/,$args->{'crsxlist'};
13936:         } else {
13937:             $xlists[0] = $args->{'crsxlist'};
13938:         }
13939:         if (@xlists > 0) {
13940:             foreach my $item (@xlists) {
13941:                 my ($xl,$gp) = split/:/,$item;
13942:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13943:                 $cenv{'internal.crosslistings'} .= $item.',';
13944:                 unless ($addcheck eq 'ok') {
13945:                     push @badclasses, $xl;
13946:                 }
13947:             }
13948:             $cenv{'internal.crosslistings'} =~ s/,$//;
13949:         }
13950:     }
13951:     if ($args->{'autoadds'}) {
13952:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13953:     }
13954:     if ($args->{'autodrops'}) {
13955:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13956:     }
13957: # check for notification of enrollment changes
13958:     my @notified = ();
13959:     if ($args->{'notify_owner'}) {
13960:         if ($args->{'ccuname'} ne '') {
13961:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13962:         }
13963:     }
13964:     if ($args->{'notify_dc'}) {
13965:         if ($uname ne '') { 
13966:             push(@notified,$uname.':'.$udom);
13967:         }
13968:     }
13969:     if (@notified > 0) {
13970:         my $notifylist;
13971:         if (@notified > 1) {
13972:             $notifylist = join(',',@notified);
13973:         } else {
13974:             $notifylist = $notified[0];
13975:         }
13976:         $cenv{'internal.notifylist'} = $notifylist;
13977:     }
13978:     if (@badclasses > 0) {
13979:         my %lt=&Apache::lonlocal::texthash(
13980:                 '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',
13981:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13982:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13983:         );
13984:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13985:                            ' ('.$lt{'adby'}.')';
13986:         if ($context eq 'auto') {
13987:             $outcome .= $badclass_msg.$linefeed;
13988:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13989:             foreach my $item (@badclasses) {
13990:                 if ($context eq 'auto') {
13991:                     $outcome .= " - $item\n";
13992:                 } else {
13993:                     $outcome .= "<li>$item</li>\n";
13994:                 }
13995:             }
13996:             if ($context eq 'auto') {
13997:                 $outcome .= $linefeed;
13998:             } else {
13999:                 $outcome .= "</ul><br /><br /></div>\n";
14000:             }
14001:         } 
14002:     }
14003:     if ($args->{'no_end_date'}) {
14004:         $args->{'endaccess'} = 0;
14005:     }
14006:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14007:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14008:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14009:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14010:     if ($args->{'showphotos'}) {
14011:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14012:     }
14013:     $cenv{'internal.authtype'} = $args->{'authtype'};
14014:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14015:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14016:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14017:             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'); 
14018:             if ($context eq 'auto') {
14019:                 $outcome .= $krb_msg;
14020:             } else {
14021:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14022:             }
14023:             $outcome .= $linefeed;
14024:         }
14025:     }
14026:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14027:        if ($args->{'setpolicy'}) {
14028:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14029:        }
14030:        if ($args->{'setcontent'}) {
14031:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14032:        }
14033:     }
14034:     if ($args->{'reshome'}) {
14035: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14036: 	$cenv{'reshome'}=~s/\/+$/\//;
14037:     }
14038: #
14039: # course has keyed access
14040: #
14041:     if ($args->{'setkeys'}) {
14042:        $cenv{'keyaccess'}='yes';
14043:     }
14044: # if specified, key authority is not course, but user
14045: # only active if keyaccess is yes
14046:     if ($args->{'keyauth'}) {
14047: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14048: 	$user = &LONCAPA::clean_username($user);
14049: 	$domain = &LONCAPA::clean_username($domain);
14050: 	if ($user ne '' && $domain ne '') {
14051: 	    $cenv{'keyauth'}=$user.':'.$domain;
14052: 	}
14053:     }
14054: 
14055:     if ($args->{'disresdis'}) {
14056:         $cenv{'pch.roles.denied'}='st';
14057:     }
14058:     if ($args->{'disablechat'}) {
14059:         $cenv{'plc.roles.denied'}='st';
14060:     }
14061: 
14062:     # Record we've not yet viewed the Course Initialization Helper for this 
14063:     # course
14064:     $cenv{'course.helper.not.run'} = 1;
14065:     #
14066:     # Use new Randomseed
14067:     #
14068:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14069:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14070:     #
14071:     # The encryption code and receipt prefix for this course
14072:     #
14073:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14074:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14075:     #
14076:     # By default, use standard grading
14077:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14078: 
14079:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14080:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14081: #
14082: # Open all assignments
14083: #
14084:     if ($args->{'openall'}) {
14085:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14086:        my %storecontent = ($storeunder         => time,
14087:                            $storeunder.'.type' => 'date_start');
14088:        
14089:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14090:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14091:    }
14092: #
14093: # Set first page
14094: #
14095:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14096: 	    || ($cloneid)) {
14097: 	use LONCAPA::map;
14098: 	$outcome .= &mt('Setting first resource').': ';
14099: 
14100: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14101:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14102: 
14103:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14104:         my $title; my $url;
14105:         if ($args->{'firstres'} eq 'syl') {
14106: 	    $title=&mt('Syllabus');
14107:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14108:         } else {
14109:             $title=&mt('Table of Contents');
14110:             $url='/adm/navmaps';
14111:         }
14112: 
14113:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14114: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14115: 
14116: 	if ($errtext) { $fatal=2; }
14117:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14118:     }
14119: 
14120:     return (1,$outcome);
14121: }
14122: 
14123: ############################################################
14124: ############################################################
14125: 
14126: #SD
14127: # only Community and Course, or anything else?
14128: sub course_type {
14129:     my ($cid) = @_;
14130:     if (!defined($cid)) {
14131:         $cid = $env{'request.course.id'};
14132:     }
14133:     if (defined($env{'course.'.$cid.'.type'})) {
14134:         return $env{'course.'.$cid.'.type'};
14135:     } else {
14136:         return 'Course';
14137:     }
14138: }
14139: 
14140: sub group_term {
14141:     my $crstype = &course_type();
14142:     my %names = (
14143:                   'Course' => 'group',
14144:                   'Community' => 'group',
14145:                 );
14146:     return $names{$crstype};
14147: }
14148: 
14149: sub course_types {
14150:     my @types = ('official','unofficial','community');
14151:     my %typename = (
14152:                          official   => 'Official course',
14153:                          unofficial => 'Unofficial course',
14154:                          community  => 'Community',
14155:                    );
14156:     return (\@types,\%typename);
14157: }
14158: 
14159: sub icon {
14160:     my ($file)=@_;
14161:     my $curfext = lc((split(/\./,$file))[-1]);
14162:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14163:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14164:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14165: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14166: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14167: 	            $curfext.".gif") {
14168: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14169: 		$curfext.".gif";
14170: 	}
14171:     }
14172:     return &lonhttpdurl($iconname);
14173: } 
14174: 
14175: sub lonhttpdurl {
14176: #
14177: # Had been used for "small fry" static images on separate port 8080.
14178: # Modify here if lightweight http functionality desired again.
14179: # Currently eliminated due to increasing firewall issues.
14180: #
14181:     my ($url)=@_;
14182:     return $url;
14183: }
14184: 
14185: sub connection_aborted {
14186:     my ($r)=@_;
14187:     $r->print(" ");$r->rflush();
14188:     my $c = $r->connection;
14189:     return $c->aborted();
14190: }
14191: 
14192: #    Escapes strings that may have embedded 's that will be put into
14193: #    strings as 'strings'.
14194: sub escape_single {
14195:     my ($input) = @_;
14196:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14197:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14198:     return $input;
14199: }
14200: 
14201: #  Same as escape_single, but escape's "'s  This 
14202: #  can be used for  "strings"
14203: sub escape_double {
14204:     my ($input) = @_;
14205:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14206:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14207:     return $input;
14208: }
14209:  
14210: #   Escapes the last element of a full URL.
14211: sub escape_url {
14212:     my ($url)   = @_;
14213:     my @urlslices = split(/\//, $url,-1);
14214:     my $lastitem = &escape(pop(@urlslices));
14215:     return join('/',@urlslices).'/'.$lastitem;
14216: }
14217: 
14218: sub compare_arrays {
14219:     my ($arrayref1,$arrayref2) = @_;
14220:     my (@difference,%count);
14221:     @difference = ();
14222:     %count = ();
14223:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14224:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14225:         foreach my $element (keys(%count)) {
14226:             if ($count{$element} == 1) {
14227:                 push(@difference,$element);
14228:             }
14229:         }
14230:     }
14231:     return @difference;
14232: }
14233: 
14234: # -------------------------------------------------------- Initialize user login
14235: sub init_user_environment {
14236:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14237:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14238: 
14239:     my $public=($username eq 'public' && $domain eq 'public');
14240: 
14241: # See if old ID present, if so, remove
14242: 
14243:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14244:     my $now=time;
14245: 
14246:     if ($public) {
14247: 	my $max_public=100;
14248: 	my $oldest;
14249: 	my $oldest_time=0;
14250: 	for(my $next=1;$next<=$max_public;$next++) {
14251: 	    if (-e $lonids."/publicuser_$next.id") {
14252: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14253: 		if ($mtime<$oldest_time || !$oldest_time) {
14254: 		    $oldest_time=$mtime;
14255: 		    $oldest=$next;
14256: 		}
14257: 	    } else {
14258: 		$cookie="publicuser_$next";
14259: 		last;
14260: 	    }
14261: 	}
14262: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14263:     } else {
14264: 	# if this isn't a robot, kill any existing non-robot sessions
14265: 	if (!$args->{'robot'}) {
14266: 	    opendir(DIR,$lonids);
14267: 	    while ($filename=readdir(DIR)) {
14268: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14269: 		    unlink($lonids.'/'.$filename);
14270: 		}
14271: 	    }
14272: 	    closedir(DIR);
14273: 	}
14274: # Give them a new cookie
14275: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14276: 		                   : $now.$$.int(rand(10000)));
14277: 	$cookie="$username\_$id\_$domain\_$authhost";
14278:     
14279: # Initialize roles
14280: 
14281: 	($userroles,$firstaccenv,$timerintenv) = 
14282:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14283:     }
14284: # ------------------------------------ Check browser type and MathML capability
14285: 
14286:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14287:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14288: 
14289: # ------------------------------------------------------------- Get environment
14290: 
14291:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14292:     my ($tmp) = keys(%userenv);
14293:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14294:     } else {
14295: 	undef(%userenv);
14296:     }
14297:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14298: 	$form->{'interface'}=$userenv{'interface'};
14299:     }
14300:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14301: 
14302: # --------------- Do not trust query string to be put directly into environment
14303:     foreach my $option ('interface','localpath','localres') {
14304:         $form->{$option}=~s/[\n\r\=]//gs;
14305:     }
14306: # --------------------------------------------------------- Write first profile
14307: 
14308:     {
14309: 	my %initial_env = 
14310: 	    ("user.name"          => $username,
14311: 	     "user.domain"        => $domain,
14312: 	     "user.home"          => $authhost,
14313: 	     "browser.type"       => $clientbrowser,
14314: 	     "browser.version"    => $clientversion,
14315: 	     "browser.mathml"     => $clientmathml,
14316: 	     "browser.unicode"    => $clientunicode,
14317: 	     "browser.os"         => $clientos,
14318:              "browser.mobile"     => $clientmobile,
14319:              "browser.info"       => $clientinfo,
14320: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14321: 	     "request.course.fn"  => '',
14322: 	     "request.course.uri" => '',
14323: 	     "request.course.sec" => '',
14324: 	     "request.role"       => 'cm',
14325: 	     "request.role.adv"   => $env{'user.adv'},
14326: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14327: 
14328:         if ($form->{'localpath'}) {
14329: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14330: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14331:         }
14332: 	
14333: 	if ($form->{'interface'}) {
14334: 	    $form->{'interface'}=~s/\W//gs;
14335: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14336: 	    $env{'browser.interface'}=$form->{'interface'};
14337: 	}
14338: 
14339:         my %is_adv = ( is_adv => $env{'user.adv'} );
14340:         my %domdef;
14341:         unless ($domain eq 'public') {
14342:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14343:         }
14344: 
14345:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14346:             $userenv{'availabletools.'.$tool} = 
14347:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14348:                                                   undef,\%userenv,\%domdef,\%is_adv);
14349:         }
14350: 
14351:         foreach my $crstype ('official','unofficial','community') {
14352:             $userenv{'canrequest.'.$crstype} =
14353:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14354:                                                   'reload','requestcourses',
14355:                                                   \%userenv,\%domdef,\%is_adv);
14356:         }
14357: 
14358:         $userenv{'canrequest.author'} =
14359:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14360:                                         'reload','requestauthor',
14361:                                         \%userenv,\%domdef,\%is_adv);
14362:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14363:                                              $domain,$username);
14364:         my $reqstatus = $reqauthor{'author_status'};
14365:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14366:             if (ref($reqauthor{'author'}) eq 'HASH') {
14367:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14368:                                                   $reqauthor{'author'}{'timestamp'};
14369:             }
14370:         }
14371: 
14372: 	$env{'user.environment'} = "$lonids/$cookie.id";
14373: 
14374: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14375: 		 &GDBM_WRCREAT(),0640)) {
14376: 	    &_add_to_env(\%disk_env,\%initial_env);
14377: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14378: 	    &_add_to_env(\%disk_env,$userroles);
14379:             if (ref($firstaccenv) eq 'HASH') {
14380:                 &_add_to_env(\%disk_env,$firstaccenv);
14381:             }
14382:             if (ref($timerintenv) eq 'HASH') {
14383:                 &_add_to_env(\%disk_env,$timerintenv);
14384:             }
14385: 	    if (ref($args->{'extra_env'})) {
14386: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14387: 	    }
14388: 	    untie(%disk_env);
14389: 	} else {
14390: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14391: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14392: 	    return 'error: '.$!;
14393: 	}
14394:     }
14395:     $env{'request.role'}='cm';
14396:     $env{'request.role.adv'}=$env{'user.adv'};
14397:     $env{'browser.type'}=$clientbrowser;
14398: 
14399:     return $cookie;
14400: 
14401: }
14402: 
14403: sub _add_to_env {
14404:     my ($idf,$env_data,$prefix) = @_;
14405:     if (ref($env_data) eq 'HASH') {
14406:         while (my ($key,$value) = each(%$env_data)) {
14407: 	    $idf->{$prefix.$key} = $value;
14408: 	    $env{$prefix.$key}   = $value;
14409:         }
14410:     }
14411: }
14412: 
14413: # --- Get the symbolic name of a problem and the url
14414: sub get_symb {
14415:     my ($request,$silent) = @_;
14416:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14417:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14418:     if ($symb eq '') {
14419:         if (!$silent) {
14420:             if (ref($request)) { 
14421:                 $request->print("Unable to handle ambiguous references:$url:.");
14422:             }
14423:             return ();
14424:         }
14425:     }
14426:     &Apache::lonenc::check_decrypt(\$symb);
14427:     return ($symb);
14428: }
14429: 
14430: # --------------------------------------------------------------Get annotation
14431: 
14432: sub get_annotation {
14433:     my ($symb,$enc) = @_;
14434: 
14435:     my $key = $symb;
14436:     if (!$enc) {
14437:         $key =
14438:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14439:     }
14440:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14441:     return $annotation{$key};
14442: }
14443: 
14444: sub clean_symb {
14445:     my ($symb,$delete_enc) = @_;
14446: 
14447:     &Apache::lonenc::check_decrypt(\$symb);
14448:     my $enc = $env{'request.enc'};
14449:     if ($delete_enc) {
14450:         delete($env{'request.enc'});
14451:     }
14452: 
14453:     return ($symb,$enc);
14454: }
14455: 
14456: sub build_release_hashes {
14457:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14458:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14459:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14460:                   (ref($randomizetry) eq 'HASH'));
14461:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14462:         my ($item,$name,$value) = split(/:/,$key);
14463:         if ($item eq 'parameter') {
14464:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14465:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14466:                     push(@{$checkparms->{$name}},$value);
14467:                 }
14468:             } else {
14469:                 push(@{$checkparms->{$name}},$value);
14470:             }
14471:         } elsif ($item eq 'resourcetag') {
14472:             if ($name eq 'responsetype') {
14473:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14474:             }
14475:         } elsif ($item eq 'course') {
14476:             if ($name eq 'crstype') {
14477:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14478:             }
14479:         }
14480:     }
14481:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14482:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14483:     return;
14484: }
14485: 
14486: sub update_content_constraints {
14487:     my ($cdom,$cnum,$chome,$cid) = @_;
14488:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14489:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14490:     my %checkresponsetypes;
14491:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14492:         my ($item,$name,$value) = split(/:/,$key);
14493:         if ($item eq 'resourcetag') {
14494:             if ($name eq 'responsetype') {
14495:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14496:             }
14497:         }
14498:     }
14499:     my $navmap = Apache::lonnavmaps::navmap->new();
14500:     if (defined($navmap)) {
14501:         my %allresponses;
14502:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14503:             my %responses = $res->responseTypes();
14504:             foreach my $key (keys(%responses)) {
14505:                 next unless(exists($checkresponsetypes{$key}));
14506:                 $allresponses{$key} += $responses{$key};
14507:             }
14508:         }
14509:         foreach my $key (keys(%allresponses)) {
14510:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14511:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14512:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14513:             }
14514:         }
14515:         undef($navmap);
14516:     }
14517:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14518:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14519:     }
14520:     return;
14521: }
14522: 
14523: sub allmaps_incourse {
14524:     my ($cdom,$cnum,$chome,$cid) = @_;
14525:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14526:         $cid = $env{'request.course.id'};
14527:         $cdom = $env{'course.'.$cid.'.domain'};
14528:         $cnum = $env{'course.'.$cid.'.num'};
14529:         $chome = $env{'course.'.$cid.'.home'};
14530:     }
14531:     my %allmaps = ();
14532:     my $lastchange =
14533:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14534:     if ($lastchange > $env{'request.course.tied'}) {
14535:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14536:         unless ($ferr) {
14537:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14538:         }
14539:     }
14540:     my $navmap = Apache::lonnavmaps::navmap->new();
14541:     if (defined($navmap)) {
14542:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14543:             $allmaps{$res->src()} = 1;
14544:         }
14545:     }
14546:     return \%allmaps;
14547: }
14548: 
14549: sub parse_supplemental_title {
14550:     my ($title) = @_;
14551: 
14552:     my ($foldertitle,$renametitle);
14553:     if ($title =~ /&amp;&amp;&amp;/) {
14554:         $title = &HTML::Entites::decode($title);
14555:     }
14556:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14557:         $renametitle=$4;
14558:         my ($time,$uname,$udom) = ($1,$2,$3);
14559:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14560:         my $name =  &plainname($uname,$udom);
14561:         $name = &HTML::Entities::encode($name,'"<>&\'');
14562:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14563:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14564:             $name.': <br />'.$foldertitle;
14565:     }
14566:     if (wantarray) {
14567:         return ($title,$foldertitle,$renametitle);
14568:     }
14569:     return $title;
14570: }
14571: 
14572: sub recurse_supplemental {
14573:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14574:     if ($suppmap) {
14575:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14576:         if ($fatal) {
14577:             $errors ++;
14578:         } else {
14579:             if ($#LONCAPA::map::resources > 0) {
14580:                 foreach my $res (@LONCAPA::map::resources) {
14581:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14582:                     if (($src ne '') && ($status eq 'res')) {
14583:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_/d+\.sequence)$}) {
14584:                             $numfiles = &recurse_supplemental($cnum,$cdom,$1,$numfiles);
14585:                         } else {
14586:                             $numfiles ++;
14587:                         }
14588:                     }
14589:                 }
14590:             }
14591:         }
14592:     }
14593:     return ($numfiles,$errors);
14594: }
14595: 
14596: sub symb_to_docspath {
14597:     my ($symb) = @_;
14598:     return unless ($symb);
14599:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14600:     if ($resurl=~/\.(sequence|page)$/) {
14601:         $mapurl=$resurl;
14602:     } elsif ($resurl eq 'adm/navmaps') {
14603:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14604:     }
14605:     my $mapresobj;
14606:     my $navmap = Apache::lonnavmaps::navmap->new();
14607:     if (ref($navmap)) {
14608:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14609:     }
14610:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14611:     my $type=$2;
14612:     my $path;
14613:     if (ref($mapresobj)) {
14614:         my $pcslist = $mapresobj->map_hierarchy();
14615:         if ($pcslist ne '') {
14616:             foreach my $pc (split(/,/,$pcslist)) {
14617:                 next if ($pc <= 1);
14618:                 my $res = $navmap->getByMapPc($pc);
14619:                 if (ref($res)) {
14620:                     my $thisurl = $res->src();
14621:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14622:                     my $thistitle = $res->title();
14623:                     $path .= '&'.
14624:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14625:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
14626:                              ':'.$res->randompick().
14627:                              ':'.$res->randomout().
14628:                              ':'.$res->encrypted().
14629:                              ':'.$res->randomorder().
14630:                              ':'.$res->is_page();
14631:                 }
14632:             }
14633:         }
14634:         $path =~ s/^\&//;
14635:         my $maptitle = $mapresobj->title();
14636:         if ($mapurl eq 'default') {
14637:             $maptitle = 'Main Content';
14638:         }
14639:         $path .= (($path ne '')? '&' : '').
14640:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14641:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
14642:                  ':'.$mapresobj->randompick().
14643:                  ':'.$mapresobj->randomout().
14644:                  ':'.$mapresobj->encrypted().
14645:                  ':'.$mapresobj->randomorder().
14646:                  ':'.$mapresobj->is_page();
14647:     } else {
14648:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14649:         my $ispage = (($type eq 'page')? 1 : '');
14650:         if ($mapurl eq 'default') {
14651:             $maptitle = 'Main Content';
14652:         }
14653:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14654:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14655:     }
14656:     unless ($mapurl eq 'default') {
14657:         $path = 'default&'.
14658:                 &Apache::lonhtmlcommon::entity_encode('Main Content').
14659:                 ':::::&'.$path;
14660:     }
14661:     return $path;
14662: }
14663: 
14664: sub captcha_display {
14665:     my ($context,$lonhost) = @_;
14666:     my ($output,$error);
14667:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14668:     if ($captcha eq 'original') {
14669:         $output = &create_captcha();
14670:         unless ($output) {
14671:             $error = 'captcha';
14672:         }
14673:     } elsif ($captcha eq 'recaptcha') {
14674:         $output = &create_recaptcha($pubkey);
14675:         unless ($output) {
14676:             $error = 'recaptcha';
14677:         }
14678:     }
14679:     return ($output,$error);
14680: }
14681: 
14682: sub captcha_response {
14683:     my ($context,$lonhost) = @_;
14684:     my ($captcha_chk,$captcha_error);
14685:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14686:     if ($captcha eq 'original') {
14687:         ($captcha_chk,$captcha_error) = &check_captcha();
14688:     } elsif ($captcha eq 'recaptcha') {
14689:         $captcha_chk = &check_recaptcha($privkey);
14690:     } else {
14691:         $captcha_chk = 1;
14692:     }
14693:     return ($captcha_chk,$captcha_error);
14694: }
14695: 
14696: sub get_captcha_config {
14697:     my ($context,$lonhost) = @_;
14698:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14699:     my $hostname = &Apache::lonnet::hostname($lonhost);
14700:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14701:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14702:     if ($context eq 'usercreation') {
14703:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14704:         if (ref($domconfig{$context}) eq 'HASH') {
14705:             $hashtocheck = $domconfig{$context}{'cancreate'};
14706:             if (ref($hashtocheck) eq 'HASH') {
14707:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14708:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14709:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14710:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14711:                     }
14712:                     if ($privkey && $pubkey) {
14713:                         $captcha = 'recaptcha';
14714:                     } else {
14715:                         $captcha = 'original';
14716:                     }
14717:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14718:                     $captcha = 'original';
14719:                 }
14720:             }
14721:         } else {
14722:             $captcha = 'captcha';
14723:         }
14724:     } elsif ($context eq 'login') {
14725:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14726:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14727:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14728:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14729:             if ($privkey && $pubkey) {
14730:                 $captcha = 'recaptcha';
14731:             } else {
14732:                 $captcha = 'original';
14733:             }
14734:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14735:             $captcha = 'original';
14736:         }
14737:     }
14738:     return ($captcha,$pubkey,$privkey);
14739: }
14740: 
14741: sub create_captcha {
14742:     my %captcha_params = &captcha_settings();
14743:     my ($output,$maxtries,$tries) = ('',10,0);
14744:     while ($tries < $maxtries) {
14745:         $tries ++;
14746:         my $captcha = Authen::Captcha->new (
14747:                                            output_folder => $captcha_params{'output_dir'},
14748:                                            data_folder   => $captcha_params{'db_dir'},
14749:                                           );
14750:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14751: 
14752:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14753:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14754:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14755:                      '<input type="text" size="5" name="code" value="" /><br />'.
14756:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14757:             last;
14758:         }
14759:     }
14760:     return $output;
14761: }
14762: 
14763: sub captcha_settings {
14764:     my %captcha_params = (
14765:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14766:                            www_output_dir => "/captchaspool",
14767:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14768:                            numchars       => '5',
14769:                          );
14770:     return %captcha_params;
14771: }
14772: 
14773: sub check_captcha {
14774:     my ($captcha_chk,$captcha_error);
14775:     my $code = $env{'form.code'};
14776:     my $md5sum = $env{'form.crypt'};
14777:     my %captcha_params = &captcha_settings();
14778:     my $captcha = Authen::Captcha->new(
14779:                       output_folder => $captcha_params{'output_dir'},
14780:                       data_folder   => $captcha_params{'db_dir'},
14781:                   );
14782:     $captcha_chk = $captcha->check_code($code,$md5sum);
14783:     my %captcha_hash = (
14784:                         0       => 'Code not checked (file error)',
14785:                        -1      => 'Failed: code expired',
14786:                        -2      => 'Failed: invalid code (not in database)',
14787:                        -3      => 'Failed: invalid code (code does not match crypt)',
14788:     );
14789:     if ($captcha_chk != 1) {
14790:         $captcha_error = $captcha_hash{$captcha_chk}
14791:     }
14792:     return ($captcha_chk,$captcha_error);
14793: }
14794: 
14795: sub create_recaptcha {
14796:     my ($pubkey) = @_;
14797:     my $captcha = Captcha::reCAPTCHA->new;
14798:     return $captcha->get_options_setter({theme => 'white'})."\n".
14799:            $captcha->get_html($pubkey).
14800:            &mt('If either word is hard to read, [_1] will replace them.',
14801:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14802:            '<br /><br />';
14803: }
14804: 
14805: sub check_recaptcha {
14806:     my ($privkey) = @_;
14807:     my $captcha_chk;
14808:     my $captcha = Captcha::reCAPTCHA->new;
14809:     my $captcha_result =
14810:         $captcha->check_answer(
14811:                                 $privkey,
14812:                                 $ENV{'REMOTE_ADDR'},
14813:                                 $env{'form.recaptcha_challenge_field'},
14814:                                 $env{'form.recaptcha_response_field'},
14815:                               );
14816:     if ($captcha_result->{is_valid}) {
14817:         $captcha_chk = 1;
14818:     }
14819:     return $captcha_chk;
14820: }
14821: 
14822: =pod
14823: 
14824: =back
14825: 
14826: =cut
14827: 
14828: 1;
14829: __END__;
14830: 

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