File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.50: download - view: text, annotated - select for diffs
Sun Sep 1 02:34:28 2013 UTC (10 years, 8 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_0_RC1
- For 2.11
  - Reverting to non-modal window for pop-up (unless browsing from a mobile
    device). Modal windows make it difficult to view documentation while
    simultaneously viewing the interface for which the help is provided.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.50 2013/09/01 02:34:28 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:         if ($env{'browser.mobile'}) {
 1238: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1239:         } else {
 1240:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1241:         }
 1242:     } elsif ($stayOnPage eq 'popup') {
 1243:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1244:     } else {
 1245: 	$link = "/adm/help/${filename}.hlp";
 1246:     }
 1247: 
 1248:     # Add the text
 1249:     if ($text ne "") {	
 1250: 	$template.='<span class="LC_help_open_topic">'
 1251:                   .'<a target="_top" href="'.$link.'">'
 1252:                   .$text.'</a>';
 1253:     }
 1254: 
 1255:     # (Always) Add the graphic
 1256:     my $title = &mt('Online Help');
 1257:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1258:     if ($imgid ne '') {
 1259:         $imgid = ' id="'.$imgid.'"';
 1260:     }
 1261:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1262:               .'<img src="'.$helpicon.'" border="0"'
 1263:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1264:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1265:               .' /></a>';
 1266:     if ($text ne "") {	
 1267:         $template.='</span>';
 1268:     }
 1269:     return $template;
 1270: 
 1271: }
 1272: 
 1273: # This is a quicky function for Latex cheatsheet editing, since it 
 1274: # appears in at least four places
 1275: sub helpLatexCheatsheet {
 1276:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1277:     my $out;
 1278:     my $addOther = '';
 1279:     if ($topic) {
 1280: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1281:     }
 1282:     $out = '<span>' # Start cheatsheet
 1283: 	  .$addOther
 1284:           .'<span>'
 1285: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1286: 	  .'</span> <span>'
 1287: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1288: 	  .'</span>';
 1289:     unless ($not_author) {
 1290:         $out .= ' <span>'
 1291: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1292: 	       .'</span>';
 1293:     }
 1294:     $out .= '</span>'; # End cheatsheet
 1295:     return $out;
 1296: }
 1297: 
 1298: sub general_help {
 1299:     my $helptopic='Student_Intro';
 1300:     if ($env{'request.role'}=~/^(ca|au)/) {
 1301: 	$helptopic='Authoring_Intro';
 1302:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1303: 	$helptopic='Course_Coordination_Intro';
 1304:     } elsif ($env{'request.role'}=~/^dc/) {
 1305:         $helptopic='Domain_Coordination_Intro';
 1306:     }
 1307:     return $helptopic;
 1308: }
 1309: 
 1310: sub update_help_link {
 1311:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1312:     my $origurl = $ENV{'REQUEST_URI'};
 1313:     $origurl=~s|^/~|/priv/|;
 1314:     my $timestamp = time;
 1315:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1316:         $$datum = &escape($$datum);
 1317:     }
 1318: 
 1319:     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";
 1320:     my $output .= <<"ENDOUTPUT";
 1321: <script type="text/javascript">
 1322: // <![CDATA[
 1323: banner_link = '$banner_link';
 1324: // ]]>
 1325: </script>
 1326: ENDOUTPUT
 1327:     return $output;
 1328: }
 1329: 
 1330: # now just updates the help link and generates a blue icon
 1331: sub help_open_menu {
 1332:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1333: 	= @_;    
 1334:     $stayOnPage = 1;
 1335:     my $output;
 1336:     if ($component_help) {
 1337: 	if (!$text) {
 1338: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1339: 				       $width,$height);
 1340: 	} else {
 1341: 	    my $help_text;
 1342: 	    $help_text=&unescape($topic);
 1343: 	    $output='<table><tr><td>'.
 1344: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1345: 				 $width,$height).'</td></tr></table>';
 1346: 	}
 1347:     }
 1348:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1349:     return $output.$banner_link;
 1350: }
 1351: 
 1352: sub top_nav_help {
 1353:     my ($text) = @_;
 1354:     $text = &mt($text);
 1355:     my $stay_on_page = 1;
 1356: 
 1357:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1358: 	                     : "javascript:helpMenu('open')";
 1359:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1360: 
 1361:     my $title = &mt('Get help');
 1362: 
 1363:     return <<"END";
 1364: $banner_link
 1365:  <a href="$link" title="$title">$text</a>
 1366: END
 1367: }
 1368: 
 1369: sub help_menu_js {
 1370:     my ($text) = @_;
 1371:     my $stayOnPage = 1;
 1372:     my $width = 620;
 1373:     my $height = 600;
 1374:     my $helptopic=&general_help();
 1375:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1376:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1377:     my $start_page =
 1378:         &Apache::loncommon::start_page('Help Menu', undef,
 1379: 				       {'frameset'    => 1,
 1380: 					'js_ready'    => 1,
 1381: 					'add_entries' => {
 1382: 					    'border' => '0',
 1383: 					    'rows'   => "110,*",},});
 1384:     my $end_page =
 1385:         &Apache::loncommon::end_page({'frameset' => 1,
 1386: 				      'js_ready' => 1,});
 1387: 
 1388:     my $template .= <<"ENDTEMPLATE";
 1389: <script type="text/javascript">
 1390: // <![CDATA[
 1391: // <!-- BEGIN LON-CAPA Internal
 1392: var banner_link = '';
 1393: function helpMenu(target) {
 1394:     var caller = this;
 1395:     if (target == 'open') {
 1396:         var newWindow = null;
 1397:         try {
 1398:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1399:         }
 1400:         catch(error) {
 1401:             writeHelp(caller);
 1402:             return;
 1403:         }
 1404:         if (newWindow) {
 1405:             caller = newWindow;
 1406:         }
 1407:     }
 1408:     writeHelp(caller);
 1409:     return;
 1410: }
 1411: function writeHelp(caller) {
 1412:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1413:     caller.document.close()
 1414:     caller.focus()
 1415: }
 1416: // END LON-CAPA Internal -->
 1417: // ]]>
 1418: </script>
 1419: ENDTEMPLATE
 1420:     return $template;
 1421: }
 1422: 
 1423: sub help_open_bug {
 1424:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1425:     unless ($env{'user.adv'}) { return ''; }
 1426:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1427:     $text = "" if (not defined $text);
 1428: 	$stayOnPage=1;
 1429:     $width = 600 if (not defined $width);
 1430:     $height = 600 if (not defined $height);
 1431: 
 1432:     $topic=~s/\W+/\+/g;
 1433:     my $link='';
 1434:     my $template='';
 1435:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1436: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1437:     if (!$stayOnPage)
 1438:     {
 1439: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1440:     }
 1441:     else
 1442:     {
 1443: 	$link = $url;
 1444:     }
 1445:     # Add the text
 1446:     if ($text ne "")
 1447:     {
 1448: 	$template .= 
 1449:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1450:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1451:     }
 1452: 
 1453:     # Add the graphic
 1454:     my $title = &mt('Report a Bug');
 1455:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1456:     $template .= <<"ENDTEMPLATE";
 1457:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1458: ENDTEMPLATE
 1459:     if ($text ne '') { $template.='</td></tr></table>' };
 1460:     return $template;
 1461: 
 1462: }
 1463: 
 1464: sub help_open_faq {
 1465:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1466:     unless ($env{'user.adv'}) { return ''; }
 1467:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1468:     $text = "" if (not defined $text);
 1469: 	$stayOnPage=1;
 1470:     $width = 350 if (not defined $width);
 1471:     $height = 400 if (not defined $height);
 1472: 
 1473:     $topic=~s/\W+/\+/g;
 1474:     my $link='';
 1475:     my $template='';
 1476:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1477:     if (!$stayOnPage)
 1478:     {
 1479: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1480:     }
 1481:     else
 1482:     {
 1483: 	$link = $url;
 1484:     }
 1485: 
 1486:     # Add the text
 1487:     if ($text ne "")
 1488:     {
 1489: 	$template .= 
 1490:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1491:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1492:     }
 1493: 
 1494:     # Add the graphic
 1495:     my $title = &mt('View the FAQ');
 1496:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1497:     $template .= <<"ENDTEMPLATE";
 1498:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1499: ENDTEMPLATE
 1500:     if ($text ne '') { $template.='</td></tr></table>' };
 1501:     return $template;
 1502: 
 1503: }
 1504: 
 1505: ###############################################################
 1506: ###############################################################
 1507: 
 1508: =pod
 1509: 
 1510: =item * &change_content_javascript():
 1511: 
 1512: This and the next function allow you to create small sections of an
 1513: otherwise static HTML page that you can update on the fly with
 1514: Javascript, even in Netscape 4.
 1515: 
 1516: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1517: must be written to the HTML page once. It will prove the Javascript
 1518: function "change(name, content)". Calling the change function with the
 1519: name of the section 
 1520: you want to update, matching the name passed to C<changable_area>, and
 1521: the new content you want to put in there, will put the content into
 1522: that area.
 1523: 
 1524: B<Note>: Netscape 4 only reserves enough space for the changable area
 1525: to contain room for the original contents. You need to "make space"
 1526: for whatever changes you wish to make, and be B<sure> to check your
 1527: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1528: it's adequate for updating a one-line status display, but little more.
 1529: This script will set the space to 100% width, so you only need to
 1530: worry about height in Netscape 4.
 1531: 
 1532: Modern browsers are much less limiting, and if you can commit to the
 1533: user not using Netscape 4, this feature may be used freely with
 1534: pretty much any HTML.
 1535: 
 1536: =cut
 1537: 
 1538: sub change_content_javascript {
 1539:     # If we're on Netscape 4, we need to use Layer-based code
 1540:     if ($env{'browser.type'} eq 'netscape' &&
 1541: 	$env{'browser.version'} =~ /^4\./) {
 1542: 	return (<<NETSCAPE4);
 1543: 	function change(name, content) {
 1544: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1545: 	    doc.open();
 1546: 	    doc.write(content);
 1547: 	    doc.close();
 1548: 	}
 1549: NETSCAPE4
 1550:     } else {
 1551: 	# Otherwise, we need to use semi-standards-compliant code
 1552: 	# (technically, "innerHTML" isn't standard but the equivalent
 1553: 	# is really scary, and every useful browser supports it
 1554: 	return (<<DOMBASED);
 1555: 	function change(name, content) {
 1556: 	    element = document.getElementById(name);
 1557: 	    element.innerHTML = content;
 1558: 	}
 1559: DOMBASED
 1560:     }
 1561: }
 1562: 
 1563: =pod
 1564: 
 1565: =item * &changable_area($name,$origContent):
 1566: 
 1567: This provides a "changable area" that can be modified on the fly via
 1568: the Javascript code provided in C<change_content_javascript>. $name is
 1569: the name you will use to reference the area later; do not repeat the
 1570: same name on a given HTML page more then once. $origContent is what
 1571: the area will originally contain, which can be left blank.
 1572: 
 1573: =cut
 1574: 
 1575: sub changable_area {
 1576:     my ($name, $origContent) = @_;
 1577: 
 1578:     if ($env{'browser.type'} eq 'netscape' &&
 1579: 	$env{'browser.version'} =~ /^4\./) {
 1580: 	# If this is netscape 4, we need to use the Layer tag
 1581: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1582:     } else {
 1583: 	return "<span id='$name'>$origContent</span>";
 1584:     }
 1585: }
 1586: 
 1587: =pod
 1588: 
 1589: =item * &viewport_geometry_js 
 1590: 
 1591: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1592: 
 1593: =cut
 1594: 
 1595: 
 1596: sub viewport_geometry_js { 
 1597:     return <<"GEOMETRY";
 1598: var Geometry = {};
 1599: function init_geometry() {
 1600:     if (Geometry.init) { return };
 1601:     Geometry.init=1;
 1602:     if (window.innerHeight) {
 1603:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1604:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1605:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1606:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1607:     }
 1608:     else if (document.documentElement && document.documentElement.clientHeight) {
 1609:         Geometry.getViewportHeight =
 1610:             function() { return document.documentElement.clientHeight; };
 1611:         Geometry.getViewportWidth =
 1612:             function() { return document.documentElement.clientWidth; };
 1613: 
 1614:         Geometry.getHorizontalScroll =
 1615:             function() { return document.documentElement.scrollLeft; };
 1616:         Geometry.getVerticalScroll =
 1617:             function() { return document.documentElement.scrollTop; };
 1618:     }
 1619:     else if (document.body.clientHeight) {
 1620:         Geometry.getViewportHeight =
 1621:             function() { return document.body.clientHeight; };
 1622:         Geometry.getViewportWidth =
 1623:             function() { return document.body.clientWidth; };
 1624:         Geometry.getHorizontalScroll =
 1625:             function() { return document.body.scrollLeft; };
 1626:         Geometry.getVerticalScroll =
 1627:             function() { return document.body.scrollTop; };
 1628:     }
 1629: }
 1630: 
 1631: GEOMETRY
 1632: }
 1633: 
 1634: =pod
 1635: 
 1636: =item * &viewport_size_js()
 1637: 
 1638: 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. 
 1639: 
 1640: =cut
 1641: 
 1642: sub viewport_size_js {
 1643:     my $geometry = &viewport_geometry_js();
 1644:     return <<"DIMS";
 1645: 
 1646: $geometry
 1647: 
 1648: function getViewportDims(width,height) {
 1649:     init_geometry();
 1650:     width.value = Geometry.getViewportWidth();
 1651:     height.value = Geometry.getViewportHeight();
 1652:     return;
 1653: }
 1654: 
 1655: DIMS
 1656: }
 1657: 
 1658: =pod
 1659: 
 1660: =item * &resize_textarea_js()
 1661: 
 1662: emits the needed javascript to resize a textarea to be as big as possible
 1663: 
 1664: creates a function resize_textrea that takes two IDs first should be
 1665: the id of the element to resize, second should be the id of a div that
 1666: surrounds everything that comes after the textarea, this routine needs
 1667: to be attached to the <body> for the onload and onresize events.
 1668: 
 1669: =back
 1670: 
 1671: =cut
 1672: 
 1673: sub resize_textarea_js {
 1674:     my $geometry = &viewport_geometry_js();
 1675:     return <<"RESIZE";
 1676:     <script type="text/javascript">
 1677: // <![CDATA[
 1678: $geometry
 1679: 
 1680: function getX(element) {
 1681:     var x = 0;
 1682:     while (element) {
 1683: 	x += element.offsetLeft;
 1684: 	element = element.offsetParent;
 1685:     }
 1686:     return x;
 1687: }
 1688: function getY(element) {
 1689:     var y = 0;
 1690:     while (element) {
 1691: 	y += element.offsetTop;
 1692: 	element = element.offsetParent;
 1693:     }
 1694:     return y;
 1695: }
 1696: 
 1697: 
 1698: function resize_textarea(textarea_id,bottom_id) {
 1699:     init_geometry();
 1700:     var textarea        = document.getElementById(textarea_id);
 1701:     //alert(textarea);
 1702: 
 1703:     var textarea_top    = getY(textarea);
 1704:     var textarea_height = textarea.offsetHeight;
 1705:     var bottom          = document.getElementById(bottom_id);
 1706:     var bottom_top      = getY(bottom);
 1707:     var bottom_height   = bottom.offsetHeight;
 1708:     var window_height   = Geometry.getViewportHeight();
 1709:     var fudge           = 23;
 1710:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1711:     if (new_height < 300) {
 1712: 	new_height = 300;
 1713:     }
 1714:     textarea.style.height=new_height+'px';
 1715: }
 1716: // ]]>
 1717: </script>
 1718: RESIZE
 1719: 
 1720: }
 1721: 
 1722: =pod
 1723: 
 1724: =head1 Excel and CSV file utility routines
 1725: 
 1726: =over 4
 1727: 
 1728: =cut
 1729: 
 1730: ###############################################################
 1731: ###############################################################
 1732: 
 1733: =pod
 1734: 
 1735: =item * &csv_translate($text) 
 1736: 
 1737: Translate $text to allow it to be output as a 'comma separated values' 
 1738: format.
 1739: 
 1740: =cut
 1741: 
 1742: ###############################################################
 1743: ###############################################################
 1744: sub csv_translate {
 1745:     my $text = shift;
 1746:     $text =~ s/\"/\"\"/g;
 1747:     $text =~ s/\n/ /g;
 1748:     return $text;
 1749: }
 1750: 
 1751: ###############################################################
 1752: ###############################################################
 1753: 
 1754: =pod
 1755: 
 1756: =item * &define_excel_formats()
 1757: 
 1758: Define some commonly used Excel cell formats.
 1759: 
 1760: Currently supported formats:
 1761: 
 1762: =over 4
 1763: 
 1764: =item header
 1765: 
 1766: =item bold
 1767: 
 1768: =item h1
 1769: 
 1770: =item h2
 1771: 
 1772: =item h3
 1773: 
 1774: =item h4
 1775: 
 1776: =item i
 1777: 
 1778: =item date
 1779: 
 1780: =back
 1781: 
 1782: Inputs: $workbook
 1783: 
 1784: Returns: $format, a hash reference.
 1785: 
 1786: 
 1787: =cut
 1788: 
 1789: ###############################################################
 1790: ###############################################################
 1791: sub define_excel_formats {
 1792:     my ($workbook) = @_;
 1793:     my $format;
 1794:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1795:                                                 bottom    => 1,
 1796:                                                 align     => 'center');
 1797:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1798:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1799:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1800:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1801:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1802:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1803:     $format->{'date'} = $workbook->add_format(num_format=>
 1804:                                             'mm/dd/yyyy hh:mm:ss');
 1805:     return $format;
 1806: }
 1807: 
 1808: ###############################################################
 1809: ###############################################################
 1810: 
 1811: =pod
 1812: 
 1813: =item * &create_workbook()
 1814: 
 1815: Create an Excel worksheet.  If it fails, output message on the
 1816: request object and return undefs.
 1817: 
 1818: Inputs: Apache request object
 1819: 
 1820: Returns (undef) on failure, 
 1821:     Excel worksheet object, scalar with filename, and formats 
 1822:     from &Apache::loncommon::define_excel_formats on success
 1823: 
 1824: =cut
 1825: 
 1826: ###############################################################
 1827: ###############################################################
 1828: sub create_workbook {
 1829:     my ($r) = @_;
 1830:         #
 1831:     # Create the excel spreadsheet
 1832:     my $filename = '/prtspool/'.
 1833:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1834:         time.'_'.rand(1000000000).'.xls';
 1835:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1836:     if (! defined($workbook)) {
 1837:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1838:         $r->print(
 1839:             '<p class="LC_error">'
 1840:            .&mt('Problems occurred in creating the new Excel file.')
 1841:            .' '.&mt('This error has been logged.')
 1842:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1843:            .'</p>'
 1844:         );
 1845:         return (undef);
 1846:     }
 1847:     #
 1848:     $workbook->set_tempdir(LONCAPA::tempdir());
 1849:     #
 1850:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1851:     return ($workbook,$filename,$format);
 1852: }
 1853: 
 1854: ###############################################################
 1855: ###############################################################
 1856: 
 1857: =pod
 1858: 
 1859: =item * &create_text_file()
 1860: 
 1861: Create a file to write to and eventually make available to the user.
 1862: If file creation fails, outputs an error message on the request object and 
 1863: return undefs.
 1864: 
 1865: Inputs: Apache request object, and file suffix
 1866: 
 1867: Returns (undef) on failure, 
 1868:     Filehandle and filename on success.
 1869: 
 1870: =cut
 1871: 
 1872: ###############################################################
 1873: ###############################################################
 1874: sub create_text_file {
 1875:     my ($r,$suffix) = @_;
 1876:     if (! defined($suffix)) { $suffix = 'txt'; };
 1877:     my $fh;
 1878:     my $filename = '/prtspool/'.
 1879:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1880:         time.'_'.rand(1000000000).'.'.$suffix;
 1881:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1882:     if (! defined($fh)) {
 1883:         $r->log_error("Couldn't open $filename for output $!");
 1884:         $r->print(
 1885:             '<p class="LC_error">'
 1886:            .&mt('Problems occurred in creating the output file.')
 1887:            .' '.&mt('This error has been logged.')
 1888:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1889:            .'</p>'
 1890:         );
 1891:     }
 1892:     return ($fh,$filename)
 1893: }
 1894: 
 1895: 
 1896: =pod 
 1897: 
 1898: =back
 1899: 
 1900: =cut
 1901: 
 1902: ###############################################################
 1903: ##        Home server <option> list generating code          ##
 1904: ###############################################################
 1905: 
 1906: # ------------------------------------------
 1907: 
 1908: sub domain_select {
 1909:     my ($name,$value,$multiple)=@_;
 1910:     my %domains=map { 
 1911: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1912:     } &Apache::lonnet::all_domains();
 1913:     if ($multiple) {
 1914: 	$domains{''}=&mt('Any domain');
 1915: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1916: 	return &multiple_select_form($name,$value,4,\%domains);
 1917:     } else {
 1918: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1919: 	return &select_form($name,$value,\%domains);
 1920:     }
 1921: }
 1922: 
 1923: #-------------------------------------------
 1924: 
 1925: =pod
 1926: 
 1927: =head1 Routines for form select boxes
 1928: 
 1929: =over 4
 1930: 
 1931: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1932: 
 1933: Returns a string containing a <select> element int multiple mode
 1934: 
 1935: 
 1936: Args:
 1937:   $name - name of the <select> element
 1938:   $value - scalar or array ref of values that should already be selected
 1939:   $size - number of rows long the select element is
 1940:   $hash - the elements should be 'option' => 'shown text'
 1941:           (shown text should already have been &mt())
 1942:   $order - (optional) array ref of the order to show the elements in
 1943: 
 1944: =cut
 1945: 
 1946: #-------------------------------------------
 1947: sub multiple_select_form {
 1948:     my ($name,$value,$size,$hash,$order)=@_;
 1949:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1950:     my $output='';
 1951:     if (! defined($size)) {
 1952:         $size = 4;
 1953:         if (scalar(keys(%$hash))<4) {
 1954:             $size = scalar(keys(%$hash));
 1955:         }
 1956:     }
 1957:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1958:     my @order;
 1959:     if (ref($order) eq 'ARRAY')  {
 1960:         @order = @{$order};
 1961:     } else {
 1962:         @order = sort(keys(%$hash));
 1963:     }
 1964:     if (exists($$hash{'select_form_order'})) {
 1965:         @order = @{$$hash{'select_form_order'}};
 1966:     }
 1967:         
 1968:     foreach my $key (@order) {
 1969:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1970:         $output.='selected="selected" ' if ($selected{$key});
 1971:         $output.='>'.$hash->{$key}."</option>\n";
 1972:     }
 1973:     $output.="</select>\n";
 1974:     return $output;
 1975: }
 1976: 
 1977: #-------------------------------------------
 1978: 
 1979: =pod
 1980: 
 1981: =item * &select_form($defdom,$name,$hashref,$onchange)
 1982: 
 1983: Returns a string containing a <select name='$name' size='1'> form to 
 1984: allow a user to select options from a ref to a hash containing:
 1985: option_name => displayed text. An optional $onchange can include
 1986: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1987: 
 1988: See lonrights.pm for an example invocation and use.
 1989: 
 1990: =cut
 1991: 
 1992: #-------------------------------------------
 1993: sub select_form {
 1994:     my ($def,$name,$hashref,$onchange) = @_;
 1995:     return unless (ref($hashref) eq 'HASH');
 1996:     if ($onchange) {
 1997:         $onchange = ' onchange="'.$onchange.'"';
 1998:     }
 1999:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2000:     my @keys;
 2001:     if (exists($hashref->{'select_form_order'})) {
 2002: 	@keys=@{$hashref->{'select_form_order'}};
 2003:     } else {
 2004: 	@keys=sort(keys(%{$hashref}));
 2005:     }
 2006:     foreach my $key (@keys) {
 2007:         $selectform.=
 2008: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2009:             ($key eq $def ? 'selected="selected" ' : '').
 2010:                 ">".$hashref->{$key}."</option>\n";
 2011:     }
 2012:     $selectform.="</select>";
 2013:     return $selectform;
 2014: }
 2015: 
 2016: # For display filters
 2017: 
 2018: sub display_filter {
 2019:     my ($context) = @_;
 2020:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2021:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2022:     my $phraseinput = 'hidden';
 2023:     my $includeinput = 'hidden';
 2024:     my ($checked,$includetypestext);
 2025:     if ($env{'form.displayfilter'} eq 'containing') {
 2026:         $phraseinput = 'text'; 
 2027:         if ($context eq 'parmslog') {
 2028:             $includeinput = 'checkbox';
 2029:             if ($env{'form.includetypes'}) {
 2030:                 $checked = ' checked="checked"';
 2031:             }
 2032:             $includetypestext = &mt('Include parameter types');
 2033:         }
 2034:     } else {
 2035:         $includetypestext = '&nbsp;';
 2036:     }
 2037:     my ($additional,$secondid,$thirdid);
 2038:     if ($context eq 'parmslog') {
 2039:         $additional = 
 2040:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2041:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2042:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2043:             '</label>';
 2044:         $secondid = 'includetypes';
 2045:         $thirdid = 'includetypestext';
 2046:     }
 2047:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2048:                                                     '$secondid','$thirdid')";
 2049:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2050: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2051: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2052: 	   '</label></span> <span class="LC_nobreak">'.
 2053:            &mt('Filter: [_1]',
 2054: 	   &select_form($env{'form.displayfilter'},
 2055: 			'displayfilter',
 2056: 			{'currentfolder' => 'Current folder/page',
 2057: 			 'containing' => 'Containing phrase',
 2058: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2059: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2060:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2061:                          '" />'.$additional;
 2062: }
 2063: 
 2064: sub display_filter_js {
 2065:     my $includetext = &mt('Include parameter types');
 2066:     return <<"ENDJS";
 2067:   
 2068: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2069:     var firstType = 'hidden';
 2070:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2071:         firstType = 'text';
 2072:     }
 2073:     firstObject = document.getElementById(firstid);
 2074:     if (typeof(firstObject) == 'object') {
 2075:         if (firstObject.type != firstType) {
 2076:             changeInputType(firstObject,firstType);
 2077:         }
 2078:     }
 2079:     if (context == 'parmslog') {
 2080:         var secondType = 'hidden';
 2081:         if (firstType == 'text') {
 2082:             secondType = 'checkbox';
 2083:         }
 2084:         secondObject = document.getElementById(secondid);  
 2085:         if (typeof(secondObject) == 'object') {
 2086:             if (secondObject.type != secondType) {
 2087:                 changeInputType(secondObject,secondType);
 2088:             }
 2089:         }
 2090:         var textItem = document.getElementById(thirdid);
 2091:         var currtext = textItem.innerHTML;
 2092:         var newtext;
 2093:         if (firstType == 'text') {
 2094:             newtext = '$includetext';
 2095:         } else {
 2096:             newtext = '&nbsp;';
 2097:         }
 2098:         if (currtext != newtext) {
 2099:             textItem.innerHTML = newtext;
 2100:         }
 2101:     }
 2102:     return;
 2103: }
 2104: 
 2105: function changeInputType(oldObject,newType) {
 2106:     var newObject = document.createElement('input');
 2107:     newObject.type = newType;
 2108:     if (oldObject.size) {
 2109:         newObject.size = oldObject.size;
 2110:     }
 2111:     if (oldObject.value) {
 2112:         newObject.value = oldObject.value;
 2113:     }
 2114:     if (oldObject.name) {
 2115:         newObject.name = oldObject.name;
 2116:     }
 2117:     if (oldObject.id) {
 2118:         newObject.id = oldObject.id;
 2119:     }
 2120:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2121:     return;
 2122: }
 2123: 
 2124: ENDJS
 2125: }
 2126: 
 2127: sub gradeleveldescription {
 2128:     my $gradelevel=shift;
 2129:     my %gradelevels=(0 => 'Not specified',
 2130: 		     1 => 'Grade 1',
 2131: 		     2 => 'Grade 2',
 2132: 		     3 => 'Grade 3',
 2133: 		     4 => 'Grade 4',
 2134: 		     5 => 'Grade 5',
 2135: 		     6 => 'Grade 6',
 2136: 		     7 => 'Grade 7',
 2137: 		     8 => 'Grade 8',
 2138: 		     9 => 'Grade 9',
 2139: 		     10 => 'Grade 10',
 2140: 		     11 => 'Grade 11',
 2141: 		     12 => 'Grade 12',
 2142: 		     13 => 'Grade 13',
 2143: 		     14 => '100 Level',
 2144: 		     15 => '200 Level',
 2145: 		     16 => '300 Level',
 2146: 		     17 => '400 Level',
 2147: 		     18 => 'Graduate Level');
 2148:     return &mt($gradelevels{$gradelevel});
 2149: }
 2150: 
 2151: sub select_level_form {
 2152:     my ($deflevel,$name)=@_;
 2153:     unless ($deflevel) { $deflevel=0; }
 2154:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2155:     for (my $i=0; $i<=18; $i++) {
 2156:         $selectform.="<option value=\"$i\" ".
 2157:             ($i==$deflevel ? 'selected="selected" ' : '').
 2158:                 ">".&gradeleveldescription($i)."</option>\n";
 2159:     }
 2160:     $selectform.="</select>";
 2161:     return $selectform;
 2162: }
 2163: 
 2164: #-------------------------------------------
 2165: 
 2166: =pod
 2167: 
 2168: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2169: 
 2170: Returns a string containing a <select name='$name' size='1'> form to 
 2171: allow a user to select the domain to preform an operation in.  
 2172: See loncreateuser.pm for an example invocation and use.
 2173: 
 2174: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2175: selected");
 2176: 
 2177: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2178: 
 2179: 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.
 2180: 
 2181: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2182: 
 2183: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2184: 
 2185: =cut
 2186: 
 2187: #-------------------------------------------
 2188: sub select_dom_form {
 2189:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2190:     if ($onchange) {
 2191:         $onchange = ' onchange="'.$onchange.'"';
 2192:     }
 2193:     my (@domains,%exclude);
 2194:     if (ref($incdoms) eq 'ARRAY') {
 2195:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2196:     } else {
 2197:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2198:     }
 2199:     if ($includeempty) { @domains=('',@domains); }
 2200:     if (ref($excdoms) eq 'ARRAY') {
 2201:         map { $exclude{$_} = 1; } @{$excdoms};
 2202:     }
 2203:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2204:     foreach my $dom (@domains) {
 2205:         next if ($exclude{$dom});
 2206:         $selectdomain.="<option value=\"$dom\" ".
 2207:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2208:         if ($showdomdesc) {
 2209:             if ($dom ne '') {
 2210:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2211:                 if ($domdesc ne '') {
 2212:                     $selectdomain .= ' ('.$domdesc.')';
 2213:                 }
 2214:             } 
 2215:         }
 2216:         $selectdomain .= "</option>\n";
 2217:     }
 2218:     $selectdomain.="</select>";
 2219:     return $selectdomain;
 2220: }
 2221: 
 2222: #-------------------------------------------
 2223: 
 2224: =pod
 2225: 
 2226: =item * &home_server_form_item($domain,$name,$defaultflag)
 2227: 
 2228: input: 4 arguments (two required, two optional) - 
 2229:     $domain - domain of new user
 2230:     $name - name of form element
 2231:     $default - Value of 'default' causes a default item to be first 
 2232:                             option, and selected by default. 
 2233:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2234:                             if 1 server found, or default, if 0 found.
 2235: output: returns 2 items: 
 2236: (a) form element which contains either:
 2237:    (i) <select name="$name">
 2238:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2239:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2240:        </select>
 2241:        form item if there are multiple library servers in $domain, or
 2242:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2243:        if there is only one library server in $domain.
 2244: 
 2245: (b) number of library servers found.
 2246: 
 2247: See loncreateuser.pm for example of use.
 2248: 
 2249: =cut
 2250: 
 2251: #-------------------------------------------
 2252: sub home_server_form_item {
 2253:     my ($domain,$name,$default,$hide) = @_;
 2254:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2255:     my $result;
 2256:     my $numlib = keys(%servers);
 2257:     if ($numlib > 1) {
 2258:         $result .= '<select name="'.$name.'" />'."\n";
 2259:         if ($default) {
 2260:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2261:                        '</option>'."\n";
 2262:         }
 2263:         foreach my $hostid (sort(keys(%servers))) {
 2264:             $result.= '<option value="'.$hostid.'">'.
 2265: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2266:         }
 2267:         $result .= '</select>'."\n";
 2268:     } elsif ($numlib == 1) {
 2269:         my $hostid;
 2270:         foreach my $item (keys(%servers)) {
 2271:             $hostid = $item;
 2272:         }
 2273:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2274:                    $hostid.'" />';
 2275:                    if (!$hide) {
 2276:                        $result .= $hostid.' '.$servers{$hostid};
 2277:                    }
 2278:                    $result .= "\n";
 2279:     } elsif ($default) {
 2280:         $result .= '<input type="hidden" name="'.$name.
 2281:                    '" value="default" />';
 2282:                    if (!$hide) {
 2283:                        $result .= &mt('default');
 2284:                    }
 2285:                    $result .= "\n";
 2286:     }
 2287:     return ($result,$numlib);
 2288: }
 2289: 
 2290: =pod
 2291: 
 2292: =back 
 2293: 
 2294: =cut
 2295: 
 2296: ###############################################################
 2297: ##                  Decoding User Agent                      ##
 2298: ###############################################################
 2299: 
 2300: =pod
 2301: 
 2302: =head1 Decoding the User Agent
 2303: 
 2304: =over 4
 2305: 
 2306: =item * &decode_user_agent()
 2307: 
 2308: Inputs: $r
 2309: 
 2310: Outputs:
 2311: 
 2312: =over 4
 2313: 
 2314: =item * $httpbrowser
 2315: 
 2316: =item * $clientbrowser
 2317: 
 2318: =item * $clientversion
 2319: 
 2320: =item * $clientmathml
 2321: 
 2322: =item * $clientunicode
 2323: 
 2324: =item * $clientos
 2325: 
 2326: =item * $clientmobile
 2327: 
 2328: =item * $clientinfo
 2329: 
 2330: =back
 2331: 
 2332: =back 
 2333: 
 2334: =cut
 2335: 
 2336: ###############################################################
 2337: ###############################################################
 2338: sub decode_user_agent {
 2339:     my ($r)=@_;
 2340:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2341:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2342:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2343:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2344:     my $clientbrowser='unknown';
 2345:     my $clientversion='0';
 2346:     my $clientmathml='';
 2347:     my $clientunicode='0';
 2348:     my $clientmobile=0;
 2349:     for (my $i=0;$i<=$#browsertype;$i++) {
 2350:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2351: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2352: 	    $clientbrowser=$bname;
 2353:             $httpbrowser=~/$vreg/i;
 2354: 	    $clientversion=$1;
 2355:             $clientmathml=($clientversion>=$minv);
 2356:             $clientunicode=($clientversion>=$univ);
 2357: 	}
 2358:     }
 2359:     my $clientos='unknown';
 2360:     my $clientinfo;
 2361:     if (($httpbrowser=~/linux/i) ||
 2362:         ($httpbrowser=~/unix/i) ||
 2363:         ($httpbrowser=~/ux/i) ||
 2364:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2365:     if (($httpbrowser=~/vax/i) ||
 2366:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2367:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2368:     if (($httpbrowser=~/mac/i) ||
 2369:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2370:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2371:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2372:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2373:         $clientmobile=lc($1);
 2374:     }
 2375:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2376:         $clientinfo = 'firefox-'.$1;
 2377:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2378:         $clientinfo = 'chromeframe-'.$1;
 2379:     }
 2380:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2381:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2382: }
 2383: 
 2384: ###############################################################
 2385: ##    Authentication changing form generation subroutines    ##
 2386: ###############################################################
 2387: ##
 2388: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2389: ## hash, and have reasonable default values.
 2390: ##
 2391: ##    formname = the name given in the <form> tag.
 2392: #-------------------------------------------
 2393: 
 2394: =pod
 2395: 
 2396: =head1 Authentication Routines
 2397: 
 2398: =over 4
 2399: 
 2400: =item * &authform_xxxxxx()
 2401: 
 2402: The authform_xxxxxx subroutines provide javascript and html forms which 
 2403: handle some of the conveniences required for authentication forms.  
 2404: This is not an optimal method, but it works.  
 2405: 
 2406: =over 4
 2407: 
 2408: =item * authform_header
 2409: 
 2410: =item * authform_authorwarning
 2411: 
 2412: =item * authform_nochange
 2413: 
 2414: =item * authform_kerberos
 2415: 
 2416: =item * authform_internal
 2417: 
 2418: =item * authform_filesystem
 2419: 
 2420: =back
 2421: 
 2422: See loncreateuser.pm for invocation and use examples.
 2423: 
 2424: =cut
 2425: 
 2426: #-------------------------------------------
 2427: sub authform_header{  
 2428:     my %in = (
 2429:         formname => 'cu',
 2430:         kerb_def_dom => '',
 2431:         @_,
 2432:     );
 2433:     $in{'formname'} = 'document.' . $in{'formname'};
 2434:     my $result='';
 2435: 
 2436: #---------------------------------------------- Code for upper case translation
 2437:     my $Javascript_toUpperCase;
 2438:     unless ($in{kerb_def_dom}) {
 2439:         $Javascript_toUpperCase =<<"END";
 2440:         switch (choice) {
 2441:            case 'krb': currentform.elements[choicearg].value =
 2442:                currentform.elements[choicearg].value.toUpperCase();
 2443:                break;
 2444:            default:
 2445:         }
 2446: END
 2447:     } else {
 2448:         $Javascript_toUpperCase = "";
 2449:     }
 2450: 
 2451:     my $radioval = "'nochange'";
 2452:     if (defined($in{'curr_authtype'})) {
 2453:         if ($in{'curr_authtype'} ne '') {
 2454:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2455:         }
 2456:     }
 2457:     my $argfield = 'null';
 2458:     if (defined($in{'mode'})) {
 2459:         if ($in{'mode'} eq 'modifycourse')  {
 2460:             if (defined($in{'curr_autharg'})) {
 2461:                 if ($in{'curr_autharg'} ne '') {
 2462:                     $argfield = "'$in{'curr_autharg'}'";
 2463:                 }
 2464:             }
 2465:         }
 2466:     }
 2467: 
 2468:     $result.=<<"END";
 2469: var current = new Object();
 2470: current.radiovalue = $radioval;
 2471: current.argfield = $argfield;
 2472: 
 2473: function changed_radio(choice,currentform) {
 2474:     var choicearg = choice + 'arg';
 2475:     // If a radio button in changed, we need to change the argfield
 2476:     if (current.radiovalue != choice) {
 2477:         current.radiovalue = choice;
 2478:         if (current.argfield != null) {
 2479:             currentform.elements[current.argfield].value = '';
 2480:         }
 2481:         if (choice == 'nochange') {
 2482:             current.argfield = null;
 2483:         } else {
 2484:             current.argfield = choicearg;
 2485:             switch(choice) {
 2486:                 case 'krb': 
 2487:                     currentform.elements[current.argfield].value = 
 2488:                         "$in{'kerb_def_dom'}";
 2489:                 break;
 2490:               default:
 2491:                 break;
 2492:             }
 2493:         }
 2494:     }
 2495:     return;
 2496: }
 2497: 
 2498: function changed_text(choice,currentform) {
 2499:     var choicearg = choice + 'arg';
 2500:     if (currentform.elements[choicearg].value !='') {
 2501:         $Javascript_toUpperCase
 2502:         // clear old field
 2503:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2504:             currentform.elements[current.argfield].value = '';
 2505:         }
 2506:         current.argfield = choicearg;
 2507:     }
 2508:     set_auth_radio_buttons(choice,currentform);
 2509:     return;
 2510: }
 2511: 
 2512: function set_auth_radio_buttons(newvalue,currentform) {
 2513:     var numauthchoices = currentform.login.length;
 2514:     if (typeof numauthchoices  == "undefined") {
 2515:         return;
 2516:     } 
 2517:     var i=0;
 2518:     while (i < numauthchoices) {
 2519:         if (currentform.login[i].value == newvalue) { break; }
 2520:         i++;
 2521:     }
 2522:     if (i == numauthchoices) {
 2523:         return;
 2524:     }
 2525:     current.radiovalue = newvalue;
 2526:     currentform.login[i].checked = true;
 2527:     return;
 2528: }
 2529: END
 2530:     return $result;
 2531: }
 2532: 
 2533: sub authform_authorwarning {
 2534:     my $result='';
 2535:     $result='<i>'.
 2536:         &mt('As a general rule, only authors or co-authors should be '.
 2537:             'filesystem authenticated '.
 2538:             '(which allows access to the server filesystem).')."</i>\n";
 2539:     return $result;
 2540: }
 2541: 
 2542: sub authform_nochange {
 2543:     my %in = (
 2544:               formname => 'document.cu',
 2545:               kerb_def_dom => 'MSU.EDU',
 2546:               @_,
 2547:           );
 2548:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2549:     my $result;
 2550:     if (!$authnum) {
 2551:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2552:     } else {
 2553:         $result = '<label>'.&mt('[_1] Do not change login data',
 2554:                   '<input type="radio" name="login" value="nochange" '.
 2555:                   'checked="checked" onclick="'.
 2556:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2557: 	    '</label>';
 2558:     }
 2559:     return $result;
 2560: }
 2561: 
 2562: sub authform_kerberos {
 2563:     my %in = (
 2564:               formname => 'document.cu',
 2565:               kerb_def_dom => 'MSU.EDU',
 2566:               kerb_def_auth => 'krb4',
 2567:               @_,
 2568:               );
 2569:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2570:         $autharg,$jscall);
 2571:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2572:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2573:        $check5 = ' checked="checked"';
 2574:     } else {
 2575:        $check4 = ' checked="checked"';
 2576:     }
 2577:     $krbarg = $in{'kerb_def_dom'};
 2578:     if (defined($in{'curr_authtype'})) {
 2579:         if ($in{'curr_authtype'} eq 'krb') {
 2580:             $krbcheck = ' checked="checked"';
 2581:             if (defined($in{'mode'})) {
 2582:                 if ($in{'mode'} eq 'modifyuser') {
 2583:                     $krbcheck = '';
 2584:                 }
 2585:             }
 2586:             if (defined($in{'curr_kerb_ver'})) {
 2587:                 if ($in{'curr_krb_ver'} eq '5') {
 2588:                     $check5 = ' checked="checked"';
 2589:                     $check4 = '';
 2590:                 } else {
 2591:                     $check4 = ' checked="checked"';
 2592:                     $check5 = '';
 2593:                 }
 2594:             }
 2595:             if (defined($in{'curr_autharg'})) {
 2596:                 $krbarg = $in{'curr_autharg'};
 2597:             }
 2598:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2599:                 if (defined($in{'curr_autharg'})) {
 2600:                     $result = 
 2601:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2602:         $in{'curr_autharg'},$krbver);
 2603:                 } else {
 2604:                     $result =
 2605:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2606:                 }
 2607:                 return $result; 
 2608:             }
 2609:         }
 2610:     } else {
 2611:         if ($authnum == 1) {
 2612:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2613:         }
 2614:     }
 2615:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2616:         return;
 2617:     } elsif ($authtype eq '') {
 2618:         if (defined($in{'mode'})) {
 2619:             if ($in{'mode'} eq 'modifycourse') {
 2620:                 if ($authnum == 1) {
 2621:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2622:                 }
 2623:             }
 2624:         }
 2625:     }
 2626:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2627:     if ($authtype eq '') {
 2628:         $authtype = '<input type="radio" name="login" value="krb" '.
 2629:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2630:                     $krbcheck.' />';
 2631:     }
 2632:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2633:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2634:          $in{'curr_authtype'} eq 'krb5') ||
 2635:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2636:          $in{'curr_authtype'} eq 'krb4')) {
 2637:         $result .= &mt
 2638:         ('[_1] Kerberos authenticated with domain [_2] '.
 2639:          '[_3] Version 4 [_4] Version 5 [_5]',
 2640:          '<label>'.$authtype,
 2641:          '</label><input type="text" size="10" name="krbarg" '.
 2642:              'value="'.$krbarg.'" '.
 2643:              'onchange="'.$jscall.'" />',
 2644:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2645:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2646: 	 '</label>');
 2647:     } elsif ($can_assign{'krb4'}) {
 2648:         $result .= &mt
 2649:         ('[_1] Kerberos authenticated with domain [_2] '.
 2650:          '[_3] Version 4 [_4]',
 2651:          '<label>'.$authtype,
 2652:          '</label><input type="text" size="10" name="krbarg" '.
 2653:              'value="'.$krbarg.'" '.
 2654:              'onchange="'.$jscall.'" />',
 2655:          '<label><input type="hidden" name="krbver" value="4" />',
 2656:          '</label>');
 2657:     } elsif ($can_assign{'krb5'}) {
 2658:         $result .= &mt
 2659:         ('[_1] Kerberos authenticated with domain [_2] '.
 2660:          '[_3] Version 5 [_4]',
 2661:          '<label>'.$authtype,
 2662:          '</label><input type="text" size="10" name="krbarg" '.
 2663:              'value="'.$krbarg.'" '.
 2664:              'onchange="'.$jscall.'" />',
 2665:          '<label><input type="hidden" name="krbver" value="5" />',
 2666:          '</label>');
 2667:     }
 2668:     return $result;
 2669: }
 2670: 
 2671: sub authform_internal {
 2672:     my %in = (
 2673:                 formname => 'document.cu',
 2674:                 kerb_def_dom => 'MSU.EDU',
 2675:                 @_,
 2676:                 );
 2677:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2678:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2679:     if (defined($in{'curr_authtype'})) {
 2680:         if ($in{'curr_authtype'} eq 'int') {
 2681:             if ($can_assign{'int'}) {
 2682:                 $intcheck = 'checked="checked" ';
 2683:                 if (defined($in{'mode'})) {
 2684:                     if ($in{'mode'} eq 'modifyuser') {
 2685:                         $intcheck = '';
 2686:                     }
 2687:                 }
 2688:                 if (defined($in{'curr_autharg'})) {
 2689:                     $intarg = $in{'curr_autharg'};
 2690:                 }
 2691:             } else {
 2692:                 $result = &mt('Currently internally authenticated.');
 2693:                 return $result;
 2694:             }
 2695:         }
 2696:     } else {
 2697:         if ($authnum == 1) {
 2698:             $authtype = '<input type="hidden" name="login" value="int" />';
 2699:         }
 2700:     }
 2701:     if (!$can_assign{'int'}) {
 2702:         return;
 2703:     } elsif ($authtype eq '') {
 2704:         if (defined($in{'mode'})) {
 2705:             if ($in{'mode'} eq 'modifycourse') {
 2706:                 if ($authnum == 1) {
 2707:                     $authtype = '<input type="radio" name="login" value="int" />';
 2708:                 }
 2709:             }
 2710:         }
 2711:     }
 2712:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2713:     if ($authtype eq '') {
 2714:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2715:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2716:     }
 2717:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2718:                $intarg.'" onchange="'.$jscall.'" />';
 2719:     $result = &mt
 2720:         ('[_1] Internally authenticated (with initial password [_2])',
 2721:          '<label>'.$authtype,'</label>'.$autharg);
 2722:     $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>';
 2723:     return $result;
 2724: }
 2725: 
 2726: sub authform_local {
 2727:     my %in = (
 2728:               formname => 'document.cu',
 2729:               kerb_def_dom => 'MSU.EDU',
 2730:               @_,
 2731:               );
 2732:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2733:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2734:     if (defined($in{'curr_authtype'})) {
 2735:         if ($in{'curr_authtype'} eq 'loc') {
 2736:             if ($can_assign{'loc'}) {
 2737:                 $loccheck = 'checked="checked" ';
 2738:                 if (defined($in{'mode'})) {
 2739:                     if ($in{'mode'} eq 'modifyuser') {
 2740:                         $loccheck = '';
 2741:                     }
 2742:                 }
 2743:                 if (defined($in{'curr_autharg'})) {
 2744:                     $locarg = $in{'curr_autharg'};
 2745:                 }
 2746:             } else {
 2747:                 $result = &mt('Currently using local (institutional) authentication.');
 2748:                 return $result;
 2749:             }
 2750:         }
 2751:     } else {
 2752:         if ($authnum == 1) {
 2753:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2754:         }
 2755:     }
 2756:     if (!$can_assign{'loc'}) {
 2757:         return;
 2758:     } elsif ($authtype eq '') {
 2759:         if (defined($in{'mode'})) {
 2760:             if ($in{'mode'} eq 'modifycourse') {
 2761:                 if ($authnum == 1) {
 2762:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2763:                 }
 2764:             }
 2765:         }
 2766:     }
 2767:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2768:     if ($authtype eq '') {
 2769:         $authtype = '<input type="radio" name="login" value="loc" '.
 2770:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2771:                     $jscall.'" />';
 2772:     }
 2773:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2774:                $locarg.'" onchange="'.$jscall.'" />';
 2775:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2776:                   '<label>'.$authtype,'</label>'.$autharg);
 2777:     return $result;
 2778: }
 2779: 
 2780: sub authform_filesystem {
 2781:     my %in = (
 2782:               formname => 'document.cu',
 2783:               kerb_def_dom => 'MSU.EDU',
 2784:               @_,
 2785:               );
 2786:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2787:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2788:     if (defined($in{'curr_authtype'})) {
 2789:         if ($in{'curr_authtype'} eq 'fsys') {
 2790:             if ($can_assign{'fsys'}) {
 2791:                 $fsyscheck = 'checked="checked" ';
 2792:                 if (defined($in{'mode'})) {
 2793:                     if ($in{'mode'} eq 'modifyuser') {
 2794:                         $fsyscheck = '';
 2795:                     }
 2796:                 }
 2797:             } else {
 2798:                 $result = &mt('Currently Filesystem Authenticated.');
 2799:                 return $result;
 2800:             }           
 2801:         }
 2802:     } else {
 2803:         if ($authnum == 1) {
 2804:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2805:         }
 2806:     }
 2807:     if (!$can_assign{'fsys'}) {
 2808:         return;
 2809:     } elsif ($authtype eq '') {
 2810:         if (defined($in{'mode'})) {
 2811:             if ($in{'mode'} eq 'modifycourse') {
 2812:                 if ($authnum == 1) {
 2813:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2814:                 }
 2815:             }
 2816:         }
 2817:     }
 2818:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2819:     if ($authtype eq '') {
 2820:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2821:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2822:                     $jscall.'" />';
 2823:     }
 2824:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2825:                ' onchange="'.$jscall.'" />';
 2826:     $result = &mt
 2827:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2828:          '<label><input type="radio" name="login" value="fsys" '.
 2829:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2830:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2831:                   'onchange="'.$jscall.'" />');
 2832:     return $result;
 2833: }
 2834: 
 2835: sub get_assignable_auth {
 2836:     my ($dom) = @_;
 2837:     if ($dom eq '') {
 2838:         $dom = $env{'request.role.domain'};
 2839:     }
 2840:     my %can_assign = (
 2841:                           krb4 => 1,
 2842:                           krb5 => 1,
 2843:                           int  => 1,
 2844:                           loc  => 1,
 2845:                      );
 2846:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2847:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2848:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2849:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2850:             my $context;
 2851:             if ($env{'request.role'} =~ /^au/) {
 2852:                 $context = 'author';
 2853:             } elsif ($env{'request.role'} =~ /^dc/) {
 2854:                 $context = 'domain';
 2855:             } elsif ($env{'request.course.id'}) {
 2856:                 $context = 'course';
 2857:             }
 2858:             if ($context) {
 2859:                 if (ref($authhash->{$context}) eq 'HASH') {
 2860:                    %can_assign = %{$authhash->{$context}}; 
 2861:                 }
 2862:             }
 2863:         }
 2864:     }
 2865:     my $authnum = 0;
 2866:     foreach my $key (keys(%can_assign)) {
 2867:         if ($can_assign{$key}) {
 2868:             $authnum ++;
 2869:         }
 2870:     }
 2871:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2872:         $authnum --;
 2873:     }
 2874:     return ($authnum,%can_assign);
 2875: }
 2876: 
 2877: ###############################################################
 2878: ##    Get Kerberos Defaults for Domain                 ##
 2879: ###############################################################
 2880: ##
 2881: ## Returns default kerberos version and an associated argument
 2882: ## as listed in file domain.tab. If not listed, provides
 2883: ## appropriate default domain and kerberos version.
 2884: ##
 2885: #-------------------------------------------
 2886: 
 2887: =pod
 2888: 
 2889: =item * &get_kerberos_defaults()
 2890: 
 2891: get_kerberos_defaults($target_domain) returns the default kerberos
 2892: version and domain. If not found, it defaults to version 4 and the 
 2893: domain of the server.
 2894: 
 2895: =over 4
 2896: 
 2897: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2898: 
 2899: =back
 2900: 
 2901: =back
 2902: 
 2903: =cut
 2904: 
 2905: #-------------------------------------------
 2906: sub get_kerberos_defaults {
 2907:     my $domain=shift;
 2908:     my ($krbdef,$krbdefdom);
 2909:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2910:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2911:         $krbdef = $domdefaults{'auth_def'};
 2912:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2913:     } else {
 2914:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2915:         my $krbdefdom=$1;
 2916:         $krbdefdom=~tr/a-z/A-Z/;
 2917:         $krbdef = "krb4";
 2918:     }
 2919:     return ($krbdef,$krbdefdom);
 2920: }
 2921: 
 2922: 
 2923: ###############################################################
 2924: ##                Thesaurus Functions                        ##
 2925: ###############################################################
 2926: 
 2927: =pod
 2928: 
 2929: =head1 Thesaurus Functions
 2930: 
 2931: =over 4
 2932: 
 2933: =item * &initialize_keywords()
 2934: 
 2935: Initializes the package variable %Keywords if it is empty.  Uses the
 2936: package variable $thesaurus_db_file.
 2937: 
 2938: =cut
 2939: 
 2940: ###################################################
 2941: 
 2942: sub initialize_keywords {
 2943:     return 1 if (scalar keys(%Keywords));
 2944:     # If we are here, %Keywords is empty, so fill it up
 2945:     #   Make sure the file we need exists...
 2946:     if (! -e $thesaurus_db_file) {
 2947:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2948:                                  " failed because it does not exist");
 2949:         return 0;
 2950:     }
 2951:     #   Set up the hash as a database
 2952:     my %thesaurus_db;
 2953:     if (! tie(%thesaurus_db,'GDBM_File',
 2954:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2955:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2956:                                  $thesaurus_db_file);
 2957:         return 0;
 2958:     } 
 2959:     #  Get the average number of appearances of a word.
 2960:     my $avecount = $thesaurus_db{'average.count'};
 2961:     #  Put keywords (those that appear > average) into %Keywords
 2962:     while (my ($word,$data)=each (%thesaurus_db)) {
 2963:         my ($count,undef) = split /:/,$data;
 2964:         $Keywords{$word}++ if ($count > $avecount);
 2965:     }
 2966:     untie %thesaurus_db;
 2967:     # Remove special values from %Keywords.
 2968:     foreach my $value ('total.count','average.count') {
 2969:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2970:   }
 2971:     return 1;
 2972: }
 2973: 
 2974: ###################################################
 2975: 
 2976: =pod
 2977: 
 2978: =item * &keyword($word)
 2979: 
 2980: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2981: than the average number of times in the thesaurus database.  Calls 
 2982: &initialize_keywords
 2983: 
 2984: =cut
 2985: 
 2986: ###################################################
 2987: 
 2988: sub keyword {
 2989:     return if (!&initialize_keywords());
 2990:     my $word=lc(shift());
 2991:     $word=~s/\W//g;
 2992:     return exists($Keywords{$word});
 2993: }
 2994: 
 2995: ###############################################################
 2996: 
 2997: =pod 
 2998: 
 2999: =item * &get_related_words()
 3000: 
 3001: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3002: an array of words.  If the keyword is not in the thesaurus, an empty array
 3003: will be returned.  The order of the words returned is determined by the
 3004: database which holds them.
 3005: 
 3006: Uses global $thesaurus_db_file.
 3007: 
 3008: 
 3009: =cut
 3010: 
 3011: ###############################################################
 3012: sub get_related_words {
 3013:     my $keyword = shift;
 3014:     my %thesaurus_db;
 3015:     if (! -e $thesaurus_db_file) {
 3016:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3017:                                  "failed because the file does not exist");
 3018:         return ();
 3019:     }
 3020:     if (! tie(%thesaurus_db,'GDBM_File',
 3021:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3022:         return ();
 3023:     } 
 3024:     my @Words=();
 3025:     my $count=0;
 3026:     if (exists($thesaurus_db{$keyword})) {
 3027: 	# The first element is the number of times
 3028: 	# the word appears.  We do not need it now.
 3029: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3030: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3031: 	my $threshold=$mostfrequentcount/10;
 3032:         foreach my $possibleword (@RelatedWords) {
 3033:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3034:             if ($wordcount>$threshold) {
 3035: 		push(@Words,$word);
 3036:                 $count++;
 3037:                 if ($count>10) { last; }
 3038: 	    }
 3039:         }
 3040:     }
 3041:     untie %thesaurus_db;
 3042:     return @Words;
 3043: }
 3044: 
 3045: =pod
 3046: 
 3047: =back
 3048: 
 3049: =cut
 3050: 
 3051: # -------------------------------------------------------------- Plaintext name
 3052: =pod
 3053: 
 3054: =head1 User Name Functions
 3055: 
 3056: =over 4
 3057: 
 3058: =item * &plainname($uname,$udom,$first)
 3059: 
 3060: Takes a users logon name and returns it as a string in
 3061: "first middle last generation" form 
 3062: if $first is set to 'lastname' then it returns it as
 3063: 'lastname generation, firstname middlename' if their is a lastname
 3064: 
 3065: =cut
 3066: 
 3067: 
 3068: ###############################################################
 3069: sub plainname {
 3070:     my ($uname,$udom,$first)=@_;
 3071:     return if (!defined($uname) || !defined($udom));
 3072:     my %names=&getnames($uname,$udom);
 3073:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3074: 					  $names{'middlename'},
 3075: 					  $names{'lastname'},
 3076: 					  $names{'generation'},$first);
 3077:     $name=~s/^\s+//;
 3078:     $name=~s/\s+$//;
 3079:     $name=~s/\s+/ /g;
 3080:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3081:     return $name;
 3082: }
 3083: 
 3084: # -------------------------------------------------------------------- Nickname
 3085: =pod
 3086: 
 3087: =item * &nickname($uname,$udom)
 3088: 
 3089: Gets a users name and returns it as a string as
 3090: 
 3091: "&quot;nickname&quot;"
 3092: 
 3093: if the user has a nickname or
 3094: 
 3095: "first middle last generation"
 3096: 
 3097: if the user does not
 3098: 
 3099: =cut
 3100: 
 3101: sub nickname {
 3102:     my ($uname,$udom)=@_;
 3103:     return if (!defined($uname) || !defined($udom));
 3104:     my %names=&getnames($uname,$udom);
 3105:     my $name=$names{'nickname'};
 3106:     if ($name) {
 3107:        $name='&quot;'.$name.'&quot;'; 
 3108:     } else {
 3109:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3110: 	     $names{'lastname'}.' '.$names{'generation'};
 3111:        $name=~s/\s+$//;
 3112:        $name=~s/\s+/ /g;
 3113:     }
 3114:     return $name;
 3115: }
 3116: 
 3117: sub getnames {
 3118:     my ($uname,$udom)=@_;
 3119:     return if (!defined($uname) || !defined($udom));
 3120:     if ($udom eq 'public' && $uname eq 'public') {
 3121: 	return ('lastname' => &mt('Public'));
 3122:     }
 3123:     my $id=$uname.':'.$udom;
 3124:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3125:     if ($cached) {
 3126: 	return %{$names};
 3127:     } else {
 3128: 	my %loadnames=&Apache::lonnet::get('environment',
 3129:                     ['firstname','middlename','lastname','generation','nickname'],
 3130: 					 $udom,$uname);
 3131: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3132: 	return %loadnames;
 3133:     }
 3134: }
 3135: 
 3136: # -------------------------------------------------------------------- getemails
 3137: 
 3138: =pod
 3139: 
 3140: =item * &getemails($uname,$udom)
 3141: 
 3142: Gets a user's email information and returns it as a hash with keys:
 3143: notification, critnotification, permanentemail
 3144: 
 3145: For notification and critnotification, values are comma-separated lists 
 3146: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3147:  
 3148: 
 3149: =cut
 3150: 
 3151: 
 3152: sub getemails {
 3153:     my ($uname,$udom)=@_;
 3154:     if ($udom eq 'public' && $uname eq 'public') {
 3155: 	return;
 3156:     }
 3157:     if (!$udom) { $udom=$env{'user.domain'}; }
 3158:     if (!$uname) { $uname=$env{'user.name'}; }
 3159:     my $id=$uname.':'.$udom;
 3160:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3161:     if ($cached) {
 3162: 	return %{$names};
 3163:     } else {
 3164: 	my %loadnames=&Apache::lonnet::get('environment',
 3165:                     			   ['notification','critnotification',
 3166: 					    'permanentemail'],
 3167: 					   $udom,$uname);
 3168: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3169: 	return %loadnames;
 3170:     }
 3171: }
 3172: 
 3173: sub flush_email_cache {
 3174:     my ($uname,$udom)=@_;
 3175:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3176:     if (!$uname) { $uname=$env{'user.name'};   }
 3177:     return if ($udom eq 'public' && $uname eq 'public');
 3178:     my $id=$uname.':'.$udom;
 3179:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3180: }
 3181: 
 3182: # -------------------------------------------------------------------- getlangs
 3183: 
 3184: =pod
 3185: 
 3186: =item * &getlangs($uname,$udom)
 3187: 
 3188: Gets a user's language preference and returns it as a hash with key:
 3189: language.
 3190: 
 3191: =cut
 3192: 
 3193: 
 3194: sub getlangs {
 3195:     my ($uname,$udom) = @_;
 3196:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3197:     if (!$uname) { $uname=$env{'user.name'};   }
 3198:     my $id=$uname.':'.$udom;
 3199:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3200:     if ($cached) {
 3201:         return %{$langs};
 3202:     } else {
 3203:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3204:                                            $udom,$uname);
 3205:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3206:         return %loadlangs;
 3207:     }
 3208: }
 3209: 
 3210: sub flush_langs_cache {
 3211:     my ($uname,$udom)=@_;
 3212:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3213:     if (!$uname) { $uname=$env{'user.name'};   }
 3214:     return if ($udom eq 'public' && $uname eq 'public');
 3215:     my $id=$uname.':'.$udom;
 3216:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3217: }
 3218: 
 3219: # ------------------------------------------------------------------ Screenname
 3220: 
 3221: =pod
 3222: 
 3223: =item * &screenname($uname,$udom)
 3224: 
 3225: Gets a users screenname and returns it as a string
 3226: 
 3227: =cut
 3228: 
 3229: sub screenname {
 3230:     my ($uname,$udom)=@_;
 3231:     if ($uname eq $env{'user.name'} &&
 3232: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3233:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3234:     return $names{'screenname'};
 3235: }
 3236: 
 3237: 
 3238: # ------------------------------------------------------------- Confirm Wrapper
 3239: =pod
 3240: 
 3241: =item * &confirmwrapper($message)
 3242: 
 3243: Wrap messages about completion of operation in box
 3244: 
 3245: =cut
 3246: 
 3247: sub confirmwrapper {
 3248:     my ($message)=@_;
 3249:     if ($message) {
 3250:         return "\n".'<div class="LC_confirm_box">'."\n"
 3251:                .$message."\n"
 3252:                .'</div>'."\n";
 3253:     } else {
 3254:         return $message;
 3255:     }
 3256: }
 3257: 
 3258: # ------------------------------------------------------------- Message Wrapper
 3259: 
 3260: sub messagewrapper {
 3261:     my ($link,$username,$domain,$subject,$text)=@_;
 3262:     return 
 3263:         '<a href="/adm/email?compose=individual&amp;'.
 3264:         'recname='.$username.'&amp;recdom='.$domain.
 3265: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3266:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3267: }
 3268: 
 3269: # --------------------------------------------------------------- Notes Wrapper
 3270: 
 3271: sub noteswrapper {
 3272:     my ($link,$un,$do)=@_;
 3273:     return 
 3274: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3275: }
 3276: 
 3277: # ------------------------------------------------------------- Aboutme Wrapper
 3278: 
 3279: sub aboutmewrapper {
 3280:     my ($link,$username,$domain,$target,$class)=@_;
 3281:     if (!defined($username)  && !defined($domain)) {
 3282:         return;
 3283:     }
 3284:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3285: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3286: }
 3287: 
 3288: # ------------------------------------------------------------ Syllabus Wrapper
 3289: 
 3290: sub syllabuswrapper {
 3291:     my ($linktext,$coursedir,$domain)=@_;
 3292:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3293: }
 3294: 
 3295: # -----------------------------------------------------------------------------
 3296: 
 3297: sub track_student_link {
 3298:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3299:     my $link ="/adm/trackstudent?";
 3300:     my $title = 'View recent activity';
 3301:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3302:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3303:         $link .= "selected_student=$sname:$sdom";
 3304:         $title .= ' of this student';
 3305:     } 
 3306:     if (defined($target) && $target !~ /^\s*$/) {
 3307:         $target = qq{target="$target"};
 3308:     } else {
 3309:         $target = '';
 3310:     }
 3311:     if ($start) { $link.='&amp;start='.$start; }
 3312:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3313:     $title = &mt($title);
 3314:     $linktext = &mt($linktext);
 3315:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3316: 	&help_open_topic('View_recent_activity');
 3317: }
 3318: 
 3319: sub slot_reservations_link {
 3320:     my ($linktext,$sname,$sdom,$target) = @_;
 3321:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3322:     my $title = 'View slot reservation history';
 3323:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3324:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3325:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3326:         $title .= ' of this student';
 3327:     }
 3328:     if (defined($target) && $target !~ /^\s*$/) {
 3329:         $target = qq{target="$target"};
 3330:     } else {
 3331:         $target = '';
 3332:     }
 3333:     $title = &mt($title);
 3334:     $linktext = &mt($linktext);
 3335:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3336: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3337: 
 3338: }
 3339: 
 3340: # ===================================================== Display a student photo
 3341: 
 3342: 
 3343: sub student_image_tag {
 3344:     my ($domain,$user)=@_;
 3345:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3346:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3347: 	return '<img src="'.$imgsrc.'" align="right" />';
 3348:     } else {
 3349: 	return '';
 3350:     }
 3351: }
 3352: 
 3353: =pod
 3354: 
 3355: =back
 3356: 
 3357: =head1 Access .tab File Data
 3358: 
 3359: =over 4
 3360: 
 3361: =item * &languageids() 
 3362: 
 3363: returns list of all language ids
 3364: 
 3365: =cut
 3366: 
 3367: sub languageids {
 3368:     return sort(keys(%language));
 3369: }
 3370: 
 3371: =pod
 3372: 
 3373: =item * &languagedescription() 
 3374: 
 3375: returns description of a specified language id
 3376: 
 3377: =cut
 3378: 
 3379: sub languagedescription {
 3380:     my $code=shift;
 3381:     return  ($supported_language{$code}?'* ':'').
 3382:             $language{$code}.
 3383: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3384: }
 3385: 
 3386: =pod
 3387: 
 3388: =item * &plainlanguagedescription
 3389: 
 3390: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3391: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3392: 
 3393: =cut
 3394: 
 3395: sub plainlanguagedescription {
 3396:     my $code=shift;
 3397:     return $language{$code};
 3398: }
 3399: 
 3400: =pod
 3401: 
 3402: =item * &supportedlanguagecode
 3403: 
 3404: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3405: code.
 3406: 
 3407: =cut
 3408: 
 3409: sub supportedlanguagecode {
 3410:     my $code=shift;
 3411:     return $supported_language{$code};
 3412: }
 3413: 
 3414: =pod
 3415: 
 3416: =item * &latexlanguage()
 3417: 
 3418: Given a language key code returns the correspondnig language to use
 3419: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3420: is no supported hyphenation for the language code.
 3421: 
 3422: =cut
 3423: 
 3424: sub latexlanguage {
 3425:     my $code = shift;
 3426:     return $latex_language{$code};
 3427: }
 3428: 
 3429: =pod
 3430: 
 3431: =item * &latexhyphenation()
 3432: 
 3433: Same as above but what's supplied is the language as it might be stored
 3434: in the metadata.
 3435: 
 3436: =cut
 3437: 
 3438: sub latexhyphenation {
 3439:     my $key = shift;
 3440:     return $latex_language_bykey{$key};
 3441: }
 3442: 
 3443: =pod
 3444: 
 3445: =item * &copyrightids() 
 3446: 
 3447: returns list of all copyrights
 3448: 
 3449: =cut
 3450: 
 3451: sub copyrightids {
 3452:     return sort(keys(%cprtag));
 3453: }
 3454: 
 3455: =pod
 3456: 
 3457: =item * &copyrightdescription() 
 3458: 
 3459: returns description of a specified copyright id
 3460: 
 3461: =cut
 3462: 
 3463: sub copyrightdescription {
 3464:     return &mt($cprtag{shift(@_)});
 3465: }
 3466: 
 3467: =pod
 3468: 
 3469: =item * &source_copyrightids() 
 3470: 
 3471: returns list of all source copyrights
 3472: 
 3473: =cut
 3474: 
 3475: sub source_copyrightids {
 3476:     return sort(keys(%scprtag));
 3477: }
 3478: 
 3479: =pod
 3480: 
 3481: =item * &source_copyrightdescription() 
 3482: 
 3483: returns description of a specified source copyright id
 3484: 
 3485: =cut
 3486: 
 3487: sub source_copyrightdescription {
 3488:     return &mt($scprtag{shift(@_)});
 3489: }
 3490: 
 3491: =pod
 3492: 
 3493: =item * &filecategories() 
 3494: 
 3495: returns list of all file categories
 3496: 
 3497: =cut
 3498: 
 3499: sub filecategories {
 3500:     return sort(keys(%category_extensions));
 3501: }
 3502: 
 3503: =pod
 3504: 
 3505: =item * &filecategorytypes() 
 3506: 
 3507: returns list of file types belonging to a given file
 3508: category
 3509: 
 3510: =cut
 3511: 
 3512: sub filecategorytypes {
 3513:     my ($cat) = @_;
 3514:     return @{$category_extensions{lc($cat)}};
 3515: }
 3516: 
 3517: =pod
 3518: 
 3519: =item * &fileembstyle() 
 3520: 
 3521: returns embedding style for a specified file type
 3522: 
 3523: =cut
 3524: 
 3525: sub fileembstyle {
 3526:     return $fe{lc(shift(@_))};
 3527: }
 3528: 
 3529: sub filemimetype {
 3530:     return $fm{lc(shift(@_))};
 3531: }
 3532: 
 3533: 
 3534: sub filecategoryselect {
 3535:     my ($name,$value)=@_;
 3536:     return &select_form($value,$name,
 3537:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3538: }
 3539: 
 3540: =pod
 3541: 
 3542: =item * &filedescription() 
 3543: 
 3544: returns description for a specified file type
 3545: 
 3546: =cut
 3547: 
 3548: sub filedescription {
 3549:     my $file_description = $fd{lc(shift())};
 3550:     $file_description =~ s:([\[\]]):~$1:g;
 3551:     return &mt($file_description);
 3552: }
 3553: 
 3554: =pod
 3555: 
 3556: =item * &filedescriptionex() 
 3557: 
 3558: returns description for a specified file type with
 3559: extra formatting
 3560: 
 3561: =cut
 3562: 
 3563: sub filedescriptionex {
 3564:     my $ex=shift;
 3565:     my $file_description = $fd{lc($ex)};
 3566:     $file_description =~ s:([\[\]]):~$1:g;
 3567:     return '.'.$ex.' '.&mt($file_description);
 3568: }
 3569: 
 3570: # End of .tab access
 3571: =pod
 3572: 
 3573: =back
 3574: 
 3575: =cut
 3576: 
 3577: # ------------------------------------------------------------------ File Types
 3578: sub fileextensions {
 3579:     return sort(keys(%fe));
 3580: }
 3581: 
 3582: # ----------------------------------------------------------- Display Languages
 3583: # returns a hash with all desired display languages
 3584: #
 3585: 
 3586: sub display_languages {
 3587:     my %languages=();
 3588:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3589: 	$languages{$lang}=1;
 3590:     }
 3591:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3592:     if ($env{'form.displaylanguage'}) {
 3593: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3594: 	    $languages{$lang}=1;
 3595:         }
 3596:     }
 3597:     return %languages;
 3598: }
 3599: 
 3600: sub languages {
 3601:     my ($possible_langs) = @_;
 3602:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3603:     if (!ref($possible_langs)) {
 3604: 	if( wantarray ) {
 3605: 	    return @preferred_langs;
 3606: 	} else {
 3607: 	    return $preferred_langs[0];
 3608: 	}
 3609:     }
 3610:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3611:     my @preferred_possibilities;
 3612:     foreach my $preferred_lang (@preferred_langs) {
 3613: 	if (exists($possibilities{$preferred_lang})) {
 3614: 	    push(@preferred_possibilities, $preferred_lang);
 3615: 	}
 3616:     }
 3617:     if( wantarray ) {
 3618: 	return @preferred_possibilities;
 3619:     }
 3620:     return $preferred_possibilities[0];
 3621: }
 3622: 
 3623: sub user_lang {
 3624:     my ($touname,$toudom,$fromcid) = @_;
 3625:     my @userlangs;
 3626:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3627:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3628:                     $env{'course.'.$fromcid.'.languages'}));
 3629:     } else {
 3630:         my %langhash = &getlangs($touname,$toudom);
 3631:         if ($langhash{'languages'} ne '') {
 3632:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3633:         } else {
 3634:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3635:             if ($domdefs{'lang_def'} ne '') {
 3636:                 @userlangs = ($domdefs{'lang_def'});
 3637:             }
 3638:         }
 3639:     }
 3640:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3641:     my $user_lh = Apache::localize->get_handle(@languages);
 3642:     return $user_lh;
 3643: }
 3644: 
 3645: 
 3646: ###############################################################
 3647: ##               Student Answer Attempts                     ##
 3648: ###############################################################
 3649: 
 3650: =pod
 3651: 
 3652: =head1 Alternate Problem Views
 3653: 
 3654: =over 4
 3655: 
 3656: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3657:     $getattempt, $regexp, $gradesub)
 3658: 
 3659: Return string with previous attempt on problem. Arguments:
 3660: 
 3661: =over 4
 3662: 
 3663: =item * $symb: Problem, including path
 3664: 
 3665: =item * $username: username of the desired student
 3666: 
 3667: =item * $domain: domain of the desired student
 3668: 
 3669: =item * $course: Course ID
 3670: 
 3671: =item * $getattempt: Leave blank for all attempts, otherwise put
 3672:     something
 3673: 
 3674: =item * $regexp: if string matches this regexp, the string will be
 3675:     sent to $gradesub
 3676: 
 3677: =item * $gradesub: routine that processes the string if it matches $regexp
 3678: 
 3679: =back
 3680: 
 3681: The output string is a table containing all desired attempts, if any.
 3682: 
 3683: =cut
 3684: 
 3685: sub get_previous_attempt {
 3686:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3687:   my $prevattempts='';
 3688:   no strict 'refs';
 3689:   if ($symb) {
 3690:     my (%returnhash)=
 3691:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3692:     if ($returnhash{'version'}) {
 3693:       my %lasthash=();
 3694:       my $version;
 3695:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3696:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3697: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3698:         }
 3699:       }
 3700:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3701:       $prevattempts.='<th>'.&mt('History').'</th>';
 3702:       my (%typeparts,%lasthidden);
 3703:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3704:       foreach my $key (sort(keys(%lasthash))) {
 3705: 	my ($ign,@parts) = split(/\./,$key);
 3706: 	if ($#parts > 0) {
 3707: 	  my $data=$parts[-1];
 3708:           next if ($data eq 'foilorder');
 3709: 	  pop(@parts);
 3710:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3711:           if ($data eq 'type') {
 3712:               unless ($showsurv) {
 3713:                   my $id = join(',',@parts);
 3714:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3715:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3716:                       $lasthidden{$ign.'.'.$id} = 1;
 3717:                   }
 3718:               }
 3719:           } 
 3720: 	} else {
 3721: 	  if ($#parts == 0) {
 3722: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3723: 	  } else {
 3724: 	    $prevattempts.='<th>'.$ign.'</th>';
 3725: 	  }
 3726: 	}
 3727:       }
 3728:       $prevattempts.=&end_data_table_header_row();
 3729:       if ($getattempt eq '') {
 3730: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3731:             my @hidden;
 3732:             if (%typeparts) {
 3733:                 foreach my $id (keys(%typeparts)) {
 3734:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3735:                         push(@hidden,$id);
 3736:                     }
 3737:                 }
 3738:             }
 3739:             $prevattempts.=&start_data_table_row().
 3740:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3741:             if (@hidden) {
 3742:                 foreach my $key (sort(keys(%lasthash))) {
 3743:                     next if ($key =~ /\.foilorder$/);
 3744:                     my $hide;
 3745:                     foreach my $id (@hidden) {
 3746:                         if ($key =~ /^\Q$id\E/) {
 3747:                             $hide = 1;
 3748:                             last;
 3749:                         }
 3750:                     }
 3751:                     if ($hide) {
 3752:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3753:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3754:                             my $value = &format_previous_attempt_value($key,
 3755:                                              $returnhash{$version.':'.$key});
 3756:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3757:                         } else {
 3758:                             $prevattempts.='<td>&nbsp;</td>';
 3759:                         }
 3760:                     } else {
 3761:                         if ($key =~ /\./) {
 3762:                             my $value = &format_previous_attempt_value($key,
 3763:                                               $returnhash{$version.':'.$key});
 3764:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3765:                         } else {
 3766:                             $prevattempts.='<td>&nbsp;</td>';
 3767:                         }
 3768:                     }
 3769:                 }
 3770:             } else {
 3771: 	        foreach my $key (sort(keys(%lasthash))) {
 3772:                     next if ($key =~ /\.foilorder$/);
 3773: 		    my $value = &format_previous_attempt_value($key,
 3774: 			            $returnhash{$version.':'.$key});
 3775: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3776: 	        }
 3777:             }
 3778: 	    $prevattempts.=&end_data_table_row();
 3779: 	 }
 3780:       }
 3781:       my @currhidden = keys(%lasthidden);
 3782:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3783:       foreach my $key (sort(keys(%lasthash))) {
 3784:           next if ($key =~ /\.foilorder$/);
 3785:           if (%typeparts) {
 3786:               my $hidden;
 3787:               foreach my $id (@currhidden) {
 3788:                   if ($key =~ /^\Q$id\E/) {
 3789:                       $hidden = 1;
 3790:                       last;
 3791:                   }
 3792:               }
 3793:               if ($hidden) {
 3794:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3795:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3796:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3797:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3798:                           $value = &$gradesub($value);
 3799:                       }
 3800:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3801:                   } else {
 3802:                       $prevattempts.='<td>&nbsp;</td>';
 3803:                   }
 3804:               } else {
 3805:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3806:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3807:                       $value = &$gradesub($value);
 3808:                   }
 3809:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3810:               }
 3811:           } else {
 3812: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3813: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3814:                   $value = &$gradesub($value);
 3815:               }
 3816: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3817:           }
 3818:       }
 3819:       $prevattempts.= &end_data_table_row().&end_data_table();
 3820:     } else {
 3821:       $prevattempts=
 3822: 	  &start_data_table().&start_data_table_row().
 3823: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3824: 	  &end_data_table_row().&end_data_table();
 3825:     }
 3826:   } else {
 3827:     $prevattempts=
 3828: 	  &start_data_table().&start_data_table_row().
 3829: 	  '<td>'.&mt('No data.').'</td>'.
 3830: 	  &end_data_table_row().&end_data_table();
 3831:   }
 3832: }
 3833: 
 3834: sub format_previous_attempt_value {
 3835:     my ($key,$value) = @_;
 3836:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3837: 	$value = &Apache::lonlocal::locallocaltime($value);
 3838:     } elsif (ref($value) eq 'ARRAY') {
 3839: 	$value = '('.join(', ', @{ $value }).')';
 3840:     } elsif ($key =~ /answerstring$/) {
 3841:         my %answers = &Apache::lonnet::str2hash($value);
 3842:         my @anskeys = sort(keys(%answers));
 3843:         if (@anskeys == 1) {
 3844:             my $answer = $answers{$anskeys[0]};
 3845:             if ($answer =~ m{\0}) {
 3846:                 $answer =~ s{\0}{,}g;
 3847:             }
 3848:             my $tag_internal_answer_name = 'INTERNAL';
 3849:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3850:                 $value = $answer; 
 3851:             } else {
 3852:                 $value = $anskeys[0].'='.$answer;
 3853:             }
 3854:         } else {
 3855:             foreach my $ans (@anskeys) {
 3856:                 my $answer = $answers{$ans};
 3857:                 if ($answer =~ m{\0}) {
 3858:                     $answer =~ s{\0}{,}g;
 3859:                 }
 3860:                 $value .=  $ans.'='.$answer.'<br />';;
 3861:             } 
 3862:         }
 3863:     } else {
 3864: 	$value = &unescape($value);
 3865:     }
 3866:     return $value;
 3867: }
 3868: 
 3869: 
 3870: sub relative_to_absolute {
 3871:     my ($url,$output)=@_;
 3872:     my $parser=HTML::TokeParser->new(\$output);
 3873:     my $token;
 3874:     my $thisdir=$url;
 3875:     my @rlinks=();
 3876:     while ($token=$parser->get_token) {
 3877: 	if ($token->[0] eq 'S') {
 3878: 	    if ($token->[1] eq 'a') {
 3879: 		if ($token->[2]->{'href'}) {
 3880: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3881: 		}
 3882: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3883: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3884: 	    } elsif ($token->[1] eq 'base') {
 3885: 		$thisdir=$token->[2]->{'href'};
 3886: 	    }
 3887: 	}
 3888:     }
 3889:     $thisdir=~s-/[^/]*$--;
 3890:     foreach my $link (@rlinks) {
 3891: 	unless (($link=~/^https?\:\/\//i) ||
 3892: 		($link=~/^\//) ||
 3893: 		($link=~/^javascript:/i) ||
 3894: 		($link=~/^mailto:/i) ||
 3895: 		($link=~/^\#/)) {
 3896: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3897: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3898: 	}
 3899:     }
 3900: # -------------------------------------------------- Deal with Applet codebases
 3901:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3902:     return $output;
 3903: }
 3904: 
 3905: =pod
 3906: 
 3907: =item * &get_student_view()
 3908: 
 3909: show a snapshot of what student was looking at
 3910: 
 3911: =cut
 3912: 
 3913: sub get_student_view {
 3914:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3915:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3916:   my (%form);
 3917:   my @elements=('symb','courseid','domain','username');
 3918:   foreach my $element (@elements) {
 3919:       $form{'grade_'.$element}=eval '$'.$element #'
 3920:   }
 3921:   if (defined($moreenv)) {
 3922:       %form=(%form,%{$moreenv});
 3923:   }
 3924:   if (defined($target)) { $form{'grade_target'} = $target; }
 3925:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3926:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3927:   $userview=~s/\<body[^\>]*\>//gi;
 3928:   $userview=~s/\<\/body\>//gi;
 3929:   $userview=~s/\<html\>//gi;
 3930:   $userview=~s/\<\/html\>//gi;
 3931:   $userview=~s/\<head\>//gi;
 3932:   $userview=~s/\<\/head\>//gi;
 3933:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3934:   $userview=&relative_to_absolute($feedurl,$userview);
 3935:   if (wantarray) {
 3936:      return ($userview,$response);
 3937:   } else {
 3938:      return $userview;
 3939:   }
 3940: }
 3941: 
 3942: sub get_student_view_with_retries {
 3943:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3944: 
 3945:     my $ok = 0;                 # True if we got a good response.
 3946:     my $content;
 3947:     my $response;
 3948: 
 3949:     # Try to get the student_view done. within the retries count:
 3950:     
 3951:     do {
 3952:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3953:          $ok      = $response->is_success;
 3954:          if (!$ok) {
 3955:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3956:          }
 3957:          $retries--;
 3958:     } while (!$ok && ($retries > 0));
 3959:     
 3960:     if (!$ok) {
 3961:        $content = '';          # On error return an empty content.
 3962:     }
 3963:     if (wantarray) {
 3964:        return ($content, $response);
 3965:     } else {
 3966:        return $content;
 3967:     }
 3968: }
 3969: 
 3970: =pod
 3971: 
 3972: =item * &get_student_answers() 
 3973: 
 3974: show a snapshot of how student was answering problem
 3975: 
 3976: =cut
 3977: 
 3978: sub get_student_answers {
 3979:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3980:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3981:   my (%moreenv);
 3982:   my @elements=('symb','courseid','domain','username');
 3983:   foreach my $element (@elements) {
 3984:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3985:   }
 3986:   $moreenv{'grade_target'}='answer';
 3987:   %moreenv=(%form,%moreenv);
 3988:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3989:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3990:   return $userview;
 3991: }
 3992: 
 3993: =pod
 3994: 
 3995: =item * &submlink()
 3996: 
 3997: Inputs: $text $uname $udom $symb $target
 3998: 
 3999: Returns: A link to grades.pm such as to see the SUBM view of a student
 4000: 
 4001: =cut
 4002: 
 4003: ###############################################
 4004: sub submlink {
 4005:     my ($text,$uname,$udom,$symb,$target)=@_;
 4006:     if (!($uname && $udom)) {
 4007: 	(my $cursymb, my $courseid,$udom,$uname)=
 4008: 	    &Apache::lonnet::whichuser($symb);
 4009: 	if (!$symb) { $symb=$cursymb; }
 4010:     }
 4011:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4012:     $symb=&escape($symb);
 4013:     if ($target) { $target=" target=\"$target\""; }
 4014:     return
 4015:         '<a href="/adm/grades?command=submission'.
 4016:         '&amp;symb='.$symb.
 4017:         '&amp;student='.$uname.
 4018:         '&amp;userdom='.$udom.'"'.
 4019:         $target.'>'.$text.'</a>';
 4020: }
 4021: ##############################################
 4022: 
 4023: =pod
 4024: 
 4025: =item * &pgrdlink()
 4026: 
 4027: Inputs: $text $uname $udom $symb $target
 4028: 
 4029: Returns: A link to grades.pm such as to see the PGRD view of a student
 4030: 
 4031: =cut
 4032: 
 4033: ###############################################
 4034: sub pgrdlink {
 4035:     my $link=&submlink(@_);
 4036:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4037:     return $link;
 4038: }
 4039: ##############################################
 4040: 
 4041: =pod
 4042: 
 4043: =item * &pprmlink()
 4044: 
 4045: Inputs: $text $uname $udom $symb $target
 4046: 
 4047: Returns: A link to parmset.pm such as to see the PPRM view of a
 4048: student and a specific resource
 4049: 
 4050: =cut
 4051: 
 4052: ###############################################
 4053: sub pprmlink {
 4054:     my ($text,$uname,$udom,$symb,$target)=@_;
 4055:     if (!($uname && $udom)) {
 4056: 	(my $cursymb, my $courseid,$udom,$uname)=
 4057: 	    &Apache::lonnet::whichuser($symb);
 4058: 	if (!$symb) { $symb=$cursymb; }
 4059:     }
 4060:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4061:     $symb=&escape($symb);
 4062:     if ($target) { $target="target=\"$target\""; }
 4063:     return '<a href="/adm/parmset?command=set&amp;'.
 4064: 	'symb='.$symb.'&amp;uname='.$uname.
 4065: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4066: }
 4067: ##############################################
 4068: 
 4069: =pod
 4070: 
 4071: =back
 4072: 
 4073: =cut
 4074: 
 4075: ###############################################
 4076: 
 4077: 
 4078: sub timehash {
 4079:     my ($thistime) = @_;
 4080:     my $timezone = &Apache::lonlocal::gettimezone();
 4081:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4082:                      ->set_time_zone($timezone);
 4083:     my $wday = $dt->day_of_week();
 4084:     if ($wday == 7) { $wday = 0; }
 4085:     return ( 'second' => $dt->second(),
 4086:              'minute' => $dt->minute(),
 4087:              'hour'   => $dt->hour(),
 4088:              'day'     => $dt->day_of_month(),
 4089:              'month'   => $dt->month(),
 4090:              'year'    => $dt->year(),
 4091:              'weekday' => $wday,
 4092:              'dayyear' => $dt->day_of_year(),
 4093:              'dlsav'   => $dt->is_dst() );
 4094: }
 4095: 
 4096: sub utc_string {
 4097:     my ($date)=@_;
 4098:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4099: }
 4100: 
 4101: sub maketime {
 4102:     my %th=@_;
 4103:     my ($epoch_time,$timezone,$dt);
 4104:     $timezone = &Apache::lonlocal::gettimezone();
 4105:     eval {
 4106:         $dt = DateTime->new( year   => $th{'year'},
 4107:                              month  => $th{'month'},
 4108:                              day    => $th{'day'},
 4109:                              hour   => $th{'hour'},
 4110:                              minute => $th{'minute'},
 4111:                              second => $th{'second'},
 4112:                              time_zone => $timezone,
 4113:                          );
 4114:     };
 4115:     if (!$@) {
 4116:         $epoch_time = $dt->epoch;
 4117:         if ($epoch_time) {
 4118:             return $epoch_time;
 4119:         }
 4120:     }
 4121:     return POSIX::mktime(
 4122:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4123:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4124: }
 4125: 
 4126: #########################################
 4127: 
 4128: sub findallcourses {
 4129:     my ($roles,$uname,$udom) = @_;
 4130:     my %roles;
 4131:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4132:     my %courses;
 4133:     my $now=time;
 4134:     if (!defined($uname)) {
 4135:         $uname = $env{'user.name'};
 4136:     }
 4137:     if (!defined($udom)) {
 4138:         $udom = $env{'user.domain'};
 4139:     }
 4140:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4141:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4142:         if (!%roles) {
 4143:             %roles = (
 4144:                        cc => 1,
 4145:                        co => 1,
 4146:                        in => 1,
 4147:                        ep => 1,
 4148:                        ta => 1,
 4149:                        cr => 1,
 4150:                        st => 1,
 4151:              );
 4152:         }
 4153:         foreach my $entry (keys(%roleshash)) {
 4154:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4155:             if ($trole =~ /^cr/) { 
 4156:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4157:             } else {
 4158:                 next if (!exists($roles{$trole}));
 4159:             }
 4160:             if ($tend) {
 4161:                 next if ($tend < $now);
 4162:             }
 4163:             if ($tstart) {
 4164:                 next if ($tstart > $now);
 4165:             }
 4166:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4167:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4168:             my $value = $trole.'/'.$cdom.'/';
 4169:             if ($secpart eq '') {
 4170:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4171:                 $sec = 'none';
 4172:                 $value .= $cnum.'/';
 4173:             } else {
 4174:                 $cnum = $cnumpart;
 4175:                 ($sec,$role) = split(/_/,$secpart);
 4176:                 $value .= $cnum.'/'.$sec;
 4177:             }
 4178:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4179:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4180:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4181:                 }
 4182:             } else {
 4183:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4184:             }
 4185:         }
 4186:     } else {
 4187:         foreach my $key (keys(%env)) {
 4188: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4189:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4190: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4191: 	        next if ($role eq 'ca' || $role eq 'aa');
 4192: 	        next if (%roles && !exists($roles{$role}));
 4193: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4194:                 my $active=1;
 4195:                 if ($starttime) {
 4196: 		    if ($now<$starttime) { $active=0; }
 4197:                 }
 4198:                 if ($endtime) {
 4199:                     if ($now>$endtime) { $active=0; }
 4200:                 }
 4201:                 if ($active) {
 4202:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4203:                     if ($sec eq '') {
 4204:                         $sec = 'none';
 4205:                     } else {
 4206:                         $value .= $sec;
 4207:                     }
 4208:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4209:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4210:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4211:                         }
 4212:                     } else {
 4213:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4214:                     }
 4215:                 }
 4216:             }
 4217:         }
 4218:     }
 4219:     return %courses;
 4220: }
 4221: 
 4222: ###############################################
 4223: 
 4224: sub blockcheck {
 4225:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4226: 
 4227:     if (!defined($udom)) {
 4228:         $udom = $env{'user.domain'};
 4229:     }
 4230:     if (!defined($uname)) {
 4231:         $uname = $env{'user.name'};
 4232:     }
 4233: 
 4234:     # If uname and udom are for a course, check for blocks in the course.
 4235: 
 4236:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4237:         my ($startblock,$endblock,$triggerblock) = 
 4238:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4239:         return ($startblock,$endblock,$triggerblock);
 4240:     }
 4241: 
 4242:     my $startblock = 0;
 4243:     my $endblock = 0;
 4244:     my $triggerblock = '';
 4245:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4246: 
 4247:     # If uname is for a user, and activity is course-specific, i.e.,
 4248:     # boards, chat or groups, check for blocking in current course only.
 4249: 
 4250:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4251:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4252:         foreach my $key (keys(%live_courses)) {
 4253:             if ($key ne $env{'request.course.id'}) {
 4254:                 delete($live_courses{$key});
 4255:             }
 4256:         }
 4257:     }
 4258: 
 4259:     my $otheruser = 0;
 4260:     my %own_courses;
 4261:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4262:         # Resource belongs to user other than current user.
 4263:         $otheruser = 1;
 4264:         # Gather courses for current user
 4265:         %own_courses = 
 4266:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4267:     }
 4268: 
 4269:     # Gather active course roles - course coordinator, instructor, 
 4270:     # exam proctor, ta, student, or custom role.
 4271: 
 4272:     foreach my $course (keys(%live_courses)) {
 4273:         my ($cdom,$cnum);
 4274:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4275:             $cdom = $env{'course.'.$course.'.domain'};
 4276:             $cnum = $env{'course.'.$course.'.num'};
 4277:         } else {
 4278:             ($cdom,$cnum) = split(/_/,$course); 
 4279:         }
 4280:         my $no_ownblock = 0;
 4281:         my $no_userblock = 0;
 4282:         if ($otheruser && $activity ne 'com') {
 4283:             # Check if current user has 'evb' priv for this
 4284:             if (defined($own_courses{$course})) {
 4285:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4286:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4287:                     if ($sec ne 'none') {
 4288:                         $checkrole .= '/'.$sec;
 4289:                     }
 4290:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4291:                         $no_ownblock = 1;
 4292:                         last;
 4293:                     }
 4294:                 }
 4295:             }
 4296:             # if they have 'evb' priv and are currently not playing student
 4297:             next if (($no_ownblock) &&
 4298:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4299:         }
 4300:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4301:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4302:             if ($sec ne 'none') {
 4303:                 $checkrole .= '/'.$sec;
 4304:             }
 4305:             if ($otheruser) {
 4306:                 # Resource belongs to user other than current user.
 4307:                 # Assemble privs for that user, and check for 'evb' priv.
 4308:                 my (%allroles,%userroles);
 4309:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4310:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4311:                         my ($trole,$tdom,$tnum,$tsec);
 4312:                         if ($entry =~ /^cr/) {
 4313:                             ($trole,$tdom,$tnum,$tsec) = 
 4314:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4315:                         } else {
 4316:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4317:                         }
 4318:                         my ($spec,$area,$trest);
 4319:                         $area = '/'.$tdom.'/'.$tnum;
 4320:                         $trest = $tnum;
 4321:                         if ($tsec ne '') {
 4322:                             $area .= '/'.$tsec;
 4323:                             $trest .= '/'.$tsec;
 4324:                         }
 4325:                         $spec = $trole.'.'.$area;
 4326:                         if ($trole =~ /^cr/) {
 4327:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4328:                                                               $tdom,$spec,$trest,$area);
 4329:                         } else {
 4330:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4331:                                                                 $tdom,$spec,$trest,$area);
 4332:                         }
 4333:                     }
 4334:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4335:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4336:                         if ($1) {
 4337:                             $no_userblock = 1;
 4338:                             last;
 4339:                         }
 4340:                     }
 4341:                 }
 4342:             } else {
 4343:                 # Resource belongs to current user
 4344:                 # Check for 'evb' priv via lonnet::allowed().
 4345:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4346:                     $no_ownblock = 1;
 4347:                     last;
 4348:                 }
 4349:             }
 4350:         }
 4351:         # if they have the evb priv and are currently not playing student
 4352:         next if (($no_ownblock) &&
 4353:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4354:         next if ($no_userblock);
 4355: 
 4356:         # Retrieve blocking times and identity of locker for course
 4357:         # of specified user, unless user has 'evb' privilege.
 4358:         
 4359:         my ($start,$end,$trigger) = 
 4360:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4361:         if (($start != 0) && 
 4362:             (($startblock == 0) || ($startblock > $start))) {
 4363:             $startblock = $start;
 4364:             if ($trigger ne '') {
 4365:                 $triggerblock = $trigger;
 4366:             }
 4367:         }
 4368:         if (($end != 0)  &&
 4369:             (($endblock == 0) || ($endblock < $end))) {
 4370:             $endblock = $end;
 4371:             if ($trigger ne '') {
 4372:                 $triggerblock = $trigger;
 4373:             }
 4374:         }
 4375:     }
 4376:     return ($startblock,$endblock,$triggerblock);
 4377: }
 4378: 
 4379: sub get_blocks {
 4380:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4381:     my $startblock = 0;
 4382:     my $endblock = 0;
 4383:     my $triggerblock = '';
 4384:     my $course = $cdom.'_'.$cnum;
 4385:     $setters->{$course} = {};
 4386:     $setters->{$course}{'staff'} = [];
 4387:     $setters->{$course}{'times'} = [];
 4388:     $setters->{$course}{'triggers'} = [];
 4389:     my (@blockers,%triggered);
 4390:     my $now = time;
 4391:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4392:     if ($activity eq 'docs') {
 4393:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4394:         foreach my $block (@blockers) {
 4395:             if ($block =~ /^firstaccess____(.+)$/) {
 4396:                 my $item = $1;
 4397:                 my $type = 'map';
 4398:                 my $timersymb = $item;
 4399:                 if ($item eq 'course') {
 4400:                     $type = 'course';
 4401:                 } elsif ($item =~ /___\d+___/) {
 4402:                     $type = 'resource';
 4403:                 } else {
 4404:                     $timersymb = &Apache::lonnet::symbread($item);
 4405:                 }
 4406:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4407:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4408:                 $triggered{$block} = {
 4409:                                        start => $start,
 4410:                                        end   => $end,
 4411:                                        type  => $type,
 4412:                                      };
 4413:             }
 4414:         }
 4415:     } else {
 4416:         foreach my $block (keys(%commblocks)) {
 4417:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4418:                 my ($start,$end) = ($1,$2);
 4419:                 if ($start <= time && $end >= time) {
 4420:                     if (ref($commblocks{$block}) eq 'HASH') {
 4421:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4422:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4423:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4424:                                     push(@blockers,$block);
 4425:                                 }
 4426:                             }
 4427:                         }
 4428:                     }
 4429:                 }
 4430:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4431:                 my $item = $1;
 4432:                 my $timersymb = $item; 
 4433:                 my $type = 'map';
 4434:                 if ($item eq 'course') {
 4435:                     $type = 'course';
 4436:                 } elsif ($item =~ /___\d+___/) {
 4437:                     $type = 'resource';
 4438:                 } else {
 4439:                     $timersymb = &Apache::lonnet::symbread($item);
 4440:                 }
 4441:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4442:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4443:                 if ($start && $end) {
 4444:                     if (($start <= time) && ($end >= time)) {
 4445:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4446:                             push(@blockers,$block);
 4447:                             $triggered{$block} = {
 4448:                                                    start => $start,
 4449:                                                    end   => $end,
 4450:                                                    type  => $type,
 4451:                                                  };
 4452:                         }
 4453:                     }
 4454:                 }
 4455:             }
 4456:         }
 4457:     }
 4458:     foreach my $blocker (@blockers) {
 4459:         my ($staff_name,$staff_dom,$title,$blocks) =
 4460:             &parse_block_record($commblocks{$blocker});
 4461:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4462:         my ($start,$end,$triggertype);
 4463:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4464:             ($start,$end) = ($1,$2);
 4465:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4466:             $start = $triggered{$blocker}{'start'};
 4467:             $end = $triggered{$blocker}{'end'};
 4468:             $triggertype = $triggered{$blocker}{'type'};
 4469:         }
 4470:         if ($start) {
 4471:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4472:             if ($triggertype) {
 4473:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4474:             } else {
 4475:                 push(@{$$setters{$course}{'triggers'}},0);
 4476:             }
 4477:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4478:                 $startblock = $start;
 4479:                 if ($triggertype) {
 4480:                     $triggerblock = $blocker;
 4481:                 }
 4482:             }
 4483:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4484:                $endblock = $end;
 4485:                if ($triggertype) {
 4486:                    $triggerblock = $blocker;
 4487:                }
 4488:             }
 4489:         }
 4490:     }
 4491:     return ($startblock,$endblock,$triggerblock);
 4492: }
 4493: 
 4494: sub parse_block_record {
 4495:     my ($record) = @_;
 4496:     my ($setuname,$setudom,$title,$blocks);
 4497:     if (ref($record) eq 'HASH') {
 4498:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4499:         $title = &unescape($record->{'event'});
 4500:         $blocks = $record->{'blocks'};
 4501:     } else {
 4502:         my @data = split(/:/,$record,3);
 4503:         if (scalar(@data) eq 2) {
 4504:             $title = $data[1];
 4505:             ($setuname,$setudom) = split(/@/,$data[0]);
 4506:         } else {
 4507:             ($setuname,$setudom,$title) = @data;
 4508:         }
 4509:         $blocks = { 'com' => 'on' };
 4510:     }
 4511:     return ($setuname,$setudom,$title,$blocks);
 4512: }
 4513: 
 4514: sub blocking_status {
 4515:     my ($activity,$uname,$udom,$url) = @_;
 4516:     my %setters;
 4517: 
 4518: # check for active blocking
 4519:     my ($startblock,$endblock,$triggerblock) = 
 4520:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4521:     my $blocked = 0;
 4522:     if ($startblock && $endblock) {
 4523:         $blocked = 1;
 4524:     }
 4525: 
 4526: # caller just wants to know whether a block is active
 4527:     if (!wantarray) { return $blocked; }
 4528: 
 4529: # build a link to a popup window containing the details
 4530:     my $querystring  = "?activity=$activity";
 4531: # $uname and $udom decide whose portfolio the user is trying to look at
 4532:     if ($activity eq 'port') {
 4533:         $querystring .= "&amp;udom=$udom"      if $udom;
 4534:         $querystring .= "&amp;uname=$uname"    if $uname;
 4535:     } elsif ($activity eq 'docs') {
 4536:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4537:     }
 4538: 
 4539:     my $output .= <<'END_MYBLOCK';
 4540: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4541:     var options = "width=" + w + ",height=" + h + ",";
 4542:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4543:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4544:     var newWin = window.open(url, wdwName, options);
 4545:     newWin.focus();
 4546: }
 4547: END_MYBLOCK
 4548: 
 4549:     $output = Apache::lonhtmlcommon::scripttag($output);
 4550:   
 4551:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4552:     my $text = &mt('Communication Blocked');
 4553:     if ($activity eq 'docs') {
 4554:         $text = &mt('Content Access Blocked');
 4555:     } elsif ($activity eq 'printout') {
 4556:         $text = &mt('Printing Blocked');
 4557:     }
 4558:     $output .= <<"END_BLOCK";
 4559: <div class='LC_comblock'>
 4560:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4561:   title='$text'>
 4562:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4563:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4564:   title='$text'>$text</a>
 4565: </div>
 4566: 
 4567: END_BLOCK
 4568: 
 4569:     return ($blocked, $output);
 4570: }
 4571: 
 4572: ###############################################
 4573: 
 4574: sub check_ip_acc {
 4575:     my ($acc)=@_;
 4576:     &Apache::lonxml::debug("acc is $acc");
 4577:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4578:         return 1;
 4579:     }
 4580:     my $allowed=0;
 4581:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4582: 
 4583:     my $name;
 4584:     foreach my $pattern (split(',',$acc)) {
 4585:         $pattern =~ s/^\s*//;
 4586:         $pattern =~ s/\s*$//;
 4587:         if ($pattern =~ /\*$/) {
 4588:             #35.8.*
 4589:             $pattern=~s/\*//;
 4590:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4591:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4592:             #35.8.3.[34-56]
 4593:             my $low=$2;
 4594:             my $high=$3;
 4595:             $pattern=$1;
 4596:             if ($ip =~ /^\Q$pattern\E/) {
 4597:                 my $last=(split(/\./,$ip))[3];
 4598:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4599:             }
 4600:         } elsif ($pattern =~ /^\*/) {
 4601:             #*.msu.edu
 4602:             $pattern=~s/\*//;
 4603:             if (!defined($name)) {
 4604:                 use Socket;
 4605:                 my $netaddr=inet_aton($ip);
 4606:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4607:             }
 4608:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4609:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4610:             #127.0.0.1
 4611:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4612:         } else {
 4613:             #some.name.com
 4614:             if (!defined($name)) {
 4615:                 use Socket;
 4616:                 my $netaddr=inet_aton($ip);
 4617:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4618:             }
 4619:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4620:         }
 4621:         if ($allowed) { last; }
 4622:     }
 4623:     return $allowed;
 4624: }
 4625: 
 4626: ###############################################
 4627: 
 4628: =pod
 4629: 
 4630: =head1 Domain Template Functions
 4631: 
 4632: =over 4
 4633: 
 4634: =item * &determinedomain()
 4635: 
 4636: Inputs: $domain (usually will be undef)
 4637: 
 4638: Returns: Determines which domain should be used for designs
 4639: 
 4640: =cut
 4641: 
 4642: ###############################################
 4643: sub determinedomain {
 4644:     my $domain=shift;
 4645:     if (! $domain) {
 4646:         # Determine domain if we have not been given one
 4647:         $domain = &Apache::lonnet::default_login_domain();
 4648:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4649:         if ($env{'request.role.domain'}) { 
 4650:             $domain=$env{'request.role.domain'}; 
 4651:         }
 4652:     }
 4653:     return $domain;
 4654: }
 4655: ###############################################
 4656: 
 4657: sub devalidate_domconfig_cache {
 4658:     my ($udom)=@_;
 4659:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4660: }
 4661: 
 4662: # ---------------------- Get domain configuration for a domain
 4663: sub get_domainconf {
 4664:     my ($udom) = @_;
 4665:     my $cachetime=1800;
 4666:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4667:     if (defined($cached)) { return %{$result}; }
 4668: 
 4669:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4670: 					     ['login','rolecolors','autoenroll'],$udom);
 4671:     my (%designhash,%legacy);
 4672:     if (keys(%domconfig) > 0) {
 4673:         if (ref($domconfig{'login'}) eq 'HASH') {
 4674:             if (keys(%{$domconfig{'login'}})) {
 4675:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4676:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4677:                         if ($key eq 'loginvia') {
 4678:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4679:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4680:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4681:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4682:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4683:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4684:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4685: 
 4686:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4687:                                             } else {
 4688:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4689:                                             }
 4690:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4691:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4692:                                             }
 4693:                                         }
 4694:                                     }
 4695:                                 }
 4696:                             }
 4697:                         } else {
 4698:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4699:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4700:                                     $domconfig{'login'}{$key}{$img};
 4701:                             }
 4702:                         }
 4703:                     } else {
 4704:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4705:                     }
 4706:                 }
 4707:             } else {
 4708:                 $legacy{'login'} = 1;
 4709:             }
 4710:         } else {
 4711:             $legacy{'login'} = 1;
 4712:         }
 4713:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4714:             if (keys(%{$domconfig{'rolecolors'}})) {
 4715:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4716:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4717:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4718:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4719:                         }
 4720:                     }
 4721:                 }
 4722:             } else {
 4723:                 $legacy{'rolecolors'} = 1;
 4724:             }
 4725:         } else {
 4726:             $legacy{'rolecolors'} = 1;
 4727:         }
 4728:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4729:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4730:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4731:             }
 4732:         }
 4733:         if (keys(%legacy) > 0) {
 4734:             my %legacyhash = &get_legacy_domconf($udom);
 4735:             foreach my $item (keys(%legacyhash)) {
 4736:                 if ($item =~ /^\Q$udom\E\.login/) {
 4737:                     if ($legacy{'login'}) { 
 4738:                         $designhash{$item} = $legacyhash{$item};
 4739:                     }
 4740:                 } else {
 4741:                     if ($legacy{'rolecolors'}) {
 4742:                         $designhash{$item} = $legacyhash{$item};
 4743:                     }
 4744:                 }
 4745:             }
 4746:         }
 4747:     } else {
 4748:         %designhash = &get_legacy_domconf($udom); 
 4749:     }
 4750:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4751: 				  $cachetime);
 4752:     return %designhash;
 4753: }
 4754: 
 4755: sub get_legacy_domconf {
 4756:     my ($udom) = @_;
 4757:     my %legacyhash;
 4758:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4759:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4760:     if (-e $designfile) {
 4761:         if ( open (my $fh,"<$designfile") ) {
 4762:             while (my $line = <$fh>) {
 4763:                 next if ($line =~ /^\#/);
 4764:                 chomp($line);
 4765:                 my ($key,$val)=(split(/\=/,$line));
 4766:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4767:             }
 4768:             close($fh);
 4769:         }
 4770:     }
 4771:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4772:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4773:     }
 4774:     return %legacyhash;
 4775: }
 4776: 
 4777: =pod
 4778: 
 4779: =item * &domainlogo()
 4780: 
 4781: Inputs: $domain (usually will be undef)
 4782: 
 4783: Returns: A link to a domain logo, if the domain logo exists.
 4784: If the domain logo does not exist, a description of the domain.
 4785: 
 4786: =cut
 4787: 
 4788: ###############################################
 4789: sub domainlogo {
 4790:     my $domain = &determinedomain(shift);
 4791:     my %designhash = &get_domainconf($domain);    
 4792:     # See if there is a logo
 4793:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4794:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4795:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4796: 	    if ($imgsrc =~ m{^/res/}) {
 4797: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4798: 		&Apache::lonnet::repcopy($local_name);
 4799: 	    }
 4800: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4801:         } 
 4802:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4803:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4804:         return &Apache::lonnet::domain($domain,'description');
 4805:     } else {
 4806:         return '';
 4807:     }
 4808: }
 4809: ##############################################
 4810: 
 4811: =pod
 4812: 
 4813: =item * &designparm()
 4814: 
 4815: Inputs: $which parameter; $domain (usually will be undef)
 4816: 
 4817: Returns: value of designparamter $which
 4818: 
 4819: =cut
 4820: 
 4821: 
 4822: ##############################################
 4823: sub designparm {
 4824:     my ($which,$domain)=@_;
 4825:     if (exists($env{'environment.color.'.$which})) {
 4826:         return $env{'environment.color.'.$which};
 4827:     }
 4828:     $domain=&determinedomain($domain);
 4829:     my %domdesign;
 4830:     unless ($domain eq 'public') {
 4831:         %domdesign = &get_domainconf($domain);
 4832:     }
 4833:     my $output;
 4834:     if ($domdesign{$domain.'.'.$which} ne '') {
 4835:         $output = $domdesign{$domain.'.'.$which};
 4836:     } else {
 4837:         $output = $defaultdesign{$which};
 4838:     }
 4839:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4840:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4841:         if ($output =~ m{^/(adm|res)/}) {
 4842:             if ($output =~ m{^/res/}) {
 4843:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4844:                 &Apache::lonnet::repcopy($local_name);
 4845:             }
 4846:             $output = &lonhttpdurl($output);
 4847:         }
 4848:     }
 4849:     return $output;
 4850: }
 4851: 
 4852: ##############################################
 4853: =pod
 4854: 
 4855: =item * &authorspace()
 4856: 
 4857: Inputs: $url (usually will be undef).
 4858: 
 4859: Returns: Path to Authoring Space containing the resource or 
 4860:          directory being viewed (or for which action is being taken). 
 4861:          If $url is provided, and begins /priv/<domain>/<uname>
 4862:          the path will be that portion of the $context argument.
 4863:          Otherwise the path will be for the author space of the current
 4864:          user when the current role is author, or for that of the 
 4865:          co-author/assistant co-author space when the current role 
 4866:          is co-author or assistant co-author.
 4867: 
 4868: =cut
 4869: 
 4870: sub authorspace {
 4871:     my ($url) = @_;
 4872:     if ($url ne '') {
 4873:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4874:            return $1;
 4875:         }
 4876:     }
 4877:     my $caname = '';
 4878:     my $cadom = '';
 4879:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4880:         ($cadom,$caname) =
 4881:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4882:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4883:         $caname = $env{'user.name'};
 4884:         $cadom = $env{'user.domain'};
 4885:     }
 4886:     if (($caname ne '') && ($cadom ne '')) {
 4887:         return "/priv/$cadom/$caname/";
 4888:     }
 4889:     return;
 4890: }
 4891: 
 4892: ##############################################
 4893: =pod
 4894: 
 4895: =item * &head_subbox()
 4896: 
 4897: Inputs: $content (contains HTML code with page functions, etc.)
 4898: 
 4899: Returns: HTML div with $content
 4900:          To be included in page header
 4901: 
 4902: =cut
 4903: 
 4904: sub head_subbox {
 4905:     my ($content)=@_;
 4906:     my $output =
 4907:         '<div class="LC_head_subbox">'
 4908:        .$content
 4909:        .'</div>'
 4910: }
 4911: 
 4912: ##############################################
 4913: =pod
 4914: 
 4915: =item * &CSTR_pageheader()
 4916: 
 4917: Input: (optional) filename from which breadcrumb trail is built.
 4918:        In most cases no input as needed, as $env{'request.filename'}
 4919:        is appropriate for use in building the breadcrumb trail.
 4920: 
 4921: Returns: HTML div with CSTR path and recent box
 4922:          To be included on Authoring Space pages
 4923: 
 4924: =cut
 4925: 
 4926: sub CSTR_pageheader {
 4927:     my ($trailfile) = @_;
 4928:     if ($trailfile eq '') {
 4929:         $trailfile = $env{'request.filename'};
 4930:     }
 4931: 
 4932: # this is for resources; directories have customtitle, and crumbs
 4933: # and select recent are created in lonpubdir.pm
 4934: 
 4935:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4936:     my ($udom,$uname,$thisdisfn)=
 4937:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 4938:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4939:     $formaction =~ s{/+}{/}g;
 4940: 
 4941:     my $parentpath = '';
 4942:     my $lastitem = '';
 4943:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4944:         $parentpath = $1;
 4945:         $lastitem = $2;
 4946:     } else {
 4947:         $lastitem = $thisdisfn;
 4948:     }
 4949: 
 4950:     my $output =
 4951:          '<div>'
 4952:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4953:         .'<b>'.&mt('Authoring Space:').'</b> '
 4954:         .'<form name="dirs" method="post" action="'.$formaction
 4955:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4956:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 4957: 
 4958:     if ($lastitem) {
 4959:         $output .=
 4960:              '<span class="LC_filename">'
 4961:             .$lastitem
 4962:             .'</span>';
 4963:     }
 4964:     $output .=
 4965:          '<br />'
 4966:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4967:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4968:         .'</form>'
 4969:         .&Apache::lonmenu::constspaceform()
 4970:         .'</div>';
 4971: 
 4972:     return $output;
 4973: }
 4974: 
 4975: ###############################################
 4976: ###############################################
 4977: 
 4978: =pod
 4979: 
 4980: =back
 4981: 
 4982: =head1 HTML Helpers
 4983: 
 4984: =over 4
 4985: 
 4986: =item * &bodytag()
 4987: 
 4988: Returns a uniform header for LON-CAPA web pages.
 4989: 
 4990: Inputs: 
 4991: 
 4992: =over 4
 4993: 
 4994: =item * $title, A title to be displayed on the page.
 4995: 
 4996: =item * $function, the current role (can be undef).
 4997: 
 4998: =item * $addentries, extra parameters for the <body> tag.
 4999: 
 5000: =item * $bodyonly, if defined, only return the <body> tag.
 5001: 
 5002: =item * $domain, if defined, force a given domain.
 5003: 
 5004: =item * $forcereg, if page should register as content page (relevant for 
 5005:             text interface only)
 5006: 
 5007: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5008:                      navigational links
 5009: 
 5010: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5011: 
 5012: =item * $no_inline_link, if true and in remote mode, don't show the
 5013:          'Switch To Inline Menu' link
 5014: 
 5015: =item * $args, optional argument valid values are
 5016:             no_auto_mt_title -> prevents &mt()ing the title arg
 5017:             inherit_jsmath -> when creating popup window in a page,
 5018:                               should it have jsmath forced on by the
 5019:                               current page
 5020: 
 5021: =item * $advtoolsref, optional argument, ref to an array containing
 5022:             inlineremote items to be added in "Functions" menu below
 5023:             breadcrumbs.
 5024: 
 5025: =back
 5026: 
 5027: Returns: A uniform header for LON-CAPA web pages.  
 5028: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5029: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5030: other decorations will be returned.
 5031: 
 5032: =cut
 5033: 
 5034: sub bodytag {
 5035:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5036:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5037: 
 5038:     my $public;
 5039:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5040:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5041:         $public = 1;
 5042:     }
 5043:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5044: 
 5045:     $function = &get_users_function() if (!$function);
 5046:     my $img =    &designparm($function.'.img',$domain);
 5047:     my $font =   &designparm($function.'.font',$domain);
 5048:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5049: 
 5050:     my %design = ( 'style'   => 'margin-top: 0',
 5051: 		   'bgcolor' => $pgbg,
 5052: 		   'text'    => $font,
 5053:                    'alink'   => &designparm($function.'.alink',$domain),
 5054: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5055: 		   'link'    => &designparm($function.'.link',$domain),);
 5056:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5057: 
 5058:  # role and realm
 5059:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5060:     if ($role  eq 'ca') {
 5061:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5062:         $realm = &plainname($rname,$rdom);
 5063:     } 
 5064: # realm
 5065:     if ($env{'request.course.id'}) {
 5066:         if ($env{'request.role'} !~ /^cr/) {
 5067:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5068:         }
 5069:         if ($env{'request.course.sec'}) {
 5070:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5071:         }   
 5072: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5073:     } else {
 5074:         $role = &Apache::lonnet::plaintext($role);
 5075:     }
 5076: 
 5077:     if (!$realm) { $realm='&nbsp;'; }
 5078: 
 5079:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5080: 
 5081: # construct main body tag
 5082:     my $bodytag = "<body $extra_body_attr>".
 5083: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5084: 
 5085:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5086: 
 5087:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5088:         return $bodytag;
 5089:     }
 5090: 
 5091:     if ($public) {
 5092: 	undef($role);
 5093:     }
 5094:     
 5095:     my $titleinfo = '<h1>'.$title.'</h1>';
 5096:     #
 5097:     # Extra info if you are the DC
 5098:     my $dc_info = '';
 5099:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5100:                         $env{'course.'.$env{'request.course.id'}.
 5101:                                  '.domain'}.'/'})) {
 5102:         my $cid = $env{'request.course.id'};
 5103:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5104:         $dc_info =~ s/\s+$//;
 5105:     }
 5106: 
 5107:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5108: 
 5109:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5110: 
 5111: 
 5112: 
 5113:     my $funclist;
 5114:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5115:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions(), 'start')."\n".
 5116:                     Apache::lonmenu::serverform();
 5117:         my $forbodytag;
 5118:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5119:                                             $forcereg,$args->{'group'},
 5120:                                             $args->{'bread_crumbs'},
 5121:                                             $advtoolsref,'',\$forbodytag);
 5122:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5123:             $funclist = $forbodytag;
 5124:         }
 5125:     } else {
 5126: 
 5127:         #    if ($env{'request.state'} eq 'construct') {
 5128:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5129:         #    }
 5130: 
 5131:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5132:             Apache::lonmenu::utilityfunctions(), 'start');
 5133: 
 5134:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5135: 
 5136:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5137:             if ($dc_info) {
 5138:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5139:             }
 5140:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5141:                            <em>$realm</em> $dc_info</div>|;
 5142:             return $bodytag;
 5143:         }
 5144: 
 5145:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5146:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5147:         }
 5148: 
 5149:         $bodytag .= $right;
 5150: 
 5151:         if ($dc_info) {
 5152:             $dc_info = &dc_courseid_toggle($dc_info);
 5153:         }
 5154:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5155: 
 5156:         #don't show menus for public users
 5157:         if (!$public){
 5158:             $bodytag .= Apache::lonmenu::secondary_menu();
 5159:             $bodytag .= Apache::lonmenu::serverform();
 5160:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5161:             if ($env{'request.state'} eq 'construct') {
 5162:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5163:                                 $args->{'bread_crumbs'});
 5164:             } elsif ($forcereg) { 
 5165:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5166:                                                             $args->{'group'});
 5167:             } else {
 5168:                 my $forbodytag;
 5169:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5170:                                                     $forcereg,$args->{'group'},
 5171:                                                     $args->{'bread_crumbs'},
 5172:                                                     $advtoolsref,'',\$forbodytag);
 5173:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5174:                     $bodytag .= $forbodytag;
 5175:                 }
 5176:             }
 5177:         }else{
 5178:             # this is to seperate menu from content when there's no secondary
 5179:             # menu. Especially needed for public accessible ressources.
 5180:             $bodytag .= '<hr style="clear:both" />';
 5181:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5182:         }
 5183: 
 5184:         return $bodytag;
 5185:     }
 5186: 
 5187: #
 5188: # Top frame rendering, Remote is up
 5189: #
 5190: 
 5191:     my $imgsrc = $img;
 5192:     if ($img =~ /^\/adm/) {
 5193:         $imgsrc = &lonhttpdurl($img);
 5194:     }
 5195:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5196: 
 5197:     # Explicit link to get inline menu
 5198:     my $menu= ($no_inline_link?''
 5199:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5200: 
 5201:     if ($dc_info) {
 5202:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5203:     }
 5204: 
 5205:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5206:     unless ($public) {
 5207:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5208:                                 undef,'LC_menubuttons_link');
 5209:     }
 5210: 
 5211:     unless ($env{'form.inhibitmenu'}) {
 5212:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5213:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5214:                        <li>$menu</li>
 5215:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5216:     }
 5217:     if ($env{'request.state'} eq 'construct') {
 5218:         if (!$public){
 5219:             if ($env{'request.state'} eq 'construct') {
 5220:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5221:                                 &Apache::lonmenu::utilityfunctions(), 'start').
 5222:                             &Apache::lonhtmlcommon::scripttag('','end').
 5223:                             &Apache::lonmenu::innerregister($forcereg,
 5224:                                                             $args->{'bread_crumbs'});
 5225:             }
 5226:         }
 5227:     }
 5228:     return $bodytag."\n".$funclist;
 5229: }
 5230: 
 5231: sub dc_courseid_toggle {
 5232:     my ($dc_info) = @_;
 5233:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5234:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5235:            &mt('(More ...)').'</a></span>'.
 5236:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5237: }
 5238: 
 5239: sub make_attr_string {
 5240:     my ($register,$attr_ref) = @_;
 5241: 
 5242:     if ($attr_ref && !ref($attr_ref)) {
 5243: 	die("addentries Must be a hash ref ".
 5244: 	    join(':',caller(1))." ".
 5245: 	    join(':',caller(0))." ");
 5246:     }
 5247: 
 5248:     if ($register) {
 5249: 	my ($on_load,$on_unload);
 5250: 	foreach my $key (keys(%{$attr_ref})) {
 5251: 	    if      (lc($key) eq 'onload') {
 5252: 		$on_load.=$attr_ref->{$key}.';';
 5253: 		delete($attr_ref->{$key});
 5254: 
 5255: 	    } elsif (lc($key) eq 'onunload') {
 5256: 		$on_unload.=$attr_ref->{$key}.';';
 5257: 		delete($attr_ref->{$key});
 5258: 	    }
 5259: 	}
 5260:         if ($env{'environment.remote'} eq 'on') {
 5261:             $attr_ref->{'onload'}  =
 5262:                 &Apache::lonmenu::loadevents().  $on_load;
 5263:             $attr_ref->{'onunload'}=
 5264:                 &Apache::lonmenu::unloadevents().$on_unload;
 5265:         } else {  
 5266: 	    $attr_ref->{'onload'}  = $on_load;
 5267: 	    $attr_ref->{'onunload'}= $on_unload;
 5268:         }
 5269:     }
 5270: 
 5271:     my $attr_string;
 5272:     foreach my $attr (keys(%$attr_ref)) {
 5273: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5274:     }
 5275:     return $attr_string;
 5276: }
 5277: 
 5278: 
 5279: ###############################################
 5280: ###############################################
 5281: 
 5282: =pod
 5283: 
 5284: =item * &endbodytag()
 5285: 
 5286: Returns a uniform footer for LON-CAPA web pages.
 5287: 
 5288: Inputs: 1 - optional reference to an args hash
 5289: If in the hash, key for noredirectlink has a value which evaluates to true,
 5290: a 'Continue' link is not displayed if the page contains an
 5291: internal redirect in the <head></head> section,
 5292: i.e., $env{'internal.head.redirect'} exists   
 5293: 
 5294: =cut
 5295: 
 5296: sub endbodytag {
 5297:     my ($args) = @_;
 5298:     my $endbodytag;
 5299:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5300:         $endbodytag='</body>';
 5301:     }
 5302:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5303:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5304:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5305: 	    $endbodytag=
 5306: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5307: 	        &mt('Continue').'</a>'.
 5308: 	        $endbodytag;
 5309:         }
 5310:     }
 5311:     return $endbodytag;
 5312: }
 5313: 
 5314: =pod
 5315: 
 5316: =item * &standard_css()
 5317: 
 5318: Returns a style sheet
 5319: 
 5320: Inputs: (all optional)
 5321:             domain         -> force to color decorate a page for a specific
 5322:                                domain
 5323:             function       -> force usage of a specific rolish color scheme
 5324:             bgcolor        -> override the default page bgcolor
 5325: 
 5326: =cut
 5327: 
 5328: sub standard_css {
 5329:     my ($function,$domain,$bgcolor) = @_;
 5330:     $function  = &get_users_function() if (!$function);
 5331:     my $img    = &designparm($function.'.img',   $domain);
 5332:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5333:     my $font   = &designparm($function.'.font',  $domain);
 5334:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5335: #second colour for later usage
 5336:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5337:     my $pgbg_or_bgcolor =
 5338: 	         $bgcolor ||
 5339: 	         &designparm($function.'.pgbg',  $domain);
 5340:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5341:     my $alink  = &designparm($function.'.alink', $domain);
 5342:     my $vlink  = &designparm($function.'.vlink', $domain);
 5343:     my $link   = &designparm($function.'.link',  $domain);
 5344: 
 5345:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5346:     my $mono                 = 'monospace';
 5347:     my $data_table_head      = $sidebg;
 5348:     my $data_table_light     = '#FAFAFA';
 5349:     my $data_table_dark      = '#E0E0E0';
 5350:     my $data_table_darker    = '#CCCCCC';
 5351:     my $data_table_highlight = '#FFFF00';
 5352:     my $mail_new             = '#FFBB77';
 5353:     my $mail_new_hover       = '#DD9955';
 5354:     my $mail_read            = '#BBBB77';
 5355:     my $mail_read_hover      = '#999944';
 5356:     my $mail_replied         = '#AAAA88';
 5357:     my $mail_replied_hover   = '#888855';
 5358:     my $mail_other           = '#99BBBB';
 5359:     my $mail_other_hover     = '#669999';
 5360:     my $table_header         = '#DDDDDD';
 5361:     my $feedback_link_bg     = '#BBBBBB';
 5362:     my $lg_border_color      = '#C8C8C8';
 5363:     my $button_hover         = '#BF2317';
 5364: 
 5365:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5366:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5367:                                              : '0 3px 0 4px';
 5368: 
 5369: 
 5370:     return <<END;
 5371: 
 5372: /* needed for iframe to allow 100% height in FF */
 5373: body, html { 
 5374:     margin: 0;
 5375:     padding: 0 0.5%;
 5376:     height: 99%; /* to avoid scrollbars */
 5377: }
 5378: 
 5379: body {
 5380:   font-family: $sans;
 5381:   line-height:130%;
 5382:   font-size:0.83em;
 5383:   color:$font;
 5384: }
 5385: 
 5386: a:focus,
 5387: a:focus img {
 5388:   color: red;
 5389: }
 5390: 
 5391: form, .inline {
 5392:   display: inline;
 5393: }
 5394: 
 5395: .LC_right {
 5396:   text-align:right;
 5397: }
 5398: 
 5399: .LC_middle {
 5400:   vertical-align:middle;
 5401: }
 5402: 
 5403: .LC_floatleft {
 5404:   float: left;
 5405: }
 5406: 
 5407: .LC_floatright {
 5408:   float: right;
 5409: }
 5410: 
 5411: .LC_400Box {
 5412:   width:400px;
 5413: }
 5414: 
 5415: .LC_iframecontainer {
 5416:     width: 98%;
 5417:     margin: 0;
 5418:     position: fixed;
 5419:     top: 8.5em;
 5420:     bottom: 0;
 5421: }
 5422: 
 5423: .LC_iframecontainer iframe{
 5424:     border: none;
 5425:     width: 100%;
 5426:     height: 100%;
 5427: }
 5428: 
 5429: .LC_filename {
 5430:   font-family: $mono;
 5431:   white-space:pre;
 5432:   font-size: 120%;
 5433: }
 5434: 
 5435: .LC_fileicon {
 5436:   border: none;
 5437:   height: 1.3em;
 5438:   vertical-align: text-bottom;
 5439:   margin-right: 0.3em;
 5440:   text-decoration:none;
 5441: }
 5442: 
 5443: .LC_setting {
 5444:   text-decoration:underline;
 5445: }
 5446: 
 5447: .LC_error {
 5448:   color: red;
 5449: }
 5450: 
 5451: .LC_warning {
 5452:   color: darkorange;
 5453: }
 5454: 
 5455: .LC_diff_removed {
 5456:   color: red;
 5457: }
 5458: 
 5459: .LC_info,
 5460: .LC_success,
 5461: .LC_diff_added {
 5462:   color: green;
 5463: }
 5464: 
 5465: div.LC_confirm_box {
 5466:   background-color: #FAFAFA;
 5467:   border: 1px solid $lg_border_color;
 5468:   margin-right: 0;
 5469:   padding: 5px;
 5470: }
 5471: 
 5472: div.LC_confirm_box .LC_error img,
 5473: div.LC_confirm_box .LC_success img {
 5474:   vertical-align: middle;
 5475: }
 5476: 
 5477: .LC_icon {
 5478:   border: none;
 5479:   vertical-align: middle;
 5480: }
 5481: 
 5482: .LC_docs_spacer {
 5483:   width: 25px;
 5484:   height: 1px;
 5485:   border: none;
 5486: }
 5487: 
 5488: .LC_internal_info {
 5489:   color: #999999;
 5490: }
 5491: 
 5492: .LC_discussion {
 5493:   background: $data_table_dark;
 5494:   border: 1px solid black;
 5495:   margin: 2px;
 5496: }
 5497: 
 5498: .LC_disc_action_left {
 5499:   background: $sidebg;
 5500:   text-align: left;
 5501:   padding: 4px;
 5502:   margin: 2px;
 5503: }
 5504: 
 5505: .LC_disc_action_right {
 5506:   background: $sidebg;
 5507:   text-align: right;
 5508:   padding: 4px;
 5509:   margin: 2px;
 5510: }
 5511: 
 5512: .LC_disc_new_item {
 5513:   background: white;
 5514:   border: 2px solid red;
 5515:   margin: 4px;
 5516:   padding: 4px;
 5517: }
 5518: 
 5519: .LC_disc_old_item {
 5520:   background: white;
 5521:   margin: 4px;
 5522:   padding: 4px;
 5523: }
 5524: 
 5525: table.LC_pastsubmission {
 5526:   border: 1px solid black;
 5527:   margin: 2px;
 5528: }
 5529: 
 5530: table#LC_menubuttons {
 5531:   width: 100%;
 5532:   background: $pgbg;
 5533:   border: 2px;
 5534:   border-collapse: separate;
 5535:   padding: 0;
 5536: }
 5537: 
 5538: table#LC_title_bar a {
 5539:   color: $fontmenu;
 5540: }
 5541: 
 5542: table#LC_title_bar {
 5543:   clear: both;
 5544:   display: none;
 5545: }
 5546: 
 5547: table#LC_title_bar,
 5548: table.LC_breadcrumbs, /* obsolete? */
 5549: table#LC_title_bar.LC_with_remote {
 5550:   width: 100%;
 5551:   border-color: $pgbg;
 5552:   border-style: solid;
 5553:   border-width: $border;
 5554:   background: $pgbg;
 5555:   color: $fontmenu;
 5556:   border-collapse: collapse;
 5557:   padding: 0;
 5558:   margin: 0;
 5559: }
 5560: 
 5561: ul.LC_breadcrumb_tools_outerlist {
 5562:     margin: 0;
 5563:     padding: 0;
 5564:     position: relative;
 5565:     list-style: none;
 5566: }
 5567: ul.LC_breadcrumb_tools_outerlist li {
 5568:     display: inline;
 5569: }
 5570: 
 5571: .LC_breadcrumb_tools_navigation {
 5572:     padding: 0;
 5573:     margin: 0;
 5574:     float: left;
 5575: }
 5576: .LC_breadcrumb_tools_tools {
 5577:     padding: 0;
 5578:     margin: 0;
 5579:     float: right;
 5580: }
 5581: 
 5582: table#LC_title_bar td {
 5583:   background: $tabbg;
 5584: }
 5585: 
 5586: table#LC_menubuttons img {
 5587:   border: none;
 5588: }
 5589: 
 5590: .LC_breadcrumbs_component {
 5591:   float: right;
 5592:   margin: 0 1em;
 5593: }
 5594: .LC_breadcrumbs_component img {
 5595:   vertical-align: middle;
 5596: }
 5597: 
 5598: td.LC_table_cell_checkbox {
 5599:   text-align: center;
 5600: }
 5601: 
 5602: .LC_fontsize_small {
 5603:   font-size: 70%;
 5604: }
 5605: 
 5606: #LC_breadcrumbs {
 5607:   clear:both;
 5608:   background: $sidebg;
 5609:   border-bottom: 1px solid $lg_border_color;
 5610:   line-height: 2.5em;
 5611:   overflow: hidden;
 5612:   margin: 0;
 5613:   padding: 0;
 5614:   text-align: left;
 5615: }
 5616: 
 5617: .LC_head_subbox, .LC_actionbox {
 5618:   clear:both;
 5619:   background: #F8F8F8; /* $sidebg; */
 5620:   border: 1px solid $sidebg;
 5621:   margin: 0 0 10px 0;
 5622:   padding: 3px;
 5623:   text-align: left;
 5624: }
 5625: 
 5626: .LC_fontsize_medium {
 5627:   font-size: 85%;
 5628: }
 5629: 
 5630: .LC_fontsize_large {
 5631:   font-size: 120%;
 5632: }
 5633: 
 5634: .LC_menubuttons_inline_text {
 5635:   color: $font;
 5636:   font-size: 90%;
 5637:   padding-left:3px;
 5638: }
 5639: 
 5640: .LC_menubuttons_inline_text img{
 5641:   vertical-align: middle;
 5642: }
 5643: 
 5644: li.LC_menubuttons_inline_text img {
 5645:   cursor:pointer;
 5646:   text-decoration: none;
 5647: }
 5648: 
 5649: .LC_menubuttons_link {
 5650:   text-decoration: none;
 5651: }
 5652: 
 5653: .LC_menubuttons_category {
 5654:   color: $font;
 5655:   background: $pgbg;
 5656:   font-size: larger;
 5657:   font-weight: bold;
 5658: }
 5659: 
 5660: td.LC_menubuttons_text {
 5661:   color: $font;
 5662: }
 5663: 
 5664: .LC_current_location {
 5665:   background: $tabbg;
 5666: }
 5667: 
 5668: table.LC_data_table {
 5669:   border: 1px solid #000000;
 5670:   border-collapse: separate;
 5671:   border-spacing: 1px;
 5672:   background: $pgbg;
 5673: }
 5674: 
 5675: .LC_data_table_dense {
 5676:   font-size: small;
 5677: }
 5678: 
 5679: table.LC_nested_outer {
 5680:   border: 1px solid #000000;
 5681:   border-collapse: collapse;
 5682:   border-spacing: 0;
 5683:   width: 100%;
 5684: }
 5685: 
 5686: table.LC_innerpickbox,
 5687: table.LC_nested {
 5688:   border: none;
 5689:   border-collapse: collapse;
 5690:   border-spacing: 0;
 5691:   width: 100%;
 5692: }
 5693: 
 5694: table.LC_data_table tr th,
 5695: table.LC_calendar tr th,
 5696: table.LC_prior_tries tr th,
 5697: table.LC_innerpickbox tr th {
 5698:   font-weight: bold;
 5699:   background-color: $data_table_head;
 5700:   color:$fontmenu;
 5701:   font-size:90%;
 5702: }
 5703: 
 5704: table.LC_innerpickbox tr th,
 5705: table.LC_innerpickbox tr td {
 5706:   vertical-align: top;
 5707: }
 5708: 
 5709: table.LC_data_table tr.LC_info_row > td {
 5710:   background-color: #CCCCCC;
 5711:   font-weight: bold;
 5712:   text-align: left;
 5713: }
 5714: 
 5715: table.LC_data_table tr.LC_odd_row > td {
 5716:   background-color: $data_table_light;
 5717:   padding: 2px;
 5718:   vertical-align: top;
 5719: }
 5720: 
 5721: table.LC_pick_box tr > td.LC_odd_row {
 5722:   background-color: $data_table_light;
 5723:   vertical-align: top;
 5724: }
 5725: 
 5726: table.LC_data_table tr.LC_even_row > td {
 5727:   background-color: $data_table_dark;
 5728:   padding: 2px;
 5729:   vertical-align: top;
 5730: }
 5731: 
 5732: table.LC_pick_box tr > td.LC_even_row {
 5733:   background-color: $data_table_dark;
 5734:   vertical-align: top;
 5735: }
 5736: 
 5737: table.LC_data_table tr.LC_data_table_highlight td {
 5738:   background-color: $data_table_darker;
 5739: }
 5740: 
 5741: table.LC_data_table tr td.LC_leftcol_header {
 5742:   background-color: $data_table_head;
 5743:   font-weight: bold;
 5744: }
 5745: 
 5746: table.LC_data_table tr.LC_empty_row td,
 5747: table.LC_nested tr.LC_empty_row td {
 5748:   font-weight: bold;
 5749:   font-style: italic;
 5750:   text-align: center;
 5751:   padding: 8px;
 5752: }
 5753: 
 5754: table.LC_data_table tr.LC_empty_row td,
 5755: table.LC_data_table tr.LC_footer_row td {
 5756:   background-color: $sidebg;
 5757: }
 5758: 
 5759: table.LC_nested tr.LC_empty_row td {
 5760:   background-color: #FFFFFF;
 5761: }
 5762: 
 5763: table.LC_caption {
 5764: }
 5765: 
 5766: table.LC_nested tr.LC_empty_row td {
 5767:   padding: 4ex
 5768: }
 5769: 
 5770: table.LC_nested_outer tr th {
 5771:   font-weight: bold;
 5772:   color:$fontmenu;
 5773:   background-color: $data_table_head;
 5774:   font-size: small;
 5775:   border-bottom: 1px solid #000000;
 5776: }
 5777: 
 5778: table.LC_nested_outer tr td.LC_subheader {
 5779:   background-color: $data_table_head;
 5780:   font-weight: bold;
 5781:   font-size: small;
 5782:   border-bottom: 1px solid #000000;
 5783:   text-align: right;
 5784: }
 5785: 
 5786: table.LC_nested tr.LC_info_row td {
 5787:   background-color: #CCCCCC;
 5788:   font-weight: bold;
 5789:   font-size: small;
 5790:   text-align: center;
 5791: }
 5792: 
 5793: table.LC_nested tr.LC_info_row td.LC_left_item,
 5794: table.LC_nested_outer tr th.LC_left_item {
 5795:   text-align: left;
 5796: }
 5797: 
 5798: table.LC_nested td {
 5799:   background-color: #FFFFFF;
 5800:   font-size: small;
 5801: }
 5802: 
 5803: table.LC_nested_outer tr th.LC_right_item,
 5804: table.LC_nested tr.LC_info_row td.LC_right_item,
 5805: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5806: table.LC_nested tr td.LC_right_item {
 5807:   text-align: right;
 5808: }
 5809: 
 5810: table.LC_nested tr.LC_odd_row td {
 5811:   background-color: #EEEEEE;
 5812: }
 5813: 
 5814: table.LC_createuser {
 5815: }
 5816: 
 5817: table.LC_createuser tr.LC_section_row td {
 5818:   font-size: small;
 5819: }
 5820: 
 5821: table.LC_createuser tr.LC_info_row td  {
 5822:   background-color: #CCCCCC;
 5823:   font-weight: bold;
 5824:   text-align: center;
 5825: }
 5826: 
 5827: table.LC_calendar {
 5828:   border: 1px solid #000000;
 5829:   border-collapse: collapse;
 5830:   width: 98%;
 5831: }
 5832: 
 5833: table.LC_calendar_pickdate {
 5834:   font-size: xx-small;
 5835: }
 5836: 
 5837: table.LC_calendar tr td {
 5838:   border: 1px solid #000000;
 5839:   vertical-align: top;
 5840:   width: 14%;
 5841: }
 5842: 
 5843: table.LC_calendar tr td.LC_calendar_day_empty {
 5844:   background-color: $data_table_dark;
 5845: }
 5846: 
 5847: table.LC_calendar tr td.LC_calendar_day_current {
 5848:   background-color: $data_table_highlight;
 5849: }
 5850: 
 5851: table.LC_data_table tr td.LC_mail_new {
 5852:   background-color: $mail_new;
 5853: }
 5854: 
 5855: table.LC_data_table tr.LC_mail_new:hover {
 5856:   background-color: $mail_new_hover;
 5857: }
 5858: 
 5859: table.LC_data_table tr td.LC_mail_read {
 5860:   background-color: $mail_read;
 5861: }
 5862: 
 5863: /*
 5864: table.LC_data_table tr.LC_mail_read:hover {
 5865:   background-color: $mail_read_hover;
 5866: }
 5867: */
 5868: 
 5869: table.LC_data_table tr td.LC_mail_replied {
 5870:   background-color: $mail_replied;
 5871: }
 5872: 
 5873: /*
 5874: table.LC_data_table tr.LC_mail_replied:hover {
 5875:   background-color: $mail_replied_hover;
 5876: }
 5877: */
 5878: 
 5879: table.LC_data_table tr td.LC_mail_other {
 5880:   background-color: $mail_other;
 5881: }
 5882: 
 5883: /*
 5884: table.LC_data_table tr.LC_mail_other:hover {
 5885:   background-color: $mail_other_hover;
 5886: }
 5887: */
 5888: 
 5889: table.LC_data_table tr > td.LC_browser_file,
 5890: table.LC_data_table tr > td.LC_browser_file_published {
 5891:   background: #AAEE77;
 5892: }
 5893: 
 5894: table.LC_data_table tr > td.LC_browser_file_locked,
 5895: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5896:   background: #FFAA99;
 5897: }
 5898: 
 5899: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5900:   background: #888888;
 5901: }
 5902: 
 5903: table.LC_data_table tr > td.LC_browser_file_modified,
 5904: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5905:   background: #F8F866;
 5906: }
 5907: 
 5908: table.LC_data_table tr.LC_browser_folder > td {
 5909:   background: #E0E8FF;
 5910: }
 5911: 
 5912: table.LC_data_table tr > td.LC_roles_is {
 5913:   /* background: #77FF77; */
 5914: }
 5915: 
 5916: table.LC_data_table tr > td.LC_roles_future {
 5917:   border-right: 8px solid #FFFF77;
 5918: }
 5919: 
 5920: table.LC_data_table tr > td.LC_roles_will {
 5921:   border-right: 8px solid #FFAA77;
 5922: }
 5923: 
 5924: table.LC_data_table tr > td.LC_roles_expired {
 5925:   border-right: 8px solid #FF7777;
 5926: }
 5927: 
 5928: table.LC_data_table tr > td.LC_roles_will_not {
 5929:   border-right: 8px solid #AAFF77;
 5930: }
 5931: 
 5932: table.LC_data_table tr > td.LC_roles_selected {
 5933:   border-right: 8px solid #11CC55;
 5934: }
 5935: 
 5936: span.LC_current_location {
 5937:   font-size:larger;
 5938:   background: $pgbg;
 5939: }
 5940: 
 5941: span.LC_current_nav_location {
 5942:   font-weight:bold;
 5943:   background: $sidebg;
 5944: }
 5945: 
 5946: span.LC_parm_menu_item {
 5947:   font-size: larger;
 5948: }
 5949: 
 5950: span.LC_parm_scope_all {
 5951:   color: red;
 5952: }
 5953: 
 5954: span.LC_parm_scope_folder {
 5955:   color: green;
 5956: }
 5957: 
 5958: span.LC_parm_scope_resource {
 5959:   color: orange;
 5960: }
 5961: 
 5962: span.LC_parm_part {
 5963:   color: blue;
 5964: }
 5965: 
 5966: span.LC_parm_folder,
 5967: span.LC_parm_symb {
 5968:   font-size: x-small;
 5969:   font-family: $mono;
 5970:   color: #AAAAAA;
 5971: }
 5972: 
 5973: ul.LC_parm_parmlist li {
 5974:   display: inline-block;
 5975:   padding: 0.3em 0.8em;
 5976:   vertical-align: top;
 5977:   width: 150px;
 5978:   border-top:1px solid $lg_border_color;
 5979: }
 5980: 
 5981: td.LC_parm_overview_level_menu,
 5982: td.LC_parm_overview_map_menu,
 5983: td.LC_parm_overview_parm_selectors,
 5984: td.LC_parm_overview_restrictions  {
 5985:   border: 1px solid black;
 5986:   border-collapse: collapse;
 5987: }
 5988: 
 5989: table.LC_parm_overview_restrictions td {
 5990:   border-width: 1px 4px 1px 4px;
 5991:   border-style: solid;
 5992:   border-color: $pgbg;
 5993:   text-align: center;
 5994: }
 5995: 
 5996: table.LC_parm_overview_restrictions th {
 5997:   background: $tabbg;
 5998:   border-width: 1px 4px 1px 4px;
 5999:   border-style: solid;
 6000:   border-color: $pgbg;
 6001: }
 6002: 
 6003: table#LC_helpmenu {
 6004:   border: none;
 6005:   height: 55px;
 6006:   border-spacing: 0;
 6007: }
 6008: 
 6009: table#LC_helpmenu fieldset legend {
 6010:   font-size: larger;
 6011: }
 6012: 
 6013: table#LC_helpmenu_links {
 6014:   width: 100%;
 6015:   border: 1px solid black;
 6016:   background: $pgbg;
 6017:   padding: 0;
 6018:   border-spacing: 1px;
 6019: }
 6020: 
 6021: table#LC_helpmenu_links tr td {
 6022:   padding: 1px;
 6023:   background: $tabbg;
 6024:   text-align: center;
 6025:   font-weight: bold;
 6026: }
 6027: 
 6028: table#LC_helpmenu_links a:link,
 6029: table#LC_helpmenu_links a:visited,
 6030: table#LC_helpmenu_links a:active {
 6031:   text-decoration: none;
 6032:   color: $font;
 6033: }
 6034: 
 6035: table#LC_helpmenu_links a:hover {
 6036:   text-decoration: underline;
 6037:   color: $vlink;
 6038: }
 6039: 
 6040: .LC_chrt_popup_exists {
 6041:   border: 1px solid #339933;
 6042:   margin: -1px;
 6043: }
 6044: 
 6045: .LC_chrt_popup_up {
 6046:   border: 1px solid yellow;
 6047:   margin: -1px;
 6048: }
 6049: 
 6050: .LC_chrt_popup {
 6051:   border: 1px solid #8888FF;
 6052:   background: #CCCCFF;
 6053: }
 6054: 
 6055: table.LC_pick_box {
 6056:   border-collapse: separate;
 6057:   background: white;
 6058:   border: 1px solid black;
 6059:   border-spacing: 1px;
 6060: }
 6061: 
 6062: table.LC_pick_box td.LC_pick_box_title {
 6063:   background: $sidebg;
 6064:   font-weight: bold;
 6065:   text-align: left;
 6066:   vertical-align: top;
 6067:   width: 184px;
 6068:   padding: 8px;
 6069: }
 6070: 
 6071: table.LC_pick_box td.LC_pick_box_value {
 6072:   text-align: left;
 6073:   padding: 8px;
 6074: }
 6075: 
 6076: table.LC_pick_box td.LC_pick_box_select {
 6077:   text-align: left;
 6078:   padding: 8px;
 6079: }
 6080: 
 6081: table.LC_pick_box td.LC_pick_box_separator {
 6082:   padding: 0;
 6083:   height: 1px;
 6084:   background: black;
 6085: }
 6086: 
 6087: table.LC_pick_box td.LC_pick_box_submit {
 6088:   text-align: right;
 6089: }
 6090: 
 6091: table.LC_pick_box td.LC_evenrow_value {
 6092:   text-align: left;
 6093:   padding: 8px;
 6094:   background-color: $data_table_light;
 6095: }
 6096: 
 6097: table.LC_pick_box td.LC_oddrow_value {
 6098:   text-align: left;
 6099:   padding: 8px;
 6100:   background-color: $data_table_light;
 6101: }
 6102: 
 6103: span.LC_helpform_receipt_cat {
 6104:   font-weight: bold;
 6105: }
 6106: 
 6107: table.LC_group_priv_box {
 6108:   background: white;
 6109:   border: 1px solid black;
 6110:   border-spacing: 1px;
 6111: }
 6112: 
 6113: table.LC_group_priv_box td.LC_pick_box_title {
 6114:   background: $tabbg;
 6115:   font-weight: bold;
 6116:   text-align: right;
 6117:   width: 184px;
 6118: }
 6119: 
 6120: table.LC_group_priv_box td.LC_groups_fixed {
 6121:   background: $data_table_light;
 6122:   text-align: center;
 6123: }
 6124: 
 6125: table.LC_group_priv_box td.LC_groups_optional {
 6126:   background: $data_table_dark;
 6127:   text-align: center;
 6128: }
 6129: 
 6130: table.LC_group_priv_box td.LC_groups_functionality {
 6131:   background: $data_table_darker;
 6132:   text-align: center;
 6133:   font-weight: bold;
 6134: }
 6135: 
 6136: table.LC_group_priv td {
 6137:   text-align: left;
 6138:   padding: 0;
 6139: }
 6140: 
 6141: .LC_navbuttons {
 6142:   margin: 2ex 0ex 2ex 0ex;
 6143: }
 6144: 
 6145: .LC_topic_bar {
 6146:   font-weight: bold;
 6147:   background: $tabbg;
 6148:   margin: 1em 0em 1em 2em;
 6149:   padding: 3px;
 6150:   font-size: 1.2em;
 6151: }
 6152: 
 6153: .LC_topic_bar span {
 6154:   left: 0.5em;
 6155:   position: absolute;
 6156:   vertical-align: middle;
 6157:   font-size: 1.2em;
 6158: }
 6159: 
 6160: table.LC_course_group_status {
 6161:   margin: 20px;
 6162: }
 6163: 
 6164: table.LC_status_selector td {
 6165:   vertical-align: top;
 6166:   text-align: center;
 6167:   padding: 4px;
 6168: }
 6169: 
 6170: div.LC_feedback_link {
 6171:   clear: both;
 6172:   background: $sidebg;
 6173:   width: 100%;
 6174:   padding-bottom: 10px;
 6175:   border: 1px $tabbg solid;
 6176:   height: 22px;
 6177:   line-height: 22px;
 6178:   padding-top: 5px;
 6179: }
 6180: 
 6181: div.LC_feedback_link img {
 6182:   height: 22px;
 6183:   vertical-align:middle;
 6184: }
 6185: 
 6186: div.LC_feedback_link a {
 6187:   text-decoration: none;
 6188: }
 6189: 
 6190: div.LC_comblock {
 6191:   display:inline;
 6192:   color:$font;
 6193:   font-size:90%;
 6194: }
 6195: 
 6196: div.LC_feedback_link div.LC_comblock {
 6197:   padding-left:5px;
 6198: }
 6199: 
 6200: div.LC_feedback_link div.LC_comblock a {
 6201:   color:$font;
 6202: }
 6203: 
 6204: span.LC_feedback_link {
 6205:   /* background: $feedback_link_bg; */
 6206:   font-size: larger;
 6207: }
 6208: 
 6209: span.LC_message_link {
 6210:   /* background: $feedback_link_bg; */
 6211:   font-size: larger;
 6212:   position: absolute;
 6213:   right: 1em;
 6214: }
 6215: 
 6216: table.LC_prior_tries {
 6217:   border: 1px solid #000000;
 6218:   border-collapse: separate;
 6219:   border-spacing: 1px;
 6220: }
 6221: 
 6222: table.LC_prior_tries td {
 6223:   padding: 2px;
 6224: }
 6225: 
 6226: .LC_answer_correct {
 6227:   background: lightgreen;
 6228:   color: darkgreen;
 6229:   padding: 6px;
 6230: }
 6231: 
 6232: .LC_answer_charged_try {
 6233:   background: #FFAAAA;
 6234:   color: darkred;
 6235:   padding: 6px;
 6236: }
 6237: 
 6238: .LC_answer_not_charged_try,
 6239: .LC_answer_no_grade,
 6240: .LC_answer_late {
 6241:   background: lightyellow;
 6242:   color: black;
 6243:   padding: 6px;
 6244: }
 6245: 
 6246: .LC_answer_previous {
 6247:   background: lightblue;
 6248:   color: darkblue;
 6249:   padding: 6px;
 6250: }
 6251: 
 6252: .LC_answer_no_message {
 6253:   background: #FFFFFF;
 6254:   color: black;
 6255:   padding: 6px;
 6256: }
 6257: 
 6258: .LC_answer_unknown {
 6259:   background: orange;
 6260:   color: black;
 6261:   padding: 6px;
 6262: }
 6263: 
 6264: span.LC_prior_numerical,
 6265: span.LC_prior_string,
 6266: span.LC_prior_custom,
 6267: span.LC_prior_reaction,
 6268: span.LC_prior_math {
 6269:   font-family: $mono;
 6270:   white-space: pre;
 6271: }
 6272: 
 6273: span.LC_prior_string {
 6274:   font-family: $mono;
 6275:   white-space: pre;
 6276: }
 6277: 
 6278: table.LC_prior_option {
 6279:   width: 100%;
 6280:   border-collapse: collapse;
 6281: }
 6282: 
 6283: table.LC_prior_rank,
 6284: table.LC_prior_match {
 6285:   border-collapse: collapse;
 6286: }
 6287: 
 6288: table.LC_prior_option tr td,
 6289: table.LC_prior_rank tr td,
 6290: table.LC_prior_match tr td {
 6291:   border: 1px solid #000000;
 6292: }
 6293: 
 6294: .LC_nobreak {
 6295:   white-space: nowrap;
 6296: }
 6297: 
 6298: span.LC_cusr_emph {
 6299:   font-style: italic;
 6300: }
 6301: 
 6302: span.LC_cusr_subheading {
 6303:   font-weight: normal;
 6304:   font-size: 85%;
 6305: }
 6306: 
 6307: div.LC_docs_entry_move {
 6308:   border: 1px solid #BBBBBB;
 6309:   background: #DDDDDD;
 6310:   width: 22px;
 6311:   padding: 1px;
 6312:   margin: 0;
 6313: }
 6314: 
 6315: table.LC_data_table tr > td.LC_docs_entry_commands,
 6316: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6317:   font-size: x-small;
 6318: }
 6319: 
 6320: .LC_docs_entry_parameter {
 6321:   white-space: nowrap;
 6322: }
 6323: 
 6324: .LC_docs_copy {
 6325:   color: #000099;
 6326: }
 6327: 
 6328: .LC_docs_cut {
 6329:   color: #550044;
 6330: }
 6331: 
 6332: .LC_docs_rename {
 6333:   color: #009900;
 6334: }
 6335: 
 6336: .LC_docs_remove {
 6337:   color: #990000;
 6338: }
 6339: 
 6340: .LC_docs_reinit_warn,
 6341: .LC_docs_ext_edit {
 6342:   font-size: x-small;
 6343: }
 6344: 
 6345: table.LC_docs_adddocs td,
 6346: table.LC_docs_adddocs th {
 6347:   border: 1px solid #BBBBBB;
 6348:   padding: 4px;
 6349:   background: #DDDDDD;
 6350: }
 6351: 
 6352: table.LC_sty_begin {
 6353:   background: #BBFFBB;
 6354: }
 6355: 
 6356: table.LC_sty_end {
 6357:   background: #FFBBBB;
 6358: }
 6359: 
 6360: table.LC_double_column {
 6361:   border-width: 0;
 6362:   border-collapse: collapse;
 6363:   width: 100%;
 6364:   padding: 2px;
 6365: }
 6366: 
 6367: table.LC_double_column tr td.LC_left_col {
 6368:   top: 2px;
 6369:   left: 2px;
 6370:   width: 47%;
 6371:   vertical-align: top;
 6372: }
 6373: 
 6374: table.LC_double_column tr td.LC_right_col {
 6375:   top: 2px;
 6376:   right: 2px;
 6377:   width: 47%;
 6378:   vertical-align: top;
 6379: }
 6380: 
 6381: div.LC_left_float {
 6382:   float: left;
 6383:   padding-right: 5%;
 6384:   padding-bottom: 4px;
 6385: }
 6386: 
 6387: div.LC_clear_float_header {
 6388:   padding-bottom: 2px;
 6389: }
 6390: 
 6391: div.LC_clear_float_footer {
 6392:   padding-top: 10px;
 6393:   clear: both;
 6394: }
 6395: 
 6396: div.LC_grade_show_user {
 6397: /*  border-left: 5px solid $sidebg; */
 6398:   border-top: 5px solid #000000;
 6399:   margin: 50px 0 0 0;
 6400:   padding: 15px 0 5px 10px;
 6401: }
 6402: 
 6403: div.LC_grade_show_user_odd_row {
 6404: /*  border-left: 5px solid #000000; */
 6405: }
 6406: 
 6407: div.LC_grade_show_user div.LC_Box {
 6408:   margin-right: 50px;
 6409: }
 6410: 
 6411: div.LC_grade_submissions,
 6412: div.LC_grade_message_center,
 6413: div.LC_grade_info_links {
 6414:   margin: 5px;
 6415:   width: 99%;
 6416:   background: #FFFFFF;
 6417: }
 6418: 
 6419: div.LC_grade_submissions_header,
 6420: div.LC_grade_message_center_header {
 6421:   font-weight: bold;
 6422:   font-size: large;
 6423: }
 6424: 
 6425: div.LC_grade_submissions_body,
 6426: div.LC_grade_message_center_body {
 6427:   border: 1px solid black;
 6428:   width: 99%;
 6429:   background: #FFFFFF;
 6430: }
 6431: 
 6432: table.LC_scantron_action {
 6433:   width: 100%;
 6434: }
 6435: 
 6436: table.LC_scantron_action tr th {
 6437:   font-weight:bold;
 6438:   font-style:normal;
 6439: }
 6440: 
 6441: .LC_edit_problem_header,
 6442: div.LC_edit_problem_footer {
 6443:   font-weight: normal;
 6444:   font-size:  medium;
 6445:   margin: 2px;
 6446:   background-color: $sidebg;
 6447: }
 6448: 
 6449: div.LC_edit_problem_header,
 6450: div.LC_edit_problem_header div,
 6451: div.LC_edit_problem_footer,
 6452: div.LC_edit_problem_footer div,
 6453: div.LC_edit_problem_editxml_header,
 6454: div.LC_edit_problem_editxml_header div {
 6455:   margin-top: 5px;
 6456: }
 6457: 
 6458: div.LC_edit_problem_header_title {
 6459:   font-weight: bold;
 6460:   font-size: larger;
 6461:   background: $tabbg;
 6462:   padding: 3px;
 6463:   margin: 0 0 5px 0;
 6464: }
 6465: 
 6466: table.LC_edit_problem_header_title {
 6467:   width: 100%;
 6468:   background: $tabbg;
 6469: }
 6470: 
 6471: div.LC_edit_problem_discards {
 6472:   float: left;
 6473:   padding-bottom: 5px;
 6474: }
 6475: 
 6476: div.LC_edit_problem_saves {
 6477:   float: right;
 6478:   padding-bottom: 5px;
 6479: }
 6480: 
 6481: .LC_edit_opt {
 6482:   padding-left: 1em;
 6483:   white-space: nowrap;
 6484: }
 6485: 
 6486: img.stift {
 6487:   border-width: 0;
 6488:   vertical-align: middle;
 6489: }
 6490: 
 6491: table td.LC_mainmenu_col_fieldset {
 6492:   vertical-align: top;
 6493: }
 6494: 
 6495: div.LC_createcourse {
 6496:   margin: 10px 10px 10px 10px;
 6497: }
 6498: 
 6499: .LC_dccid {
 6500:   float: right;
 6501:   margin: 0.2em 0 0 0;
 6502:   padding: 0;
 6503:   font-size: 90%;
 6504:   display:none;
 6505: }
 6506: 
 6507: ol.LC_primary_menu a:hover,
 6508: ol#LC_MenuBreadcrumbs a:hover,
 6509: ol#LC_PathBreadcrumbs a:hover,
 6510: ul#LC_secondary_menu a:hover,
 6511: .LC_FormSectionClearButton input:hover
 6512: ul.LC_TabContent   li:hover a {
 6513:   color:$button_hover;
 6514:   text-decoration:none;
 6515: }
 6516: 
 6517: h1 {
 6518:   padding: 0;
 6519:   line-height:130%;
 6520: }
 6521: 
 6522: h2,
 6523: h3,
 6524: h4,
 6525: h5,
 6526: h6 {
 6527:   margin: 5px 0 5px 0;
 6528:   padding: 0;
 6529:   line-height:130%;
 6530: }
 6531: 
 6532: .LC_hcell {
 6533:   padding:3px 15px 3px 15px;
 6534:   margin: 0;
 6535:   background-color:$tabbg;
 6536:   color:$fontmenu;
 6537:   border-bottom:solid 1px $lg_border_color;
 6538: }
 6539: 
 6540: .LC_Box > .LC_hcell {
 6541:   margin: 0 -10px 10px -10px;
 6542: }
 6543: 
 6544: .LC_noBorder {
 6545:   border: 0;
 6546: }
 6547: 
 6548: .LC_FormSectionClearButton input {
 6549:   background-color:transparent;
 6550:   border: none;
 6551:   cursor:pointer;
 6552:   text-decoration:underline;
 6553: }
 6554: 
 6555: .LC_help_open_topic {
 6556:   color: #FFFFFF;
 6557:   background-color: #EEEEFF;
 6558:   margin: 1px;
 6559:   padding: 4px;
 6560:   border: 1px solid #000033;
 6561:   white-space: nowrap;
 6562:   /* vertical-align: middle; */
 6563: }
 6564: 
 6565: dl,
 6566: ul,
 6567: div,
 6568: fieldset {
 6569:   margin: 10px 10px 10px 0;
 6570:   /* overflow: hidden; */
 6571: }
 6572: 
 6573: fieldset > legend {
 6574:   font-weight: bold;
 6575:   padding: 0 5px 0 5px;
 6576: }
 6577: 
 6578: #LC_nav_bar {
 6579:   float: left;
 6580:   background-color: $pgbg_or_bgcolor;
 6581:   margin: 0 0 2px 0;
 6582: }
 6583: 
 6584: #LC_realm {
 6585:   margin: 0.2em 0 0 0;
 6586:   padding: 0;
 6587:   font-weight: bold;
 6588:   text-align: center;
 6589:   background-color: $pgbg_or_bgcolor;
 6590: }
 6591: 
 6592: #LC_nav_bar em {
 6593:   font-weight: bold;
 6594:   font-style: normal;
 6595: }
 6596: 
 6597: ol.LC_primary_menu {
 6598:   margin: 0;
 6599:   padding: 0;
 6600:   background-color: $pgbg_or_bgcolor;
 6601: }
 6602: 
 6603: ol#LC_PathBreadcrumbs {
 6604:   margin: 0;
 6605: }
 6606: 
 6607: ol.LC_primary_menu li {
 6608:   color: RGB(80, 80, 80);
 6609:   vertical-align: middle;
 6610:   text-align: left;
 6611:   list-style: none;
 6612:   float: left;
 6613: }
 6614: 
 6615: ol.LC_primary_menu li a {
 6616:   display: block;
 6617:   margin: 0;
 6618:   padding: 0 5px 0 10px;
 6619:   text-decoration: none;
 6620: }
 6621: 
 6622: ol.LC_primary_menu li ul {
 6623:   display: none;
 6624:   width: 10em;
 6625:   background-color: $data_table_light;
 6626: }
 6627: 
 6628: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6629:   display: block;
 6630:   position: absolute;
 6631:   margin: 0;
 6632:   padding: 0;
 6633:   z-index: 2;
 6634: }
 6635: 
 6636: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6637:   font-size: 90%;
 6638:   vertical-align: top;
 6639:   float: none;
 6640:   border-left: 1px solid black;
 6641:   border-right: 1px solid black;
 6642: }
 6643: 
 6644: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6645:   background-color:$data_table_light;
 6646: }
 6647: 
 6648: ol.LC_primary_menu li li a:hover {
 6649:    color:$button_hover;
 6650:    background-color:$data_table_dark;
 6651: }
 6652: 
 6653: ol.LC_primary_menu li img {
 6654:   vertical-align: bottom;
 6655:   height: 1.1em;
 6656:   margin: 0.2em 0 0 0;
 6657: }
 6658: 
 6659: ol.LC_primary_menu a {
 6660:   color: RGB(80, 80, 80);
 6661:   text-decoration: none;
 6662: }
 6663: 
 6664: ol.LC_primary_menu a.LC_new_message {
 6665:   font-weight:bold;
 6666:   color: darkred;
 6667: }
 6668: 
 6669: ol.LC_docs_parameters {
 6670:   margin-left: 0;
 6671:   padding: 0;
 6672:   list-style: none;
 6673: }
 6674: 
 6675: ol.LC_docs_parameters li {
 6676:   margin: 0;
 6677:   padding-right: 20px;
 6678:   display: inline;
 6679: }
 6680: 
 6681: ol.LC_docs_parameters li:before {
 6682:   content: "\\002022 \\0020";
 6683: }
 6684: 
 6685: li.LC_docs_parameters_title {
 6686:   font-weight: bold;
 6687: }
 6688: 
 6689: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6690:   content: "";
 6691: }
 6692: 
 6693: ul#LC_secondary_menu {
 6694:   clear: right;
 6695:   color: $fontmenu;
 6696:   background: $tabbg;
 6697:   list-style: none;
 6698:   padding: 0;
 6699:   margin: 0;
 6700:   width: 100%;
 6701:   text-align: left;
 6702:   float: left;
 6703: }
 6704: 
 6705: ul#LC_secondary_menu li {
 6706:   font-weight: bold;
 6707:   line-height: 1.8em;
 6708:   border-right: 1px solid black;
 6709:   vertical-align: middle;
 6710:   float: left;
 6711: }
 6712: 
 6713: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6714:   background-color: $data_table_light;
 6715: }
 6716: 
 6717: ul#LC_secondary_menu li a {
 6718:   padding: 0 0.8em;
 6719: }
 6720: 
 6721: ul#LC_secondary_menu li ul {
 6722:   display: none;
 6723: }
 6724: 
 6725: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6726:   display: block;
 6727:   position: absolute;
 6728:   margin: 0;
 6729:   padding: 0;
 6730:   list-style:none;
 6731:   float: none;
 6732:   background-color: $data_table_light;
 6733:   z-index: 2;
 6734:   margin-left: -1px;
 6735: }
 6736: 
 6737: ul#LC_secondary_menu li ul li {
 6738:   font-size: 90%;
 6739:   vertical-align: top;
 6740:   border-left: 1px solid black;
 6741:   border-right: 1px solid black;
 6742:   background-color: $data_table_light;
 6743:   list-style:none;
 6744:   float: none;
 6745: }
 6746: 
 6747: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6748:   background-color: $data_table_dark;
 6749: }
 6750: 
 6751: ul.LC_TabContent {
 6752:   display:block;
 6753:   background: $sidebg;
 6754:   border-bottom: solid 1px $lg_border_color;
 6755:   list-style:none;
 6756:   margin: -1px -10px 0 -10px;
 6757:   padding: 0;
 6758: }
 6759: 
 6760: ul.LC_TabContent li,
 6761: ul.LC_TabContentBigger li {
 6762:   float:left;
 6763: }
 6764: 
 6765: ul#LC_secondary_menu li a {
 6766:   color: $fontmenu;
 6767:   text-decoration: none;
 6768: }
 6769: 
 6770: ul.LC_TabContent {
 6771:   min-height:20px;
 6772: }
 6773: 
 6774: ul.LC_TabContent li {
 6775:   vertical-align:middle;
 6776:   padding: 0 16px 0 10px;
 6777:   background-color:$tabbg;
 6778:   border-bottom:solid 1px $lg_border_color;
 6779:   border-left: solid 1px $font;
 6780: }
 6781: 
 6782: ul.LC_TabContent .right {
 6783:   float:right;
 6784: }
 6785: 
 6786: ul.LC_TabContent li a,
 6787: ul.LC_TabContent li {
 6788:   color:rgb(47,47,47);
 6789:   text-decoration:none;
 6790:   font-size:95%;
 6791:   font-weight:bold;
 6792:   min-height:20px;
 6793: }
 6794: 
 6795: ul.LC_TabContent li a:hover,
 6796: ul.LC_TabContent li a:focus {
 6797:   color: $button_hover;
 6798:   background:none;
 6799:   outline:none;
 6800: }
 6801: 
 6802: ul.LC_TabContent li:hover {
 6803:   color: $button_hover;
 6804:   cursor:pointer;
 6805: }
 6806: 
 6807: ul.LC_TabContent li.active {
 6808:   color: $font;
 6809:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6810:   border-bottom:solid 1px #FFFFFF;
 6811:   cursor: default;
 6812: }
 6813: 
 6814: ul.LC_TabContent li.active a {
 6815:   color:$font;
 6816:   background:#FFFFFF;
 6817:   outline: none;
 6818: }
 6819: 
 6820: ul.LC_TabContent li.goback {
 6821:   float: left;
 6822:   border-left: none;
 6823: }
 6824: 
 6825: #maincoursedoc {
 6826:   clear:both;
 6827: }
 6828: 
 6829: ul.LC_TabContentBigger {
 6830:   display:block;
 6831:   list-style:none;
 6832:   padding: 0;
 6833: }
 6834: 
 6835: ul.LC_TabContentBigger li {
 6836:   vertical-align:bottom;
 6837:   height: 30px;
 6838:   font-size:110%;
 6839:   font-weight:bold;
 6840:   color: #737373;
 6841: }
 6842: 
 6843: ul.LC_TabContentBigger li.active {
 6844:   position: relative;
 6845:   top: 1px;
 6846: }
 6847: 
 6848: ul.LC_TabContentBigger li a {
 6849:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6850:   height: 30px;
 6851:   line-height: 30px;
 6852:   text-align: center;
 6853:   display: block;
 6854:   text-decoration: none;
 6855:   outline: none;  
 6856: }
 6857: 
 6858: ul.LC_TabContentBigger li.active a {
 6859:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6860:   color:$font;
 6861: }
 6862: 
 6863: ul.LC_TabContentBigger li b {
 6864:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6865:   display: block;
 6866:   float: left;
 6867:   padding: 0 30px;
 6868:   border-bottom: 1px solid $lg_border_color;
 6869: }
 6870: 
 6871: ul.LC_TabContentBigger li:hover b {
 6872:   color:$button_hover;
 6873: }
 6874: 
 6875: ul.LC_TabContentBigger li.active b {
 6876:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6877:   color:$font;
 6878:   border: 0;
 6879: }
 6880: 
 6881: 
 6882: ul.LC_CourseBreadcrumbs {
 6883:   background: $sidebg;
 6884:   height: 2em;
 6885:   padding-left: 10px;
 6886:   margin: 0;
 6887:   list-style-position: inside;
 6888: }
 6889: 
 6890: ol#LC_MenuBreadcrumbs,
 6891: ol#LC_PathBreadcrumbs {
 6892:   padding-left: 10px;
 6893:   margin: 0;
 6894:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6895: }
 6896: 
 6897: ol#LC_MenuBreadcrumbs li,
 6898: ol#LC_PathBreadcrumbs li,
 6899: ul.LC_CourseBreadcrumbs li {
 6900:   display: inline;
 6901:   white-space: normal;  
 6902: }
 6903: 
 6904: ol#LC_MenuBreadcrumbs li a,
 6905: ul.LC_CourseBreadcrumbs li a {
 6906:   text-decoration: none;
 6907:   font-size:90%;
 6908: }
 6909: 
 6910: ol#LC_MenuBreadcrumbs h1 {
 6911:   display: inline;
 6912:   font-size: 90%;
 6913:   line-height: 2.5em;
 6914:   margin: 0;
 6915:   padding: 0;
 6916: }
 6917: 
 6918: ol#LC_PathBreadcrumbs li a {
 6919:   text-decoration:none;
 6920:   font-size:100%;
 6921:   font-weight:bold;
 6922: }
 6923: 
 6924: .LC_Box {
 6925:   border: solid 1px $lg_border_color;
 6926:   padding: 0 10px 10px 10px;
 6927: }
 6928: 
 6929: .LC_DocsBox {
 6930:   border: solid 1px $lg_border_color;
 6931:   padding: 0 0 10px 10px;
 6932: }
 6933: 
 6934: .LC_AboutMe_Image {
 6935:   float:left;
 6936:   margin-right:10px;
 6937: }
 6938: 
 6939: .LC_Clear_AboutMe_Image {
 6940:   clear:left;
 6941: }
 6942: 
 6943: dl.LC_ListStyleClean dt {
 6944:   padding-right: 5px;
 6945:   display: table-header-group;
 6946: }
 6947: 
 6948: dl.LC_ListStyleClean dd {
 6949:   display: table-row;
 6950: }
 6951: 
 6952: .LC_ListStyleClean,
 6953: .LC_ListStyleSimple,
 6954: .LC_ListStyleNormal,
 6955: .LC_ListStyleSpecial {
 6956:   /* display:block; */
 6957:   list-style-position: inside;
 6958:   list-style-type: none;
 6959:   overflow: hidden;
 6960:   padding: 0;
 6961: }
 6962: 
 6963: .LC_ListStyleSimple li,
 6964: .LC_ListStyleSimple dd,
 6965: .LC_ListStyleNormal li,
 6966: .LC_ListStyleNormal dd,
 6967: .LC_ListStyleSpecial li,
 6968: .LC_ListStyleSpecial dd {
 6969:   margin: 0;
 6970:   padding: 5px 5px 5px 10px;
 6971:   clear: both;
 6972: }
 6973: 
 6974: .LC_ListStyleClean li,
 6975: .LC_ListStyleClean dd {
 6976:   padding-top: 0;
 6977:   padding-bottom: 0;
 6978: }
 6979: 
 6980: .LC_ListStyleSimple dd,
 6981: .LC_ListStyleSimple li {
 6982:   border-bottom: solid 1px $lg_border_color;
 6983: }
 6984: 
 6985: .LC_ListStyleSpecial li,
 6986: .LC_ListStyleSpecial dd {
 6987:   list-style-type: none;
 6988:   background-color: RGB(220, 220, 220);
 6989:   margin-bottom: 4px;
 6990: }
 6991: 
 6992: table.LC_SimpleTable {
 6993:   margin:5px;
 6994:   border:solid 1px $lg_border_color;
 6995: }
 6996: 
 6997: table.LC_SimpleTable tr {
 6998:   padding: 0;
 6999:   border:solid 1px $lg_border_color;
 7000: }
 7001: 
 7002: table.LC_SimpleTable thead {
 7003:   background:rgb(220,220,220);
 7004: }
 7005: 
 7006: div.LC_columnSection {
 7007:   display: block;
 7008:   clear: both;
 7009:   overflow: hidden;
 7010:   margin: 0;
 7011: }
 7012: 
 7013: div.LC_columnSection>* {
 7014:   float: left;
 7015:   margin: 10px 20px 10px 0;
 7016:   overflow:hidden;
 7017: }
 7018: 
 7019: table em {
 7020:   font-weight: bold;
 7021:   font-style: normal;
 7022: }
 7023: 
 7024: table.LC_tableBrowseRes,
 7025: table.LC_tableOfContent {
 7026:   border:none;
 7027:   border-spacing: 1px;
 7028:   padding: 3px;
 7029:   background-color: #FFFFFF;
 7030:   font-size: 90%;
 7031: }
 7032: 
 7033: table.LC_tableOfContent {
 7034:   border-collapse: collapse;
 7035: }
 7036: 
 7037: table.LC_tableBrowseRes a,
 7038: table.LC_tableOfContent a {
 7039:   background-color: transparent;
 7040:   text-decoration: none;
 7041: }
 7042: 
 7043: table.LC_tableOfContent img {
 7044:   border: none;
 7045:   height: 1.3em;
 7046:   vertical-align: text-bottom;
 7047:   margin-right: 0.3em;
 7048: }
 7049: 
 7050: a#LC_content_toolbar_firsthomework {
 7051:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7052: }
 7053: 
 7054: a#LC_content_toolbar_everything {
 7055:   background-image:url(/res/adm/pages/show-all.gif);
 7056: }
 7057: 
 7058: a#LC_content_toolbar_uncompleted {
 7059:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7060: }
 7061: 
 7062: #LC_content_toolbar_clearbubbles {
 7063:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7064: }
 7065: 
 7066: a#LC_content_toolbar_changefolder {
 7067:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7068: }
 7069: 
 7070: a#LC_content_toolbar_changefolder_toggled {
 7071:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7072: }
 7073: 
 7074: a#LC_content_toolbar_edittoplevel {
 7075:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7076: }
 7077: 
 7078: ul#LC_toolbar li a:hover {
 7079:   background-position: bottom center;
 7080: }
 7081: 
 7082: ul#LC_toolbar {
 7083:   padding: 0;
 7084:   margin: 2px;
 7085:   list-style:none;
 7086:   position:relative;
 7087:   background-color:white;
 7088:   overflow: auto;
 7089: }
 7090: 
 7091: ul#LC_toolbar li {
 7092:   border:1px solid white;
 7093:   padding: 0;
 7094:   margin: 0;
 7095:   float: left;
 7096:   display:inline;
 7097:   vertical-align:middle;
 7098:   white-space: nowrap;
 7099: }
 7100: 
 7101: 
 7102: a.LC_toolbarItem {
 7103:   display:block;
 7104:   padding: 0;
 7105:   margin: 0;
 7106:   height: 32px;
 7107:   width: 32px;
 7108:   color:white;
 7109:   border: none;
 7110:   background-repeat:no-repeat;
 7111:   background-color:transparent;
 7112: }
 7113: 
 7114: ul.LC_funclist {
 7115:     margin: 0;
 7116:     padding: 0.5em 1em 0.5em 0;
 7117: }
 7118: 
 7119: ul.LC_funclist > li:first-child {
 7120:     font-weight:bold; 
 7121:     margin-left:0.8em;
 7122: }
 7123: 
 7124: ul.LC_funclist + ul.LC_funclist {
 7125:     /* 
 7126:        left border as a seperator if we have more than
 7127:        one list 
 7128:     */
 7129:     border-left: 1px solid $sidebg;
 7130:     /* 
 7131:        this hides the left border behind the border of the 
 7132:        outer box if element is wrapped to the next 'line' 
 7133:     */
 7134:     margin-left: -1px;
 7135: }
 7136: 
 7137: ul.LC_funclist li {
 7138:   display: inline;
 7139:   white-space: nowrap;
 7140:   margin: 0 0 0 25px;
 7141:   line-height: 150%;
 7142: }
 7143: 
 7144: .LC_hidden {
 7145:   display: none;
 7146: }
 7147: 
 7148: .LCmodal-overlay {
 7149: 		position:fixed;
 7150: 		top:0;
 7151: 		right:0;
 7152: 		bottom:0;
 7153: 		left:0;
 7154: 		height:100%;
 7155: 		width:100%;
 7156: 		margin:0;
 7157: 		padding:0;
 7158: 		background:#999;
 7159: 		opacity:.75;
 7160: 		filter: alpha(opacity=75);
 7161: 		-moz-opacity: 0.75;
 7162: 		z-index:101;
 7163: }
 7164: 
 7165: * html .LCmodal-overlay {   
 7166: 		position: absolute;
 7167: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7168: }
 7169: 
 7170: .LCmodal-window {
 7171: 		position:fixed;
 7172: 		top:50%;
 7173: 		left:50%;
 7174: 		margin:0;
 7175: 		padding:0;
 7176: 		z-index:102;
 7177: 	}
 7178: 
 7179: * html .LCmodal-window {
 7180: 		position:absolute;
 7181: }
 7182: 
 7183: .LCclose-window {
 7184: 		position:absolute;
 7185: 		width:32px;
 7186: 		height:32px;
 7187: 		right:8px;
 7188: 		top:8px;
 7189: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7190: 		text-indent:-99999px;
 7191: 		overflow:hidden;
 7192: 		cursor:pointer;
 7193: }
 7194: 
 7195: /*
 7196:   styles used by TTH when "Default set of options to pass to tth/m
 7197:   when converting TeX" in course settings has been set
 7198: 
 7199:   option passed: -t
 7200: 
 7201: */
 7202: 
 7203: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7204: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7205: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7206: td div.norm {line-height:normal;}
 7207: 
 7208: /*
 7209:   option passed -y3
 7210: */
 7211: 
 7212: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7213: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7214: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7215: 
 7216: END
 7217: }
 7218: 
 7219: =pod
 7220: 
 7221: =item * &headtag()
 7222: 
 7223: Returns a uniform footer for LON-CAPA web pages.
 7224: 
 7225: Inputs: $title - optional title for the head
 7226:         $head_extra - optional extra HTML to put inside the <head>
 7227:         $args - optional arguments
 7228:             force_register - if is true call registerurl so the remote is 
 7229:                              informed
 7230:             redirect       -> array ref of
 7231:                                    1- seconds before redirect occurs
 7232:                                    2- url to redirect to
 7233:                                    3- whether the side effect should occur
 7234:                            (side effect of setting 
 7235:                                $env{'internal.head.redirect'} to the url 
 7236:                                redirected too)
 7237:             domain         -> force to color decorate a page for a specific
 7238:                                domain
 7239:             function       -> force usage of a specific rolish color scheme
 7240:             bgcolor        -> override the default page bgcolor
 7241:             no_auto_mt_title
 7242:                            -> prevent &mt()ing the title arg
 7243: 
 7244: =cut
 7245: 
 7246: sub headtag {
 7247:     my ($title,$head_extra,$args) = @_;
 7248:     
 7249:     my $function = $args->{'function'} || &get_users_function();
 7250:     my $domain   = $args->{'domain'}   || &determinedomain();
 7251:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7252:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7253: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7254: 		   #time(),
 7255: 		   $env{'environment.color.timestamp'},
 7256: 		   $function,$domain,$bgcolor);
 7257: 
 7258:     $url = '/adm/css/'.&escape($url).'.css';
 7259: 
 7260:     my $result =
 7261: 	'<head>'.
 7262: 	&font_settings();
 7263: 
 7264:     my $inhibitprint = &print_suppression();
 7265: 
 7266:     if (!$args->{'frameset'}) {
 7267: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7268:     }
 7269:     if ($args->{'force_register'}) {
 7270:         $result .= &Apache::lonmenu::registerurl(1);
 7271:     }
 7272:     if (!$args->{'no_nav_bar'} 
 7273: 	&& !$args->{'only_body'}
 7274: 	&& !$args->{'frameset'}) {
 7275: 	$result .= &help_menu_js();
 7276:         $result.=&modal_window();
 7277:         $result.=&togglebox_script();
 7278:         $result.=&wishlist_window();
 7279:         $result.=&LCprogressbarUpdate_script();
 7280:     } else {
 7281:         if ($args->{'add_modal'}) {
 7282:            $result.=&modal_window();
 7283:         }
 7284:         if ($args->{'add_wishlist'}) {
 7285:            $result.=&wishlist_window();
 7286:         }
 7287:         if ($args->{'add_togglebox'}) {
 7288:            $result.=&togglebox_script();
 7289:         }
 7290:         if ($args->{'add_progressbar'}) {
 7291:            $result.=&LCprogressbarUpdate_script();
 7292:         }
 7293:     }
 7294:     if (ref($args->{'redirect'})) {
 7295: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7296: 	$url = &Apache::lonenc::check_encrypt($url);
 7297: 	if (!$inhibit_continue) {
 7298: 	    $env{'internal.head.redirect'} = $url;
 7299: 	}
 7300: 	$result.=<<ADDMETA
 7301: <meta http-equiv="pragma" content="no-cache" />
 7302: <meta http-equiv="Refresh" content="$time; url=$url" />
 7303: ADDMETA
 7304:     }
 7305:     if (!defined($title)) {
 7306: 	$title = 'The LearningOnline Network with CAPA';
 7307:     }
 7308:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7309:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7310: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7311:         .$inhibitprint
 7312: 	.$head_extra;
 7313:     if ($env{'browser.mobile'}) {
 7314:         $result .= '
 7315: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7316: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7317:     }
 7318:     return $result.'</head>';
 7319: }
 7320: 
 7321: =pod
 7322: 
 7323: =item * &font_settings()
 7324: 
 7325: Returns neccessary <meta> to set the proper encoding
 7326: 
 7327: Inputs: none
 7328: 
 7329: =cut
 7330: 
 7331: sub font_settings {
 7332:     my $headerstring='';
 7333:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7334: 	$headerstring.=
 7335: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7336:     }
 7337:     return $headerstring;
 7338: }
 7339: 
 7340: =pod
 7341: 
 7342: =item * &print_suppression()
 7343: 
 7344: In course context returns css which causes the body to be blank when media="print",
 7345: if printout generation is unavailable for the current resource.
 7346: 
 7347: This could be because:
 7348: 
 7349: (a) printstartdate is in the future
 7350: 
 7351: (b) printenddate is in the past
 7352: 
 7353: (c) there is an active exam block with "printout"
 7354: functionality blocked
 7355: 
 7356: Users with pav, pfo or evb privileges are exempt.
 7357: 
 7358: Inputs: none
 7359: 
 7360: =cut
 7361: 
 7362: 
 7363: sub print_suppression {
 7364:     my $noprint;
 7365:     if ($env{'request.course.id'}) {
 7366:         my $scope = $env{'request.course.id'};
 7367:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7368:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7369:             return;
 7370:         }
 7371:         if ($env{'request.course.sec'} ne '') {
 7372:             $scope .= "/$env{'request.course.sec'}";
 7373:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7374:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7375:                 return;
 7376:             }
 7377:         }
 7378:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7379:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7380:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7381:         if ($blocked) {
 7382:             my $checkrole = "cm./$cdom/$cnum";
 7383:             if ($env{'request.course.sec'} ne '') {
 7384:                 $checkrole .= "/$env{'request.course.sec'}";
 7385:             }
 7386:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7387:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7388:                 $noprint = 1;
 7389:             }
 7390:         }
 7391:         unless ($noprint) {
 7392:             my $symb = &Apache::lonnet::symbread();
 7393:             if ($symb ne '') {
 7394:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7395:                 if (ref($navmap)) {
 7396:                     my $res = $navmap->getBySymb($symb);
 7397:                     if (ref($res)) {
 7398:                         if (!$res->resprintable()) {
 7399:                             $noprint = 1;
 7400:                         }
 7401:                     }
 7402:                 }
 7403:             }
 7404:         }
 7405:         if ($noprint) {
 7406:             return <<"ENDSTYLE";
 7407: <style type="text/css" media="print">
 7408:     body { display:none }
 7409: </style>
 7410: ENDSTYLE
 7411:         }
 7412:     }
 7413:     return;
 7414: }
 7415: 
 7416: =pod
 7417: 
 7418: =item * &xml_begin()
 7419: 
 7420: Returns the needed doctype and <html>
 7421: 
 7422: Inputs: none
 7423: 
 7424: =cut
 7425: 
 7426: sub xml_begin {
 7427:     my $output='';
 7428: 
 7429:     if ($env{'browser.mathml'}) {
 7430: 	$output='<?xml version="1.0"?>'
 7431:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7432: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7433:             
 7434: #	    .'<!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">] >'
 7435: 	    .'<!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">'
 7436:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7437: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7438:     } else {
 7439: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7440:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7441:     }
 7442:     return $output;
 7443: }
 7444: 
 7445: =pod
 7446: 
 7447: =item * &start_page()
 7448: 
 7449: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7450: 
 7451: Inputs:
 7452: 
 7453: =over 4
 7454: 
 7455: $title - optional title for the page
 7456: 
 7457: $head_extra - optional extra HTML to incude inside the <head>
 7458: 
 7459: $args - additional optional args supported are:
 7460: 
 7461: =over 8
 7462: 
 7463:              only_body      -> is true will set &bodytag() onlybodytag
 7464:                                     arg on
 7465:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7466:              add_entries    -> additional attributes to add to the  <body>
 7467:              domain         -> force to color decorate a page for a 
 7468:                                     specific domain
 7469:              function       -> force usage of a specific rolish color
 7470:                                     scheme
 7471:              redirect       -> see &headtag()
 7472:              bgcolor        -> override the default page bg color
 7473:              js_ready       -> return a string ready for being used in 
 7474:                                     a javascript writeln
 7475:              html_encode    -> return a string ready for being used in 
 7476:                                     a html attribute
 7477:              force_register -> if is true will turn on the &bodytag()
 7478:                                     $forcereg arg
 7479:              frameset       -> if true will start with a <frameset>
 7480:                                     rather than <body>
 7481:              skip_phases    -> hash ref of 
 7482:                                     head -> skip the <html><head> generation
 7483:                                     body -> skip all <body> generation
 7484:              no_inline_link -> if true and in remote mode, don't show the
 7485:                                     'Switch To Inline Menu' link
 7486:              no_auto_mt_title -> prevent &mt()ing the title arg
 7487:              inherit_jsmath -> when creating popup window in a page,
 7488:                                     should it have jsmath forced on by the
 7489:                                     current page
 7490:              bread_crumbs ->             Array containing breadcrumbs
 7491:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7492:              group          -> includes the current group, if page is for a
 7493:                                specific group
 7494: 
 7495: =back
 7496: 
 7497: =back
 7498: 
 7499: =cut
 7500: 
 7501: sub start_page {
 7502:     my ($title,$head_extra,$args) = @_;
 7503:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7504: 
 7505:     $env{'internal.start_page'}++;
 7506:     my ($result,@advtools);
 7507: 
 7508:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7509:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7510:     }
 7511:     
 7512:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7513: 	if ($args->{'frameset'}) {
 7514: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7515: 						$args->{'add_entries'});
 7516: 	    $result .= "\n<frameset $attr_string>\n";
 7517:         } else {
 7518:             $result .=
 7519:                 &bodytag($title, 
 7520:                          $args->{'function'},       $args->{'add_entries'},
 7521:                          $args->{'only_body'},      $args->{'domain'},
 7522:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7523:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7524:                          $args,                     \@advtools);
 7525:         }
 7526:     }
 7527: 
 7528:     if ($args->{'js_ready'}) {
 7529: 		$result = &js_ready($result);
 7530:     }
 7531:     if ($args->{'html_encode'}) {
 7532: 		$result = &html_encode($result);
 7533:     }
 7534: 
 7535:     # Preparation for new and consistent functionlist at top of screen
 7536:     # if ($args->{'functionlist'}) {
 7537:     #            $result .= &build_functionlist();
 7538:     #}
 7539: 
 7540:     # Don't add anything more if only_body wanted or in const space
 7541:     return $result if    $args->{'only_body'} 
 7542:                       || $env{'request.state'} eq 'construct';
 7543: 
 7544:     #Breadcrumbs
 7545:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7546: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7547: 		#if any br links exists, add them to the breadcrumbs
 7548: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7549: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7550: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7551: 			}
 7552: 		}
 7553:                 # if @advtools array contains items add then to the breadcrumbs
 7554:                 if (@advtools > 0) {
 7555:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7556:                 }
 7557: 
 7558: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7559: 		if(exists($args->{'bread_crumbs_component'})){
 7560: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7561: 		}else{
 7562: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7563: 		}
 7564:     } elsif (($env{'environment.remote'} eq 'on') &&
 7565:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7566:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7567:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7568:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7569:     }
 7570:     return $result;
 7571: }
 7572: 
 7573: sub end_page {
 7574:     my ($args) = @_;
 7575:     $env{'internal.end_page'}++;
 7576:     my $result;
 7577:     if ($args->{'discussion'}) {
 7578: 	my ($target,$parser);
 7579: 	if (ref($args->{'discussion'})) {
 7580: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7581: 				$args->{'discussion'}{'parser'});
 7582: 	}
 7583: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7584:     }
 7585:     if ($args->{'frameset'}) {
 7586: 	$result .= '</frameset>';
 7587:     } else {
 7588: 	$result .= &endbodytag($args);
 7589:     }
 7590:     unless ($args->{'notbody'}) {
 7591:         $result .= "\n</html>";
 7592:     }
 7593: 
 7594:     if ($args->{'js_ready'}) {
 7595: 	$result = &js_ready($result);
 7596:     }
 7597: 
 7598:     if ($args->{'html_encode'}) {
 7599: 	$result = &html_encode($result);
 7600:     }
 7601: 
 7602:     return $result;
 7603: }
 7604: 
 7605: sub wishlist_window {
 7606:     return(<<'ENDWISHLIST');
 7607: <script type="text/javascript">
 7608: // <![CDATA[
 7609: // <!-- BEGIN LON-CAPA Internal
 7610: function set_wishlistlink(title, path) {
 7611:     if (!title) {
 7612:         title = document.title;
 7613:         title = title.replace(/^LON-CAPA /,'');
 7614:     }
 7615:     if (!path) {
 7616:         path = location.pathname;
 7617:     }
 7618:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7619:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7620: }
 7621: // END LON-CAPA Internal -->
 7622: // ]]>
 7623: </script>
 7624: ENDWISHLIST
 7625: }
 7626: 
 7627: sub modal_window {
 7628:     return(<<'ENDMODAL');
 7629: <script type="text/javascript">
 7630: // <![CDATA[
 7631: // <!-- BEGIN LON-CAPA Internal
 7632: var modalWindow = {
 7633: 	parent:"body",
 7634: 	windowId:null,
 7635: 	content:null,
 7636: 	width:null,
 7637: 	height:null,
 7638: 	close:function()
 7639: 	{
 7640: 	        $(".LCmodal-window").remove();
 7641: 	        $(".LCmodal-overlay").remove();
 7642: 	},
 7643: 	open:function()
 7644: 	{
 7645: 		var modal = "";
 7646: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7647: 		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;\">";
 7648: 		modal += this.content;
 7649: 		modal += "</div>";	
 7650: 
 7651: 		$(this.parent).append(modal);
 7652: 
 7653: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7654: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7655: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7656: 	}
 7657: };
 7658: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7659: 	{
 7660: 		modalWindow.windowId = "myModal";
 7661: 		modalWindow.width = width;
 7662: 		modalWindow.height = height;
 7663: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7664: 		modalWindow.open();
 7665: 	};	
 7666: // END LON-CAPA Internal -->
 7667: // ]]>
 7668: </script>
 7669: ENDMODAL
 7670: }
 7671: 
 7672: sub modal_link {
 7673:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7674:     unless ($width) { $width=480; }
 7675:     unless ($height) { $height=400; }
 7676:     unless ($scrolling) { $scrolling='yes'; }
 7677:     unless ($transparency) { $transparency='true'; }
 7678: 
 7679:     my $target_attr;
 7680:     if (defined($target)) {
 7681:         $target_attr = 'target="'.$target.'"';
 7682:     }
 7683:     return <<"ENDLINK";
 7684: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7685:            $linktext</a>
 7686: ENDLINK
 7687: }
 7688: 
 7689: sub modal_adhoc_script {
 7690:     my ($funcname,$width,$height,$content)=@_;
 7691:     return (<<ENDADHOC);
 7692: <script type="text/javascript">
 7693: // <![CDATA[
 7694:         var $funcname = function()
 7695:         {
 7696:                 modalWindow.windowId = "myModal";
 7697:                 modalWindow.width = $width;
 7698:                 modalWindow.height = $height;
 7699:                 modalWindow.content = '$content';
 7700:                 modalWindow.open();
 7701:         };  
 7702: // ]]>
 7703: </script>
 7704: ENDADHOC
 7705: }
 7706: 
 7707: sub modal_adhoc_inner {
 7708:     my ($funcname,$width,$height,$content)=@_;
 7709:     my $innerwidth=$width-20;
 7710:     $content=&js_ready(
 7711:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7712:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7713:                  $content.
 7714:                  &end_scrollbox().
 7715:                  &end_page()
 7716:              );
 7717:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7718: }
 7719: 
 7720: sub modal_adhoc_window {
 7721:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7722:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7723:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7724: }
 7725: 
 7726: sub modal_adhoc_launch {
 7727:     my ($funcname,$width,$height,$content)=@_;
 7728:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7729: <script type="text/javascript">
 7730: // <![CDATA[
 7731: $funcname();
 7732: // ]]>
 7733: </script>
 7734: ENDLAUNCH
 7735: }
 7736: 
 7737: sub modal_adhoc_close {
 7738:     return (<<ENDCLOSE);
 7739: <script type="text/javascript">
 7740: // <![CDATA[
 7741: modalWindow.close();
 7742: // ]]>
 7743: </script>
 7744: ENDCLOSE
 7745: }
 7746: 
 7747: sub togglebox_script {
 7748:    return(<<ENDTOGGLE);
 7749: <script type="text/javascript"> 
 7750: // <![CDATA[
 7751: function LCtoggleDisplay(id,hidetext,showtext) {
 7752:    link = document.getElementById(id + "link").childNodes[0];
 7753:    with (document.getElementById(id).style) {
 7754:       if (display == "none" ) {
 7755:           display = "inline";
 7756:           link.nodeValue = hidetext;
 7757:         } else {
 7758:           display = "none";
 7759:           link.nodeValue = showtext;
 7760:        }
 7761:    }
 7762: }
 7763: // ]]>
 7764: </script>
 7765: ENDTOGGLE
 7766: }
 7767: 
 7768: sub start_togglebox {
 7769:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7770:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7771:     unless ($showtext) { $showtext=&mt('show'); }
 7772:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7773:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7774:     return &start_data_table().
 7775:            &start_data_table_header_row().
 7776:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7777:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7778:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7779:            &end_data_table_header_row().
 7780:            '<tr id="'.$id.'" style="display:none""><td>';
 7781: }
 7782: 
 7783: sub end_togglebox {
 7784:     return '</td></tr>'.&end_data_table();
 7785: }
 7786: 
 7787: sub LCprogressbar_script {
 7788:    my ($id)=@_;
 7789:    return(<<ENDPROGRESS);
 7790: <script type="text/javascript">
 7791: // <![CDATA[
 7792: \$('#progressbar$id').progressbar({
 7793:   value: 0,
 7794:   change: function(event, ui) {
 7795:     var newVal = \$(this).progressbar('option', 'value');
 7796:     \$('.pblabel', this).text(LCprogressTxt);
 7797:   }
 7798: });
 7799: // ]]>
 7800: </script>
 7801: ENDPROGRESS
 7802: }
 7803: 
 7804: sub LCprogressbarUpdate_script {
 7805:    return(<<ENDPROGRESSUPDATE);
 7806: <style type="text/css">
 7807: .ui-progressbar { position:relative; }
 7808: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7809: </style>
 7810: <script type="text/javascript">
 7811: // <![CDATA[
 7812: var LCprogressTxt='---';
 7813: 
 7814: function LCupdateProgress(percent,progresstext,id) {
 7815:    LCprogressTxt=progresstext;
 7816:    \$('#progressbar'+id).progressbar('value',percent);
 7817: }
 7818: // ]]>
 7819: </script>
 7820: ENDPROGRESSUPDATE
 7821: }
 7822: 
 7823: my $LClastpercent;
 7824: my $LCidcnt;
 7825: my $LCcurrentid;
 7826: 
 7827: sub LCprogressbar {
 7828:     my ($r)=(@_);
 7829:     $LClastpercent=0;
 7830:     $LCidcnt++;
 7831:     $LCcurrentid=$$.'_'.$LCidcnt;
 7832:     my $starting=&mt('Starting');
 7833:     my $content=(<<ENDPROGBAR);
 7834:   <div id="progressbar$LCcurrentid">
 7835:     <span class="pblabel">$starting</span>
 7836:   </div>
 7837: ENDPROGBAR
 7838:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7839: }
 7840: 
 7841: sub LCprogressbarUpdate {
 7842:     my ($r,$val,$text)=@_;
 7843:     unless ($val) { 
 7844:        if ($LClastpercent) {
 7845:            $val=$LClastpercent;
 7846:        } else {
 7847:            $val=0;
 7848:        }
 7849:     }
 7850:     if ($val<0) { $val=0; }
 7851:     if ($val>100) { $val=0; }
 7852:     $LClastpercent=$val;
 7853:     unless ($text) { $text=$val.'%'; }
 7854:     $text=&js_ready($text);
 7855:     &r_print($r,<<ENDUPDATE);
 7856: <script type="text/javascript">
 7857: // <![CDATA[
 7858: LCupdateProgress($val,'$text','$LCcurrentid');
 7859: // ]]>
 7860: </script>
 7861: ENDUPDATE
 7862: }
 7863: 
 7864: sub LCprogressbarClose {
 7865:     my ($r)=@_;
 7866:     $LClastpercent=0;
 7867:     &r_print($r,<<ENDCLOSE);
 7868: <script type="text/javascript">
 7869: // <![CDATA[
 7870: \$("#progressbar$LCcurrentid").hide('slow'); 
 7871: // ]]>
 7872: </script>
 7873: ENDCLOSE
 7874: }
 7875: 
 7876: sub r_print {
 7877:     my ($r,$to_print)=@_;
 7878:     if ($r) {
 7879:       $r->print($to_print);
 7880:       $r->rflush();
 7881:     } else {
 7882:       print($to_print);
 7883:     }
 7884: }
 7885: 
 7886: sub html_encode {
 7887:     my ($result) = @_;
 7888: 
 7889:     $result = &HTML::Entities::encode($result,'<>&"');
 7890:     
 7891:     return $result;
 7892: }
 7893: 
 7894: sub js_ready {
 7895:     my ($result) = @_;
 7896: 
 7897:     $result =~ s/[\n\r]/ /xmsg;
 7898:     $result =~ s/\\/\\\\/xmsg;
 7899:     $result =~ s/'/\\'/xmsg;
 7900:     $result =~ s{</}{<\\/}xmsg;
 7901:     
 7902:     return $result;
 7903: }
 7904: 
 7905: sub validate_page {
 7906:     if (  exists($env{'internal.start_page'})
 7907: 	  &&     $env{'internal.start_page'} > 1) {
 7908: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7909: 				 $env{'internal.start_page'}.' '.
 7910: 				 $ENV{'request.filename'});
 7911:     }
 7912:     if (  exists($env{'internal.end_page'})
 7913: 	  &&     $env{'internal.end_page'} > 1) {
 7914: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7915: 				 $env{'internal.end_page'}.' '.
 7916: 				 $env{'request.filename'});
 7917:     }
 7918:     if (     exists($env{'internal.start_page'})
 7919: 	&& ! exists($env{'internal.end_page'})) {
 7920: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7921: 				 $env{'request.filename'});
 7922:     }
 7923:     if (   ! exists($env{'internal.start_page'})
 7924: 	&&   exists($env{'internal.end_page'})) {
 7925: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7926: 				 $env{'request.filename'});
 7927:     }
 7928: }
 7929: 
 7930: 
 7931: sub start_scrollbox {
 7932:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready)=@_;
 7933:     unless ($outerwidth) { $outerwidth='520px'; }
 7934:     unless ($width) { $width='500px'; }
 7935:     unless ($height) { $height='200px'; }
 7936:     my ($table_id,$div_id,$tdcol);
 7937:     if ($id ne '') {
 7938:         $table_id = ' id="table_'.$id.'"';
 7939:         $div_id = ' id="div_'.$id.'"';
 7940:     }
 7941:     if ($bgcolor ne '') {
 7942:         $tdcol = "background-color: $bgcolor;";
 7943:     }
 7944:     my $nicescroll_js;
 7945:     if ($env{'browser.mobile'}) {
 7946:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 7947:     }
 7948:     return <<"END";
 7949: $nicescroll_js
 7950: 
 7951: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 7952: <div style="overflow:auto; width:$width; height: $height;"$div_id>
 7953: END
 7954: }
 7955: 
 7956: sub end_scrollbox {
 7957:     return '</div></td></tr></table>';
 7958: }
 7959: 
 7960: sub nicescroll_javascript {
 7961:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 7962:     my %options;
 7963:     if (ref($cursor) eq 'HASH') {
 7964:         %options = %{$cursor};
 7965:     }
 7966:     unless ($options{'railalign'} =~ /^left|right$/) {
 7967:         $options{'railalign'} = 'left';
 7968:     }
 7969:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7970:         my $function  = &get_users_function();
 7971:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 7972:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 7973:             $options{'cursorcolor'} = '#00F';
 7974:         }
 7975:     }
 7976:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 7977:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 7978:             $options{'cursoropacity'}='1.0';
 7979:         }
 7980:     } else {
 7981:         $options{'cursoropacity'}='1.0';
 7982:     }
 7983:     if ($options{'cursorfixedheight'} eq 'none') {
 7984:         delete($options{'cursorfixedheight'});
 7985:     } else {
 7986:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 7987:     }
 7988:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 7989:         delete($options{'railoffset'});
 7990:     }
 7991:     my @niceoptions;
 7992:     while (my($key,$value) = each(%options)) {
 7993:         if ($value =~ /^\{.+\}$/) {
 7994:             push(@niceoptions,$key.':'.$value);
 7995:         } else {
 7996:             push(@niceoptions,$key.':"'.$value.'"');
 7997:         }
 7998:     }
 7999:     my $nicescroll_js = '
 8000: $(document).ready(
 8001:       function() {
 8002:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8003:       }
 8004: );
 8005: ';
 8006:     if ($framecheck) {
 8007:         $nicescroll_js .= '
 8008: function expand_div(caller) {
 8009:     if (top === self) {
 8010:         document.getElementById("'.$id.'").style.width = "auto";
 8011:         document.getElementById("'.$id.'").style.height = "auto";
 8012:     } else {
 8013:         try {
 8014:             if (parent.frames) {
 8015:                 if (parent.frames.length > 1) {
 8016:                     var framesrc = parent.frames[1].location.href;
 8017:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8018:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8019:                         document.getElementById("'.$id.'").style.width = "auto";
 8020:                         document.getElementById("'.$id.'").style.height = "auto";
 8021:                     }
 8022:                 }
 8023:             }
 8024:         } catch (e) {
 8025:             return;
 8026:         }
 8027:     }
 8028:     return;
 8029: }
 8030: ';
 8031:     }
 8032:     if ($needjsready) {
 8033:         $nicescroll_js = '
 8034: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8035:     } else {
 8036:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8037:     }
 8038:     return $nicescroll_js;
 8039: }
 8040: 
 8041: sub simple_error_page {
 8042:     my ($r,$title,$msg,$args) = @_;
 8043:     if (ref($args) eq 'HASH') {
 8044:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8045:     } else {
 8046:         $msg = &mt($msg);
 8047:     }
 8048: 
 8049:     my $page =
 8050: 	&Apache::loncommon::start_page($title).
 8051: 	'<p class="LC_error">'.$msg.'</p>'.
 8052: 	&Apache::loncommon::end_page();
 8053:     if (ref($r)) {
 8054: 	$r->print($page);
 8055: 	return;
 8056:     }
 8057:     return $page;
 8058: }
 8059: 
 8060: {
 8061:     my @row_count;
 8062: 
 8063:     sub start_data_table_count {
 8064:         unshift(@row_count, 0);
 8065:         return;
 8066:     }
 8067: 
 8068:     sub end_data_table_count {
 8069:         shift(@row_count);
 8070:         return;
 8071:     }
 8072: 
 8073:     sub start_data_table {
 8074: 	my ($add_class,$id) = @_;
 8075: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8076:         my $table_id;
 8077:         if (defined($id)) {
 8078:             $table_id = ' id="'.$id.'"';
 8079:         }
 8080: 	&start_data_table_count();
 8081: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8082:     }
 8083: 
 8084:     sub end_data_table {
 8085: 	&end_data_table_count();
 8086: 	return '</table>'."\n";;
 8087:     }
 8088: 
 8089:     sub start_data_table_row {
 8090: 	my ($add_class, $id) = @_;
 8091: 	$row_count[0]++;
 8092: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8093: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8094:         $id = (' id="'.$id.'"') unless ($id eq '');
 8095:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8096:     }
 8097:     
 8098:     sub continue_data_table_row {
 8099: 	my ($add_class, $id) = @_;
 8100: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8101: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8102:         $id = (' id="'.$id.'"') unless ($id eq '');
 8103:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8104:     }
 8105: 
 8106:     sub end_data_table_row {
 8107: 	return '</tr>'."\n";;
 8108:     }
 8109: 
 8110:     sub start_data_table_empty_row {
 8111: #	$row_count[0]++;
 8112: 	return  '<tr class="LC_empty_row" >'."\n";;
 8113:     }
 8114: 
 8115:     sub end_data_table_empty_row {
 8116: 	return '</tr>'."\n";;
 8117:     }
 8118: 
 8119:     sub start_data_table_header_row {
 8120: 	return  '<tr class="LC_header_row">'."\n";;
 8121:     }
 8122: 
 8123:     sub end_data_table_header_row {
 8124: 	return '</tr>'."\n";;
 8125:     }
 8126: 
 8127:     sub data_table_caption {
 8128:         my $caption = shift;
 8129:         return "<caption class=\"LC_caption\">$caption</caption>";
 8130:     }
 8131: }
 8132: 
 8133: =pod
 8134: 
 8135: =item * &inhibit_menu_check($arg)
 8136: 
 8137: Checks for a inhibitmenu state and generates output to preserve it
 8138: 
 8139: Inputs:         $arg - can be any of
 8140:                      - undef - in which case the return value is a string 
 8141:                                to add  into arguments list of a uri
 8142:                      - 'input' - in which case the return value is a HTML
 8143:                                  <form> <input> field of type hidden to
 8144:                                  preserve the value
 8145:                      - a url - in which case the return value is the url with
 8146:                                the neccesary cgi args added to preserve the
 8147:                                inhibitmenu state
 8148:                      - a ref to a url - no return value, but the string is
 8149:                                         updated to include the neccessary cgi
 8150:                                         args to preserve the inhibitmenu state
 8151: 
 8152: =cut
 8153: 
 8154: sub inhibit_menu_check {
 8155:     my ($arg) = @_;
 8156:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8157:     if ($arg eq 'input') {
 8158: 	if ($env{'form.inhibitmenu'}) {
 8159: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8160: 	} else {
 8161: 	    return
 8162: 	}
 8163:     }
 8164:     if ($env{'form.inhibitmenu'}) {
 8165: 	if (ref($arg)) {
 8166: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8167: 	} elsif ($arg eq '') {
 8168: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8169: 	} else {
 8170: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8171: 	}
 8172:     }
 8173:     if (!ref($arg)) {
 8174: 	return $arg;
 8175:     }
 8176: }
 8177: 
 8178: ###############################################
 8179: 
 8180: =pod
 8181: 
 8182: =back
 8183: 
 8184: =head1 User Information Routines
 8185: 
 8186: =over 4
 8187: 
 8188: =item * &get_users_function()
 8189: 
 8190: Used by &bodytag to determine the current users primary role.
 8191: Returns either 'student','coordinator','admin', or 'author'.
 8192: 
 8193: =cut
 8194: 
 8195: ###############################################
 8196: sub get_users_function {
 8197:     my $function = 'norole';
 8198:     if ($env{'request.role'}=~/^(st)/) {
 8199:         $function='student';
 8200:     }
 8201:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8202:         $function='coordinator';
 8203:     }
 8204:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8205:         $function='admin';
 8206:     }
 8207:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8208:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8209:         $function='author';
 8210:     }
 8211:     return $function;
 8212: }
 8213: 
 8214: ###############################################
 8215: 
 8216: =pod
 8217: 
 8218: =item * &show_course()
 8219: 
 8220: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8221: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8222: 
 8223: Inputs:
 8224: None
 8225: 
 8226: Outputs:
 8227: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8228: 
 8229: =cut
 8230: 
 8231: ###############################################
 8232: sub show_course {
 8233:     my $course = !$env{'user.adv'};
 8234:     if (!$env{'user.adv'}) {
 8235:         foreach my $env (keys(%env)) {
 8236:             next if ($env !~ m/^user\.priv\./);
 8237:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8238:                 $course = 0;
 8239:                 last;
 8240:             }
 8241:         }
 8242:     }
 8243:     return $course;
 8244: }
 8245: 
 8246: ###############################################
 8247: 
 8248: =pod
 8249: 
 8250: =item * &check_user_status()
 8251: 
 8252: Determines current status of supplied role for a
 8253: specific user. Roles can be active, previous or future.
 8254: 
 8255: Inputs: 
 8256: user's domain, user's username, course's domain,
 8257: course's number, optional section ID.
 8258: 
 8259: Outputs:
 8260: role status: active, previous or future. 
 8261: 
 8262: =cut
 8263: 
 8264: sub check_user_status {
 8265:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8266:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8267:     my @uroles = keys %userinfo;
 8268:     my $srchstr;
 8269:     my $active_chk = 'none';
 8270:     my $now = time;
 8271:     if (@uroles > 0) {
 8272:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8273:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8274:         } else {
 8275:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8276:         }
 8277:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8278:             my $role_end = 0;
 8279:             my $role_start = 0;
 8280:             $active_chk = 'active';
 8281:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8282:                 $role_end = $1;
 8283:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8284:                     $role_start = $1;
 8285:                 }
 8286:             }
 8287:             if ($role_start > 0) {
 8288:                 if ($now < $role_start) {
 8289:                     $active_chk = 'future';
 8290:                 }
 8291:             }
 8292:             if ($role_end > 0) {
 8293:                 if ($now > $role_end) {
 8294:                     $active_chk = 'previous';
 8295:                 }
 8296:             }
 8297:         }
 8298:     }
 8299:     return $active_chk;
 8300: }
 8301: 
 8302: ###############################################
 8303: 
 8304: =pod
 8305: 
 8306: =item * &get_sections()
 8307: 
 8308: Determines all the sections for a course including
 8309: sections with students and sections containing other roles.
 8310: Incoming parameters: 
 8311: 
 8312: 1. domain
 8313: 2. course number 
 8314: 3. reference to array containing roles for which sections should 
 8315: be gathered (optional).
 8316: 4. reference to array containing status types for which sections 
 8317: should be gathered (optional).
 8318: 
 8319: If the third argument is undefined, sections are gathered for any role. 
 8320: If the fourth argument is undefined, sections are gathered for any status.
 8321: Permissible values are 'active' or 'future' or 'previous'.
 8322:  
 8323: Returns section hash (keys are section IDs, values are
 8324: number of users in each section), subject to the
 8325: optional roles filter, optional status filter 
 8326: 
 8327: =cut
 8328: 
 8329: ###############################################
 8330: sub get_sections {
 8331:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8332:     if (!defined($cdom) || !defined($cnum)) {
 8333:         my $cid =  $env{'request.course.id'};
 8334: 
 8335: 	return if (!defined($cid));
 8336: 
 8337:         $cdom = $env{'course.'.$cid.'.domain'};
 8338:         $cnum = $env{'course.'.$cid.'.num'};
 8339:     }
 8340: 
 8341:     my %sectioncount;
 8342:     my $now = time;
 8343: 
 8344:     my $check_students = 1;
 8345:     my $only_students = 0;
 8346:     if (ref($possible_roles) eq 'ARRAY') {
 8347:         if (grep(/^st$/,@{$possible_roles})) {
 8348:             if (@{$possible_roles} == 1) {
 8349:                 $only_students = 1;
 8350:             }
 8351:         } else {
 8352:             $check_students = 0;
 8353:         }
 8354:     }
 8355: 
 8356:     if ($check_students) {
 8357: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8358: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8359: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8360:         my $start_index = &Apache::loncoursedata::CL_START();
 8361:         my $end_index = &Apache::loncoursedata::CL_END();
 8362:         my $status;
 8363: 	while (my ($student,$data) = each(%$classlist)) {
 8364: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8365: 				                     $data->[$status_index],
 8366:                                                      $data->[$start_index],
 8367:                                                      $data->[$end_index]);
 8368:             if ($stu_status eq 'Active') {
 8369:                 $status = 'active';
 8370:             } elsif ($end < $now) {
 8371:                 $status = 'previous';
 8372:             } elsif ($start > $now) {
 8373:                 $status = 'future';
 8374:             } 
 8375: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8376:                 if ((!defined($possible_status)) || (($status ne '') && 
 8377:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8378: 		    $sectioncount{$section}++;
 8379:                 }
 8380: 	    }
 8381: 	}
 8382:     }
 8383:     if ($only_students) {
 8384:         return %sectioncount;
 8385:     }
 8386:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8387:     foreach my $user (sort(keys(%courseroles))) {
 8388: 	if ($user !~ /^(\w{2})/) { next; }
 8389: 	my ($role) = ($user =~ /^(\w{2})/);
 8390: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8391: 	my ($section,$status);
 8392: 	if ($role eq 'cr' &&
 8393: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8394: 	    $section=$1;
 8395: 	}
 8396: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8397: 	if (!defined($section) || $section eq '-1') { next; }
 8398:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8399:         if ($end == -1 && $start == -1) {
 8400:             next; #deleted role
 8401:         }
 8402:         if (!defined($possible_status)) { 
 8403:             $sectioncount{$section}++;
 8404:         } else {
 8405:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8406:                 $status = 'active';
 8407:             } elsif ($end < $now) {
 8408:                 $status = 'future';
 8409:             } elsif ($start > $now) {
 8410:                 $status = 'previous';
 8411:             }
 8412:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8413:                 $sectioncount{$section}++;
 8414:             }
 8415:         }
 8416:     }
 8417:     return %sectioncount;
 8418: }
 8419: 
 8420: ###############################################
 8421: 
 8422: =pod
 8423: 
 8424: =item * &get_course_users()
 8425: 
 8426: Retrieves usernames:domains for users in the specified course
 8427: with specific role(s), and access status. 
 8428: 
 8429: Incoming parameters:
 8430: 1. course domain
 8431: 2. course number
 8432: 3. access status: users must have - either active, 
 8433: previous, future, or all.
 8434: 4. reference to array of permissible roles
 8435: 5. reference to array of section restrictions (optional)
 8436: 6. reference to results object (hash of hashes).
 8437: 7. reference to optional userdata hash
 8438: 8. reference to optional statushash
 8439: 9. flag if privileged users (except those set to unhide in
 8440:    course settings) should be excluded    
 8441: Keys of top level results hash are roles.
 8442: Keys of inner hashes are username:domain, with 
 8443: values set to access type.
 8444: Optional userdata hash returns an array with arguments in the 
 8445: same order as loncoursedata::get_classlist() for student data.
 8446: 
 8447: Optional statushash returns
 8448: 
 8449: Entries for end, start, section and status are blank because
 8450: of the possibility of multiple values for non-student roles.
 8451: 
 8452: =cut
 8453: 
 8454: ###############################################
 8455: 
 8456: sub get_course_users {
 8457:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8458:     my %idx = ();
 8459:     my %seclists;
 8460: 
 8461:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8462:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8463:     $idx{end} = &Apache::loncoursedata::CL_END();
 8464:     $idx{start} = &Apache::loncoursedata::CL_START();
 8465:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8466:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8467:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8468:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8469: 
 8470:     if (grep(/^st$/,@{$roles})) {
 8471:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8472:         my $now = time;
 8473:         foreach my $student (keys(%{$classlist})) {
 8474:             my $match = 0;
 8475:             my $secmatch = 0;
 8476:             my $section = $$classlist{$student}[$idx{section}];
 8477:             my $status = $$classlist{$student}[$idx{status}];
 8478:             if ($section eq '') {
 8479:                 $section = 'none';
 8480:             }
 8481:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8482:                 if (grep(/^all$/,@{$sections})) {
 8483:                     $secmatch = 1;
 8484:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8485:                     if (grep(/^none$/,@{$sections})) {
 8486:                         $secmatch = 1;
 8487:                     }
 8488:                 } else {  
 8489: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8490: 		        $secmatch = 1;
 8491:                     }
 8492: 		}
 8493:                 if (!$secmatch) {
 8494:                     next;
 8495:                 }
 8496:             }
 8497:             if (defined($$types{'active'})) {
 8498:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8499:                     push(@{$$users{st}{$student}},'active');
 8500:                     $match = 1;
 8501:                 }
 8502:             }
 8503:             if (defined($$types{'previous'})) {
 8504:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8505:                     push(@{$$users{st}{$student}},'previous');
 8506:                     $match = 1;
 8507:                 }
 8508:             }
 8509:             if (defined($$types{'future'})) {
 8510:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8511:                     push(@{$$users{st}{$student}},'future');
 8512:                     $match = 1;
 8513:                 }
 8514:             }
 8515:             if ($match) {
 8516:                 push(@{$seclists{$student}},$section);
 8517:                 if (ref($userdata) eq 'HASH') {
 8518:                     $$userdata{$student} = $$classlist{$student};
 8519:                 }
 8520:                 if (ref($statushash) eq 'HASH') {
 8521:                     $statushash->{$student}{'st'}{$section} = $status;
 8522:                 }
 8523:             }
 8524:         }
 8525:     }
 8526:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8527:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8528:         my $now = time;
 8529:         my %displaystatus = ( previous => 'Expired',
 8530:                               active   => 'Active',
 8531:                               future   => 'Future',
 8532:                             );
 8533:         my (%nothide,@possdoms);
 8534:         if ($hidepriv) {
 8535:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8536:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8537:                 if ($user !~ /:/) {
 8538:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8539:                 } else {
 8540:                     $nothide{$user} = 1;
 8541:                 }
 8542:             }
 8543:             my @possdoms = ($cdom);
 8544:             if ($coursehash{'checkforpriv'}) {
 8545:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8546:             }
 8547:         }
 8548:         foreach my $person (sort(keys(%coursepersonnel))) {
 8549:             my $match = 0;
 8550:             my $secmatch = 0;
 8551:             my $status;
 8552:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8553:             $user =~ s/:$//;
 8554:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8555:             if ($end == -1 || $start == -1) {
 8556:                 next;
 8557:             }
 8558:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8559:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8560:                 my ($uname,$udom) = split(/:/,$user);
 8561:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8562:                     if (grep(/^all$/,@{$sections})) {
 8563:                         $secmatch = 1;
 8564:                     } elsif ($usec eq '') {
 8565:                         if (grep(/^none$/,@{$sections})) {
 8566:                             $secmatch = 1;
 8567:                         }
 8568:                     } else {
 8569:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8570:                             $secmatch = 1;
 8571:                         }
 8572:                     }
 8573:                     if (!$secmatch) {
 8574:                         next;
 8575:                     }
 8576:                 }
 8577:                 if ($usec eq '') {
 8578:                     $usec = 'none';
 8579:                 }
 8580:                 if ($uname ne '' && $udom ne '') {
 8581:                     if ($hidepriv) {
 8582:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8583:                             (!$nothide{$uname.':'.$udom})) {
 8584:                             next;
 8585:                         }
 8586:                     }
 8587:                     if ($end > 0 && $end < $now) {
 8588:                         $status = 'previous';
 8589:                     } elsif ($start > $now) {
 8590:                         $status = 'future';
 8591:                     } else {
 8592:                         $status = 'active';
 8593:                     }
 8594:                     foreach my $type (keys(%{$types})) { 
 8595:                         if ($status eq $type) {
 8596:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8597:                                 push(@{$$users{$role}{$user}},$type);
 8598:                             }
 8599:                             $match = 1;
 8600:                         }
 8601:                     }
 8602:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8603:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8604: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8605:                         }
 8606:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8607:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8608:                         }
 8609:                         if (ref($statushash) eq 'HASH') {
 8610:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8611:                         }
 8612:                     }
 8613:                 }
 8614:             }
 8615:         }
 8616:         if (grep(/^ow$/,@{$roles})) {
 8617:             if ((defined($cdom)) && (defined($cnum))) {
 8618:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8619:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8620:                     my $owner = $csettings{'internal.courseowner'};
 8621:                     next if ($owner eq '');
 8622:                     my ($ownername,$ownerdom);
 8623:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8624:                         $ownername = $1;
 8625:                         $ownerdom = $2;
 8626:                     } else {
 8627:                         $ownername = $owner;
 8628:                         $ownerdom = $cdom;
 8629:                         $owner = $ownername.':'.$ownerdom;
 8630:                     }
 8631:                     @{$$users{'ow'}{$owner}} = 'any';
 8632:                     if (defined($userdata) && 
 8633: 			!exists($$userdata{$owner})) {
 8634: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8635:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8636:                             push(@{$seclists{$owner}},'none');
 8637:                         }
 8638:                         if (ref($statushash) eq 'HASH') {
 8639:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8640:                         }
 8641: 		    }
 8642:                 }
 8643:             }
 8644:         }
 8645:         foreach my $user (keys(%seclists)) {
 8646:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8647:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8648:         }
 8649:     }
 8650:     return;
 8651: }
 8652: 
 8653: sub get_user_info {
 8654:     my ($udom,$uname,$idx,$userdata) = @_;
 8655:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8656: 	&plainname($uname,$udom,'lastname');
 8657:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8658:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8659:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8660:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8661:     return;
 8662: }
 8663: 
 8664: ###############################################
 8665: 
 8666: =pod
 8667: 
 8668: =item * &get_user_quota()
 8669: 
 8670: Retrieves quota assigned for storage of user files.
 8671: Default is to report quota for portfolio files.
 8672: 
 8673: Incoming parameters:
 8674: 1. user's username
 8675: 2. user's domain
 8676: 3. quota name - portfolio, author, or course
 8677:    (if no quota name provided, defaults to portfolio).
 8678: 4. crstype - official, unofficial or community, if quota name is
 8679:    course
 8680: 
 8681: Returns:
 8682: 1. Disk quota (in Mb) assigned to student.
 8683: 2. (Optional) Type of setting: custom or default
 8684:    (individually assigned or default for user's 
 8685:    institutional status).
 8686: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8687:    or student - types as defined in localenroll::inst_usertypes 
 8688:    for user's domain, which determines default quota for user.
 8689: 4. (Optional) - Default quota which would apply to the user.
 8690: 
 8691: If a value has been stored in the user's environment, 
 8692: it will return that, otherwise it returns the maximal default
 8693: defined for the user's institutional status(es) in the domain.
 8694: 
 8695: =cut
 8696: 
 8697: ###############################################
 8698: 
 8699: 
 8700: sub get_user_quota {
 8701:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8702:     my ($quota,$quotatype,$settingstatus,$defquota);
 8703:     if (!defined($udom)) {
 8704:         $udom = $env{'user.domain'};
 8705:     }
 8706:     if (!defined($uname)) {
 8707:         $uname = $env{'user.name'};
 8708:     }
 8709:     if (($udom eq '' || $uname eq '') ||
 8710:         ($udom eq 'public') && ($uname eq 'public')) {
 8711:         $quota = 0;
 8712:         $quotatype = 'default';
 8713:         $defquota = 0; 
 8714:     } else {
 8715:         my $inststatus;
 8716:         if ($quotaname eq 'course') {
 8717:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8718:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8719:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8720:             } else {
 8721:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8722:                 $quota = $cenv{'internal.uploadquota'};
 8723:             }
 8724:         } else {
 8725:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8726:                 if ($quotaname eq 'author') {
 8727:                     $quota = $env{'environment.authorquota'};
 8728:                 } else {
 8729:                     $quota = $env{'environment.portfolioquota'};
 8730:                 }
 8731:                 $inststatus = $env{'environment.inststatus'};
 8732:             } else {
 8733:                 my %userenv = 
 8734:                     &Apache::lonnet::get('environment',['portfolioquota',
 8735:                                          'authorquota','inststatus'],$udom,$uname);
 8736:                 my ($tmp) = keys(%userenv);
 8737:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8738:                     if ($quotaname eq 'author') {
 8739:                         $quota = $userenv{'authorquota'};
 8740:                     } else {
 8741:                         $quota = $userenv{'portfolioquota'};
 8742:                     }
 8743:                     $inststatus = $userenv{'inststatus'};
 8744:                 } else {
 8745:                     undef(%userenv);
 8746:                 }
 8747:             }
 8748:         }
 8749:         if ($quota eq '' || wantarray) {
 8750:             if ($quotaname eq 'course') {
 8751:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8752:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || ($crstype eq 'community')) {
 8753:                     $defquota = $domdefs{$crstype.'quota'};
 8754:                 }
 8755:                 if ($defquota eq '') {
 8756:                     $defquota = 500;
 8757:                 }
 8758:             } else {
 8759:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8760:             }
 8761:             if ($quota eq '') {
 8762:                 $quota = $defquota;
 8763:                 $quotatype = 'default';
 8764:             } else {
 8765:                 $quotatype = 'custom';
 8766:             }
 8767:         }
 8768:     }
 8769:     if (wantarray) {
 8770:         return ($quota,$quotatype,$settingstatus,$defquota);
 8771:     } else {
 8772:         return $quota;
 8773:     }
 8774: }
 8775: 
 8776: ###############################################
 8777: 
 8778: =pod
 8779: 
 8780: =item * &default_quota()
 8781: 
 8782: Retrieves default quota assigned for storage of user portfolio files,
 8783: given an (optional) user's institutional status.
 8784: 
 8785: Incoming parameters:
 8786: 
 8787: 1. domain
 8788: 2. (Optional) institutional status(es).  This is a : separated list of 
 8789:    status types (e.g., faculty, staff, student etc.)
 8790:    which apply to the user for whom the default is being retrieved.
 8791:    If the institutional status string in undefined, the domain
 8792:    default quota will be returned.
 8793: 3.  quota name - portfolio, author, or course
 8794:    (if no quota name provided, defaults to portfolio).
 8795: 
 8796: Returns:
 8797: 
 8798: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8799: 2. (Optional) institutional type which determined the value of the
 8800:    default quota.
 8801: 
 8802: If a value has been stored in the domain's configuration db,
 8803: it will return that, otherwise it returns 20 (for backwards 
 8804: compatibility with domains which have not set up a configuration
 8805: db file; the original statically defined portfolio quota was 20 Mb). 
 8806: 
 8807: If the user's status includes multiple types (e.g., staff and student),
 8808: the largest default quota which applies to the user determines the
 8809: default quota returned.
 8810: 
 8811: =cut
 8812: 
 8813: ###############################################
 8814: 
 8815: 
 8816: sub default_quota {
 8817:     my ($udom,$inststatus,$quotaname) = @_;
 8818:     my ($defquota,$settingstatus);
 8819:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8820:                                             ['quotas'],$udom);
 8821:     my $key = 'defaultquota';
 8822:     if ($quotaname eq 'author') {
 8823:         $key = 'authorquota';
 8824:     }
 8825:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8826:         if ($inststatus ne '') {
 8827:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8828:             foreach my $item (@statuses) {
 8829:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8830:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8831:                         if ($defquota eq '') {
 8832:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8833:                             $settingstatus = $item;
 8834:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8835:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8836:                             $settingstatus = $item;
 8837:                         }
 8838:                     }
 8839:                 } elsif ($key eq 'defaultquota') {
 8840:                     if ($quotahash{'quotas'}{$item} ne '') {
 8841:                         if ($defquota eq '') {
 8842:                             $defquota = $quotahash{'quotas'}{$item};
 8843:                             $settingstatus = $item;
 8844:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8845:                             $defquota = $quotahash{'quotas'}{$item};
 8846:                             $settingstatus = $item;
 8847:                         }
 8848:                     }
 8849:                 }
 8850:             }
 8851:         }
 8852:         if ($defquota eq '') {
 8853:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8854:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8855:             } elsif ($key eq 'defaultquota') {
 8856:                 $defquota = $quotahash{'quotas'}{'default'};
 8857:             }
 8858:             $settingstatus = 'default';
 8859:             if ($defquota eq '') {
 8860:                 if ($quotaname eq 'author') {
 8861:                     $defquota = 500;
 8862:                 }
 8863:             }
 8864:         }
 8865:     } else {
 8866:         $settingstatus = 'default';
 8867:         if ($quotaname eq 'author') {
 8868:             $defquota = 500;
 8869:         } else {
 8870:             $defquota = 20;
 8871:         }
 8872:     }
 8873:     if (wantarray) {
 8874:         return ($defquota,$settingstatus);
 8875:     } else {
 8876:         return $defquota;
 8877:     }
 8878: }
 8879: 
 8880: ###############################################
 8881: 
 8882: =pod
 8883: 
 8884: =item * &excess_filesize_warning()
 8885: 
 8886: Returns warning message if upload of file to authoring space, or copying
 8887: of existing file within authoring space will cause quota for the authoring
 8888: space to be exceeded.
 8889: 
 8890: Same, if upload of a file directly to a course/community via Course Editor
 8891: will cause quota for uploaded content for the course to be exceeded.
 8892: 
 8893: Inputs: 6
 8894: 1. username or coursenum
 8895: 2. domain
 8896: 3. context ('author' or 'course')
 8897: 4. filename of file for which action is being requested
 8898: 5. filesize (kB) of file
 8899: 6. action being taken: copy or upload.
 8900: 
 8901: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8902:          otherwise return null.
 8903: 
 8904: =back
 8905: 
 8906: =cut
 8907: 
 8908: sub excess_filesize_warning {
 8909:     my ($uname,$udom,$context,$filename,$filesize,$action) = @_;
 8910:     my $current_disk_usage = 0;
 8911:     my $disk_quota = &get_user_quota($uname,$udom,$context); #expressed in MB
 8912:     if ($context eq 'author') {
 8913:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8914:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8915:     } else {
 8916:         foreach my $subdir ('docs','supplemental') {
 8917:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8918:         }
 8919:     }
 8920:     $disk_quota = int($disk_quota * 1000);
 8921:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8922:         return '<p><span class="LC_warning">'.
 8923:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8924:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
 8925:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8926:                             $disk_quota,$current_disk_usage).
 8927:                '</p>';
 8928:     }
 8929:     return;
 8930: }
 8931: 
 8932: ###############################################
 8933: 
 8934: 
 8935: sub get_secgrprole_info {
 8936:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8937:     my %sections_count = &get_sections($cdom,$cnum);
 8938:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8939:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8940:     my @groups = sort(keys(%curr_groups));
 8941:     my $allroles = [];
 8942:     my $rolehash;
 8943:     my $accesshash = {
 8944:                      active => 'Currently has access',
 8945:                      future => 'Will have future access',
 8946:                      previous => 'Previously had access',
 8947:                   };
 8948:     if ($needroles) {
 8949:         $rolehash = {'all' => 'all'};
 8950:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8951: 	if (&Apache::lonnet::error(%user_roles)) {
 8952: 	    undef(%user_roles);
 8953: 	}
 8954:         foreach my $item (keys(%user_roles)) {
 8955:             my ($role)=split(/\:/,$item,2);
 8956:             if ($role eq 'cr') { next; }
 8957:             if ($role =~ /^cr/) {
 8958:                 $$rolehash{$role} = (split('/',$role))[3];
 8959:             } else {
 8960:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8961:             }
 8962:         }
 8963:         foreach my $key (sort(keys(%{$rolehash}))) {
 8964:             push(@{$allroles},$key);
 8965:         }
 8966:         push (@{$allroles},'st');
 8967:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8968:     }
 8969:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8970: }
 8971: 
 8972: sub user_picker {
 8973:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8974:     my $currdom = $dom;
 8975:     my %curr_selected = (
 8976:                         srchin => 'dom',
 8977:                         srchby => 'lastname',
 8978:                       );
 8979:     my $srchterm;
 8980:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8981:         if ($srch->{'srchby'} ne '') {
 8982:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8983:         }
 8984:         if ($srch->{'srchin'} ne '') {
 8985:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8986:         }
 8987:         if ($srch->{'srchtype'} ne '') {
 8988:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8989:         }
 8990:         if ($srch->{'srchdomain'} ne '') {
 8991:             $currdom = $srch->{'srchdomain'};
 8992:         }
 8993:         $srchterm = $srch->{'srchterm'};
 8994:     }
 8995:     my %lt=&Apache::lonlocal::texthash(
 8996:                     'usr'       => 'Search criteria',
 8997:                     'doma'      => 'Domain/institution to search',
 8998:                     'uname'     => 'username',
 8999:                     'lastname'  => 'last name',
 9000:                     'lastfirst' => 'last name, first name',
 9001:                     'crs'       => 'in this course',
 9002:                     'dom'       => 'in selected LON-CAPA domain', 
 9003:                     'alc'       => 'all LON-CAPA',
 9004:                     'instd'     => 'in institutional directory for selected domain',
 9005:                     'exact'     => 'is',
 9006:                     'contains'  => 'contains',
 9007:                     'begins'    => 'begins with',
 9008:                     'youm'      => "You must include some text to search for.",
 9009:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9010:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9011:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9012:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9013:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9014:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9015:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9016:                                        );
 9017:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9018:     my $srchinsel = ' <select name="srchin">';
 9019: 
 9020:     my @srchins = ('crs','dom','alc','instd');
 9021: 
 9022:     foreach my $option (@srchins) {
 9023:         # FIXME 'alc' option unavailable until 
 9024:         #       loncreateuser::print_user_query_page()
 9025:         #       has been completed.
 9026:         next if ($option eq 'alc');
 9027:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9028:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9029:         if ($curr_selected{'srchin'} eq $option) {
 9030:             $srchinsel .= ' 
 9031:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9032:         } else {
 9033:             $srchinsel .= '
 9034:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9035:         }
 9036:     }
 9037:     $srchinsel .= "\n  </select>\n";
 9038: 
 9039:     my $srchbysel =  ' <select name="srchby">';
 9040:     foreach my $option ('lastname','lastfirst','uname') {
 9041:         if ($curr_selected{'srchby'} eq $option) {
 9042:             $srchbysel .= '
 9043:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9044:         } else {
 9045:             $srchbysel .= '
 9046:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9047:          }
 9048:     }
 9049:     $srchbysel .= "\n  </select>\n";
 9050: 
 9051:     my $srchtypesel = ' <select name="srchtype">';
 9052:     foreach my $option ('begins','contains','exact') {
 9053:         if ($curr_selected{'srchtype'} eq $option) {
 9054:             $srchtypesel .= '
 9055:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9056:         } else {
 9057:             $srchtypesel .= '
 9058:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9059:         }
 9060:     }
 9061:     $srchtypesel .= "\n  </select>\n";
 9062: 
 9063:     my ($newuserscript,$new_user_create);
 9064:     my $context_dom = $env{'request.role.domain'};
 9065:     if ($context eq 'requestcrs') {
 9066:         if ($env{'form.coursedom'} ne '') { 
 9067:             $context_dom = $env{'form.coursedom'};
 9068:         }
 9069:     }
 9070:     if ($forcenewuser) {
 9071:         if (ref($srch) eq 'HASH') {
 9072:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9073:                 if ($cancreate) {
 9074:                     $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>';
 9075:                 } else {
 9076:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9077:                     my %usertypetext = (
 9078:                         official   => 'institutional',
 9079:                         unofficial => 'non-institutional',
 9080:                     );
 9081:                     $new_user_create = '<p class="LC_warning">'
 9082:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9083:                                       .' '
 9084:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9085:                                           ,'<a href="'.$helplink.'">','</a>')
 9086:                                       .'</p><br />';
 9087:                 }
 9088:             }
 9089:         }
 9090: 
 9091:         $newuserscript = <<"ENDSCRIPT";
 9092: 
 9093: function setSearch(createnew,callingForm) {
 9094:     if (createnew == 1) {
 9095:         for (var i=0; i<callingForm.srchby.length; i++) {
 9096:             if (callingForm.srchby.options[i].value == 'uname') {
 9097:                 callingForm.srchby.selectedIndex = i;
 9098:             }
 9099:         }
 9100:         for (var i=0; i<callingForm.srchin.length; i++) {
 9101:             if ( callingForm.srchin.options[i].value == 'dom') {
 9102: 		callingForm.srchin.selectedIndex = i;
 9103:             }
 9104:         }
 9105:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9106:             if (callingForm.srchtype.options[i].value == 'exact') {
 9107:                 callingForm.srchtype.selectedIndex = i;
 9108:             }
 9109:         }
 9110:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9111:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9112:                 callingForm.srchdomain.selectedIndex = i;
 9113:             }
 9114:         }
 9115:     }
 9116: }
 9117: ENDSCRIPT
 9118: 
 9119:     }
 9120: 
 9121:     my $output = <<"END_BLOCK";
 9122: <script type="text/javascript">
 9123: // <![CDATA[
 9124: function validateEntry(callingForm) {
 9125: 
 9126:     var checkok = 1;
 9127:     var srchin;
 9128:     for (var i=0; i<callingForm.srchin.length; i++) {
 9129: 	if ( callingForm.srchin[i].checked ) {
 9130: 	    srchin = callingForm.srchin[i].value;
 9131: 	}
 9132:     }
 9133: 
 9134:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9135:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9136:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9137:     var srchterm =  callingForm.srchterm.value;
 9138:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9139:     var msg = "";
 9140: 
 9141:     if (srchterm == "") {
 9142:         checkok = 0;
 9143:         msg += "$lt{'youm'}\\n";
 9144:     }
 9145: 
 9146:     if (srchtype== 'begins') {
 9147:         if (srchterm.length < 2) {
 9148:             checkok = 0;
 9149:             msg += "$lt{'thte'}\\n";
 9150:         }
 9151:     }
 9152: 
 9153:     if (srchtype== 'contains') {
 9154:         if (srchterm.length < 3) {
 9155:             checkok = 0;
 9156:             msg += "$lt{'thet'}\\n";
 9157:         }
 9158:     }
 9159:     if (srchin == 'instd') {
 9160:         if (srchdomain == '') {
 9161:             checkok = 0;
 9162:             msg += "$lt{'yomc'}\\n";
 9163:         }
 9164:     }
 9165:     if (srchin == 'dom') {
 9166:         if (srchdomain == '') {
 9167:             checkok = 0;
 9168:             msg += "$lt{'ymcd'}\\n";
 9169:         }
 9170:     }
 9171:     if (srchby == 'lastfirst') {
 9172:         if (srchterm.indexOf(",") == -1) {
 9173:             checkok = 0;
 9174:             msg += "$lt{'whus'}\\n";
 9175:         }
 9176:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9177:             checkok = 0;
 9178:             msg += "$lt{'whse'}\\n";
 9179:         }
 9180:     }
 9181:     if (checkok == 0) {
 9182:         alert("$lt{'thfo'}\\n"+msg);
 9183:         return;
 9184:     }
 9185:     if (checkok == 1) {
 9186:         callingForm.submit();
 9187:     }
 9188: }
 9189: 
 9190: $newuserscript
 9191: 
 9192: // ]]>
 9193: </script>
 9194: 
 9195: $new_user_create
 9196: 
 9197: END_BLOCK
 9198: 
 9199:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9200:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9201:                $domform.
 9202:                &Apache::lonhtmlcommon::row_closure().
 9203:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9204:                $srchbysel.
 9205:                $srchtypesel. 
 9206:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9207:                $srchinsel.
 9208:                &Apache::lonhtmlcommon::row_closure(1). 
 9209:                &Apache::lonhtmlcommon::end_pick_box().
 9210:                '<br />';
 9211:     return $output;
 9212: }
 9213: 
 9214: sub user_rule_check {
 9215:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9216:     my $response;
 9217:     if (ref($usershash) eq 'HASH') {
 9218:         foreach my $user (keys(%{$usershash})) {
 9219:             my ($uname,$udom) = split(/:/,$user);
 9220:             next if ($udom eq '' || $uname eq '');
 9221:             my ($id,$newuser);
 9222:             if (ref($usershash->{$user}) eq 'HASH') {
 9223:                 $newuser = $usershash->{$user}->{'newuser'};
 9224:                 $id = $usershash->{$user}->{'id'};
 9225:             }
 9226:             my $inst_response;
 9227:             if (ref($checks) eq 'HASH') {
 9228:                 if (defined($checks->{'username'})) {
 9229:                     ($inst_response,%{$inst_results->{$user}}) = 
 9230:                         &Apache::lonnet::get_instuser($udom,$uname);
 9231:                 } elsif (defined($checks->{'id'})) {
 9232:                     ($inst_response,%{$inst_results->{$user}}) =
 9233:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9234:                 }
 9235:             } else {
 9236:                 ($inst_response,%{$inst_results->{$user}}) =
 9237:                     &Apache::lonnet::get_instuser($udom,$uname);
 9238:                 return;
 9239:             }
 9240:             if (!$got_rules->{$udom}) {
 9241:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9242:                                                   ['usercreation'],$udom);
 9243:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9244:                     foreach my $item ('username','id') {
 9245:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9246:                             $$curr_rules{$udom}{$item} = 
 9247:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9248:                         }
 9249:                     }
 9250:                 }
 9251:                 $got_rules->{$udom} = 1;  
 9252:             }
 9253:             foreach my $item (keys(%{$checks})) {
 9254:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9255:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9256:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9257:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9258:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9259:                                 if ($rule_check{$rule}) {
 9260:                                     $$rulematch{$user}{$item} = $rule;
 9261:                                     if ($inst_response eq 'ok') {
 9262:                                         if (ref($inst_results) eq 'HASH') {
 9263:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9264:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9265:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9266:                                                 }
 9267:                                             }
 9268:                                         }
 9269:                                     }
 9270:                                     last;
 9271:                                 }
 9272:                             }
 9273:                         }
 9274:                     }
 9275:                 }
 9276:             }
 9277:         }
 9278:     }
 9279:     return;
 9280: }
 9281: 
 9282: sub user_rule_formats {
 9283:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9284:     my %text = ( 
 9285:                  'username' => 'Usernames',
 9286:                  'id'       => 'IDs',
 9287:                );
 9288:     my $output;
 9289:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9290:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9291:         if (@{$ruleorder} > 0) {
 9292:             $output = '<br />'.
 9293:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9294:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9295:                       ' <ul>';
 9296:             foreach my $rule (@{$ruleorder}) {
 9297:                 if (ref($curr_rules) eq 'ARRAY') {
 9298:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9299:                         if (ref($rules->{$rule}) eq 'HASH') {
 9300:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9301:                                         $rules->{$rule}{'desc'}.'</li>';
 9302:                         }
 9303:                     }
 9304:                 }
 9305:             }
 9306:             $output .= '</ul>';
 9307:         }
 9308:     }
 9309:     return $output;
 9310: }
 9311: 
 9312: sub instrule_disallow_msg {
 9313:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9314:     my $response;
 9315:     my %text = (
 9316:                   item   => 'username',
 9317:                   items  => 'usernames',
 9318:                   match  => 'matches',
 9319:                   do     => 'does',
 9320:                   action => 'a username',
 9321:                   one    => 'one',
 9322:                );
 9323:     if ($count > 1) {
 9324:         $text{'item'} = 'usernames';
 9325:         $text{'match'} ='match';
 9326:         $text{'do'} = 'do';
 9327:         $text{'action'} = 'usernames',
 9328:         $text{'one'} = 'ones';
 9329:     }
 9330:     if ($checkitem eq 'id') {
 9331:         $text{'items'} = 'IDs';
 9332:         $text{'item'} = 'ID';
 9333:         $text{'action'} = 'an ID';
 9334:         if ($count > 1) {
 9335:             $text{'item'} = 'IDs';
 9336:             $text{'action'} = 'IDs';
 9337:         }
 9338:     }
 9339:     $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 />';
 9340:     if ($mode eq 'upload') {
 9341:         if ($checkitem eq 'username') {
 9342:             $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'}.");
 9343:         } elsif ($checkitem eq 'id') {
 9344:             $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.");
 9345:         }
 9346:     } elsif ($mode eq 'selfcreate') {
 9347:         if ($checkitem eq 'id') {
 9348:             $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.");
 9349:         }
 9350:     } else {
 9351:         if ($checkitem eq 'username') {
 9352:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9353:         } elsif ($checkitem eq 'id') {
 9354:             $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.");
 9355:         }
 9356:     }
 9357:     return $response;
 9358: }
 9359: 
 9360: sub personal_data_fieldtitles {
 9361:     my %fieldtitles = &Apache::lonlocal::texthash (
 9362:                         id => 'Student/Employee ID',
 9363:                         permanentemail => 'E-mail address',
 9364:                         lastname => 'Last Name',
 9365:                         firstname => 'First Name',
 9366:                         middlename => 'Middle Name',
 9367:                         generation => 'Generation',
 9368:                         gen => 'Generation',
 9369:                         inststatus => 'Affiliation',
 9370:                    );
 9371:     return %fieldtitles;
 9372: }
 9373: 
 9374: sub sorted_inst_types {
 9375:     my ($dom) = @_;
 9376:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9377:     my $othertitle = &mt('All users');
 9378:     if ($env{'request.course.id'}) {
 9379:         $othertitle  = &mt('Any users');
 9380:     }
 9381:     my @types;
 9382:     if (ref($order) eq 'ARRAY') {
 9383:         @types = @{$order};
 9384:     }
 9385:     if (@types == 0) {
 9386:         if (ref($usertypes) eq 'HASH') {
 9387:             @types = sort(keys(%{$usertypes}));
 9388:         }
 9389:     }
 9390:     if (keys(%{$usertypes}) > 0) {
 9391:         $othertitle = &mt('Other users');
 9392:     }
 9393:     return ($othertitle,$usertypes,\@types);
 9394: }
 9395: 
 9396: sub get_institutional_codes {
 9397:     my ($settings,$allcourses,$LC_code) = @_;
 9398: # Get complete list of course sections to update
 9399:     my @currsections = ();
 9400:     my @currxlists = ();
 9401:     my $coursecode = $$settings{'internal.coursecode'};
 9402: 
 9403:     if ($$settings{'internal.sectionnums'} ne '') {
 9404:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9405:     }
 9406: 
 9407:     if ($$settings{'internal.crosslistings'} ne '') {
 9408:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9409:     }
 9410: 
 9411:     if (@currxlists > 0) {
 9412:         foreach (@currxlists) {
 9413:             if (m/^([^:]+):(\w*)$/) {
 9414:                 unless (grep/^$1$/,@{$allcourses}) {
 9415:                     push @{$allcourses},$1;
 9416:                     $$LC_code{$1} = $2;
 9417:                 }
 9418:             }
 9419:         }
 9420:     }
 9421:  
 9422:     if (@currsections > 0) {
 9423:         foreach (@currsections) {
 9424:             if (m/^(\w+):(\w*)$/) {
 9425:                 my $sec = $coursecode.$1;
 9426:                 my $lc_sec = $2;
 9427:                 unless (grep/^$sec$/,@{$allcourses}) {
 9428:                     push @{$allcourses},$sec;
 9429:                     $$LC_code{$sec} = $lc_sec;
 9430:                 }
 9431:             }
 9432:         }
 9433:     }
 9434:     return;
 9435: }
 9436: 
 9437: sub get_standard_codeitems {
 9438:     return ('Year','Semester','Department','Number','Section');
 9439: }
 9440: 
 9441: =pod
 9442: 
 9443: =head1 Slot Helpers
 9444: 
 9445: =over 4
 9446: 
 9447: =item * sorted_slots()
 9448: 
 9449: Sorts an array of slot names in order of an optional sort key,
 9450: default sort is by slot start time (earliest first). 
 9451: 
 9452: Inputs:
 9453: 
 9454: =over 4
 9455: 
 9456: slotsarr  - Reference to array of unsorted slot names.
 9457: 
 9458: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9459: 
 9460: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9461: 
 9462: =back
 9463: 
 9464: Returns:
 9465: 
 9466: =over 4
 9467: 
 9468: sorted   - An array of slot names sorted by a specified sort key 
 9469:            (default sort key is start time of the slot).
 9470: 
 9471: =back
 9472: 
 9473: =cut
 9474: 
 9475: 
 9476: sub sorted_slots {
 9477:     my ($slotsarr,$slots,$sortkey) = @_;
 9478:     if ($sortkey eq '') {
 9479:         $sortkey = 'starttime';
 9480:     }
 9481:     my @sorted;
 9482:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9483:         @sorted =
 9484:             sort {
 9485:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9486:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9487:                      }
 9488:                      if (ref($slots->{$a})) { return -1;}
 9489:                      if (ref($slots->{$b})) { return 1;}
 9490:                      return 0;
 9491:                  } @{$slotsarr};
 9492:     }
 9493:     return @sorted;
 9494: }
 9495: 
 9496: =pod
 9497: 
 9498: =item * get_future_slots()
 9499: 
 9500: Inputs:
 9501: 
 9502: =over 4
 9503: 
 9504: cnum - course number
 9505: 
 9506: cdom - course domain
 9507: 
 9508: now - current UNIX time
 9509: 
 9510: symb - optional symb
 9511: 
 9512: =back
 9513: 
 9514: Returns:
 9515: 
 9516: =over 4
 9517: 
 9518: sorted_reservable - ref to array of student_schedulable slots currently 
 9519:                     reservable, ordered by end date of reservation period.
 9520: 
 9521: reservable_now - ref to hash of student_schedulable slots currently
 9522:                  reservable.
 9523: 
 9524:     Keys in inner hash are:
 9525:     (a) symb: either blank or symb to which slot use is restricted.
 9526:     (b) endreserve: end date of reservation period. 
 9527: 
 9528: sorted_future - ref to array of student_schedulable slots reservable in
 9529:                 the future, ordered by start date of reservation period.
 9530: 
 9531: future_reservable - ref to hash of student_schedulable slots reservable
 9532:                     in the future.
 9533: 
 9534:     Keys in inner hash are:
 9535:     (a) symb: either blank or symb to which slot use is restricted.
 9536:     (b) startreserve:  start date of reservation period.
 9537: 
 9538: =back
 9539: 
 9540: =cut
 9541: 
 9542: sub get_future_slots {
 9543:     my ($cnum,$cdom,$now,$symb) = @_;
 9544:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9545:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9546:     foreach my $slot (keys(%slots)) {
 9547:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9548:         if ($symb) {
 9549:             next if (($slots{$slot}->{'symb'} ne '') && 
 9550:                      ($slots{$slot}->{'symb'} ne $symb));
 9551:         }
 9552:         if (($slots{$slot}->{'starttime'} > $now) &&
 9553:             ($slots{$slot}->{'endtime'} > $now)) {
 9554:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9555:                 my $userallowed = 0;
 9556:                 if ($slots{$slot}->{'allowedsections'}) {
 9557:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9558:                     if (!defined($env{'request.role.sec'})
 9559:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9560:                         $userallowed=1;
 9561:                     } else {
 9562:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9563:                             $userallowed=1;
 9564:                         }
 9565:                     }
 9566:                     unless ($userallowed) {
 9567:                         if (defined($env{'request.course.groups'})) {
 9568:                             my @groups = split(/:/,$env{'request.course.groups'});
 9569:                             foreach my $group (@groups) {
 9570:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9571:                                     $userallowed=1;
 9572:                                     last;
 9573:                                 }
 9574:                             }
 9575:                         }
 9576:                     }
 9577:                 }
 9578:                 if ($slots{$slot}->{'allowedusers'}) {
 9579:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9580:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9581:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9582:                         $userallowed = 1;
 9583:                     }
 9584:                 }
 9585:                 next unless($userallowed);
 9586:             }
 9587:             my $startreserve = $slots{$slot}->{'startreserve'};
 9588:             my $endreserve = $slots{$slot}->{'endreserve'};
 9589:             my $symb = $slots{$slot}->{'symb'};
 9590:             if (($startreserve < $now) &&
 9591:                 (!$endreserve || $endreserve > $now)) {
 9592:                 my $lastres = $endreserve;
 9593:                 if (!$lastres) {
 9594:                     $lastres = $slots{$slot}->{'starttime'};
 9595:                 }
 9596:                 $reservable_now{$slot} = {
 9597:                                            symb       => $symb,
 9598:                                            endreserve => $lastres
 9599:                                          };
 9600:             } elsif (($startreserve > $now) &&
 9601:                      (!$endreserve || $endreserve > $startreserve)) {
 9602:                 $future_reservable{$slot} = {
 9603:                                               symb         => $symb,
 9604:                                               startreserve => $startreserve
 9605:                                             };
 9606:             }
 9607:         }
 9608:     }
 9609:     my @unsorted_reservable = keys(%reservable_now);
 9610:     if (@unsorted_reservable > 0) {
 9611:         @sorted_reservable = 
 9612:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9613:     }
 9614:     my @unsorted_future = keys(%future_reservable);
 9615:     if (@unsorted_future > 0) {
 9616:         @sorted_future =
 9617:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9618:     }
 9619:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9620: }
 9621: 
 9622: =pod
 9623: 
 9624: =back
 9625: 
 9626: =head1 HTTP Helpers
 9627: 
 9628: =over 4
 9629: 
 9630: =item * &get_unprocessed_cgi($query,$possible_names)
 9631: 
 9632: Modify the %env hash to contain unprocessed CGI form parameters held in
 9633: $query.  The parameters listed in $possible_names (an array reference),
 9634: will be set in $env{'form.name'} if they do not already exist.
 9635: 
 9636: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9637: $possible_names is an ref to an array of form element names.  As an example:
 9638: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9639: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9640: 
 9641: =cut
 9642: 
 9643: sub get_unprocessed_cgi {
 9644:   my ($query,$possible_names)= @_;
 9645:   # $Apache::lonxml::debug=1;
 9646:   foreach my $pair (split(/&/,$query)) {
 9647:     my ($name, $value) = split(/=/,$pair);
 9648:     $name = &unescape($name);
 9649:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9650:       $value =~ tr/+/ /;
 9651:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9652:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9653:     }
 9654:   }
 9655: }
 9656: 
 9657: =pod
 9658: 
 9659: =item * &cacheheader() 
 9660: 
 9661: returns cache-controlling header code
 9662: 
 9663: =cut
 9664: 
 9665: sub cacheheader {
 9666:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9667:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9668:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9669:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9670:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9671:     return $output;
 9672: }
 9673: 
 9674: =pod
 9675: 
 9676: =item * &no_cache($r) 
 9677: 
 9678: specifies header code to not have cache
 9679: 
 9680: =cut
 9681: 
 9682: sub no_cache {
 9683:     my ($r) = @_;
 9684:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9685: 	$env{'request.method'} ne 'GET') { return ''; }
 9686:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9687:     $r->no_cache(1);
 9688:     $r->header_out("Expires" => $date);
 9689:     $r->header_out("Pragma" => "no-cache");
 9690: }
 9691: 
 9692: sub content_type {
 9693:     my ($r,$type,$charset) = @_;
 9694:     if ($r) {
 9695: 	#  Note that printout.pl calls this with undef for $r.
 9696: 	&no_cache($r);
 9697:     }
 9698:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9699:     unless ($charset) {
 9700: 	$charset=&Apache::lonlocal::current_encoding;
 9701:     }
 9702:     if ($charset) { $type.='; charset='.$charset; }
 9703:     if ($r) {
 9704: 	$r->content_type($type);
 9705:     } else {
 9706: 	print("Content-type: $type\n\n");
 9707:     }
 9708: }
 9709: 
 9710: =pod
 9711: 
 9712: =item * &add_to_env($name,$value) 
 9713: 
 9714: adds $name to the %env hash with value
 9715: $value, if $name already exists, the entry is converted to an array
 9716: reference and $value is added to the array.
 9717: 
 9718: =cut
 9719: 
 9720: sub add_to_env {
 9721:   my ($name,$value)=@_;
 9722:   if (defined($env{$name})) {
 9723:     if (ref($env{$name})) {
 9724:       #already have multiple values
 9725:       push(@{ $env{$name} },$value);
 9726:     } else {
 9727:       #first time seeing multiple values, convert hash entry to an arrayref
 9728:       my $first=$env{$name};
 9729:       undef($env{$name});
 9730:       push(@{ $env{$name} },$first,$value);
 9731:     }
 9732:   } else {
 9733:     $env{$name}=$value;
 9734:   }
 9735: }
 9736: 
 9737: =pod
 9738: 
 9739: =item * &get_env_multiple($name) 
 9740: 
 9741: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9742: values may be defined and end up as an array ref.
 9743: 
 9744: returns an array of values
 9745: 
 9746: =cut
 9747: 
 9748: sub get_env_multiple {
 9749:     my ($name) = @_;
 9750:     my @values;
 9751:     if (defined($env{$name})) {
 9752:         # exists is it an array
 9753:         if (ref($env{$name})) {
 9754:             @values=@{ $env{$name} };
 9755:         } else {
 9756:             $values[0]=$env{$name};
 9757:         }
 9758:     }
 9759:     return(@values);
 9760: }
 9761: 
 9762: sub ask_for_embedded_content {
 9763:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9764:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9765:         %currsubfile,%unused,$rem);
 9766:     my $counter = 0;
 9767:     my $numnew = 0;
 9768:     my $numremref = 0;
 9769:     my $numinvalid = 0;
 9770:     my $numpathchg = 0;
 9771:     my $numexisting = 0;
 9772:     my $numunused = 0;
 9773:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9774:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9775:     my $heading = &mt('Upload embedded files');
 9776:     my $buttontext = &mt('Upload');
 9777: 
 9778:     my ($navmap,$cdom,$cnum);
 9779:     if ($env{'request.course.id'}) {
 9780:         if ($actionurl eq '/adm/dependencies') {
 9781:             $navmap = Apache::lonnavmaps::navmap->new();
 9782:         }
 9783:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9784:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9785:     }
 9786:     if (($actionurl eq '/adm/portfolio') ||
 9787:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9788:         my $current_path='/';
 9789:         if ($env{'form.currentpath'}) {
 9790:             $current_path = $env{'form.currentpath'};
 9791:         }
 9792:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9793:             $udom = $cdom;
 9794:             $uname = $cnum;
 9795:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9796:         } else {
 9797:             $udom = $env{'user.domain'};
 9798:             $uname = $env{'user.name'};
 9799:             $url = '/userfiles/portfolio';
 9800:         }
 9801:         $toplevel = $url.'/';
 9802:         $url .= $current_path;
 9803:         $getpropath = 1;
 9804:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9805:              ($actionurl eq '/adm/imsimport')) { 
 9806:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9807:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9808:         $toplevel = $url;
 9809:         if ($rest ne '') {
 9810:             $url .= $rest;
 9811:         }
 9812:     } elsif ($actionurl eq '/adm/coursedocs') {
 9813:         if (ref($args) eq 'HASH') {
 9814:             $url = $args->{'docs_url'};
 9815:             $toplevel = $url;
 9816:             if ($args->{'context'} eq 'paste') {
 9817:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9818:                 ($path) =
 9819:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9820:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9821:                 $fileloc =~ s{^/}{};
 9822:             }
 9823:         }
 9824:     } elsif ($actionurl eq '/adm/dependencies') {
 9825:         if ($env{'request.course.id'} ne '') {
 9826:             if (ref($args) eq 'HASH') {
 9827:                 $url = $args->{'docs_url'};
 9828:                 $title = $args->{'docs_title'};
 9829:                 $toplevel = $url;
 9830:                 unless ($toplevel =~ m{^/}) {
 9831:                     $toplevel = "/$url";
 9832:                 }
 9833:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9834:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9835:                     $path = $1;
 9836:                 } else {
 9837:                     ($path) =
 9838:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9839:                 }
 9840:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9841:                 $fileloc =~ s{^/}{};
 9842:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9843:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9844:             }
 9845:         }
 9846:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9847:         $udom = $cdom;
 9848:         $uname = $cnum;
 9849:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9850:         $toplevel = $url;
 9851:         $path = $url;
 9852:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9853:         $fileloc =~ s{^/}{};
 9854:     }
 9855:     foreach my $file (keys(%{$allfiles})) {
 9856:         my $embed_file;
 9857:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9858:             $embed_file = $1;
 9859:         } else {
 9860:             $embed_file = $file;
 9861:         }
 9862:         my $absolutepath;
 9863:         my $cleaned_file = &clean_path($embed_file);
 9864:         if ($cleaned_file =~ m{^\w+://}) {
 9865:             $newfiles{$cleaned_file} = 1;
 9866:             $mapping{$cleaned_file} = $embed_file;
 9867:         } else {
 9868:             if ($embed_file =~ m{^/}) {
 9869:                 $absolutepath = $embed_file;
 9870:             }
 9871:             if ($cleaned_file =~ m{/}) {
 9872:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
 9873:                 $path = &check_for_traversal($path,$url,$toplevel);
 9874:                 my $item = $fname;
 9875:                 if ($path ne '') {
 9876:                     $item = $path.'/'.$fname;
 9877:                     $subdependencies{$path}{$fname} = 1;
 9878:                 } else {
 9879:                     $dependencies{$item} = 1;
 9880:                 }
 9881:                 if ($absolutepath) {
 9882:                     $mapping{$item} = $absolutepath;
 9883:                 } else {
 9884:                     $mapping{$item} = $embed_file;
 9885:                 }
 9886:             } else {
 9887:                 $dependencies{$embed_file} = 1;
 9888:                 if ($absolutepath) {
 9889:                     $mapping{$cleaned_file} = $absolutepath;
 9890:                 } else {
 9891:                     $mapping{$cleaned_file} = $embed_file;
 9892:                 }
 9893:             }
 9894:         }
 9895:     }
 9896:     my $dirptr = 16384;
 9897:     foreach my $path (keys(%subdependencies)) {
 9898:         $currsubfile{$path} = {};
 9899:         if (($actionurl eq '/adm/portfolio') ||
 9900:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9901:             my ($sublistref,$listerror) =
 9902:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9903:             if (ref($sublistref) eq 'ARRAY') {
 9904:                 foreach my $line (@{$sublistref}) {
 9905:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9906:                     $currsubfile{$path}{$file_name} = 1;
 9907:                 }
 9908:             }
 9909:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9910:             if (opendir(my $dir,$url.'/'.$path)) {
 9911:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9912:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9913:             }
 9914:         } elsif (($actionurl eq '/adm/dependencies') ||
 9915:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9916:                   ($args->{'context'} eq 'paste')) ||
 9917:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9918:             if ($env{'request.course.id'} ne '') {
 9919:                 my $dir;
 9920:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9921:                     $dir = $fileloc;
 9922:                 } else {
 9923:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9924:                 }
 9925:                 if ($dir ne '') {
 9926:                     my ($sublistref,$listerror) =
 9927:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9928:                     if (ref($sublistref) eq 'ARRAY') {
 9929:                         foreach my $line (@{$sublistref}) {
 9930:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9931:                                 undef,$mtime)=split(/\&/,$line,12);
 9932:                             unless (($testdir&$dirptr) ||
 9933:                                     ($file_name =~ /^\.\.?$/)) {
 9934:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9935:                             }
 9936:                         }
 9937:                     }
 9938:                 }
 9939:             }
 9940:         }
 9941:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9942:             if (exists($currsubfile{$path}{$file})) {
 9943:                 my $item = $path.'/'.$file;
 9944:                 unless ($mapping{$item} eq $item) {
 9945:                     $pathchanges{$item} = 1;
 9946:                 }
 9947:                 $existing{$item} = 1;
 9948:                 $numexisting ++;
 9949:             } else {
 9950:                 $newfiles{$path.'/'.$file} = 1;
 9951:             }
 9952:         }
 9953:         if ($actionurl eq '/adm/dependencies') {
 9954:             foreach my $path (keys(%currsubfile)) {
 9955:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9956:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9957:                          unless ($subdependencies{$path}{$file}) {
 9958:                              next if (($rem ne '') &&
 9959:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9960:                                        (ref($navmap) &&
 9961:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9962:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9963:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9964:                              $unused{$path.'/'.$file} = 1; 
 9965:                          }
 9966:                     }
 9967:                 }
 9968:             }
 9969:         }
 9970:     }
 9971:     my %currfile;
 9972:     if (($actionurl eq '/adm/portfolio') ||
 9973:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9974:         my ($dirlistref,$listerror) =
 9975:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9976:         if (ref($dirlistref) eq 'ARRAY') {
 9977:             foreach my $line (@{$dirlistref}) {
 9978:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9979:                 $currfile{$file_name} = 1;
 9980:             }
 9981:         }
 9982:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9983:         if (opendir(my $dir,$url)) {
 9984:             my @dir_list = grep(!/^\./,readdir($dir));
 9985:             map {$currfile{$_} = 1;} @dir_list;
 9986:         }
 9987:     } elsif (($actionurl eq '/adm/dependencies') ||
 9988:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9989:               ($args->{'context'} eq 'paste')) ||
 9990:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9991:         if ($env{'request.course.id'} ne '') {
 9992:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9993:             if ($dir ne '') {
 9994:                 my ($dirlistref,$listerror) =
 9995:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9996:                 if (ref($dirlistref) eq 'ARRAY') {
 9997:                     foreach my $line (@{$dirlistref}) {
 9998:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9999:                             $size,undef,$mtime)=split(/\&/,$line,12);
10000:                         unless (($testdir&$dirptr) ||
10001:                                 ($file_name =~ /^\.\.?$/)) {
10002:                             $currfile{$file_name} = [$size,$mtime];
10003:                         }
10004:                     }
10005:                 }
10006:             }
10007:         }
10008:     }
10009:     foreach my $file (keys(%dependencies)) {
10010:         if (exists($currfile{$file})) {
10011:             unless ($mapping{$file} eq $file) {
10012:                 $pathchanges{$file} = 1;
10013:             }
10014:             $existing{$file} = 1;
10015:             $numexisting ++;
10016:         } else {
10017:             $newfiles{$file} = 1;
10018:         }
10019:     }
10020:     foreach my $file (keys(%currfile)) {
10021:         unless (($file eq $filename) ||
10022:                 ($file eq $filename.'.bak') ||
10023:                 ($dependencies{$file})) {
10024:             if ($actionurl eq '/adm/dependencies') {
10025:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10026:                     next if (($rem ne '') &&
10027:                              (($env{"httpref.$rem".$file} ne '') ||
10028:                               (ref($navmap) &&
10029:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10030:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10031:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10032:                 }
10033:             }
10034:             $unused{$file} = 1;
10035:         }
10036:     }
10037:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10038:         ($args->{'context'} eq 'paste')) {
10039:         $counter = scalar(keys(%existing));
10040:         $numpathchg = scalar(keys(%pathchanges));
10041:         return ($output,$counter,$numpathchg,\%existing);
10042:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10043:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10044:         $counter = scalar(keys(%existing));
10045:         $numpathchg = scalar(keys(%pathchanges));
10046:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10047:     }
10048:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10049:         if ($actionurl eq '/adm/dependencies') {
10050:             next if ($embed_file =~ m{^\w+://});
10051:         }
10052:         $upload_output .= &start_data_table_row().
10053:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10054:                           '<span class="LC_filename">'.$embed_file.'</span>';
10055:         unless ($mapping{$embed_file} eq $embed_file) {
10056:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10057:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10058:         }
10059:         $upload_output .= '</td>';
10060:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10061:             $upload_output.='<td align="right">'.
10062:                             '<span class="LC_info LC_fontsize_medium">'.
10063:                             &mt("URL points to web address").'</span>';
10064:             $numremref++;
10065:         } elsif ($args->{'error_on_invalid_names'}
10066:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10067:             $upload_output.='<td align="right"><span class="LC_warning">'.
10068:                             &mt('Invalid characters').'</span>';
10069:             $numinvalid++;
10070:         } else {
10071:             $upload_output .= '<td>'.
10072:                               &embedded_file_element('upload_embedded',$counter,
10073:                                                      $embed_file,\%mapping,
10074:                                                      $allfiles,$codebase,'upload');
10075:             $counter ++;
10076:             $numnew ++;
10077:         }
10078:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10079:     }
10080:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10081:         if ($actionurl eq '/adm/dependencies') {
10082:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10083:             $modify_output .= &start_data_table_row().
10084:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10085:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10086:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10087:                               '<td>'.$size.'</td>'.
10088:                               '<td>'.$mtime.'</td>'.
10089:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10090:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10091:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10092:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10093:                               &embedded_file_element('upload_embedded',$counter,
10094:                                                      $embed_file,\%mapping,
10095:                                                      $allfiles,$codebase,'modify').
10096:                               '</div></td>'.
10097:                               &end_data_table_row()."\n";
10098:             $counter ++;
10099:         } else {
10100:             $upload_output .= &start_data_table_row().
10101:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10102:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10103:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10104:                               &Apache::loncommon::end_data_table_row()."\n";
10105:         }
10106:     }
10107:     my $delidx = $counter;
10108:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10109:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10110:         $delete_output .= &start_data_table_row().
10111:                           '<td><img src="'.&icon($oldfile).'" />'.
10112:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10113:                           '<td>'.$size.'</td>'.
10114:                           '<td>'.$mtime.'</td>'.
10115:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10116:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10117:                           &embedded_file_element('upload_embedded',$delidx,
10118:                                                  $oldfile,\%mapping,$allfiles,
10119:                                                  $codebase,'delete').'</td>'.
10120:                           &end_data_table_row()."\n"; 
10121:         $numunused ++;
10122:         $delidx ++;
10123:     }
10124:     if ($upload_output) {
10125:         $upload_output = &start_data_table().
10126:                          $upload_output.
10127:                          &end_data_table()."\n";
10128:     }
10129:     if ($modify_output) {
10130:         $modify_output = &start_data_table().
10131:                          &start_data_table_header_row().
10132:                          '<th>'.&mt('File').'</th>'.
10133:                          '<th>'.&mt('Size (KB)').'</th>'.
10134:                          '<th>'.&mt('Modified').'</th>'.
10135:                          '<th>'.&mt('Upload replacement?').'</th>'.
10136:                          &end_data_table_header_row().
10137:                          $modify_output.
10138:                          &end_data_table()."\n";
10139:     }
10140:     if ($delete_output) {
10141:         $delete_output = &start_data_table().
10142:                          &start_data_table_header_row().
10143:                          '<th>'.&mt('File').'</th>'.
10144:                          '<th>'.&mt('Size (KB)').'</th>'.
10145:                          '<th>'.&mt('Modified').'</th>'.
10146:                          '<th>'.&mt('Delete?').'</th>'.
10147:                          &end_data_table_header_row().
10148:                          $delete_output.
10149:                          &end_data_table()."\n";
10150:     }
10151:     my $applies = 0;
10152:     if ($numremref) {
10153:         $applies ++;
10154:     }
10155:     if ($numinvalid) {
10156:         $applies ++;
10157:     }
10158:     if ($numexisting) {
10159:         $applies ++;
10160:     }
10161:     if ($counter || $numunused) {
10162:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10163:                   ' method="post" enctype="multipart/form-data">'."\n".
10164:                   $state.'<h3>'.$heading.'</h3>'; 
10165:         if ($actionurl eq '/adm/dependencies') {
10166:             if ($numnew) {
10167:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10168:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10169:                            $upload_output.'<br />'."\n";
10170:             }
10171:             if ($numexisting) {
10172:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10173:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10174:                            $modify_output.'<br />'."\n";
10175:                            $buttontext = &mt('Save changes');
10176:             }
10177:             if ($numunused) {
10178:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10179:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10180:                            $delete_output.'<br />'."\n";
10181:                            $buttontext = &mt('Save changes');
10182:             }
10183:         } else {
10184:             $output .= $upload_output.'<br />'."\n";
10185:         }
10186:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10187:                    $counter.'" />'."\n";
10188:         if ($actionurl eq '/adm/dependencies') { 
10189:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10190:                        $numnew.'" />'."\n";
10191:         } elsif ($actionurl eq '') {
10192:             $output .=  '<input type="hidden" name="phase" value="three" />';
10193:         }
10194:     } elsif ($applies) {
10195:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10196:         if ($applies > 1) {
10197:             $output .=  
10198:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10199:             if ($numremref) {
10200:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10201:             }
10202:             if ($numinvalid) {
10203:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10204:             }
10205:             if ($numexisting) {
10206:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10207:             }
10208:             $output .= '</ul><br />';
10209:         } elsif ($numremref) {
10210:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10211:         } elsif ($numinvalid) {
10212:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10213:         } elsif ($numexisting) {
10214:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10215:         }
10216:         $output .= $upload_output.'<br />';
10217:     }
10218:     my ($pathchange_output,$chgcount);
10219:     $chgcount = $counter;
10220:     if (keys(%pathchanges) > 0) {
10221:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10222:             if ($counter) {
10223:                 $output .= &embedded_file_element('pathchange',$chgcount,
10224:                                                   $embed_file,\%mapping,
10225:                                                   $allfiles,$codebase,'change');
10226:             } else {
10227:                 $pathchange_output .= 
10228:                     &start_data_table_row().
10229:                     '<td><input type ="checkbox" name="namechange" value="'.
10230:                     $chgcount.'" checked="checked" /></td>'.
10231:                     '<td>'.$mapping{$embed_file}.'</td>'.
10232:                     '<td>'.$embed_file.
10233:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10234:                                            \%mapping,$allfiles,$codebase,'change').
10235:                     '</td>'.&end_data_table_row();
10236:             }
10237:             $numpathchg ++;
10238:             $chgcount ++;
10239:         }
10240:     }
10241:     if (($counter) || ($numunused)) {
10242:         if ($numpathchg) {
10243:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10244:                        $numpathchg.'" />'."\n";
10245:         }
10246:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10247:             ($actionurl eq '/adm/imsimport')) {
10248:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10249:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10250:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10251:         } elsif ($actionurl eq '/adm/dependencies') {
10252:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10253:         }
10254:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10255:     } elsif ($numpathchg) {
10256:         my %pathchange = ();
10257:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10258:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10259:             $output .= '<p>'.&mt('or').'</p>'; 
10260:         }
10261:     }
10262:     return ($output,$counter,$numpathchg);
10263: }
10264: 
10265: 
10266: =pod
10267: 
10268: =item * clean_path($name)
10269: 
10270: Performs clean-up of directories, subdirectories and filename in an
10271: embedded object, referenced in an HTML file which is being uploaded
10272: to a course or portfolio, where
10273: "Upload embedded images/multimedia files if HTML file" checkbox was
10274: checked.
10275: 
10276: Clean-up is similar to replacements in lonnet::clean_filename()
10277: except each / between sub-directory and next level is preserved.
10278: 
10279: =cut
10280: 
10281: sub clean_path {
10282:     my ($embed_file) = @_;
10283:     $embed_file =~s{^/+}{};
10284:     my @contents;
10285:     if ($embed_file =~ m{/}) {
10286:         @contents = split(/\//,$embed_file);
10287:     } else {
10288:         @contents = ($embed_file);
10289:     }
10290:     my $lastidx = scalar(@contents)-1;
10291:     for (my $i=0; $i<=$lastidx; $i++) {
10292:         $contents[$i]=~s{\\}{/}g;
10293:         $contents[$i]=~s/\s+/\_/g;
10294:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10295:         if ($i == $lastidx) {
10296:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10297:         }
10298:     }
10299:     if ($lastidx > 0) {
10300:         return join('/',@contents);
10301:     } else {
10302:         return $contents[0];
10303:     }
10304: }
10305: 
10306: sub embedded_file_element {
10307:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10308:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10309:                    (ref($codebase) eq 'HASH'));
10310:     my $output;
10311:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10312:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10313:     }
10314:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10315:                &escape($embed_file).'" />';
10316:     unless (($context eq 'upload_embedded') && 
10317:             ($mapping->{$embed_file} eq $embed_file)) {
10318:         $output .='
10319:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10320:     }
10321:     my $attrib;
10322:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10323:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10324:     }
10325:     $output .=
10326:         "\n\t\t".
10327:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10328:         $attrib.'" />';
10329:     if (exists($codebase->{$mapping->{$embed_file}})) {
10330:         $output .=
10331:             "\n\t\t".
10332:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10333:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10334:     }
10335:     return $output;
10336: }
10337: 
10338: sub get_dependency_details {
10339:     my ($currfile,$currsubfile,$embed_file) = @_;
10340:     my ($size,$mtime,$showsize,$showmtime);
10341:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10342:         if ($embed_file =~ m{/}) {
10343:             my ($path,$fname) = split(/\//,$embed_file);
10344:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10345:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10346:             }
10347:         } else {
10348:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10349:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10350:             }
10351:         }
10352:         $showsize = $size/1024.0;
10353:         $showsize = sprintf("%.1f",$showsize);
10354:         if ($mtime > 0) {
10355:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10356:         }
10357:     }
10358:     return ($showsize,$showmtime);
10359: }
10360: 
10361: sub ask_embedded_js {
10362:     return <<"END";
10363: <script type="text/javascript"">
10364: // <![CDATA[
10365: function toggleBrowse(counter) {
10366:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10367:     var fileid = document.getElementById('embedded_item_'+counter);
10368:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10369:     if (chkboxid.checked == true) {
10370:         uploaddivid.style.display='block';
10371:     } else {
10372:         uploaddivid.style.display='none';
10373:         fileid.value = '';
10374:     }
10375: }
10376: // ]]>
10377: </script>
10378: 
10379: END
10380: }
10381: 
10382: sub upload_embedded {
10383:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10384:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10385:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10386:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10387:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10388:         my $orig_uploaded_filename =
10389:             $env{'form.embedded_item_'.$i.'.filename'};
10390:         foreach my $type ('orig','ref','attrib','codebase') {
10391:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10392:                 $env{'form.embedded_'.$type.'_'.$i} =
10393:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10394:             }
10395:         }
10396:         my ($path,$fname) =
10397:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10398:         # no path, whole string is fname
10399:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10400:         $fname = &Apache::lonnet::clean_filename($fname);
10401:         # See if there is anything left
10402:         next if ($fname eq '');
10403: 
10404:         # Check if file already exists as a file or directory.
10405:         my ($state,$msg);
10406:         if ($context eq 'portfolio') {
10407:             my $port_path = $dirpath;
10408:             if ($group ne '') {
10409:                 $port_path = "groups/$group/$port_path";
10410:             }
10411:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10412:                                               $fname,$group,'embedded_item_'.$i,
10413:                                               $dir_root,$port_path,$disk_quota,
10414:                                               $current_disk_usage,$uname,$udom);
10415:             if ($state eq 'will_exceed_quota'
10416:                 || $state eq 'file_locked') {
10417:                 $output .= $msg;
10418:                 next;
10419:             }
10420:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10421:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10422:             if ($state eq 'exists') {
10423:                 $output .= $msg;
10424:                 next;
10425:             }
10426:         }
10427:         # Check if extension is valid
10428:         if (($fname =~ /\.(\w+)$/) &&
10429:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10430:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10431:             next;
10432:         } elsif (($fname =~ /\.(\w+)$/) &&
10433:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10434:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10435:             next;
10436:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10437:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10438:             next;
10439:         }
10440:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10441:         my $subdir = $path;
10442:         $subdir =~ s{/+$}{};
10443:         if ($context eq 'portfolio') {
10444:             my $result;
10445:             if ($state eq 'existingfile') {
10446:                 $result=
10447:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10448:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10449:             } else {
10450:                 $result=
10451:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10452:                                                     $dirpath.
10453:                                                     $env{'form.currentpath'}.$subdir);
10454:                 if ($result !~ m|^/uploaded/|) {
10455:                     $output .= '<span class="LC_error">'
10456:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10457:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10458:                                .'</span><br />';
10459:                     next;
10460:                 } else {
10461:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10462:                                $path.$fname.'</span>').'<br />';     
10463:                 }
10464:             }
10465:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10466:             my $extendedsubdir = $dirpath.'/'.$subdir;
10467:             $extendedsubdir =~ s{/+$}{};
10468:             my $result =
10469:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10470:             if ($result !~ m|^/uploaded/|) {
10471:                 $output .= '<span class="LC_error">'
10472:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10473:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10474:                            .'</span><br />';
10475:                     next;
10476:             } else {
10477:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10478:                            $path.$fname.'</span>').'<br />';
10479:                 if ($context eq 'syllabus') {
10480:                     &Apache::lonnet::make_public_indefinitely($result);
10481:                 }
10482:             }
10483:         } else {
10484: # Save the file
10485:             my $target = $env{'form.embedded_item_'.$i};
10486:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10487:             my $dest = $fullpath.$fname;
10488:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10489:             my @parts=split(/\//,"$dirpath/$path");
10490:             my $count;
10491:             my $filepath = $dir_root;
10492:             foreach my $subdir (@parts) {
10493:                 $filepath .= "/$subdir";
10494:                 if (!-e $filepath) {
10495:                     mkdir($filepath,0770);
10496:                 }
10497:             }
10498:             my $fh;
10499:             if (!open($fh,'>'.$dest)) {
10500:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10501:                 $output .= '<span class="LC_error">'.
10502:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10503:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10504:                            '</span><br />';
10505:             } else {
10506:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10507:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10508:                     $output .= '<span class="LC_error">'.
10509:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10510:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10511:                               '</span><br />';
10512:                 } else {
10513:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10514:                                $url.'</span>').'<br />';
10515:                     unless ($context eq 'testbank') {
10516:                         $footer .= &mt('View embedded file: [_1]',
10517:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10518:                     }
10519:                 }
10520:                 close($fh);
10521:             }
10522:         }
10523:         if ($env{'form.embedded_ref_'.$i}) {
10524:             $pathchange{$i} = 1;
10525:         }
10526:     }
10527:     if ($output) {
10528:         $output = '<p>'.$output.'</p>';
10529:     }
10530:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10531:     $returnflag = 'ok';
10532:     my $numpathchgs = scalar(keys(%pathchange));
10533:     if ($numpathchgs > 0) {
10534:         if ($context eq 'portfolio') {
10535:             $output .= '<p>'.&mt('or').'</p>';
10536:         } elsif ($context eq 'testbank') {
10537:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10538:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10539:             $returnflag = 'modify_orightml';
10540:         }
10541:     }
10542:     return ($output.$footer,$returnflag,$numpathchgs);
10543: }
10544: 
10545: sub modify_html_form {
10546:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10547:     my $end = 0;
10548:     my $modifyform;
10549:     if ($context eq 'upload_embedded') {
10550:         return unless (ref($pathchange) eq 'HASH');
10551:         if ($env{'form.number_embedded_items'}) {
10552:             $end += $env{'form.number_embedded_items'};
10553:         }
10554:         if ($env{'form.number_pathchange_items'}) {
10555:             $end += $env{'form.number_pathchange_items'};
10556:         }
10557:         if ($end) {
10558:             for (my $i=0; $i<$end; $i++) {
10559:                 if ($i < $env{'form.number_embedded_items'}) {
10560:                     next unless($pathchange->{$i});
10561:                 }
10562:                 $modifyform .=
10563:                     &start_data_table_row().
10564:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10565:                     'checked="checked" /></td>'.
10566:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10567:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10568:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10569:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10570:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10571:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10572:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10573:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10574:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10575:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10576:                     &end_data_table_row();
10577:             }
10578:         }
10579:     } else {
10580:         $modifyform = $pathchgtable;
10581:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10582:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10583:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10584:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10585:         }
10586:     }
10587:     if ($modifyform) {
10588:         if ($actionurl eq '/adm/dependencies') {
10589:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10590:         }
10591:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10592:                '<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".
10593:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10594:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10595:                '</ol></p>'."\n".'<p>'.
10596:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10597:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10598:                &start_data_table()."\n".
10599:                &start_data_table_header_row().
10600:                '<th>'.&mt('Change?').'</th>'.
10601:                '<th>'.&mt('Current reference').'</th>'.
10602:                '<th>'.&mt('Required reference').'</th>'.
10603:                &end_data_table_header_row()."\n".
10604:                $modifyform.
10605:                &end_data_table().'<br />'."\n".$hiddenstate.
10606:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10607:                '</form>'."\n";
10608:     }
10609:     return;
10610: }
10611: 
10612: sub modify_html_refs {
10613:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10614:     my $container;
10615:     if ($context eq 'portfolio') {
10616:         $container = $env{'form.container'};
10617:     } elsif ($context eq 'coursedoc') {
10618:         $container = $env{'form.primaryurl'};
10619:     } elsif ($context eq 'manage_dependencies') {
10620:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10621:         $container = "/$container";
10622:     } elsif ($context eq 'syllabus') {
10623:         $container = $url;
10624:     } else {
10625:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10626:     }
10627:     my (%allfiles,%codebase,$output,$content);
10628:     my @changes = &get_env_multiple('form.namechange');
10629:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10630:         if (wantarray) {
10631:             return ('',0,0); 
10632:         } else {
10633:             return;
10634:         }
10635:     }
10636:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10637:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10638:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10639:             if (wantarray) {
10640:                 return ('',0,0);
10641:             } else {
10642:                 return;
10643:             }
10644:         } 
10645:         $content = &Apache::lonnet::getfile($container);
10646:         if ($content eq '-1') {
10647:             if (wantarray) {
10648:                 return ('',0,0);
10649:             } else {
10650:                 return;
10651:             }
10652:         }
10653:     } else {
10654:         unless ($container =~ /^\Q$dir_root\E/) {
10655:             if (wantarray) {
10656:                 return ('',0,0);
10657:             } else {
10658:                 return;
10659:             }
10660:         } 
10661:         if (open(my $fh,"<$container")) {
10662:             $content = join('', <$fh>);
10663:             close($fh);
10664:         } else {
10665:             if (wantarray) {
10666:                 return ('',0,0);
10667:             } else {
10668:                 return;
10669:             }
10670:         }
10671:     }
10672:     my ($count,$codebasecount) = (0,0);
10673:     my $mm = new File::MMagic;
10674:     my $mime_type = $mm->checktype_contents($content);
10675:     if ($mime_type eq 'text/html') {
10676:         my $parse_result = 
10677:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10678:                                                     \%codebase,\$content);
10679:         if ($parse_result eq 'ok') {
10680:             foreach my $i (@changes) {
10681:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10682:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10683:                 if ($allfiles{$ref}) {
10684:                     my $newname =  $orig;
10685:                     my ($attrib_regexp,$codebase);
10686:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10687:                     if ($attrib_regexp =~ /:/) {
10688:                         $attrib_regexp =~ s/\:/|/g;
10689:                     }
10690:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10691:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10692:                         $count += $numchg;
10693:                         $allfiles{$newname} = $allfiles{$ref};
10694:                         delete($allfiles{$ref});
10695:                     }
10696:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10697:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10698:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10699:                         $codebasecount ++;
10700:                     }
10701:                 }
10702:             }
10703:             my $skiprewrites;
10704:             if ($count || $codebasecount) {
10705:                 my $saveresult;
10706:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10707:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10708:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10709:                     if ($url eq $container) {
10710:                         my ($fname) = ($container =~ m{/([^/]+)$});
10711:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10712:                                             $count,'<span class="LC_filename">'.
10713:                                             $fname.'</span>').'</p>';
10714:                     } else {
10715:                          $output = '<p class="LC_error">'.
10716:                                    &mt('Error: update failed for: [_1].',
10717:                                    '<span class="LC_filename">'.
10718:                                    $container.'</span>').'</p>';
10719:                     }
10720:                     if ($context eq 'syllabus') {
10721:                         unless ($saveresult eq 'ok') {
10722:                             $skiprewrites = 1;
10723:                         }
10724:                     }
10725:                 } else {
10726:                     if (open(my $fh,">$container")) {
10727:                         print $fh $content;
10728:                         close($fh);
10729:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10730:                                   $count,'<span class="LC_filename">'.
10731:                                   $container.'</span>').'</p>';
10732:                     } else {
10733:                          $output = '<p class="LC_error">'.
10734:                                    &mt('Error: could not update [_1].',
10735:                                    '<span class="LC_filename">'.
10736:                                    $container.'</span>').'</p>';
10737:                     }
10738:                 }
10739:             }
10740:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10741:                 my ($actionurl,$state);
10742:                 $actionurl = "/public/$udom/$uname/syllabus";
10743:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10744:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10745:                                               \%codebase,
10746:                                               {'context' => 'rewrites',
10747:                                                'ignore_remote_references' => 1,});
10748:                 if (ref($mapping) eq 'HASH') {
10749:                     my $rewrites = 0;
10750:                     foreach my $key (keys(%{$mapping})) {
10751:                         next if ($key =~ m{^https?://});
10752:                         my $ref = $mapping->{$key};
10753:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10754:                         my $attrib;
10755:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10756:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10757:                         }
10758:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10759:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10760:                             $rewrites += $numchg;
10761:                         }
10762:                     }
10763:                     if ($rewrites) {
10764:                         my $saveresult;
10765:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10766:                         if ($url eq $container) {
10767:                             my ($fname) = ($container =~ m{/([^/]+)$});
10768:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10769:                                             $count,'<span class="LC_filename">'.
10770:                                             $fname.'</span>').'</p>';
10771:                         } else {
10772:                             $output .= '<p class="LC_error">'.
10773:                                        &mt('Error: could not update links in [_1].',
10774:                                        '<span class="LC_filename">'.
10775:                                        $container.'</span>').'</p>';
10776: 
10777:                         }
10778:                     }
10779:                 }
10780:             }
10781:         } else {
10782:             &logthis('Failed to parse '.$container.
10783:                      ' to modify references: '.$parse_result);
10784:         }
10785:     }
10786:     if (wantarray) {
10787:         return ($output,$count,$codebasecount);
10788:     } else {
10789:         return $output;
10790:     }
10791: }
10792: 
10793: sub check_for_existing {
10794:     my ($path,$fname,$element) = @_;
10795:     my ($state,$msg);
10796:     if (-d $path.'/'.$fname) {
10797:         $state = 'exists';
10798:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10799:     } elsif (-e $path.'/'.$fname) {
10800:         $state = 'exists';
10801:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10802:     }
10803:     if ($state eq 'exists') {
10804:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10805:     }
10806:     return ($state,$msg);
10807: }
10808: 
10809: sub check_for_upload {
10810:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10811:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10812:     my $filesize = length($env{'form.'.$element});
10813:     if (!$filesize) {
10814:         my $msg = '<span class="LC_error">'.
10815:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10816:                       '<span class="LC_filename">'.$fname.'</span>',
10817:                       $filesize).'<br />'.
10818:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10819:                   '</span>';
10820:         return ('zero_bytes',$msg);
10821:     }
10822:     $filesize =  $filesize/1000; #express in k (1024?)
10823:     my $getpropath = 1;
10824:     my ($dirlistref,$listerror) =
10825:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10826:     my $found_file = 0;
10827:     my $locked_file = 0;
10828:     my @lockers;
10829:     my $navmap;
10830:     if ($env{'request.course.id'}) {
10831:         $navmap = Apache::lonnavmaps::navmap->new();
10832:     }
10833:     if (ref($dirlistref) eq 'ARRAY') {
10834:         foreach my $line (@{$dirlistref}) {
10835:             my ($file_name,$rest)=split(/\&/,$line,2);
10836:             if ($file_name eq $fname){
10837:                 $file_name = $path.$file_name;
10838:                 if ($group ne '') {
10839:                     $file_name = $group.$file_name;
10840:                 }
10841:                 $found_file = 1;
10842:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10843:                     foreach my $lock (@lockers) {
10844:                         if (ref($lock) eq 'ARRAY') {
10845:                             my ($symb,$crsid) = @{$lock};
10846:                             if ($crsid eq $env{'request.course.id'}) {
10847:                                 if (ref($navmap)) {
10848:                                     my $res = $navmap->getBySymb($symb);
10849:                                     foreach my $part (@{$res->parts()}) { 
10850:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10851:                                         unless (($slot_status == $res->RESERVED) ||
10852:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10853:                                             $locked_file = 1;
10854:                                         }
10855:                                     }
10856:                                 } else {
10857:                                     $locked_file = 1;
10858:                                 }
10859:                             } else {
10860:                                 $locked_file = 1;
10861:                             }
10862:                         }
10863:                    }
10864:                 } else {
10865:                     my @info = split(/\&/,$rest);
10866:                     my $currsize = $info[6]/1000;
10867:                     if ($currsize < $filesize) {
10868:                         my $extra = $filesize - $currsize;
10869:                         if (($current_disk_usage + $extra) > $disk_quota) {
10870:                             my $msg = '<span class="LC_error">'.
10871:                                       &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.',
10872:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10873:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10874:                                                    $disk_quota,$current_disk_usage);
10875:                             return ('will_exceed_quota',$msg);
10876:                         }
10877:                     }
10878:                 }
10879:             }
10880:         }
10881:     }
10882:     if (($current_disk_usage + $filesize) > $disk_quota){
10883:         my $msg = '<span class="LC_error">'.
10884:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10885:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10886:         return ('will_exceed_quota',$msg);
10887:     } elsif ($found_file) {
10888:         if ($locked_file) {
10889:             my $msg = '<span class="LC_error">';
10890:             $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>');
10891:             $msg .= '</span><br />';
10892:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10893:             return ('file_locked',$msg);
10894:         } else {
10895:             my $msg = '<span class="LC_error">';
10896:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10897:             $msg .= '</span>';
10898:             return ('existingfile',$msg);
10899:         }
10900:     }
10901: }
10902: 
10903: sub check_for_traversal {
10904:     my ($path,$url,$toplevel) = @_;
10905:     my @parts=split(/\//,$path);
10906:     my $cleanpath;
10907:     my $fullpath = $url;
10908:     for (my $i=0;$i<@parts;$i++) {
10909:         next if ($parts[$i] eq '.');
10910:         if ($parts[$i] eq '..') {
10911:             $fullpath =~ s{([^/]+/)$}{};
10912:         } else {
10913:             $fullpath .= $parts[$i].'/';
10914:         }
10915:     }
10916:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10917:         $cleanpath = $1;
10918:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10919:         my $curr_toprel = $1;
10920:         my @parts = split(/\//,$curr_toprel);
10921:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10922:         my @urlparts = split(/\//,$url_toprel);
10923:         my $doubledots;
10924:         my $startdiff = -1;
10925:         for (my $i=0; $i<@urlparts; $i++) {
10926:             if ($startdiff == -1) {
10927:                 unless ($urlparts[$i] eq $parts[$i]) {
10928:                     $startdiff = $i;
10929:                     $doubledots .= '../';
10930:                 }
10931:             } else {
10932:                 $doubledots .= '../';
10933:             }
10934:         }
10935:         if ($startdiff > -1) {
10936:             $cleanpath = $doubledots;
10937:             for (my $i=$startdiff; $i<@parts; $i++) {
10938:                 $cleanpath .= $parts[$i].'/';
10939:             }
10940:         }
10941:     }
10942:     $cleanpath =~ s{(/)$}{};
10943:     return $cleanpath;
10944: }
10945: 
10946: sub is_archive_file {
10947:     my ($mimetype) = @_;
10948:     if (($mimetype eq 'application/octet-stream') ||
10949:         ($mimetype eq 'application/x-stuffit') ||
10950:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10951:         return 1;
10952:     }
10953:     return;
10954: }
10955: 
10956: sub decompress_form {
10957:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10958:     my %lt = &Apache::lonlocal::texthash (
10959:         this => 'This file is an archive file.',
10960:         camt => 'This file is a Camtasia archive file.',
10961:         itsc => 'Its contents are as follows:',
10962:         youm => 'You may wish to extract its contents.',
10963:         extr => 'Extract contents',
10964:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10965:         proa => 'Process automatically?',
10966:         yes  => 'Yes',
10967:         no   => 'No',
10968:         fold => 'Title for folder containing movie',
10969:         movi => 'Title for page containing embedded movie', 
10970:     );
10971:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10972:     my ($is_camtasia,$topdir,%toplevel,@paths);
10973:     my $info = &list_archive_contents($fileloc,\@paths);
10974:     if (@paths) {
10975:         foreach my $path (@paths) {
10976:             $path =~ s{^/}{};
10977:             if ($path =~ m{^([^/]+)/$}) {
10978:                 $topdir = $1;
10979:             }
10980:             if ($path =~ m{^([^/]+)/}) {
10981:                 $toplevel{$1} = $path;
10982:             } else {
10983:                 $toplevel{$path} = $path;
10984:             }
10985:         }
10986:     }
10987:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10988:         my @camtasia = ("$topdir/","$topdir/index.html",
10989:                         "$topdir/media/",
10990:                         "$topdir/media/$topdir.mp4",
10991:                         "$topdir/media/FirstFrame.png",
10992:                         "$topdir/media/player.swf",
10993:                         "$topdir/media/swfobject.js",
10994:                         "$topdir/media/expressInstall.swf");
10995:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10996:         if (@diffs == 0) {
10997:             $is_camtasia = 1;
10998:         }
10999:     }
11000:     my $output;
11001:     if ($is_camtasia) {
11002:         $output = <<"ENDCAM";
11003: <script type="text/javascript" language="Javascript">
11004: // <![CDATA[
11005: 
11006: function camtasiaToggle() {
11007:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11008:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11009:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
11010: 
11011:                 document.getElementById('camtasia_titles').style.display='block';
11012:             } else {
11013:                 document.getElementById('camtasia_titles').style.display='none';
11014:             }
11015:         }
11016:     }
11017:     return;
11018: }
11019: 
11020: // ]]>
11021: </script>
11022: <p>$lt{'camt'}</p>
11023: ENDCAM
11024:     } else {
11025:         $output = '<p>'.$lt{'this'};
11026:         if ($info eq '') {
11027:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11028:         } else {
11029:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11030:                        '<div><pre>'.$info.'</pre></div>';
11031:         }
11032:     }
11033:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11034:     my $duplicates;
11035:     my $num = 0;
11036:     if (ref($dirlist) eq 'ARRAY') {
11037:         foreach my $item (@{$dirlist}) {
11038:             if (ref($item) eq 'ARRAY') {
11039:                 if (exists($toplevel{$item->[0]})) {
11040:                     $duplicates .= 
11041:                         &start_data_table_row().
11042:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11043:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11044:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11045:                         'value="1" />'.&mt('Yes').'</label>'.
11046:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11047:                         '<td>'.$item->[0].'</td>';
11048:                     if ($item->[2]) {
11049:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11050:                     } else {
11051:                         $duplicates .= '<td>'.&mt('File').'</td>';
11052:                     }
11053:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11054:                                    '<td>'.
11055:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11056:                                    '</td>'.
11057:                                    &end_data_table_row();
11058:                     $num ++;
11059:                 }
11060:             }
11061:         }
11062:     }
11063:     my $itemcount;
11064:     if (@paths > 0) {
11065:         $itemcount = scalar(@paths);
11066:     } else {
11067:         $itemcount = 1;
11068:     }
11069:     if ($is_camtasia) {
11070:         $output .= $lt{'auto'}.'<br />'.
11071:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11072:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11073:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11074:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11075:                    $lt{'no'}.'</label></span><br />'.
11076:                    '<div id="camtasia_titles" style="display:block">'.
11077:                    &Apache::lonhtmlcommon::start_pick_box().
11078:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11079:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11080:                    &Apache::lonhtmlcommon::row_closure().
11081:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11082:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11083:                    &Apache::lonhtmlcommon::row_closure(1).
11084:                    &Apache::lonhtmlcommon::end_pick_box().
11085:                    '</div>';
11086:     }
11087:     $output .= 
11088:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11089:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11090:         "\n";
11091:     if ($duplicates ne '') {
11092:         $output .= '<p><span class="LC_warning">'.
11093:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11094:                    &start_data_table().
11095:                    &start_data_table_header_row().
11096:                    '<th>'.&mt('Overwrite?').'</th>'.
11097:                    '<th>'.&mt('Name').'</th>'.
11098:                    '<th>'.&mt('Type').'</th>'.
11099:                    '<th>'.&mt('Size').'</th>'.
11100:                    '<th>'.&mt('Last modified').'</th>'.
11101:                    &end_data_table_header_row().
11102:                    $duplicates.
11103:                    &end_data_table().
11104:                    '</p>';
11105:     }
11106:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11107:     if (ref($hiddenelements) eq 'HASH') {
11108:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11109:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11110:         }
11111:     }
11112:     $output .= <<"END";
11113: <br />
11114: <input type="submit" name="decompress" value="$lt{'extr'}" />
11115: </form>
11116: $noextract
11117: END
11118:     return $output;
11119: }
11120: 
11121: sub decompression_utility {
11122:     my ($program) = @_;
11123:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11124:     my $location;
11125:     if (grep(/^\Q$program\E$/,@utilities)) { 
11126:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11127:                          '/usr/sbin/') {
11128:             if (-x $dir.$program) {
11129:                 $location = $dir.$program;
11130:                 last;
11131:             }
11132:         }
11133:     }
11134:     return $location;
11135: }
11136: 
11137: sub list_archive_contents {
11138:     my ($file,$pathsref) = @_;
11139:     my (@cmd,$output);
11140:     my $needsregexp;
11141:     if ($file =~ /\.zip$/) {
11142:         @cmd = (&decompression_utility('unzip'),"-l");
11143:         $needsregexp = 1;
11144:     } elsif (($file =~ m/\.tar\.gz$/) ||
11145:              ($file =~ /\.tgz$/)) {
11146:         @cmd = (&decompression_utility('tar'),"-ztf");
11147:     } elsif ($file =~ /\.tar\.bz2$/) {
11148:         @cmd = (&decompression_utility('tar'),"-jtf");
11149:     } elsif ($file =~ m|\.tar$|) {
11150:         @cmd = (&decompression_utility('tar'),"-tf");
11151:     }
11152:     if (@cmd) {
11153:         undef($!);
11154:         undef($@);
11155:         if (open(my $fh,"-|", @cmd, $file)) {
11156:             while (my $line = <$fh>) {
11157:                 $output .= $line;
11158:                 chomp($line);
11159:                 my $item;
11160:                 if ($needsregexp) {
11161:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11162:                 } else {
11163:                     $item = $line;
11164:                 }
11165:                 if ($item ne '') {
11166:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11167:                         push(@{$pathsref},$item);
11168:                     } 
11169:                 }
11170:             }
11171:             close($fh);
11172:         }
11173:     }
11174:     return $output;
11175: }
11176: 
11177: sub decompress_uploaded_file {
11178:     my ($file,$dir) = @_;
11179:     &Apache::lonnet::appenv({'cgi.file' => $file});
11180:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11181:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11182:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11183:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11184:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11185:     my $decompressed = $env{'cgi.decompressed'};
11186:     &Apache::lonnet::delenv('cgi.file');
11187:     &Apache::lonnet::delenv('cgi.dir');
11188:     &Apache::lonnet::delenv('cgi.decompressed');
11189:     return ($decompressed,$result);
11190: }
11191: 
11192: sub process_decompression {
11193:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11194:     my ($dir,$error,$warning,$output);
11195:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11196:         $error = &mt('Filename not a supported archive file type.').
11197:                  '<br />'.&mt('Filename should end with one of: [_1].',
11198:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11199:     } else {
11200:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11201:         if ($docuhome eq 'no_host') {
11202:             $error = &mt('Could not determine home server for course.');
11203:         } else {
11204:             my @ids=&Apache::lonnet::current_machine_ids();
11205:             my $currdir = "$dir_root/$destination";
11206:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11207:                 $dir = &LONCAPA::propath($docudom,$docuname).
11208:                        "$dir_root/$destination";
11209:             } else {
11210:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11211:                        "$dir_root/$docudom/$docuname/$destination";
11212:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11213:                     $error = &mt('Archive file not found.');
11214:                 }
11215:             }
11216:             my (@to_overwrite,@to_skip);
11217:             if ($env{'form.archive_overwrite_total'} > 0) {
11218:                 my $total = $env{'form.archive_overwrite_total'};
11219:                 for (my $i=0; $i<$total; $i++) {
11220:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11221:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11222:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11223:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11224:                     }
11225:                 }
11226:             }
11227:             my $numskip = scalar(@to_skip);
11228:             if (($numskip > 0) && 
11229:                 ($numskip == $env{'form.archive_itemcount'})) {
11230:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11231:             } elsif ($dir eq '') {
11232:                 $error = &mt('Directory containing archive file unavailable.');
11233:             } elsif (!$error) {
11234:                 my ($decompressed,$display);
11235:                 if ($numskip > 0) {
11236:                     my $tempdir = time.'_'.$$.int(rand(10000));
11237:                     mkdir("$dir/$tempdir",0755);
11238:                     system("mv $dir/$file $dir/$tempdir/$file");
11239:                     ($decompressed,$display) = 
11240:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11241:                     foreach my $item (@to_skip) {
11242:                         if (($item ne '') && ($item !~ /\.\./)) {
11243:                             if (-f "$dir/$tempdir/$item") { 
11244:                                 unlink("$dir/$tempdir/$item");
11245:                             } elsif (-d "$dir/$tempdir/$item") {
11246:                                 system("rm -rf $dir/$tempdir/$item");
11247:                             }
11248:                         }
11249:                     }
11250:                     system("mv $dir/$tempdir/* $dir");
11251:                     rmdir("$dir/$tempdir");   
11252:                 } else {
11253:                     ($decompressed,$display) = 
11254:                         &decompress_uploaded_file($file,$dir);
11255:                 }
11256:                 if ($decompressed eq 'ok') {
11257:                     $output = '<p class="LC_info">'.
11258:                               &mt('Files extracted successfully from archive.').
11259:                               '</p>'."\n";
11260:                     my ($warning,$result,@contents);
11261:                     my ($newdirlistref,$newlisterror) =
11262:                         &Apache::lonnet::dirlist($currdir,$docudom,
11263:                                                  $docuname,1);
11264:                     my (%is_dir,%changes,@newitems);
11265:                     my $dirptr = 16384;
11266:                     if (ref($newdirlistref) eq 'ARRAY') {
11267:                         foreach my $dir_line (@{$newdirlistref}) {
11268:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11269:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11270:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11271:                                 push(@newitems,$item);
11272:                                 if ($dirptr&$testdir) {
11273:                                     $is_dir{$item} = 1;
11274:                                 }
11275:                                 $changes{$item} = 1;
11276:                             }
11277:                         }
11278:                     }
11279:                     if (keys(%changes) > 0) {
11280:                         foreach my $item (sort(@newitems)) {
11281:                             if ($changes{$item}) {
11282:                                 push(@contents,$item);
11283:                             }
11284:                         }
11285:                     }
11286:                     if (@contents > 0) {
11287:                         my $wantform;
11288:                         unless ($env{'form.autoextract_camtasia'}) {
11289:                             $wantform = 1;
11290:                         }
11291:                         my (%children,%parent,%dirorder,%titles);
11292:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11293:                                                                 $currdir,\%is_dir,
11294:                                                                 \%children,\%parent,
11295:                                                                 \@contents,\%dirorder,
11296:                                                                 \%titles,$wantform);
11297:                         if ($datatable ne '') {
11298:                             $output .= &archive_options_form('decompressed',$datatable,
11299:                                                              $count,$hiddenelem);
11300:                             my $startcount = 6;
11301:                             $output .= &archive_javascript($startcount,$count,
11302:                                                            \%titles,\%children);
11303:                         }
11304:                         if ($env{'form.autoextract_camtasia'}) {
11305:                             my %displayed;
11306:                             my $total = 1;
11307:                             $env{'form.archive_directory'} = [];
11308:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11309:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11310:                                 $path =~ s{/$}{};
11311:                                 my $item;
11312:                                 if ($path ne '') {
11313:                                     $item = "$path/$titles{$i}";
11314:                                 } else {
11315:                                     $item = $titles{$i};
11316:                                 }
11317:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11318:                                 if ($item eq $contents[0]) {
11319:                                     push(@{$env{'form.archive_directory'}},$i);
11320:                                     $env{'form.archive_'.$i} = 'display';
11321:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11322:                                     $displayed{'folder'} = $i;
11323:                                 } elsif ($item eq "$contents[0]/index.html") {
11324:                                     $env{'form.archive_'.$i} = 'display';
11325:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11326:                                     $displayed{'web'} = $i;
11327:                                 } else {
11328:                                     if ($item eq "$contents[0]/media") {
11329:                                         push(@{$env{'form.archive_directory'}},$i);
11330:                                     }
11331:                                     $env{'form.archive_'.$i} = 'dependency';
11332:                                 }
11333:                                 $total ++;
11334:                             }
11335:                             for (my $i=1; $i<$total; $i++) {
11336:                                 next if ($i == $displayed{'web'});
11337:                                 next if ($i == $displayed{'folder'});
11338:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11339:                             }
11340:                             $env{'form.phase'} = 'decompress_cleanup';
11341:                             $env{'form.archivedelete'} = 1;
11342:                             $env{'form.archive_count'} = $total-1;
11343:                             $output .=
11344:                                 &process_extracted_files('coursedocs',$docudom,
11345:                                                          $docuname,$destination,
11346:                                                          $dir_root,$hiddenelem);
11347:                         }
11348:                     } else {
11349:                         $warning = &mt('No new items extracted from archive file.');
11350:                     }
11351:                 } else {
11352:                     $output = $display;
11353:                     $error = &mt('An error occurred during extraction from the archive file.');
11354:                 }
11355:             }
11356:         }
11357:     }
11358:     if ($error) {
11359:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11360:                    $error.'</p>'."\n";
11361:     }
11362:     if ($warning) {
11363:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11364:     }
11365:     return $output;
11366: }
11367: 
11368: sub get_extracted {
11369:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11370:         $titles,$wantform) = @_;
11371:     my $count = 0;
11372:     my $depth = 0;
11373:     my $datatable;
11374:     my @hierarchy;
11375:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11376:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11377:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11378:     foreach my $item (@{$contents}) {
11379:         $count ++;
11380:         @{$dirorder->{$count}} = @hierarchy;
11381:         $titles->{$count} = $item;
11382:         &archive_hierarchy($depth,$count,$parent,$children);
11383:         if ($wantform) {
11384:             $datatable .= &archive_row($is_dir->{$item},$item,
11385:                                        $currdir,$depth,$count);
11386:         }
11387:         if ($is_dir->{$item}) {
11388:             $depth ++;
11389:             push(@hierarchy,$count);
11390:             $parent->{$depth} = $count;
11391:             $datatable .=
11392:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11393:                                            \$depth,\$count,\@hierarchy,$dirorder,
11394:                                            $children,$parent,$titles,$wantform);
11395:             $depth --;
11396:             pop(@hierarchy);
11397:         }
11398:     }
11399:     return ($count,$datatable);
11400: }
11401: 
11402: sub recurse_extracted_archive {
11403:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11404:         $children,$parent,$titles,$wantform) = @_;
11405:     my $result='';
11406:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11407:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11408:             (ref($dirorder) eq 'HASH')) {
11409:         return $result;
11410:     }
11411:     my $dirptr = 16384;
11412:     my ($newdirlistref,$newlisterror) =
11413:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11414:     if (ref($newdirlistref) eq 'ARRAY') {
11415:         foreach my $dir_line (@{$newdirlistref}) {
11416:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11417:             unless ($item =~ /^\.+$/) {
11418:                 $$count ++;
11419:                 @{$dirorder->{$$count}} = @{$hierarchy};
11420:                 $titles->{$$count} = $item;
11421:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11422: 
11423:                 my $is_dir;
11424:                 if ($dirptr&$testdir) {
11425:                     $is_dir = 1;
11426:                 }
11427:                 if ($wantform) {
11428:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11429:                 }
11430:                 if ($is_dir) {
11431:                     $$depth ++;
11432:                     push(@{$hierarchy},$$count);
11433:                     $parent->{$$depth} = $$count;
11434:                     $result .=
11435:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11436:                                                    $docuname,$depth,$count,
11437:                                                    $hierarchy,$dirorder,$children,
11438:                                                    $parent,$titles,$wantform);
11439:                     $$depth --;
11440:                     pop(@{$hierarchy});
11441:                 }
11442:             }
11443:         }
11444:     }
11445:     return $result;
11446: }
11447: 
11448: sub archive_hierarchy {
11449:     my ($depth,$count,$parent,$children) =@_;
11450:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11451:         if (exists($parent->{$depth})) {
11452:              $children->{$parent->{$depth}} .= $count.':';
11453:         }
11454:     }
11455:     return;
11456: }
11457: 
11458: sub archive_row {
11459:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11460:     my ($name) = ($item =~ m{([^/]+)$});
11461:     my %choices = &Apache::lonlocal::texthash (
11462:                                        'display'    => 'Add as file',
11463:                                        'dependency' => 'Include as dependency',
11464:                                        'discard'    => 'Discard',
11465:                                       );
11466:     if ($is_dir) {
11467:         $choices{'display'} = &mt('Add as folder'); 
11468:     }
11469:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11470:     my $offset = 0;
11471:     foreach my $action ('display','dependency','discard') {
11472:         $offset ++;
11473:         if ($action ne 'display') {
11474:             $offset ++;
11475:         }  
11476:         $output .= '<td><span class="LC_nobreak">'.
11477:                    '<label><input type="radio" name="archive_'.$count.
11478:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11479:         my $text = $choices{$action};
11480:         if ($is_dir) {
11481:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11482:             if ($action eq 'display') {
11483:                 $text = &mt('Add as folder');
11484:             }
11485:         } else {
11486:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11487: 
11488:         }
11489:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11490:         if ($action eq 'dependency') {
11491:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11492:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11493:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11494:                        '<option value=""></option>'."\n".
11495:                        '</select>'."\n".
11496:                        '</div>';
11497:         } elsif ($action eq 'display') {
11498:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11499:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11500:                        '</div>';
11501:         }
11502:         $output .= '</td>';
11503:     }
11504:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11505:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11506:     for (my $i=0; $i<$depth; $i++) {
11507:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11508:     }
11509:     if ($is_dir) {
11510:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11511:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11512:     } else {
11513:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11514:     }
11515:     $output .= '&nbsp;'.$name.'</td>'."\n".
11516:                &end_data_table_row();
11517:     return $output;
11518: }
11519: 
11520: sub archive_options_form {
11521:     my ($form,$display,$count,$hiddenelem) = @_;
11522:     my %lt = &Apache::lonlocal::texthash(
11523:                perm => 'Permanently remove archive file?',
11524:                hows => 'How should each extracted item be incorporated in the course?',
11525:                cont => 'Content actions for all',
11526:                addf => 'Add as folder/file',
11527:                incd => 'Include as dependency for a displayed file',
11528:                disc => 'Discard',
11529:                no   => 'No',
11530:                yes  => 'Yes',
11531:                save => 'Save',
11532:     );
11533:     my $output = <<"END";
11534: <form name="$form" method="post" action="">
11535: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11536: <label>
11537:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11538: </label>
11539: &nbsp;
11540: <label>
11541:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11542: </span>
11543: </p>
11544: <input type="hidden" name="phase" value="decompress_cleanup" />
11545: <br />$lt{'hows'}
11546: <div class="LC_columnSection">
11547:   <fieldset>
11548:     <legend>$lt{'cont'}</legend>
11549:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11550:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11551:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11552:   </fieldset>
11553: </div>
11554: END
11555:     return $output.
11556:            &start_data_table()."\n".
11557:            $display."\n".
11558:            &end_data_table()."\n".
11559:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11560:            $hiddenelem.
11561:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11562:            '</form>';
11563: }
11564: 
11565: sub archive_javascript {
11566:     my ($startcount,$numitems,$titles,$children) = @_;
11567:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11568:     my $maintitle = $env{'form.comment'};
11569:     my $scripttag = <<START;
11570: <script type="text/javascript">
11571: // <![CDATA[
11572: 
11573: function checkAll(form,prefix) {
11574:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11575:     for (var i=0; i < form.elements.length; i++) {
11576:         var id = form.elements[i].id;
11577:         if ((id != '') && (id != undefined)) {
11578:             if (idstr.test(id)) {
11579:                 if (form.elements[i].type == 'radio') {
11580:                     form.elements[i].checked = true;
11581:                     var nostart = i-$startcount;
11582:                     var offset = nostart%7;
11583:                     var count = (nostart-offset)/7;    
11584:                     dependencyCheck(form,count,offset);
11585:                 }
11586:             }
11587:         }
11588:     }
11589: }
11590: 
11591: function propagateCheck(form,count) {
11592:     if (count > 0) {
11593:         var startelement = $startcount + ((count-1) * 7);
11594:         for (var j=1; j<6; j++) {
11595:             if ((j != 2) && (j != 4)) {
11596:                 var item = startelement + j; 
11597:                 if (form.elements[item].type == 'radio') {
11598:                     if (form.elements[item].checked) {
11599:                         containerCheck(form,count,j);
11600:                         break;
11601:                     }
11602:                 }
11603:             }
11604:         }
11605:     }
11606: }
11607: 
11608: numitems = $numitems
11609: var titles = new Array(numitems);
11610: var parents = new Array(numitems);
11611: for (var i=0; i<numitems; i++) {
11612:     parents[i] = new Array;
11613: }
11614: var maintitle = '$maintitle';
11615: 
11616: START
11617: 
11618:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11619:         my @contents = split(/:/,$children->{$container});
11620:         for (my $i=0; $i<@contents; $i ++) {
11621:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11622:         }
11623:     }
11624: 
11625:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11626:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11627:     }
11628: 
11629:     $scripttag .= <<END;
11630: 
11631: function containerCheck(form,count,offset) {
11632:     if (count > 0) {
11633:         dependencyCheck(form,count,offset);
11634:         var item = (offset+$startcount)+7*(count-1);
11635:         form.elements[item].checked = true;
11636:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11637:             if (parents[count].length > 0) {
11638:                 for (var j=0; j<parents[count].length; j++) {
11639:                     containerCheck(form,parents[count][j],offset);
11640:                 }
11641:             }
11642:         }
11643:     }
11644: }
11645: 
11646: function dependencyCheck(form,count,offset) {
11647:     if (count > 0) {
11648:         var chosen = (offset+$startcount)+7*(count-1);
11649:         var depitem = $startcount + ((count-1) * 7) + 4;
11650:         var currtype = form.elements[depitem].type;
11651:         if (form.elements[chosen].value == 'dependency') {
11652:             document.getElementById('arc_depon_'+count).style.display='block'; 
11653:             form.elements[depitem].options.length = 0;
11654:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11655:             for (var i=1; i<=numitems; i++) {
11656:                 if (i == count) {
11657:                     continue;
11658:                 }
11659:                 var startelement = $startcount + (i-1) * 7;
11660:                 for (var j=1; j<6; j++) {
11661:                     if ((j != 2) && (j!= 4)) {
11662:                         var item = startelement + j;
11663:                         if (form.elements[item].type == 'radio') {
11664:                             if (form.elements[item].checked) {
11665:                                 if (form.elements[item].value == 'display') {
11666:                                     var n = form.elements[depitem].options.length;
11667:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11668:                                 }
11669:                             }
11670:                         }
11671:                     }
11672:                 }
11673:             }
11674:         } else {
11675:             document.getElementById('arc_depon_'+count).style.display='none';
11676:             form.elements[depitem].options.length = 0;
11677:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11678:         }
11679:         titleCheck(form,count,offset);
11680:     }
11681: }
11682: 
11683: function propagateSelect(form,count,offset) {
11684:     if (count > 0) {
11685:         var item = (1+offset+$startcount)+7*(count-1);
11686:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11687:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11688:             if (parents[count].length > 0) {
11689:                 for (var j=0; j<parents[count].length; j++) {
11690:                     containerSelect(form,parents[count][j],offset,picked);
11691:                 }
11692:             }
11693:         }
11694:     }
11695: }
11696: 
11697: function containerSelect(form,count,offset,picked) {
11698:     if (count > 0) {
11699:         var item = (offset+$startcount)+7*(count-1);
11700:         if (form.elements[item].type == 'radio') {
11701:             if (form.elements[item].value == 'dependency') {
11702:                 if (form.elements[item+1].type == 'select-one') {
11703:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11704:                         if (form.elements[item+1].options[i].value == picked) {
11705:                             form.elements[item+1].selectedIndex = i;
11706:                             break;
11707:                         }
11708:                     }
11709:                 }
11710:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11711:                     if (parents[count].length > 0) {
11712:                         for (var j=0; j<parents[count].length; j++) {
11713:                             containerSelect(form,parents[count][j],offset,picked);
11714:                         }
11715:                     }
11716:                 }
11717:             }
11718:         }
11719:     }
11720: }
11721: 
11722: function titleCheck(form,count,offset) {
11723:     if (count > 0) {
11724:         var chosen = (offset+$startcount)+7*(count-1);
11725:         var depitem = $startcount + ((count-1) * 7) + 2;
11726:         var currtype = form.elements[depitem].type;
11727:         if (form.elements[chosen].value == 'display') {
11728:             document.getElementById('arc_title_'+count).style.display='block';
11729:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11730:                 document.getElementById('archive_title_'+count).value=maintitle;
11731:             }
11732:         } else {
11733:             document.getElementById('arc_title_'+count).style.display='none';
11734:             if (currtype == 'text') { 
11735:                 document.getElementById('archive_title_'+count).value='';
11736:             }
11737:         }
11738:     }
11739:     return;
11740: }
11741: 
11742: // ]]>
11743: </script>
11744: END
11745:     return $scripttag;
11746: }
11747: 
11748: sub process_extracted_files {
11749:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11750:     my $numitems = $env{'form.archive_count'};
11751:     return unless ($numitems);
11752:     my @ids=&Apache::lonnet::current_machine_ids();
11753:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11754:         %folders,%containers,%mapinner,%prompttofetch);
11755:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11756:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11757:         $prefix = &LONCAPA::propath($docudom,$docuname);
11758:         $pathtocheck = "$dir_root/$destination";
11759:         $dir = $dir_root;
11760:         $ishome = 1;
11761:     } else {
11762:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11763:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11764:         $dir = "$dir_root/$docudom/$docuname";    
11765:     }
11766:     my $currdir = "$dir_root/$destination";
11767:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11768:     if ($env{'form.folderpath'}) {
11769:         my @items = split('&',$env{'form.folderpath'});
11770:         $folders{'0'} = $items[-2];
11771:         if ($env{'form.folderpath'} =~ /\:1$/) {
11772:             $containers{'0'}='page';
11773:         } else {
11774:             $containers{'0'}='sequence';
11775:         }
11776:     }
11777:     my @archdirs = &get_env_multiple('form.archive_directory');
11778:     if ($numitems) {
11779:         for (my $i=1; $i<=$numitems; $i++) {
11780:             my $path = $env{'form.archive_content_'.$i};
11781:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11782:                 my $item = $1;
11783:                 $toplevelitems{$item} = $i;
11784:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11785:                     $is_dir{$item} = 1;
11786:                 }
11787:             }
11788:         }
11789:     }
11790:     my ($output,%children,%parent,%titles,%dirorder,$result);
11791:     if (keys(%toplevelitems) > 0) {
11792:         my @contents = sort(keys(%toplevelitems));
11793:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11794:                                            \%parent,\@contents,\%dirorder,\%titles);
11795:     }
11796:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11797:     if ($numitems) {
11798:         for (my $i=1; $i<=$numitems; $i++) {
11799:             next if ($env{'form.archive_'.$i} eq 'dependency');
11800:             my $path = $env{'form.archive_content_'.$i};
11801:             if ($path =~ /^\Q$pathtocheck\E/) {
11802:                 if ($env{'form.archive_'.$i} eq 'discard') {
11803:                     if ($prefix ne '' && $path ne '') {
11804:                         if (-e $prefix.$path) {
11805:                             if ((@archdirs > 0) && 
11806:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11807:                                 $todeletedir{$prefix.$path} = 1;
11808:                             } else {
11809:                                 $todelete{$prefix.$path} = 1;
11810:                             }
11811:                         }
11812:                     }
11813:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11814:                     my ($docstitle,$title,$url,$outer);
11815:                     ($title) = ($path =~ m{/([^/]+)$});
11816:                     $docstitle = $env{'form.archive_title_'.$i};
11817:                     if ($docstitle eq '') {
11818:                         $docstitle = $title;
11819:                     }
11820:                     $outer = 0;
11821:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11822:                         if (@{$dirorder{$i}} > 0) {
11823:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11824:                                 if ($env{'form.archive_'.$item} eq 'display') {
11825:                                     $outer = $item;
11826:                                     last;
11827:                                 }
11828:                             }
11829:                         }
11830:                     }
11831:                     my ($errtext,$fatal) = 
11832:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11833:                                                '/'.$folders{$outer}.'.'.
11834:                                                $containers{$outer});
11835:                     next if ($fatal);
11836:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11837:                         if ($context eq 'coursedocs') {
11838:                             $mapinner{$i} = time;
11839:                             $folders{$i} = 'default_'.$mapinner{$i};
11840:                             $containers{$i} = 'sequence';
11841:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11842:                                       $folders{$i}.'.'.$containers{$i};
11843:                             my $newidx = &LONCAPA::map::getresidx();
11844:                             $LONCAPA::map::resources[$newidx]=
11845:                                 $docstitle.':'.$url.':false:normal:res';
11846:                             push(@LONCAPA::map::order,$newidx);
11847:                             my ($outtext,$errtext) =
11848:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11849:                                                         $docuname.'/'.$folders{$outer}.
11850:                                                         '.'.$containers{$outer},1,1);
11851:                             $newseqid{$i} = $newidx;
11852:                             unless ($errtext) {
11853:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11854:                             }
11855:                         }
11856:                     } else {
11857:                         if ($context eq 'coursedocs') {
11858:                             my $newidx=&LONCAPA::map::getresidx();
11859:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11860:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11861:                                       $title;
11862:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11863:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11864:                             }
11865:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11866:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11867:                             }
11868:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11869:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11870:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11871:                                 unless ($ishome) {
11872:                                     my $fetch = "$newdest{$i}/$title";
11873:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11874:                                     $prompttofetch{$fetch} = 1;
11875:                                 }
11876:                             }
11877:                             $LONCAPA::map::resources[$newidx]=
11878:                                 $docstitle.':'.$url.':false:normal:res';
11879:                             push(@LONCAPA::map::order, $newidx);
11880:                             my ($outtext,$errtext)=
11881:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11882:                                                         $docuname.'/'.$folders{$outer}.
11883:                                                         '.'.$containers{$outer},1,1);
11884:                             unless ($errtext) {
11885:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11886:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11887:                                 }
11888:                             }
11889:                         }
11890:                     }
11891:                 }
11892:             } else {
11893:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11894:             }
11895:         }
11896:         for (my $i=1; $i<=$numitems; $i++) {
11897:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11898:             my $path = $env{'form.archive_content_'.$i};
11899:             if ($path =~ /^\Q$pathtocheck\E/) {
11900:                 my ($title) = ($path =~ m{/([^/]+)$});
11901:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11902:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11903:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11904:                         my ($itemidx,$fullpath,$relpath);
11905:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11906:                             my $container = $dirorder{$referrer{$i}}->[-1];
11907:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11908:                                 if ($dirorder{$i}->[$j] eq $container) {
11909:                                     $itemidx = $j;
11910:                                 }
11911:                             }
11912:                         }
11913:                         if ($itemidx eq '') {
11914:                             $itemidx =  0;
11915:                         }
11916:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11917:                             if ($mapinner{$referrer{$i}}) {
11918:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11919:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11920:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11921:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11922:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11923:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11924:                                             if (!-e $fullpath) {
11925:                                                 mkdir($fullpath,0755);
11926:                                             }
11927:                                         }
11928:                                     } else {
11929:                                         last;
11930:                                     }
11931:                                 }
11932:                             }
11933:                         } elsif ($newdest{$referrer{$i}}) {
11934:                             $fullpath = $newdest{$referrer{$i}};
11935:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11936:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11937:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11938:                                     last;
11939:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11940:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11941:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11942:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11943:                                         if (!-e $fullpath) {
11944:                                             mkdir($fullpath,0755);
11945:                                         }
11946:                                     }
11947:                                 } else {
11948:                                     last;
11949:                                 }
11950:                             }
11951:                         }
11952:                         if ($fullpath ne '') {
11953:                             if (-e "$prefix$path") {
11954:                                 system("mv $prefix$path $fullpath/$title");
11955:                             }
11956:                             if (-e "$fullpath/$title") {
11957:                                 my $showpath;
11958:                                 if ($relpath ne '') {
11959:                                     $showpath = "$relpath/$title";
11960:                                 } else {
11961:                                     $showpath = "/$title";
11962:                                 }
11963:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11964:                             }
11965:                             unless ($ishome) {
11966:                                 my $fetch = "$fullpath/$title";
11967:                                 $fetch =~ s/^\Q$prefix$dir\E//;
11968:                                 $prompttofetch{$fetch} = 1;
11969:                             }
11970:                         }
11971:                     }
11972:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11973:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11974:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11975:                 }
11976:             } else {
11977:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11978:             }
11979:         }
11980:         if (keys(%todelete)) {
11981:             foreach my $key (keys(%todelete)) {
11982:                 unlink($key);
11983:             }
11984:         }
11985:         if (keys(%todeletedir)) {
11986:             foreach my $key (keys(%todeletedir)) {
11987:                 rmdir($key);
11988:             }
11989:         }
11990:         foreach my $dir (sort(keys(%is_dir))) {
11991:             if (($pathtocheck ne '') && ($dir ne ''))  {
11992:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11993:             }
11994:         }
11995:         if ($result ne '') {
11996:             $output .= '<ul>'."\n".
11997:                        $result."\n".
11998:                        '</ul>';
11999:         }
12000:         unless ($ishome) {
12001:             my $replicationfail;
12002:             foreach my $item (keys(%prompttofetch)) {
12003:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12004:                 unless ($fetchresult eq 'ok') {
12005:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12006:                 }
12007:             }
12008:             if ($replicationfail) {
12009:                 $output .= '<p class="LC_error">'.
12010:                            &mt('Course home server failed to retrieve:').'<ul>'.
12011:                            $replicationfail.
12012:                            '</ul></p>';
12013:             }
12014:         }
12015:     } else {
12016:         $warning = &mt('No items found in archive.');
12017:     }
12018:     if ($error) {
12019:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12020:                    $error.'</p>'."\n";
12021:     }
12022:     if ($warning) {
12023:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12024:     }
12025:     return $output;
12026: }
12027: 
12028: sub cleanup_empty_dirs {
12029:     my ($path) = @_;
12030:     if (($path ne '') && (-d $path)) {
12031:         if (opendir(my $dirh,$path)) {
12032:             my @dircontents = grep(!/^\./,readdir($dirh));
12033:             my $numitems = 0;
12034:             foreach my $item (@dircontents) {
12035:                 if (-d "$path/$item") {
12036:                     &cleanup_empty_dirs("$path/$item");
12037:                     if (-e "$path/$item") {
12038:                         $numitems ++;
12039:                     }
12040:                 } else {
12041:                     $numitems ++;
12042:                 }
12043:             }
12044:             if ($numitems == 0) {
12045:                 rmdir($path);
12046:             }
12047:             closedir($dirh);
12048:         }
12049:     }
12050:     return;
12051: }
12052: 
12053: =pod
12054: 
12055: =item &get_folder_hierarchy()
12056: 
12057: Provides hierarchy of names of folders/sub-folders containing the current
12058: item,
12059: 
12060: Inputs: 3
12061:      - $navmap - navmaps object
12062: 
12063:      - $map - url for map (either the trigger itself, or map containing
12064:                            the resource, which is the trigger).
12065: 
12066:      - $showitem - 1 => show title for map itself; 0 => do not show.
12067: 
12068: Outputs: 1 @pathitems - array of folder/subfolder names.
12069: 
12070: =cut
12071: 
12072: sub get_folder_hierarchy {
12073:     my ($navmap,$map,$showitem) = @_;
12074:     my @pathitems;
12075:     if (ref($navmap)) {
12076:         my $mapres = $navmap->getResourceByUrl($map);
12077:         if (ref($mapres)) {
12078:             my $pcslist = $mapres->map_hierarchy();
12079:             if ($pcslist ne '') {
12080:                 my @pcs = split(/,/,$pcslist);
12081:                 foreach my $pc (@pcs) {
12082:                     if ($pc == 1) {
12083:                         push(@pathitems,&mt('Main Content'));
12084:                     } else {
12085:                         my $res = $navmap->getByMapPc($pc);
12086:                         if (ref($res)) {
12087:                             my $title = $res->compTitle();
12088:                             $title =~ s/\W+/_/g;
12089:                             if ($title ne '') {
12090:                                 push(@pathitems,$title);
12091:                             }
12092:                         }
12093:                     }
12094:                 }
12095:             }
12096:             if ($showitem) {
12097:                 if ($mapres->{ID} eq '0.0') {
12098:                     push(@pathitems,&mt('Main Content'));
12099:                 } else {
12100:                     my $maptitle = $mapres->compTitle();
12101:                     $maptitle =~ s/\W+/_/g;
12102:                     if ($maptitle ne '') {
12103:                         push(@pathitems,$maptitle);
12104:                     }
12105:                 }
12106:             }
12107:         }
12108:     }
12109:     return @pathitems;
12110: }
12111: 
12112: =pod
12113: 
12114: =item * &get_turnedin_filepath()
12115: 
12116: Determines path in a user's portfolio file for storage of files uploaded
12117: to a specific essayresponse or dropbox item.
12118: 
12119: Inputs: 3 required + 1 optional.
12120: $symb is symb for resource, $uname and $udom are for current user (required).
12121: $caller is optional (can be "submission", if routine is called when storing
12122: an upoaded file when "Submit Answer" button was pressed).
12123: 
12124: Returns array containing $path and $multiresp. 
12125: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12126: than one file upload item.  Callers of routine should append partid as a 
12127: subdirectory to $path in cases where $multiresp is 1.
12128: 
12129: Called by: homework/essayresponse.pm and homework/structuretags.pm
12130: 
12131: =cut
12132: 
12133: sub get_turnedin_filepath {
12134:     my ($symb,$uname,$udom,$caller) = @_;
12135:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12136:     my $turnindir;
12137:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12138:     $turnindir = $userhash{'turnindir'};
12139:     my ($path,$multiresp);
12140:     if ($turnindir eq '') {
12141:         if ($caller eq 'submission') {
12142:             $turnindir = &mt('turned in');
12143:             $turnindir =~ s/\W+/_/g;
12144:             my %newhash = (
12145:                             'turnindir' => $turnindir,
12146:                           );
12147:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12148:         }
12149:     }
12150:     if ($turnindir ne '') {
12151:         $path = '/'.$turnindir.'/';
12152:         my ($multipart,$turnin,@pathitems);
12153:         my $navmap = Apache::lonnavmaps::navmap->new();
12154:         if (defined($navmap)) {
12155:             my $mapres = $navmap->getResourceByUrl($map);
12156:             if (ref($mapres)) {
12157:                 my $pcslist = $mapres->map_hierarchy();
12158:                 if ($pcslist ne '') {
12159:                     foreach my $pc (split(/,/,$pcslist)) {
12160:                         my $res = $navmap->getByMapPc($pc);
12161:                         if (ref($res)) {
12162:                             my $title = $res->compTitle();
12163:                             $title =~ s/\W+/_/g;
12164:                             if ($title ne '') {
12165:                                 if (($pc > 1) && (length($title) > 12)) {
12166:                                     $title = substr($title,0,12);
12167:                                 }
12168:                                 push(@pathitems,$title);
12169:                             }
12170:                         }
12171:                     }
12172:                 }
12173:                 my $maptitle = $mapres->compTitle();
12174:                 $maptitle =~ s/\W+/_/g;
12175:                 if ($maptitle ne '') {
12176:                     if (length($maptitle) > 12) {
12177:                         $maptitle = substr($maptitle,0,12);
12178:                     }
12179:                     push(@pathitems,$maptitle);
12180:                 }
12181:                 unless ($env{'request.state'} eq 'construct') {
12182:                     my $res = $navmap->getBySymb($symb);
12183:                     if (ref($res)) {
12184:                         my $partlist = $res->parts();
12185:                         my $totaluploads = 0;
12186:                         if (ref($partlist) eq 'ARRAY') {
12187:                             foreach my $part (@{$partlist}) {
12188:                                 my @types = $res->responseType($part);
12189:                                 my @ids = $res->responseIds($part);
12190:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12191:                                     if ($types[$i] eq 'essay') {
12192:                                         my $partid = $part.'_'.$ids[$i];
12193:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12194:                                             $totaluploads ++;
12195:                                         }
12196:                                     }
12197:                                 }
12198:                             }
12199:                             if ($totaluploads > 1) {
12200:                                 $multiresp = 1;
12201:                             }
12202:                         }
12203:                     }
12204:                 }
12205:             } else {
12206:                 return;
12207:             }
12208:         } else {
12209:             return;
12210:         }
12211:         my $restitle=&Apache::lonnet::gettitle($symb);
12212:         $restitle =~ s/\W+/_/g;
12213:         if ($restitle eq '') {
12214:             $restitle = ($resurl =~ m{/[^/]+$});
12215:             if ($restitle eq '') {
12216:                 $restitle = time;
12217:             }
12218:         }
12219:         if (length($restitle) > 12) {
12220:             $restitle = substr($restitle,0,12);
12221:         }
12222:         push(@pathitems,$restitle);
12223:         $path .= join('/',@pathitems);
12224:     }
12225:     return ($path,$multiresp);
12226: }
12227: 
12228: =pod
12229: 
12230: =back
12231: 
12232: =head1 CSV Upload/Handling functions
12233: 
12234: =over 4
12235: 
12236: =item * &upfile_store($r)
12237: 
12238: Store uploaded file, $r should be the HTTP Request object,
12239: needs $env{'form.upfile'}
12240: returns $datatoken to be put into hidden field
12241: 
12242: =cut
12243: 
12244: sub upfile_store {
12245:     my $r=shift;
12246:     $env{'form.upfile'}=~s/\r/\n/gs;
12247:     $env{'form.upfile'}=~s/\f/\n/gs;
12248:     $env{'form.upfile'}=~s/\n+/\n/gs;
12249:     $env{'form.upfile'}=~s/\n+$//gs;
12250: 
12251:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12252: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12253:     {
12254:         my $datafile = $r->dir_config('lonDaemons').
12255:                            '/tmp/'.$datatoken.'.tmp';
12256:         if ( open(my $fh,">$datafile") ) {
12257:             print $fh $env{'form.upfile'};
12258:             close($fh);
12259:         }
12260:     }
12261:     return $datatoken;
12262: }
12263: 
12264: =pod
12265: 
12266: =item * &load_tmp_file($r)
12267: 
12268: Load uploaded file from tmp, $r should be the HTTP Request object,
12269: needs $env{'form.datatoken'},
12270: sets $env{'form.upfile'} to the contents of the file
12271: 
12272: =cut
12273: 
12274: sub load_tmp_file {
12275:     my $r=shift;
12276:     my @studentdata=();
12277:     {
12278:         my $studentfile = $r->dir_config('lonDaemons').
12279:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12280:         if ( open(my $fh,"<$studentfile") ) {
12281:             @studentdata=<$fh>;
12282:             close($fh);
12283:         }
12284:     }
12285:     $env{'form.upfile'}=join('',@studentdata);
12286: }
12287: 
12288: =pod
12289: 
12290: =item * &upfile_record_sep()
12291: 
12292: Separate uploaded file into records
12293: returns array of records,
12294: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12295: 
12296: =cut
12297: 
12298: sub upfile_record_sep {
12299:     if ($env{'form.upfiletype'} eq 'xml') {
12300:     } else {
12301: 	my @records;
12302: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12303: 	    if ($line=~/^\s*$/) { next; }
12304: 	    push(@records,$line);
12305: 	}
12306: 	return @records;
12307:     }
12308: }
12309: 
12310: =pod
12311: 
12312: =item * &record_sep($record)
12313: 
12314: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12315: 
12316: =cut
12317: 
12318: sub takeleft {
12319:     my $index=shift;
12320:     return substr('0000'.$index,-4,4);
12321: }
12322: 
12323: sub record_sep {
12324:     my $record=shift;
12325:     my %components=();
12326:     if ($env{'form.upfiletype'} eq 'xml') {
12327:     } elsif ($env{'form.upfiletype'} eq 'space') {
12328:         my $i=0;
12329:         foreach my $field (split(/\s+/,$record)) {
12330:             $field=~s/^(\"|\')//;
12331:             $field=~s/(\"|\')$//;
12332:             $components{&takeleft($i)}=$field;
12333:             $i++;
12334:         }
12335:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12336:         my $i=0;
12337:         foreach my $field (split(/\t/,$record)) {
12338:             $field=~s/^(\"|\')//;
12339:             $field=~s/(\"|\')$//;
12340:             $components{&takeleft($i)}=$field;
12341:             $i++;
12342:         }
12343:     } else {
12344:         my $separator=',';
12345:         if ($env{'form.upfiletype'} eq 'semisv') {
12346:             $separator=';';
12347:         }
12348:         my $i=0;
12349: # the character we are looking for to indicate the end of a quote or a record 
12350:         my $looking_for=$separator;
12351: # do not add the characters to the fields
12352:         my $ignore=0;
12353: # we just encountered a separator (or the beginning of the record)
12354:         my $just_found_separator=1;
12355: # store the field we are working on here
12356:         my $field='';
12357: # work our way through all characters in record
12358:         foreach my $character ($record=~/(.)/g) {
12359:             if ($character eq $looking_for) {
12360:                if ($character ne $separator) {
12361: # Found the end of a quote, again looking for separator
12362:                   $looking_for=$separator;
12363:                   $ignore=1;
12364:                } else {
12365: # Found a separator, store away what we got
12366:                   $components{&takeleft($i)}=$field;
12367: 	          $i++;
12368:                   $just_found_separator=1;
12369:                   $ignore=0;
12370:                   $field='';
12371:                }
12372:                next;
12373:             }
12374: # single or double quotation marks after a separator indicate beginning of a quote
12375: # we are now looking for the end of the quote and need to ignore separators
12376:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12377:                $looking_for=$character;
12378:                next;
12379:             }
12380: # ignore would be true after we reached the end of a quote
12381:             if ($ignore) { next; }
12382:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12383:             $field.=$character;
12384:             $just_found_separator=0; 
12385:         }
12386: # catch the very last entry, since we never encountered the separator
12387:         $components{&takeleft($i)}=$field;
12388:     }
12389:     return %components;
12390: }
12391: 
12392: ######################################################
12393: ######################################################
12394: 
12395: =pod
12396: 
12397: =item * &upfile_select_html()
12398: 
12399: Return HTML code to select a file from the users machine and specify 
12400: the file type.
12401: 
12402: =cut
12403: 
12404: ######################################################
12405: ######################################################
12406: sub upfile_select_html {
12407:     my %Types = (
12408:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12409:                  semisv => &mt('Semicolon separated values'),
12410:                  space => &mt('Space separated'),
12411:                  tab   => &mt('Tabulator separated'),
12412: #                 xml   => &mt('HTML/XML'),
12413:                  );
12414:     my $Str = '<input type="file" name="upfile" size="50" />'.
12415:         '<br />'.&mt('Type').': <select name="upfiletype">';
12416:     foreach my $type (sort(keys(%Types))) {
12417:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12418:     }
12419:     $Str .= "</select>\n";
12420:     return $Str;
12421: }
12422: 
12423: sub get_samples {
12424:     my ($records,$toget) = @_;
12425:     my @samples=({});
12426:     my $got=0;
12427:     foreach my $rec (@$records) {
12428: 	my %temp = &record_sep($rec);
12429: 	if (! grep(/\S/, values(%temp))) { next; }
12430: 	if (%temp) {
12431: 	    $samples[$got]=\%temp;
12432: 	    $got++;
12433: 	    if ($got == $toget) { last; }
12434: 	}
12435:     }
12436:     return \@samples;
12437: }
12438: 
12439: ######################################################
12440: ######################################################
12441: 
12442: =pod
12443: 
12444: =item * &csv_print_samples($r,$records)
12445: 
12446: Prints a table of sample values from each column uploaded $r is an
12447: Apache Request ref, $records is an arrayref from
12448: &Apache::loncommon::upfile_record_sep
12449: 
12450: =cut
12451: 
12452: ######################################################
12453: ######################################################
12454: sub csv_print_samples {
12455:     my ($r,$records) = @_;
12456:     my $samples = &get_samples($records,5);
12457: 
12458:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12459:               &start_data_table_header_row());
12460:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12461:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12462:     $r->print(&end_data_table_header_row());
12463:     foreach my $hash (@$samples) {
12464: 	$r->print(&start_data_table_row());
12465: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12466: 	    $r->print('<td>');
12467: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12468: 	    $r->print('</td>');
12469: 	}
12470: 	$r->print(&end_data_table_row());
12471:     }
12472:     $r->print(&end_data_table().'<br />'."\n");
12473: }
12474: 
12475: ######################################################
12476: ######################################################
12477: 
12478: =pod
12479: 
12480: =item * &csv_print_select_table($r,$records,$d)
12481: 
12482: Prints a table to create associations between values and table columns.
12483: 
12484: $r is an Apache Request ref,
12485: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12486: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12487: 
12488: =cut
12489: 
12490: ######################################################
12491: ######################################################
12492: sub csv_print_select_table {
12493:     my ($r,$records,$d) = @_;
12494:     my $i=0;
12495:     my $samples = &get_samples($records,1);
12496:     $r->print(&mt('Associate columns with student attributes.')."\n".
12497: 	      &start_data_table().&start_data_table_header_row().
12498:               '<th>'.&mt('Attribute').'</th>'.
12499:               '<th>'.&mt('Column').'</th>'.
12500:               &end_data_table_header_row()."\n");
12501:     foreach my $array_ref (@$d) {
12502: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12503: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12504: 
12505: 	$r->print('<td><select name="f'.$i.'"'.
12506: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12507: 	$r->print('<option value="none"></option>');
12508: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12509: 	    $r->print('<option value="'.$sample.'"'.
12510:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12511:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12512: 	}
12513: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12514: 	$i++;
12515:     }
12516:     $r->print(&end_data_table());
12517:     $i--;
12518:     return $i;
12519: }
12520: 
12521: ######################################################
12522: ######################################################
12523: 
12524: =pod
12525: 
12526: =item * &csv_samples_select_table($r,$records,$d)
12527: 
12528: Prints a table of sample values from the upload and can make associate samples to internal names.
12529: 
12530: $r is an Apache Request ref,
12531: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12532: $d is an array of 2 element arrays (internal name, displayed name)
12533: 
12534: =cut
12535: 
12536: ######################################################
12537: ######################################################
12538: sub csv_samples_select_table {
12539:     my ($r,$records,$d) = @_;
12540:     my $i=0;
12541:     #
12542:     my $max_samples = 5;
12543:     my $samples = &get_samples($records,$max_samples);
12544:     $r->print(&start_data_table().
12545:               &start_data_table_header_row().'<th>'.
12546:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12547:               &end_data_table_header_row());
12548: 
12549:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12550: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12551: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12552: 	foreach my $option (@$d) {
12553: 	    my ($value,$display,$defaultcol)=@{ $option };
12554: 	    $r->print('<option value="'.$value.'"'.
12555:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12556:                       $display.'</option>');
12557: 	}
12558: 	$r->print('</select></td><td>');
12559: 	foreach my $line (0..($max_samples-1)) {
12560: 	    if (defined($samples->[$line]{$key})) { 
12561: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12562: 	    }
12563: 	}
12564: 	$r->print('</td>'.&end_data_table_row());
12565: 	$i++;
12566:     }
12567:     $r->print(&end_data_table());
12568:     $i--;
12569:     return($i);
12570: }
12571: 
12572: ######################################################
12573: ######################################################
12574: 
12575: =pod
12576: 
12577: =item * &clean_excel_name($name)
12578: 
12579: Returns a replacement for $name which does not contain any illegal characters.
12580: 
12581: =cut
12582: 
12583: ######################################################
12584: ######################################################
12585: sub clean_excel_name {
12586:     my ($name) = @_;
12587:     $name =~ s/[:\*\?\/\\]//g;
12588:     if (length($name) > 31) {
12589:         $name = substr($name,0,31);
12590:     }
12591:     return $name;
12592: }
12593: 
12594: =pod
12595: 
12596: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12597: 
12598: Returns either 1 or undef
12599: 
12600: 1 if the part is to be hidden, undef if it is to be shown
12601: 
12602: Arguments are:
12603: 
12604: $id the id of the part to be checked
12605: $symb, optional the symb of the resource to check
12606: $udom, optional the domain of the user to check for
12607: $uname, optional the username of the user to check for
12608: 
12609: =cut
12610: 
12611: sub check_if_partid_hidden {
12612:     my ($id,$symb,$udom,$uname) = @_;
12613:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12614: 					 $symb,$udom,$uname);
12615:     my $truth=1;
12616:     #if the string starts with !, then the list is the list to show not hide
12617:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12618:     my @hiddenlist=split(/,/,$hiddenparts);
12619:     foreach my $checkid (@hiddenlist) {
12620: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12621:     }
12622:     return !$truth;
12623: }
12624: 
12625: 
12626: ############################################################
12627: ############################################################
12628: 
12629: =pod
12630: 
12631: =back 
12632: 
12633: =head1 cgi-bin script and graphing routines
12634: 
12635: =over 4
12636: 
12637: =item * &get_cgi_id()
12638: 
12639: Inputs: none
12640: 
12641: Returns an id which can be used to pass environment variables
12642: to various cgi-bin scripts.  These environment variables will
12643: be removed from the users environment after a given time by
12644: the routine &Apache::lonnet::transfer_profile_to_env.
12645: 
12646: =cut
12647: 
12648: ############################################################
12649: ############################################################
12650: my $uniq=0;
12651: sub get_cgi_id {
12652:     $uniq=($uniq+1)%100000;
12653:     return (time.'_'.$$.'_'.$uniq);
12654: }
12655: 
12656: ############################################################
12657: ############################################################
12658: 
12659: =pod
12660: 
12661: =item * &DrawBarGraph()
12662: 
12663: Facilitates the plotting of data in a (stacked) bar graph.
12664: Puts plot definition data into the users environment in order for 
12665: graph.png to plot it.  Returns an <img> tag for the plot.
12666: The bars on the plot are labeled '1','2',...,'n'.
12667: 
12668: Inputs:
12669: 
12670: =over 4
12671: 
12672: =item $Title: string, the title of the plot
12673: 
12674: =item $xlabel: string, text describing the X-axis of the plot
12675: 
12676: =item $ylabel: string, text describing the Y-axis of the plot
12677: 
12678: =item $Max: scalar, the maximum Y value to use in the plot
12679: If $Max is < any data point, the graph will not be rendered.
12680: 
12681: =item $colors: array ref holding the colors to be used for the data sets when
12682: they are plotted.  If undefined, default values will be used.
12683: 
12684: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12685: 
12686: =item @Values: An array of array references.  Each array reference holds data
12687: to be plotted in a stacked bar chart.
12688: 
12689: =item If the final element of @Values is a hash reference the key/value
12690: pairs will be added to the graph definition.
12691: 
12692: =back
12693: 
12694: Returns:
12695: 
12696: An <img> tag which references graph.png and the appropriate identifying
12697: information for the plot.
12698: 
12699: =cut
12700: 
12701: ############################################################
12702: ############################################################
12703: sub DrawBarGraph {
12704:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12705:     #
12706:     if (! defined($colors)) {
12707:         $colors = ['#33ff00', 
12708:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12709:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12710:                   ]; 
12711:     }
12712:     my $extra_settings = {};
12713:     if (ref($Values[-1]) eq 'HASH') {
12714:         $extra_settings = pop(@Values);
12715:     }
12716:     #
12717:     my $identifier = &get_cgi_id();
12718:     my $id = 'cgi.'.$identifier;        
12719:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12720:         return '';
12721:     }
12722:     #
12723:     my @Labels;
12724:     if (defined($labels)) {
12725:         @Labels = @$labels;
12726:     } else {
12727:         for (my $i=0;$i<@{$Values[0]};$i++) {
12728:             push (@Labels,$i+1);
12729:         }
12730:     }
12731:     #
12732:     my $NumBars = scalar(@{$Values[0]});
12733:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12734:     my %ValuesHash;
12735:     my $NumSets=1;
12736:     foreach my $array (@Values) {
12737:         next if (! ref($array));
12738:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12739:             join(',',@$array);
12740:     }
12741:     #
12742:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12743:     if ($NumBars < 3) {
12744:         $width = 120+$NumBars*32;
12745:         $xskip = 1;
12746:         $bar_width = 30;
12747:     } elsif ($NumBars < 5) {
12748:         $width = 120+$NumBars*20;
12749:         $xskip = 1;
12750:         $bar_width = 20;
12751:     } elsif ($NumBars < 10) {
12752:         $width = 120+$NumBars*15;
12753:         $xskip = 1;
12754:         $bar_width = 15;
12755:     } elsif ($NumBars <= 25) {
12756:         $width = 120+$NumBars*11;
12757:         $xskip = 5;
12758:         $bar_width = 8;
12759:     } elsif ($NumBars <= 50) {
12760:         $width = 120+$NumBars*8;
12761:         $xskip = 5;
12762:         $bar_width = 4;
12763:     } else {
12764:         $width = 120+$NumBars*8;
12765:         $xskip = 5;
12766:         $bar_width = 4;
12767:     }
12768:     #
12769:     $Max = 1 if ($Max < 1);
12770:     if ( int($Max) < $Max ) {
12771:         $Max++;
12772:         $Max = int($Max);
12773:     }
12774:     $Title  = '' if (! defined($Title));
12775:     $xlabel = '' if (! defined($xlabel));
12776:     $ylabel = '' if (! defined($ylabel));
12777:     $ValuesHash{$id.'.title'}    = &escape($Title);
12778:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12779:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12780:     $ValuesHash{$id.'.y_max_value'} = $Max;
12781:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12782:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12783:     $ValuesHash{$id.'.PlotType'} = 'bar';
12784:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12785:     $ValuesHash{$id.'.height'}   = $height;
12786:     $ValuesHash{$id.'.width'}    = $width;
12787:     $ValuesHash{$id.'.xskip'}    = $xskip;
12788:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12789:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12790:     #
12791:     # Deal with other parameters
12792:     while (my ($key,$value) = each(%$extra_settings)) {
12793:         $ValuesHash{$id.'.'.$key} = $value;
12794:     }
12795:     #
12796:     &Apache::lonnet::appenv(\%ValuesHash);
12797:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12798: }
12799: 
12800: ############################################################
12801: ############################################################
12802: 
12803: =pod
12804: 
12805: =item * &DrawXYGraph()
12806: 
12807: Facilitates the plotting of data in an XY graph.
12808: Puts plot definition data into the users environment in order for 
12809: graph.png to plot it.  Returns an <img> tag for the plot.
12810: 
12811: Inputs:
12812: 
12813: =over 4
12814: 
12815: =item $Title: string, the title of the plot
12816: 
12817: =item $xlabel: string, text describing the X-axis of the plot
12818: 
12819: =item $ylabel: string, text describing the Y-axis of the plot
12820: 
12821: =item $Max: scalar, the maximum Y value to use in the plot
12822: If $Max is < any data point, the graph will not be rendered.
12823: 
12824: =item $colors: Array ref containing the hex color codes for the data to be 
12825: plotted in.  If undefined, default values will be used.
12826: 
12827: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12828: 
12829: =item $Ydata: Array ref containing Array refs.  
12830: Each of the contained arrays will be plotted as a separate curve.
12831: 
12832: =item %Values: hash indicating or overriding any default values which are 
12833: passed to graph.png.  
12834: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12835: 
12836: =back
12837: 
12838: Returns:
12839: 
12840: An <img> tag which references graph.png and the appropriate identifying
12841: information for the plot.
12842: 
12843: =cut
12844: 
12845: ############################################################
12846: ############################################################
12847: sub DrawXYGraph {
12848:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12849:     #
12850:     # Create the identifier for the graph
12851:     my $identifier = &get_cgi_id();
12852:     my $id = 'cgi.'.$identifier;
12853:     #
12854:     $Title  = '' if (! defined($Title));
12855:     $xlabel = '' if (! defined($xlabel));
12856:     $ylabel = '' if (! defined($ylabel));
12857:     my %ValuesHash = 
12858:         (
12859:          $id.'.title'  => &escape($Title),
12860:          $id.'.xlabel' => &escape($xlabel),
12861:          $id.'.ylabel' => &escape($ylabel),
12862:          $id.'.y_max_value'=> $Max,
12863:          $id.'.labels'     => join(',',@$Xlabels),
12864:          $id.'.PlotType'   => 'XY',
12865:          );
12866:     #
12867:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12868:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12869:     }
12870:     #
12871:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12872:         return '';
12873:     }
12874:     my $NumSets=1;
12875:     foreach my $array (@{$Ydata}){
12876:         next if (! ref($array));
12877:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12878:     }
12879:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12880:     #
12881:     # Deal with other parameters
12882:     while (my ($key,$value) = each(%Values)) {
12883:         $ValuesHash{$id.'.'.$key} = $value;
12884:     }
12885:     #
12886:     &Apache::lonnet::appenv(\%ValuesHash);
12887:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12888: }
12889: 
12890: ############################################################
12891: ############################################################
12892: 
12893: =pod
12894: 
12895: =item * &DrawXYYGraph()
12896: 
12897: Facilitates the plotting of data in an XY graph with two Y axes.
12898: Puts plot definition data into the users environment in order for 
12899: graph.png to plot it.  Returns an <img> tag for the plot.
12900: 
12901: Inputs:
12902: 
12903: =over 4
12904: 
12905: =item $Title: string, the title of the plot
12906: 
12907: =item $xlabel: string, text describing the X-axis of the plot
12908: 
12909: =item $ylabel: string, text describing the Y-axis of the plot
12910: 
12911: =item $colors: Array ref containing the hex color codes for the data to be 
12912: plotted in.  If undefined, default values will be used.
12913: 
12914: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12915: 
12916: =item $Ydata1: The first data set
12917: 
12918: =item $Min1: The minimum value of the left Y-axis
12919: 
12920: =item $Max1: The maximum value of the left Y-axis
12921: 
12922: =item $Ydata2: The second data set
12923: 
12924: =item $Min2: The minimum value of the right Y-axis
12925: 
12926: =item $Max2: The maximum value of the left Y-axis
12927: 
12928: =item %Values: hash indicating or overriding any default values which are 
12929: passed to graph.png.  
12930: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12931: 
12932: =back
12933: 
12934: Returns:
12935: 
12936: An <img> tag which references graph.png and the appropriate identifying
12937: information for the plot.
12938: 
12939: =cut
12940: 
12941: ############################################################
12942: ############################################################
12943: sub DrawXYYGraph {
12944:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12945:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12946:     #
12947:     # Create the identifier for the graph
12948:     my $identifier = &get_cgi_id();
12949:     my $id = 'cgi.'.$identifier;
12950:     #
12951:     $Title  = '' if (! defined($Title));
12952:     $xlabel = '' if (! defined($xlabel));
12953:     $ylabel = '' if (! defined($ylabel));
12954:     my %ValuesHash = 
12955:         (
12956:          $id.'.title'  => &escape($Title),
12957:          $id.'.xlabel' => &escape($xlabel),
12958:          $id.'.ylabel' => &escape($ylabel),
12959:          $id.'.labels' => join(',',@$Xlabels),
12960:          $id.'.PlotType' => 'XY',
12961:          $id.'.NumSets' => 2,
12962:          $id.'.two_axes' => 1,
12963:          $id.'.y1_max_value' => $Max1,
12964:          $id.'.y1_min_value' => $Min1,
12965:          $id.'.y2_max_value' => $Max2,
12966:          $id.'.y2_min_value' => $Min2,
12967:          );
12968:     #
12969:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12970:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12971:     }
12972:     #
12973:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12974:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12975:         return '';
12976:     }
12977:     my $NumSets=1;
12978:     foreach my $array ($Ydata1,$Ydata2){
12979:         next if (! ref($array));
12980:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12981:     }
12982:     #
12983:     # Deal with other parameters
12984:     while (my ($key,$value) = each(%Values)) {
12985:         $ValuesHash{$id.'.'.$key} = $value;
12986:     }
12987:     #
12988:     &Apache::lonnet::appenv(\%ValuesHash);
12989:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12990: }
12991: 
12992: ############################################################
12993: ############################################################
12994: 
12995: =pod
12996: 
12997: =back 
12998: 
12999: =head1 Statistics helper routines?  
13000: 
13001: Bad place for them but what the hell.
13002: 
13003: =over 4
13004: 
13005: =item * &chartlink()
13006: 
13007: Returns a link to the chart for a specific student.  
13008: 
13009: Inputs:
13010: 
13011: =over 4
13012: 
13013: =item $linktext: The text of the link
13014: 
13015: =item $sname: The students username
13016: 
13017: =item $sdomain: The students domain
13018: 
13019: =back
13020: 
13021: =back
13022: 
13023: =cut
13024: 
13025: ############################################################
13026: ############################################################
13027: sub chartlink {
13028:     my ($linktext, $sname, $sdomain) = @_;
13029:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13030:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13031:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13032:        '">'.$linktext.'</a>';
13033: }
13034: 
13035: #######################################################
13036: #######################################################
13037: 
13038: =pod
13039: 
13040: =head1 Course Environment Routines
13041: 
13042: =over 4
13043: 
13044: =item * &restore_course_settings()
13045: 
13046: =item * &store_course_settings()
13047: 
13048: Restores/Store indicated form parameters from the course environment.
13049: Will not overwrite existing values of the form parameters.
13050: 
13051: Inputs: 
13052: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13053: 
13054: a hash ref describing the data to be stored.  For example:
13055:    
13056: %Save_Parameters = ('Status' => 'scalar',
13057:     'chartoutputmode' => 'scalar',
13058:     'chartoutputdata' => 'scalar',
13059:     'Section' => 'array',
13060:     'Group' => 'array',
13061:     'StudentData' => 'array',
13062:     'Maps' => 'array');
13063: 
13064: Returns: both routines return nothing
13065: 
13066: =back
13067: 
13068: =cut
13069: 
13070: #######################################################
13071: #######################################################
13072: sub store_course_settings {
13073:     return &store_settings($env{'request.course.id'},@_);
13074: }
13075: 
13076: sub store_settings {
13077:     # save to the environment
13078:     # appenv the same items, just to be safe
13079:     my $udom  = $env{'user.domain'};
13080:     my $uname = $env{'user.name'};
13081:     my ($context,$prefix,$Settings) = @_;
13082:     my %SaveHash;
13083:     my %AppHash;
13084:     while (my ($setting,$type) = each(%$Settings)) {
13085:         my $basename = join('.','internal',$context,$prefix,$setting);
13086:         my $envname = 'environment.'.$basename;
13087:         if (exists($env{'form.'.$setting})) {
13088:             # Save this value away
13089:             if ($type eq 'scalar' &&
13090:                 (! exists($env{$envname}) || 
13091:                  $env{$envname} ne $env{'form.'.$setting})) {
13092:                 $SaveHash{$basename} = $env{'form.'.$setting};
13093:                 $AppHash{$envname}   = $env{'form.'.$setting};
13094:             } elsif ($type eq 'array') {
13095:                 my $stored_form;
13096:                 if (ref($env{'form.'.$setting})) {
13097:                     $stored_form = join(',',
13098:                                         map {
13099:                                             &escape($_);
13100:                                         } sort(@{$env{'form.'.$setting}}));
13101:                 } else {
13102:                     $stored_form = 
13103:                         &escape($env{'form.'.$setting});
13104:                 }
13105:                 # Determine if the array contents are the same.
13106:                 if ($stored_form ne $env{$envname}) {
13107:                     $SaveHash{$basename} = $stored_form;
13108:                     $AppHash{$envname}   = $stored_form;
13109:                 }
13110:             }
13111:         }
13112:     }
13113:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13114:                                           $udom,$uname);
13115:     if ($put_result !~ /^(ok|delayed)/) {
13116:         &Apache::lonnet::logthis('unable to save form parameters, '.
13117:                                  'got error:'.$put_result);
13118:     }
13119:     # Make sure these settings stick around in this session, too
13120:     &Apache::lonnet::appenv(\%AppHash);
13121:     return;
13122: }
13123: 
13124: sub restore_course_settings {
13125:     return &restore_settings($env{'request.course.id'},@_);
13126: }
13127: 
13128: sub restore_settings {
13129:     my ($context,$prefix,$Settings) = @_;
13130:     while (my ($setting,$type) = each(%$Settings)) {
13131:         next if (exists($env{'form.'.$setting}));
13132:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13133:             '.'.$setting;
13134:         if (exists($env{$envname})) {
13135:             if ($type eq 'scalar') {
13136:                 $env{'form.'.$setting} = $env{$envname};
13137:             } elsif ($type eq 'array') {
13138:                 $env{'form.'.$setting} = [ 
13139:                                            map { 
13140:                                                &unescape($_); 
13141:                                            } split(',',$env{$envname})
13142:                                            ];
13143:             }
13144:         }
13145:     }
13146: }
13147: 
13148: #######################################################
13149: #######################################################
13150: 
13151: =pod
13152: 
13153: =head1 Domain E-mail Routines  
13154: 
13155: =over 4
13156: 
13157: =item * &build_recipient_list()
13158: 
13159: Build recipient lists for following types of e-mail:
13160: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13161: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13162: module change checking, student/employee ID conflict checks, as
13163: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13164: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13165: 
13166: Inputs:
13167: defmail (scalar - email address of default recipient),
13168: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13169: requestsmail, updatesmail, or idconflictsmail).
13170: 
13171: defdom (domain for which to retrieve configuration settings),
13172: 
13173: origmail (scalar - email address of recipient from loncapa.conf,
13174: i.e., predates configuration by DC via domainprefs.pm
13175: 
13176: Returns: comma separated list of addresses to which to send e-mail.
13177: 
13178: =back
13179: 
13180: =cut
13181: 
13182: ############################################################
13183: ############################################################
13184: sub build_recipient_list {
13185:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13186:     my @recipients;
13187:     my $otheremails;
13188:     my %domconfig =
13189:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13190:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13191:         if (exists($domconfig{'contacts'}{$mailing})) {
13192:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13193:                 my @contacts = ('adminemail','supportemail');
13194:                 foreach my $item (@contacts) {
13195:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13196:                         my $addr = $domconfig{'contacts'}{$item}; 
13197:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13198:                             push(@recipients,$addr);
13199:                         }
13200:                     }
13201:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13202:                 }
13203:             }
13204:         } elsif ($origmail ne '') {
13205:             push(@recipients,$origmail);
13206:         }
13207:     } elsif ($origmail ne '') {
13208:         push(@recipients,$origmail);
13209:     }
13210:     if (defined($defmail)) {
13211:         if ($defmail ne '') {
13212:             push(@recipients,$defmail);
13213:         }
13214:     }
13215:     if ($otheremails) {
13216:         my @others;
13217:         if ($otheremails =~ /,/) {
13218:             @others = split(/,/,$otheremails);
13219:         } else {
13220:             push(@others,$otheremails);
13221:         }
13222:         foreach my $addr (@others) {
13223:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13224:                 push(@recipients,$addr);
13225:             }
13226:         }
13227:     }
13228:     my $recipientlist = join(',',@recipients); 
13229:     return $recipientlist;
13230: }
13231: 
13232: ############################################################
13233: ############################################################
13234: 
13235: =pod
13236: 
13237: =head1 Course Catalog Routines
13238: 
13239: =over 4
13240: 
13241: =item * &gather_categories()
13242: 
13243: Converts category definitions - keys of categories hash stored in  
13244: coursecategories in configuration.db on the primary library server in a 
13245: domain - to an array.  Also generates javascript and idx hash used to 
13246: generate Domain Coordinator interface for editing Course Categories.
13247: 
13248: Inputs:
13249: 
13250: categories (reference to hash of category definitions).
13251: 
13252: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13253:       categories and subcategories).
13254: 
13255: idx (reference to hash of counters used in Domain Coordinator interface for 
13256:       editing Course Categories).
13257: 
13258: jsarray (reference to array of categories used to create Javascript arrays for
13259:          Domain Coordinator interface for editing Course Categories).
13260: 
13261: Returns: nothing
13262: 
13263: Side effects: populates cats, idx and jsarray. 
13264: 
13265: =cut
13266: 
13267: sub gather_categories {
13268:     my ($categories,$cats,$idx,$jsarray) = @_;
13269:     my %counters;
13270:     my $num = 0;
13271:     foreach my $item (keys(%{$categories})) {
13272:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13273:         if ($container eq '' && $depth == 0) {
13274:             $cats->[$depth][$categories->{$item}] = $cat;
13275:         } else {
13276:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13277:         }
13278:         my ($escitem,$tail) = split(/:/,$item,2);
13279:         if ($counters{$tail} eq '') {
13280:             $counters{$tail} = $num;
13281:             $num ++;
13282:         }
13283:         if (ref($idx) eq 'HASH') {
13284:             $idx->{$item} = $counters{$tail};
13285:         }
13286:         if (ref($jsarray) eq 'ARRAY') {
13287:             push(@{$jsarray->[$counters{$tail}]},$item);
13288:         }
13289:     }
13290:     return;
13291: }
13292: 
13293: =pod
13294: 
13295: =item * &extract_categories()
13296: 
13297: Used to generate breadcrumb trails for course categories.
13298: 
13299: Inputs:
13300: 
13301: categories (reference to hash of category definitions).
13302: 
13303: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13304:       categories and subcategories).
13305: 
13306: trails (reference to array of breacrumb trails for each category).
13307: 
13308: allitems (reference to hash - key is category key 
13309:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13310: 
13311: idx (reference to hash of counters used in Domain Coordinator interface for
13312:       editing Course Categories).
13313: 
13314: jsarray (reference to array of categories used to create Javascript arrays for
13315:          Domain Coordinator interface for editing Course Categories).
13316: 
13317: subcats (reference to hash of arrays containing all subcategories within each 
13318:          category, -recursive)
13319: 
13320: Returns: nothing
13321: 
13322: Side effects: populates trails and allitems hash references.
13323: 
13324: =cut
13325: 
13326: sub extract_categories {
13327:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13328:     if (ref($categories) eq 'HASH') {
13329:         &gather_categories($categories,$cats,$idx,$jsarray);
13330:         if (ref($cats->[0]) eq 'ARRAY') {
13331:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13332:                 my $name = $cats->[0][$i];
13333:                 my $item = &escape($name).'::0';
13334:                 my $trailstr;
13335:                 if ($name eq 'instcode') {
13336:                     $trailstr = &mt('Official courses (with institutional codes)');
13337:                 } elsif ($name eq 'communities') {
13338:                     $trailstr = &mt('Communities');
13339:                 } else {
13340:                     $trailstr = $name;
13341:                 }
13342:                 if ($allitems->{$item} eq '') {
13343:                     push(@{$trails},$trailstr);
13344:                     $allitems->{$item} = scalar(@{$trails})-1;
13345:                 }
13346:                 my @parents = ($name);
13347:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13348:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13349:                         my $category = $cats->[1]{$name}[$j];
13350:                         if (ref($subcats) eq 'HASH') {
13351:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13352:                         }
13353:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13354:                     }
13355:                 } else {
13356:                     if (ref($subcats) eq 'HASH') {
13357:                         $subcats->{$item} = [];
13358:                     }
13359:                 }
13360:             }
13361:         }
13362:     }
13363:     return;
13364: }
13365: 
13366: =pod
13367: 
13368: =item *&recurse_categories()
13369: 
13370: Recursively used to generate breadcrumb trails for course categories.
13371: 
13372: Inputs:
13373: 
13374: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13375:       categories and subcategories).
13376: 
13377: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13378: 
13379: category (current course category, for which breadcrumb trail is being generated).
13380: 
13381: trails (reference to array of breadcrumb trails for each category).
13382: 
13383: allitems (reference to hash - key is category key
13384:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13385: 
13386: parents (array containing containers directories for current category, 
13387:          back to top level). 
13388: 
13389: Returns: nothing
13390: 
13391: Side effects: populates trails and allitems hash references
13392: 
13393: =cut
13394: 
13395: sub recurse_categories {
13396:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13397:     my $shallower = $depth - 1;
13398:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13399:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13400:             my $name = $cats->[$depth]{$category}[$k];
13401:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13402:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13403:             if ($allitems->{$item} eq '') {
13404:                 push(@{$trails},$trailstr);
13405:                 $allitems->{$item} = scalar(@{$trails})-1;
13406:             }
13407:             my $deeper = $depth+1;
13408:             push(@{$parents},$category);
13409:             if (ref($subcats) eq 'HASH') {
13410:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13411:                 for (my $j=@{$parents}; $j>=0; $j--) {
13412:                     my $higher;
13413:                     if ($j > 0) {
13414:                         $higher = &escape($parents->[$j]).':'.
13415:                                   &escape($parents->[$j-1]).':'.$j;
13416:                     } else {
13417:                         $higher = &escape($parents->[$j]).'::'.$j;
13418:                     }
13419:                     push(@{$subcats->{$higher}},$subcat);
13420:                 }
13421:             }
13422:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13423:                                 $subcats);
13424:             pop(@{$parents});
13425:         }
13426:     } else {
13427:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13428:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13429:         if ($allitems->{$item} eq '') {
13430:             push(@{$trails},$trailstr);
13431:             $allitems->{$item} = scalar(@{$trails})-1;
13432:         }
13433:     }
13434:     return;
13435: }
13436: 
13437: =pod
13438: 
13439: =item *&assign_categories_table()
13440: 
13441: Create a datatable for display of hierarchical categories in a domain,
13442: with checkboxes to allow a course to be categorized. 
13443: 
13444: Inputs:
13445: 
13446: cathash - reference to hash of categories defined for the domain (from
13447:           configuration.db)
13448: 
13449: currcat - scalar with an & separated list of categories assigned to a course. 
13450: 
13451: type    - scalar contains course type (Course or Community).
13452: 
13453: Returns: $output (markup to be displayed) 
13454: 
13455: =cut
13456: 
13457: sub assign_categories_table {
13458:     my ($cathash,$currcat,$type) = @_;
13459:     my $output;
13460:     if (ref($cathash) eq 'HASH') {
13461:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13462:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13463:         $maxdepth = scalar(@cats);
13464:         if (@cats > 0) {
13465:             my $itemcount = 0;
13466:             if (ref($cats[0]) eq 'ARRAY') {
13467:                 my @currcategories;
13468:                 if ($currcat ne '') {
13469:                     @currcategories = split('&',$currcat);
13470:                 }
13471:                 my $table;
13472:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13473:                     my $parent = $cats[0][$i];
13474:                     next if ($parent eq 'instcode');
13475:                     if ($type eq 'Community') {
13476:                         next unless ($parent eq 'communities');
13477:                     } else {
13478:                         next if ($parent eq 'communities');
13479:                     }
13480:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13481:                     my $item = &escape($parent).'::0';
13482:                     my $checked = '';
13483:                     if (@currcategories > 0) {
13484:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13485:                             $checked = ' checked="checked"';
13486:                         }
13487:                     }
13488:                     my $parent_title = $parent;
13489:                     if ($parent eq 'communities') {
13490:                         $parent_title = &mt('Communities');
13491:                     }
13492:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13493:                               '<input type="checkbox" name="usecategory" value="'.
13494:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13495:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13496:                     my $depth = 1;
13497:                     push(@path,$parent);
13498:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13499:                     pop(@path);
13500:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13501:                     $itemcount ++;
13502:                 }
13503:                 if ($itemcount) {
13504:                     $output = &Apache::loncommon::start_data_table().
13505:                               $table.
13506:                               &Apache::loncommon::end_data_table();
13507:                 }
13508:             }
13509:         }
13510:     }
13511:     return $output;
13512: }
13513: 
13514: =pod
13515: 
13516: =item *&assign_category_rows()
13517: 
13518: Create a datatable row for display of nested categories in a domain,
13519: with checkboxes to allow a course to be categorized,called recursively.
13520: 
13521: Inputs:
13522: 
13523: itemcount - track row number for alternating colors
13524: 
13525: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13526:       categories and subcategories.
13527: 
13528: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13529: 
13530: parent - parent of current category item
13531: 
13532: path - Array containing all categories back up through the hierarchy from the
13533:        current category to the top level.
13534: 
13535: currcategories - reference to array of current categories assigned to the course
13536: 
13537: Returns: $output (markup to be displayed).
13538: 
13539: =cut
13540: 
13541: sub assign_category_rows {
13542:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13543:     my ($text,$name,$item,$chgstr);
13544:     if (ref($cats) eq 'ARRAY') {
13545:         my $maxdepth = scalar(@{$cats});
13546:         if (ref($cats->[$depth]) eq 'HASH') {
13547:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13548:                 my $numchildren = @{$cats->[$depth]{$parent}};
13549:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13550:                 $text .= '<td><table class="LC_data_table">';
13551:                 for (my $j=0; $j<$numchildren; $j++) {
13552:                     $name = $cats->[$depth]{$parent}[$j];
13553:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13554:                     my $deeper = $depth+1;
13555:                     my $checked = '';
13556:                     if (ref($currcategories) eq 'ARRAY') {
13557:                         if (@{$currcategories} > 0) {
13558:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13559:                                 $checked = ' checked="checked"';
13560:                             }
13561:                         }
13562:                     }
13563:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13564:                              '<input type="checkbox" name="usecategory" value="'.
13565:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13566:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13567:                              '</td><td>';
13568:                     if (ref($path) eq 'ARRAY') {
13569:                         push(@{$path},$name);
13570:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13571:                         pop(@{$path});
13572:                     }
13573:                     $text .= '</td></tr>';
13574:                 }
13575:                 $text .= '</table></td>';
13576:             }
13577:         }
13578:     }
13579:     return $text;
13580: }
13581: 
13582: ############################################################
13583: ############################################################
13584: 
13585: 
13586: sub commit_customrole {
13587:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13588:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13589:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13590:                          ($end?', ending '.localtime($end):'').': <b>'.
13591:               &Apache::lonnet::assigncustomrole(
13592:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13593:                  '</b><br />';
13594:     return $output;
13595: }
13596: 
13597: sub commit_standardrole {
13598:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13599:     my ($output,$logmsg,$linefeed);
13600:     if ($context eq 'auto') {
13601:         $linefeed = "\n";
13602:     } else {
13603:         $linefeed = "<br />\n";
13604:     }  
13605:     if ($three eq 'st') {
13606:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13607:                                          $one,$two,$sec,$context,$credits);
13608:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13609:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13610:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13611:         } else {
13612:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13613:                ($start?', '.&mt('starting').' '.localtime($start):'').
13614:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13615:             if ($context eq 'auto') {
13616:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13617:             } else {
13618:                $output .= '<b>'.$result.'</b>'.$linefeed.
13619:                &mt('Add to classlist').': <b>ok</b>';
13620:             }
13621:             $output .= $linefeed;
13622:         }
13623:     } else {
13624:         $output = &mt('Assigning').' '.$three.' in '.$url.
13625:                ($start?', '.&mt('starting').' '.localtime($start):'').
13626:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13627:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13628:         if ($context eq 'auto') {
13629:             $output .= $result.$linefeed;
13630:         } else {
13631:             $output .= '<b>'.$result.'</b>'.$linefeed;
13632:         }
13633:     }
13634:     return $output;
13635: }
13636: 
13637: sub commit_studentrole {
13638:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13639:         $credits) = @_;
13640:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13641:     if ($context eq 'auto') {
13642:         $linefeed = "\n";
13643:     } else {
13644:         $linefeed = '<br />'."\n";
13645:     }
13646:     if (defined($one) && defined($two)) {
13647:         my $cid=$one.'_'.$two;
13648:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13649:         my $secchange = 0;
13650:         my $expire_role_result;
13651:         my $modify_section_result;
13652:         if ($oldsec ne '-1') { 
13653:             if ($oldsec ne $sec) {
13654:                 $secchange = 1;
13655:                 my $now = time;
13656:                 my $uurl='/'.$cid;
13657:                 $uurl=~s/\_/\//g;
13658:                 if ($oldsec) {
13659:                     $uurl.='/'.$oldsec;
13660:                 }
13661:                 $oldsecurl = $uurl;
13662:                 $expire_role_result = 
13663:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13664:                 if ($env{'request.course.sec'} ne '') { 
13665:                     if ($expire_role_result eq 'refused') {
13666:                         my @roles = ('st');
13667:                         my @statuses = ('previous');
13668:                         my @roledoms = ($one);
13669:                         my $withsec = 1;
13670:                         my %roleshash = 
13671:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13672:                                               \@statuses,\@roles,\@roledoms,$withsec);
13673:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13674:                             my ($oldstart,$oldend) = 
13675:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13676:                             if ($oldend > 0 && $oldend <= $now) {
13677:                                 $expire_role_result = 'ok';
13678:                             }
13679:                         }
13680:                     }
13681:                 }
13682:                 $result = $expire_role_result;
13683:             }
13684:         }
13685:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13686:             $modify_section_result = 
13687:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13688:                                                            undef,undef,undef,$sec,
13689:                                                            $end,$start,'','',$cid,
13690:                                                            '',$context,$credits);
13691:             if ($modify_section_result =~ /^ok/) {
13692:                 if ($secchange == 1) {
13693:                     if ($sec eq '') {
13694:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13695:                     } else {
13696:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13697:                     }
13698:                 } elsif ($oldsec eq '-1') {
13699:                     if ($sec eq '') {
13700:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13701:                     } else {
13702:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13703:                     }
13704:                 } else {
13705:                     if ($sec eq '') {
13706:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13707:                     } else {
13708:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13709:                     }
13710:                 }
13711:             } else {
13712:                 if ($secchange) {       
13713:                     $$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;
13714:                 } else {
13715:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13716:                 }
13717:             }
13718:             $result = $modify_section_result;
13719:         } elsif ($secchange == 1) {
13720:             if ($oldsec eq '') {
13721:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13722:             } else {
13723:                 $$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;
13724:             }
13725:             if ($expire_role_result eq 'refused') {
13726:                 my $newsecurl = '/'.$cid;
13727:                 $newsecurl =~ s/\_/\//g;
13728:                 if ($sec ne '') {
13729:                     $newsecurl.='/'.$sec;
13730:                 }
13731:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13732:                     if ($sec eq '') {
13733:                         $$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;
13734:                     } else {
13735:                         $$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;
13736:                     }
13737:                 }
13738:             }
13739:         }
13740:     } else {
13741:         $$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;
13742:         $result = "error: incomplete course id\n";
13743:     }
13744:     return $result;
13745: }
13746: 
13747: sub show_role_extent {
13748:     my ($scope,$context,$role) = @_;
13749:     $scope =~ s{^/}{};
13750:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13751:     push(@courseroles,'co');
13752:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13753:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13754:         $scope =~ s{/}{_};
13755:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13756:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13757:         my ($audom,$auname) = split(/\//,$scope);
13758:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13759:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13760:     } else {
13761:         $scope =~ s{/$}{};
13762:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13763:                    &Apache::lonnet::domain($scope,'description').'</span>');
13764:     }
13765: }
13766: 
13767: ############################################################
13768: ############################################################
13769: 
13770: sub check_clone {
13771:     my ($args,$linefeed) = @_;
13772:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13773:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13774:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13775:     my $clonemsg;
13776:     my $can_clone = 0;
13777:     my $lctype = lc($args->{'crstype'});
13778:     if ($lctype ne 'community') {
13779:         $lctype = 'course';
13780:     }
13781:     if ($clonehome eq 'no_host') {
13782:         if ($args->{'crstype'} eq 'Community') {
13783:             $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'});
13784:         } else {
13785:             $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'});
13786:         }     
13787:     } else {
13788: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13789:         if ($args->{'crstype'} eq 'Community') {
13790:             if ($clonedesc{'type'} ne 'Community') {
13791:                  $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'});
13792:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13793:             }
13794:         }
13795: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13796:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13797: 	    $can_clone = 1;
13798: 	} else {
13799: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13800: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13801: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13802:             if (grep(/^\*$/,@cloners)) {
13803:                 $can_clone = 1;
13804:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13805:                 $can_clone = 1;
13806:             } else {
13807:                 my $ccrole = 'cc';
13808:                 if ($args->{'crstype'} eq 'Community') {
13809:                     $ccrole = 'co';
13810:                 }
13811: 	        my %roleshash =
13812: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13813: 					 $args->{'ccdomain'},
13814:                                          'userroles',['active'],[$ccrole],
13815: 					 [$args->{'clonedomain'}]);
13816: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13817:                     $can_clone = 1;
13818:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13819:                     $can_clone = 1;
13820:                 } else {
13821:                     if ($args->{'crstype'} eq 'Community') {
13822:                         $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'});
13823:                     } else {
13824:                         $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'});
13825:                     }
13826: 	        }
13827: 	    }
13828:         }
13829:     }
13830:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13831: }
13832: 
13833: sub construct_course {
13834:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13835:     my $outcome;
13836:     my $linefeed =  '<br />'."\n";
13837:     if ($context eq 'auto') {
13838:         $linefeed = "\n";
13839:     }
13840: 
13841: #
13842: # Are we cloning?
13843: #
13844:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13845:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13846: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13847: 	if ($context ne 'auto') {
13848:             if ($clonemsg ne '') {
13849: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13850:             }
13851: 	}
13852: 	$outcome .= $clonemsg.$linefeed;
13853: 
13854:         if (!$can_clone) {
13855: 	    return (0,$outcome);
13856: 	}
13857:     }
13858: 
13859: #
13860: # Open course
13861: #
13862:     my $crstype = lc($args->{'crstype'});
13863:     my %cenv=();
13864:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13865:                                              $args->{'cdescr'},
13866:                                              $args->{'curl'},
13867:                                              $args->{'course_home'},
13868:                                              $args->{'nonstandard'},
13869:                                              $args->{'crscode'},
13870:                                              $args->{'ccuname'}.':'.
13871:                                              $args->{'ccdomain'},
13872:                                              $args->{'crstype'},
13873:                                              $cnum,$context,$category);
13874: 
13875:     # Note: The testing routines depend on this being output; see 
13876:     # Utils::Course. This needs to at least be output as a comment
13877:     # if anyone ever decides to not show this, and Utils::Course::new
13878:     # will need to be suitably modified.
13879:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13880:     if ($$courseid =~ /^error:/) {
13881:         return (0,$outcome);
13882:     }
13883: 
13884: #
13885: # Check if created correctly
13886: #
13887:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13888:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13889:     if ($crsuhome eq 'no_host') {
13890:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13891:         return (0,$outcome);
13892:     }
13893:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13894: 
13895: #
13896: # Do the cloning
13897: #   
13898:     if ($can_clone && $cloneid) {
13899: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13900: 	if ($context ne 'auto') {
13901: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13902: 	}
13903: 	$outcome .= $clonemsg.$linefeed;
13904: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13905: # Copy all files
13906: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13907: # Restore URL
13908: 	$cenv{'url'}=$oldcenv{'url'};
13909: # Restore title
13910: 	$cenv{'description'}=$oldcenv{'description'};
13911: # Restore creation date, creator and creation context.
13912:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13913:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13914:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13915: # Mark as cloned
13916: 	$cenv{'clonedfrom'}=$cloneid;
13917: # Need to clone grading mode
13918:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13919:         $cenv{'grading'}=$newenv{'grading'};
13920: # Do not clone these environment entries
13921:         &Apache::lonnet::del('environment',
13922:                   ['default_enrollment_start_date',
13923:                    'default_enrollment_end_date',
13924:                    'question.email',
13925:                    'policy.email',
13926:                    'comment.email',
13927:                    'pch.users.denied',
13928:                    'plc.users.denied',
13929:                    'hidefromcat',
13930:                    'checkforpriv',
13931:                    'categories'],
13932:                    $$crsudom,$$crsunum);
13933:     }
13934: 
13935: #
13936: # Set environment (will override cloned, if existing)
13937: #
13938:     my @sections = ();
13939:     my @xlists = ();
13940:     if ($args->{'crstype'}) {
13941:         $cenv{'type'}=$args->{'crstype'};
13942:     }
13943:     if ($args->{'crsid'}) {
13944:         $cenv{'courseid'}=$args->{'crsid'};
13945:     }
13946:     if ($args->{'crscode'}) {
13947:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13948:     }
13949:     if ($args->{'crsquota'} ne '') {
13950:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13951:     } else {
13952:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13953:     }
13954:     if ($args->{'ccuname'}) {
13955:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13956:                                         ':'.$args->{'ccdomain'};
13957:     } else {
13958:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13959:     }
13960:     if ($args->{'defaultcredits'}) {
13961:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
13962:     }
13963:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13964:     if ($args->{'crssections'}) {
13965:         $cenv{'internal.sectionnums'} = '';
13966:         if ($args->{'crssections'} =~ m/,/) {
13967:             @sections = split/,/,$args->{'crssections'};
13968:         } else {
13969:             $sections[0] = $args->{'crssections'};
13970:         }
13971:         if (@sections > 0) {
13972:             foreach my $item (@sections) {
13973:                 my ($sec,$gp) = split/:/,$item;
13974:                 my $class = $args->{'crscode'}.$sec;
13975:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13976:                 $cenv{'internal.sectionnums'} .= $item.',';
13977:                 unless ($addcheck eq 'ok') {
13978:                     push @badclasses, $class;
13979:                 }
13980:             }
13981:             $cenv{'internal.sectionnums'} =~ s/,$//;
13982:         }
13983:     }
13984: # do not hide course coordinator from staff listing, 
13985: # even if privileged
13986:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13987: # add course coordinator's domain to domains to check for privileged users
13988: # if different to course domain
13989:     if ($$crsudom ne $args->{'ccdomain'}) {
13990:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
13991:     }
13992: # add crosslistings
13993:     if ($args->{'crsxlist'}) {
13994:         $cenv{'internal.crosslistings'}='';
13995:         if ($args->{'crsxlist'} =~ m/,/) {
13996:             @xlists = split/,/,$args->{'crsxlist'};
13997:         } else {
13998:             $xlists[0] = $args->{'crsxlist'};
13999:         }
14000:         if (@xlists > 0) {
14001:             foreach my $item (@xlists) {
14002:                 my ($xl,$gp) = split/:/,$item;
14003:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14004:                 $cenv{'internal.crosslistings'} .= $item.',';
14005:                 unless ($addcheck eq 'ok') {
14006:                     push @badclasses, $xl;
14007:                 }
14008:             }
14009:             $cenv{'internal.crosslistings'} =~ s/,$//;
14010:         }
14011:     }
14012:     if ($args->{'autoadds'}) {
14013:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14014:     }
14015:     if ($args->{'autodrops'}) {
14016:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14017:     }
14018: # check for notification of enrollment changes
14019:     my @notified = ();
14020:     if ($args->{'notify_owner'}) {
14021:         if ($args->{'ccuname'} ne '') {
14022:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14023:         }
14024:     }
14025:     if ($args->{'notify_dc'}) {
14026:         if ($uname ne '') { 
14027:             push(@notified,$uname.':'.$udom);
14028:         }
14029:     }
14030:     if (@notified > 0) {
14031:         my $notifylist;
14032:         if (@notified > 1) {
14033:             $notifylist = join(',',@notified);
14034:         } else {
14035:             $notifylist = $notified[0];
14036:         }
14037:         $cenv{'internal.notifylist'} = $notifylist;
14038:     }
14039:     if (@badclasses > 0) {
14040:         my %lt=&Apache::lonlocal::texthash(
14041:                 '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',
14042:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14043:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14044:         );
14045:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14046:                            ' ('.$lt{'adby'}.')';
14047:         if ($context eq 'auto') {
14048:             $outcome .= $badclass_msg.$linefeed;
14049:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14050:             foreach my $item (@badclasses) {
14051:                 if ($context eq 'auto') {
14052:                     $outcome .= " - $item\n";
14053:                 } else {
14054:                     $outcome .= "<li>$item</li>\n";
14055:                 }
14056:             }
14057:             if ($context eq 'auto') {
14058:                 $outcome .= $linefeed;
14059:             } else {
14060:                 $outcome .= "</ul><br /><br /></div>\n";
14061:             }
14062:         } 
14063:     }
14064:     if ($args->{'no_end_date'}) {
14065:         $args->{'endaccess'} = 0;
14066:     }
14067:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14068:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14069:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14070:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14071:     if ($args->{'showphotos'}) {
14072:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14073:     }
14074:     $cenv{'internal.authtype'} = $args->{'authtype'};
14075:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14076:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14077:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14078:             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'); 
14079:             if ($context eq 'auto') {
14080:                 $outcome .= $krb_msg;
14081:             } else {
14082:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14083:             }
14084:             $outcome .= $linefeed;
14085:         }
14086:     }
14087:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14088:        if ($args->{'setpolicy'}) {
14089:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14090:        }
14091:        if ($args->{'setcontent'}) {
14092:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14093:        }
14094:     }
14095:     if ($args->{'reshome'}) {
14096: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14097: 	$cenv{'reshome'}=~s/\/+$/\//;
14098:     }
14099: #
14100: # course has keyed access
14101: #
14102:     if ($args->{'setkeys'}) {
14103:        $cenv{'keyaccess'}='yes';
14104:     }
14105: # if specified, key authority is not course, but user
14106: # only active if keyaccess is yes
14107:     if ($args->{'keyauth'}) {
14108: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14109: 	$user = &LONCAPA::clean_username($user);
14110: 	$domain = &LONCAPA::clean_username($domain);
14111: 	if ($user ne '' && $domain ne '') {
14112: 	    $cenv{'keyauth'}=$user.':'.$domain;
14113: 	}
14114:     }
14115: 
14116:     if ($args->{'disresdis'}) {
14117:         $cenv{'pch.roles.denied'}='st';
14118:     }
14119:     if ($args->{'disablechat'}) {
14120:         $cenv{'plc.roles.denied'}='st';
14121:     }
14122: 
14123:     # Record we've not yet viewed the Course Initialization Helper for this 
14124:     # course
14125:     $cenv{'course.helper.not.run'} = 1;
14126:     #
14127:     # Use new Randomseed
14128:     #
14129:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14130:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14131:     #
14132:     # The encryption code and receipt prefix for this course
14133:     #
14134:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14135:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14136:     #
14137:     # By default, use standard grading
14138:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14139: 
14140:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14141:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14142: #
14143: # Open all assignments
14144: #
14145:     if ($args->{'openall'}) {
14146:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14147:        my %storecontent = ($storeunder         => time,
14148:                            $storeunder.'.type' => 'date_start');
14149:        
14150:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14151:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14152:    }
14153: #
14154: # Set first page
14155: #
14156:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14157: 	    || ($cloneid)) {
14158: 	use LONCAPA::map;
14159: 	$outcome .= &mt('Setting first resource').': ';
14160: 
14161: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14162:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14163: 
14164:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14165:         my $title; my $url;
14166:         if ($args->{'firstres'} eq 'syl') {
14167: 	    $title=&mt('Syllabus');
14168:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14169:         } else {
14170:             $title=&mt('Table of Contents');
14171:             $url='/adm/navmaps';
14172:         }
14173: 
14174:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14175: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14176: 
14177: 	if ($errtext) { $fatal=2; }
14178:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14179:     }
14180: 
14181:     return (1,$outcome);
14182: }
14183: 
14184: ############################################################
14185: ############################################################
14186: 
14187: #SD
14188: # only Community and Course, or anything else?
14189: sub course_type {
14190:     my ($cid) = @_;
14191:     if (!defined($cid)) {
14192:         $cid = $env{'request.course.id'};
14193:     }
14194:     if (defined($env{'course.'.$cid.'.type'})) {
14195:         return $env{'course.'.$cid.'.type'};
14196:     } else {
14197:         return 'Course';
14198:     }
14199: }
14200: 
14201: sub group_term {
14202:     my $crstype = &course_type();
14203:     my %names = (
14204:                   'Course' => 'group',
14205:                   'Community' => 'group',
14206:                 );
14207:     return $names{$crstype};
14208: }
14209: 
14210: sub course_types {
14211:     my @types = ('official','unofficial','community');
14212:     my %typename = (
14213:                          official   => 'Official course',
14214:                          unofficial => 'Unofficial course',
14215:                          community  => 'Community',
14216:                    );
14217:     return (\@types,\%typename);
14218: }
14219: 
14220: sub icon {
14221:     my ($file)=@_;
14222:     my $curfext = lc((split(/\./,$file))[-1]);
14223:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14224:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14225:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14226: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14227: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14228: 	            $curfext.".gif") {
14229: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14230: 		$curfext.".gif";
14231: 	}
14232:     }
14233:     return &lonhttpdurl($iconname);
14234: } 
14235: 
14236: sub lonhttpdurl {
14237: #
14238: # Had been used for "small fry" static images on separate port 8080.
14239: # Modify here if lightweight http functionality desired again.
14240: # Currently eliminated due to increasing firewall issues.
14241: #
14242:     my ($url)=@_;
14243:     return $url;
14244: }
14245: 
14246: sub connection_aborted {
14247:     my ($r)=@_;
14248:     $r->print(" ");$r->rflush();
14249:     my $c = $r->connection;
14250:     return $c->aborted();
14251: }
14252: 
14253: #    Escapes strings that may have embedded 's that will be put into
14254: #    strings as 'strings'.
14255: sub escape_single {
14256:     my ($input) = @_;
14257:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14258:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14259:     return $input;
14260: }
14261: 
14262: #  Same as escape_single, but escape's "'s  This 
14263: #  can be used for  "strings"
14264: sub escape_double {
14265:     my ($input) = @_;
14266:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14267:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14268:     return $input;
14269: }
14270:  
14271: #   Escapes the last element of a full URL.
14272: sub escape_url {
14273:     my ($url)   = @_;
14274:     my @urlslices = split(/\//, $url,-1);
14275:     my $lastitem = &escape(pop(@urlslices));
14276:     return join('/',@urlslices).'/'.$lastitem;
14277: }
14278: 
14279: sub compare_arrays {
14280:     my ($arrayref1,$arrayref2) = @_;
14281:     my (@difference,%count);
14282:     @difference = ();
14283:     %count = ();
14284:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14285:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14286:         foreach my $element (keys(%count)) {
14287:             if ($count{$element} == 1) {
14288:                 push(@difference,$element);
14289:             }
14290:         }
14291:     }
14292:     return @difference;
14293: }
14294: 
14295: # -------------------------------------------------------- Initialize user login
14296: sub init_user_environment {
14297:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14298:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14299: 
14300:     my $public=($username eq 'public' && $domain eq 'public');
14301: 
14302: # See if old ID present, if so, remove
14303: 
14304:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14305:     my $now=time;
14306: 
14307:     if ($public) {
14308: 	my $max_public=100;
14309: 	my $oldest;
14310: 	my $oldest_time=0;
14311: 	for(my $next=1;$next<=$max_public;$next++) {
14312: 	    if (-e $lonids."/publicuser_$next.id") {
14313: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14314: 		if ($mtime<$oldest_time || !$oldest_time) {
14315: 		    $oldest_time=$mtime;
14316: 		    $oldest=$next;
14317: 		}
14318: 	    } else {
14319: 		$cookie="publicuser_$next";
14320: 		last;
14321: 	    }
14322: 	}
14323: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14324:     } else {
14325: 	# if this isn't a robot, kill any existing non-robot sessions
14326: 	if (!$args->{'robot'}) {
14327: 	    opendir(DIR,$lonids);
14328: 	    while ($filename=readdir(DIR)) {
14329: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14330: 		    unlink($lonids.'/'.$filename);
14331: 		}
14332: 	    }
14333: 	    closedir(DIR);
14334: 	}
14335: # Give them a new cookie
14336: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14337: 		                   : $now.$$.int(rand(10000)));
14338: 	$cookie="$username\_$id\_$domain\_$authhost";
14339:     
14340: # Initialize roles
14341: 
14342: 	($userroles,$firstaccenv,$timerintenv) = 
14343:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14344:     }
14345: # ------------------------------------ Check browser type and MathML capability
14346: 
14347:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14348:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14349: 
14350: # ------------------------------------------------------------- Get environment
14351: 
14352:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14353:     my ($tmp) = keys(%userenv);
14354:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14355:     } else {
14356: 	undef(%userenv);
14357:     }
14358:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14359: 	$form->{'interface'}=$userenv{'interface'};
14360:     }
14361:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14362: 
14363: # --------------- Do not trust query string to be put directly into environment
14364:     foreach my $option ('interface','localpath','localres') {
14365:         $form->{$option}=~s/[\n\r\=]//gs;
14366:     }
14367: # --------------------------------------------------------- Write first profile
14368: 
14369:     {
14370: 	my %initial_env = 
14371: 	    ("user.name"          => $username,
14372: 	     "user.domain"        => $domain,
14373: 	     "user.home"          => $authhost,
14374: 	     "browser.type"       => $clientbrowser,
14375: 	     "browser.version"    => $clientversion,
14376: 	     "browser.mathml"     => $clientmathml,
14377: 	     "browser.unicode"    => $clientunicode,
14378: 	     "browser.os"         => $clientos,
14379:              "browser.mobile"     => $clientmobile,
14380:              "browser.info"       => $clientinfo,
14381: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14382: 	     "request.course.fn"  => '',
14383: 	     "request.course.uri" => '',
14384: 	     "request.course.sec" => '',
14385: 	     "request.role"       => 'cm',
14386: 	     "request.role.adv"   => $env{'user.adv'},
14387: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14388: 
14389:         if ($form->{'localpath'}) {
14390: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14391: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14392:         }
14393: 	
14394: 	if ($form->{'interface'}) {
14395: 	    $form->{'interface'}=~s/\W//gs;
14396: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14397: 	    $env{'browser.interface'}=$form->{'interface'};
14398: 	}
14399: 
14400:         my %is_adv = ( is_adv => $env{'user.adv'} );
14401:         my %domdef;
14402:         unless ($domain eq 'public') {
14403:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14404:         }
14405: 
14406:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14407:             $userenv{'availabletools.'.$tool} = 
14408:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14409:                                                   undef,\%userenv,\%domdef,\%is_adv);
14410:         }
14411: 
14412:         foreach my $crstype ('official','unofficial','community') {
14413:             $userenv{'canrequest.'.$crstype} =
14414:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14415:                                                   'reload','requestcourses',
14416:                                                   \%userenv,\%domdef,\%is_adv);
14417:         }
14418: 
14419:         $userenv{'canrequest.author'} =
14420:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14421:                                         'reload','requestauthor',
14422:                                         \%userenv,\%domdef,\%is_adv);
14423:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14424:                                              $domain,$username);
14425:         my $reqstatus = $reqauthor{'author_status'};
14426:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14427:             if (ref($reqauthor{'author'}) eq 'HASH') {
14428:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14429:                                                   $reqauthor{'author'}{'timestamp'};
14430:             }
14431:         }
14432: 
14433: 	$env{'user.environment'} = "$lonids/$cookie.id";
14434: 
14435: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14436: 		 &GDBM_WRCREAT(),0640)) {
14437: 	    &_add_to_env(\%disk_env,\%initial_env);
14438: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14439: 	    &_add_to_env(\%disk_env,$userroles);
14440:             if (ref($firstaccenv) eq 'HASH') {
14441:                 &_add_to_env(\%disk_env,$firstaccenv);
14442:             }
14443:             if (ref($timerintenv) eq 'HASH') {
14444:                 &_add_to_env(\%disk_env,$timerintenv);
14445:             }
14446: 	    if (ref($args->{'extra_env'})) {
14447: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14448: 	    }
14449: 	    untie(%disk_env);
14450: 	} else {
14451: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14452: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14453: 	    return 'error: '.$!;
14454: 	}
14455:     }
14456:     $env{'request.role'}='cm';
14457:     $env{'request.role.adv'}=$env{'user.adv'};
14458:     $env{'browser.type'}=$clientbrowser;
14459: 
14460:     return $cookie;
14461: 
14462: }
14463: 
14464: sub _add_to_env {
14465:     my ($idf,$env_data,$prefix) = @_;
14466:     if (ref($env_data) eq 'HASH') {
14467:         while (my ($key,$value) = each(%$env_data)) {
14468: 	    $idf->{$prefix.$key} = $value;
14469: 	    $env{$prefix.$key}   = $value;
14470:         }
14471:     }
14472: }
14473: 
14474: # --- Get the symbolic name of a problem and the url
14475: sub get_symb {
14476:     my ($request,$silent) = @_;
14477:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14478:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14479:     if ($symb eq '') {
14480:         if (!$silent) {
14481:             if (ref($request)) { 
14482:                 $request->print("Unable to handle ambiguous references:$url:.");
14483:             }
14484:             return ();
14485:         }
14486:     }
14487:     &Apache::lonenc::check_decrypt(\$symb);
14488:     return ($symb);
14489: }
14490: 
14491: # --------------------------------------------------------------Get annotation
14492: 
14493: sub get_annotation {
14494:     my ($symb,$enc) = @_;
14495: 
14496:     my $key = $symb;
14497:     if (!$enc) {
14498:         $key =
14499:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14500:     }
14501:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14502:     return $annotation{$key};
14503: }
14504: 
14505: sub clean_symb {
14506:     my ($symb,$delete_enc) = @_;
14507: 
14508:     &Apache::lonenc::check_decrypt(\$symb);
14509:     my $enc = $env{'request.enc'};
14510:     if ($delete_enc) {
14511:         delete($env{'request.enc'});
14512:     }
14513: 
14514:     return ($symb,$enc);
14515: }
14516: 
14517: sub build_release_hashes {
14518:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14519:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14520:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14521:                   (ref($randomizetry) eq 'HASH'));
14522:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14523:         my ($item,$name,$value) = split(/:/,$key);
14524:         if ($item eq 'parameter') {
14525:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14526:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14527:                     push(@{$checkparms->{$name}},$value);
14528:                 }
14529:             } else {
14530:                 push(@{$checkparms->{$name}},$value);
14531:             }
14532:         } elsif ($item eq 'resourcetag') {
14533:             if ($name eq 'responsetype') {
14534:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14535:             }
14536:         } elsif ($item eq 'course') {
14537:             if ($name eq 'crstype') {
14538:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14539:             }
14540:         }
14541:     }
14542:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14543:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14544:     return;
14545: }
14546: 
14547: sub update_content_constraints {
14548:     my ($cdom,$cnum,$chome,$cid) = @_;
14549:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14550:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14551:     my %checkresponsetypes;
14552:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14553:         my ($item,$name,$value) = split(/:/,$key);
14554:         if ($item eq 'resourcetag') {
14555:             if ($name eq 'responsetype') {
14556:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14557:             }
14558:         }
14559:     }
14560:     my $navmap = Apache::lonnavmaps::navmap->new();
14561:     if (defined($navmap)) {
14562:         my %allresponses;
14563:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14564:             my %responses = $res->responseTypes();
14565:             foreach my $key (keys(%responses)) {
14566:                 next unless(exists($checkresponsetypes{$key}));
14567:                 $allresponses{$key} += $responses{$key};
14568:             }
14569:         }
14570:         foreach my $key (keys(%allresponses)) {
14571:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14572:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14573:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14574:             }
14575:         }
14576:         undef($navmap);
14577:     }
14578:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14579:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14580:     }
14581:     return;
14582: }
14583: 
14584: sub allmaps_incourse {
14585:     my ($cdom,$cnum,$chome,$cid) = @_;
14586:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14587:         $cid = $env{'request.course.id'};
14588:         $cdom = $env{'course.'.$cid.'.domain'};
14589:         $cnum = $env{'course.'.$cid.'.num'};
14590:         $chome = $env{'course.'.$cid.'.home'};
14591:     }
14592:     my %allmaps = ();
14593:     my $lastchange =
14594:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14595:     if ($lastchange > $env{'request.course.tied'}) {
14596:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14597:         unless ($ferr) {
14598:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14599:         }
14600:     }
14601:     my $navmap = Apache::lonnavmaps::navmap->new();
14602:     if (defined($navmap)) {
14603:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14604:             $allmaps{$res->src()} = 1;
14605:         }
14606:     }
14607:     return \%allmaps;
14608: }
14609: 
14610: sub parse_supplemental_title {
14611:     my ($title) = @_;
14612: 
14613:     my ($foldertitle,$renametitle);
14614:     if ($title =~ /&amp;&amp;&amp;/) {
14615:         $title = &HTML::Entites::decode($title);
14616:     }
14617:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14618:         $renametitle=$4;
14619:         my ($time,$uname,$udom) = ($1,$2,$3);
14620:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14621:         my $name =  &plainname($uname,$udom);
14622:         $name = &HTML::Entities::encode($name,'"<>&\'');
14623:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14624:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14625:             $name.': <br />'.$foldertitle;
14626:     }
14627:     if (wantarray) {
14628:         return ($title,$foldertitle,$renametitle);
14629:     }
14630:     return $title;
14631: }
14632: 
14633: sub recurse_supplemental {
14634:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14635:     if ($suppmap) {
14636:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14637:         if ($fatal) {
14638:             $errors ++;
14639:         } else {
14640:             if ($#LONCAPA::map::resources > 0) {
14641:                 foreach my $res (@LONCAPA::map::resources) {
14642:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14643:                     if (($src ne '') && ($status eq 'res')) {
14644:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14645:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14646:                         } else {
14647:                             $numfiles ++;
14648:                         }
14649:                     }
14650:                 }
14651:             }
14652:         }
14653:     }
14654:     return ($numfiles,$errors);
14655: }
14656: 
14657: sub symb_to_docspath {
14658:     my ($symb) = @_;
14659:     return unless ($symb);
14660:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14661:     if ($resurl=~/\.(sequence|page)$/) {
14662:         $mapurl=$resurl;
14663:     } elsif ($resurl eq 'adm/navmaps') {
14664:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14665:     }
14666:     my $mapresobj;
14667:     my $navmap = Apache::lonnavmaps::navmap->new();
14668:     if (ref($navmap)) {
14669:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14670:     }
14671:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14672:     my $type=$2;
14673:     my $path;
14674:     if (ref($mapresobj)) {
14675:         my $pcslist = $mapresobj->map_hierarchy();
14676:         if ($pcslist ne '') {
14677:             foreach my $pc (split(/,/,$pcslist)) {
14678:                 next if ($pc <= 1);
14679:                 my $res = $navmap->getByMapPc($pc);
14680:                 if (ref($res)) {
14681:                     my $thisurl = $res->src();
14682:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14683:                     my $thistitle = $res->title();
14684:                     $path .= '&'.
14685:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14686:                              &escape($thistitle).
14687:                              ':'.$res->randompick().
14688:                              ':'.$res->randomout().
14689:                              ':'.$res->encrypted().
14690:                              ':'.$res->randomorder().
14691:                              ':'.$res->is_page();
14692:                 }
14693:             }
14694:         }
14695:         $path =~ s/^\&//;
14696:         my $maptitle = $mapresobj->title();
14697:         if ($mapurl eq 'default') {
14698:             $maptitle = 'Main Content';
14699:         }
14700:         $path .= (($path ne '')? '&' : '').
14701:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14702:                  &escape($maptitle).
14703:                  ':'.$mapresobj->randompick().
14704:                  ':'.$mapresobj->randomout().
14705:                  ':'.$mapresobj->encrypted().
14706:                  ':'.$mapresobj->randomorder().
14707:                  ':'.$mapresobj->is_page();
14708:     } else {
14709:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14710:         my $ispage = (($type eq 'page')? 1 : '');
14711:         if ($mapurl eq 'default') {
14712:             $maptitle = 'Main Content';
14713:         }
14714:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14715:                 &escape($maptitle).':::::'.$ispage;
14716:     }
14717:     unless ($mapurl eq 'default') {
14718:         $path = 'default&'.
14719:                 &escape('Main Content').
14720:                 ':::::&'.$path;
14721:     }
14722:     return $path;
14723: }
14724: 
14725: sub captcha_display {
14726:     my ($context,$lonhost) = @_;
14727:     my ($output,$error);
14728:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14729:     if ($captcha eq 'original') {
14730:         $output = &create_captcha();
14731:         unless ($output) {
14732:             $error = 'captcha';
14733:         }
14734:     } elsif ($captcha eq 'recaptcha') {
14735:         $output = &create_recaptcha($pubkey);
14736:         unless ($output) {
14737:             $error = 'recaptcha';
14738:         }
14739:     }
14740:     return ($output,$error);
14741: }
14742: 
14743: sub captcha_response {
14744:     my ($context,$lonhost) = @_;
14745:     my ($captcha_chk,$captcha_error);
14746:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14747:     if ($captcha eq 'original') {
14748:         ($captcha_chk,$captcha_error) = &check_captcha();
14749:     } elsif ($captcha eq 'recaptcha') {
14750:         $captcha_chk = &check_recaptcha($privkey);
14751:     } else {
14752:         $captcha_chk = 1;
14753:     }
14754:     return ($captcha_chk,$captcha_error);
14755: }
14756: 
14757: sub get_captcha_config {
14758:     my ($context,$lonhost) = @_;
14759:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14760:     my $hostname = &Apache::lonnet::hostname($lonhost);
14761:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14762:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14763:     if ($context eq 'usercreation') {
14764:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14765:         if (ref($domconfig{$context}) eq 'HASH') {
14766:             $hashtocheck = $domconfig{$context}{'cancreate'};
14767:             if (ref($hashtocheck) eq 'HASH') {
14768:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14769:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14770:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14771:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14772:                     }
14773:                     if ($privkey && $pubkey) {
14774:                         $captcha = 'recaptcha';
14775:                     } else {
14776:                         $captcha = 'original';
14777:                     }
14778:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14779:                     $captcha = 'original';
14780:                 }
14781:             }
14782:         } else {
14783:             $captcha = 'captcha';
14784:         }
14785:     } elsif ($context eq 'login') {
14786:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14787:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14788:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14789:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14790:             if ($privkey && $pubkey) {
14791:                 $captcha = 'recaptcha';
14792:             } else {
14793:                 $captcha = 'original';
14794:             }
14795:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14796:             $captcha = 'original';
14797:         }
14798:     }
14799:     return ($captcha,$pubkey,$privkey);
14800: }
14801: 
14802: sub create_captcha {
14803:     my %captcha_params = &captcha_settings();
14804:     my ($output,$maxtries,$tries) = ('',10,0);
14805:     while ($tries < $maxtries) {
14806:         $tries ++;
14807:         my $captcha = Authen::Captcha->new (
14808:                                            output_folder => $captcha_params{'output_dir'},
14809:                                            data_folder   => $captcha_params{'db_dir'},
14810:                                           );
14811:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14812: 
14813:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14814:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14815:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14816:                      '<input type="text" size="5" name="code" value="" /><br />'.
14817:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14818:             last;
14819:         }
14820:     }
14821:     return $output;
14822: }
14823: 
14824: sub captcha_settings {
14825:     my %captcha_params = (
14826:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14827:                            www_output_dir => "/captchaspool",
14828:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14829:                            numchars       => '5',
14830:                          );
14831:     return %captcha_params;
14832: }
14833: 
14834: sub check_captcha {
14835:     my ($captcha_chk,$captcha_error);
14836:     my $code = $env{'form.code'};
14837:     my $md5sum = $env{'form.crypt'};
14838:     my %captcha_params = &captcha_settings();
14839:     my $captcha = Authen::Captcha->new(
14840:                       output_folder => $captcha_params{'output_dir'},
14841:                       data_folder   => $captcha_params{'db_dir'},
14842:                   );
14843:     $captcha_chk = $captcha->check_code($code,$md5sum);
14844:     my %captcha_hash = (
14845:                         0       => 'Code not checked (file error)',
14846:                        -1      => 'Failed: code expired',
14847:                        -2      => 'Failed: invalid code (not in database)',
14848:                        -3      => 'Failed: invalid code (code does not match crypt)',
14849:     );
14850:     if ($captcha_chk != 1) {
14851:         $captcha_error = $captcha_hash{$captcha_chk}
14852:     }
14853:     return ($captcha_chk,$captcha_error);
14854: }
14855: 
14856: sub create_recaptcha {
14857:     my ($pubkey) = @_;
14858:     my $captcha = Captcha::reCAPTCHA->new;
14859:     return $captcha->get_options_setter({theme => 'white'})."\n".
14860:            $captcha->get_html($pubkey).
14861:            &mt('If either word is hard to read, [_1] will replace them.',
14862:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14863:            '<br /><br />';
14864: }
14865: 
14866: sub check_recaptcha {
14867:     my ($privkey) = @_;
14868:     my $captcha_chk;
14869:     my $captcha = Captcha::reCAPTCHA->new;
14870:     my $captcha_result =
14871:         $captcha->check_answer(
14872:                                 $privkey,
14873:                                 $ENV{'REMOTE_ADDR'},
14874:                                 $env{'form.recaptcha_challenge_field'},
14875:                                 $env{'form.recaptcha_response_field'},
14876:                               );
14877:     if ($captcha_result->{is_valid}) {
14878:         $captcha_chk = 1;
14879:     }
14880:     return $captcha_chk;
14881: }
14882: 
14883: =pod
14884: 
14885: =back
14886: 
14887: =cut
14888: 
14889: 1;
14890: __END__;
14891: 

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