File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1240: download - view: text, annotated - select for diffs
Tue Apr 5 02:02:27 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6808. New course container -- "Placement" for Placement Tests.
  - Completion status shown to students in place of icons on right side
    of inline menu.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1240 2016/04/05 02:02:27 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 Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale::Catalog;
   76: use Encode();
   77: use Text::Aspell;
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use MIME::Lite;
   85: use MIME::Types;
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %supported_codes;
  171: my %latex_language;		# For choosing hyphenation in <transl..>
  172: my %latex_language_bykey;	# for choosing hyphenation from metadata
  173: my %cprtag;
  174: my %scprtag;
  175: my %fe; my %fd; my %fm;
  176: my %category_extensions;
  177: 
  178: # ---------------------------------------------- Thesaurus variables
  179: #
  180: # %Keywords:
  181: #      A hash used by &keyword to determine if a word is considered a keyword.
  182: # $thesaurus_db_file 
  183: #      Scalar containing the full path to the thesaurus database.
  184: 
  185: my %Keywords;
  186: my $thesaurus_db_file;
  187: 
  188: #
  189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  190: # thesaurus.tab, and filecategories.tab.
  191: #
  192: BEGIN {
  193:     # Variable initialization
  194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  195:     #
  196:     unless ($readit) {
  197: # ------------------------------------------------------------------- languages
  198:     {
  199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  200:                                    '/language.tab';
  201:         if ( open(my $fh,"<$langtabfile") ) {
  202:             while (my $line = <$fh>) {
  203:                 next if ($line=~/^\#/);
  204:                 chomp($line);
  205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  206:                 $language{$key}=$val.' - '.$enc;
  207:                 if ($sup) {
  208:                     $supported_language{$key}=$sup;
  209: 		    $supported_codes{$key}   = $code;
  210:                 }
  211: 		if ($latex) {
  212: 		    $latex_language_bykey{$key} = $latex;
  213: 		    $latex_language{$code} = $latex;
  214: 		}
  215:             }
  216:             close($fh);
  217:         }
  218:     }
  219: # ------------------------------------------------------------------ copyrights
  220:     {
  221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  222:                                   '/copyright.tab';
  223:         if ( open (my $fh,"<$copyrightfile") ) {
  224:             while (my $line = <$fh>) {
  225:                 next if ($line=~/^\#/);
  226:                 chomp($line);
  227:                 my ($key,$val)=(split(/\s+/,$line,2));
  228:                 $cprtag{$key}=$val;
  229:             }
  230:             close($fh);
  231:         }
  232:     }
  233: # ----------------------------------------------------------- source copyrights
  234:     {
  235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  236:                                   '/source_copyright.tab';
  237:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  238:             while (my $line = <$fh>) {
  239:                 next if ($line =~ /^\#/);
  240:                 chomp($line);
  241:                 my ($key,$val)=(split(/\s+/,$line,2));
  242:                 $scprtag{$key}=$val;
  243:             }
  244:             close($fh);
  245:         }
  246:     }
  247: 
  248: # -------------------------------------------------------------- default domain designs
  249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  250:     my $designfile = $designdir.'/default.tab';
  251:     if ( open (my $fh,"<$designfile") ) {
  252:         while (my $line = <$fh>) {
  253:             next if ($line =~ /^\#/);
  254:             chomp($line);
  255:             my ($key,$val)=(split(/\=/,$line));
  256:             if ($val) { $defaultdesign{$key}=$val; }
  257:         }
  258:         close($fh);
  259:     }
  260: 
  261: # ------------------------------------------------------------- file categories
  262:     {
  263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                                   '/filecategories.tab';
  265:         if ( open (my $fh,"<$categoryfile") ) {
  266: 	    while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($extension,$category)=(split(/\s+/,$line,2));
  270:                 push @{$category_extensions{lc($category)}},$extension;
  271:             }
  272:             close($fh);
  273:         }
  274: 
  275:     }
  276: # ------------------------------------------------------------------ file types
  277:     {
  278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  279:                '/filetypes.tab';
  280:         if ( open (my $fh,"<$typesfile") ) {
  281:             while (my $line = <$fh>) {
  282: 		next if ($line =~ /^\#/);
  283: 		chomp($line);
  284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  285:                 if ($descr ne '') {
  286:                     $fe{$ending}=lc($emb);
  287:                     $fd{$ending}=$descr;
  288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  289:                 }
  290:             }
  291:             close($fh);
  292:         }
  293:     }
  294:     &Apache::lonnet::logthis(
  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
  296:     $readit=1;
  297:     }  # end of unless($readit) 
  298:     
  299: }
  300: 
  301: ###############################################################
  302: ##           HTML and Javascript Helper Functions            ##
  303: ###############################################################
  304: 
  305: =pod 
  306: 
  307: =head1 HTML and Javascript Functions
  308: 
  309: =over 4
  310: 
  311: =item * &browser_and_searcher_javascript()
  312: 
  313: X<browsing, javascript>X<searching, javascript>Returns a string
  314: containing javascript with two functions, C<openbrowser> and
  315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  316: tags.
  317: 
  318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  319: 
  320: inputs: formname, elementname, only, omit
  321: 
  322: formname and elementname indicate the name of the html form and name of
  323: the element that the results of the browsing selection are to be placed in. 
  324: 
  325: Specifying 'only' will restrict the browser to displaying only files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: Specifying 'omit' will restrict the browser to NOT displaying files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: =item * &opensearcher(formname,elementname) [javascript]
  332: 
  333: Inputs: formname, elementname
  334: 
  335: formname and elementname specify the name of the html form and the name
  336: of the element the selection from the search results will be placed in.
  337: 
  338: =cut
  339: 
  340: sub browser_and_searcher_javascript {
  341:     my ($mode)=@_;
  342:     if (!defined($mode)) { $mode='edit'; }
  343:     my $resurl=&escape_single(&lastresurl());
  344:     return <<END;
  345: // <!-- BEGIN LON-CAPA Internal
  346:     var editbrowser = null;
  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
  348:         var url = '$resurl/?';
  349:         if (editbrowser == null) {
  350:             url += 'launch=1&';
  351:         }
  352:         url += 'catalogmode=interactive&';
  353:         url += 'mode=$mode&';
  354:         url += 'inhibitmenu=yes&';
  355:         url += 'form=' + formname + '&';
  356:         if (only != null) {
  357:             url += 'only=' + only + '&';
  358:         } else {
  359:             url += 'only=&';
  360: 	}
  361:         if (omit != null) {
  362:             url += 'omit=' + omit + '&';
  363:         } else {
  364:             url += 'omit=&';
  365: 	}
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editbrowser = open(url,title,options,'1');
  376:         editbrowser.focus();
  377:     }
  378:     var editsearcher;
  379:     function opensearcher(formname,elementname,titleelement) {
  380:         var url = '/adm/searchcat?';
  381:         if (editsearcher == null) {
  382:             url += 'launch=1&';
  383:         }
  384:         url += 'catalogmode=interactive&';
  385:         url += 'mode=$mode&';
  386:         url += 'form=' + formname + '&';
  387:         if (titleelement != null) {
  388:             url += 'titleelement=' + titleelement + '&';
  389:         } else {
  390: 	    url += 'titleelement=&';
  391: 	}
  392:         url += 'element=' + elementname + '';
  393:         var title = 'Search';
  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  395:         options += ',width=700,height=600';
  396:         editsearcher = open(url,title,options,'1');
  397:         editsearcher.focus();
  398:     }
  399: // END LON-CAPA Internal -->
  400: END
  401: }
  402: 
  403: sub lastresurl {
  404:     if ($env{'environment.lastresurl'}) {
  405: 	return $env{'environment.lastresurl'}
  406:     } else {
  407: 	return '/res';
  408:     }
  409: }
  410: 
  411: sub storeresurl {
  412:     my $resurl=&Apache::lonnet::clutter(shift);
  413:     unless ($resurl=~/^\/res/) { return 0; }
  414:     $resurl=~s/\/$//;
  415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  417:     return 1;
  418: }
  419: 
  420: sub studentbrowser_javascript {
  421:    unless (
  422:             (($env{'request.course.id'}) && 
  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  425: 					  '/'.$env{'request.course.sec'})
  426: 	      ))
  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
  428:           ) { return ''; }  
  429:    return (<<'ENDSTDBRW');
  430: <script type="text/javascript" language="Javascript">
  431: // <![CDATA[
  432:     var stdeditbrowser;
  433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  434:         var url = '/adm/pickstudent?';
  435:         var filter;
  436: 	if (!ignorefilter) {
  437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  438: 	}
  439:         if (filter != null) {
  440:            if (filter != '') {
  441:                url += 'filter='+filter+'&';
  442: 	   }
  443:         }
  444:         url += 'form=' + formname + '&unameelement='+uname+
  445:                                     '&udomelement='+udom+
  446:                                     '&clicker='+clicker;
  447: 	if (roleflag) { url+="&roles=1"; }
  448:         if (courseadvonly) { url+="&courseadvonly=1"; }
  449:         var title = 'Student_Browser';
  450:         var options = 'scrollbars=1,resizable=1,menubar=0';
  451:         options += ',width=700,height=600';
  452:         stdeditbrowser = open(url,title,options,'1');
  453:         stdeditbrowser.focus();
  454:     }
  455: // ]]>
  456: </script>
  457: ENDSTDBRW
  458: }
  459: 
  460: sub resourcebrowser_javascript {
  461:    unless ($env{'request.course.id'}) { return ''; }
  462:    return (<<'ENDRESBRW');
  463: <script type="text/javascript" language="Javascript">
  464: // <![CDATA[
  465:     var reseditbrowser;
  466:     function openresbrowser(formname,reslink) {
  467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  468:         var title = 'Resource_Browser';
  469:         var options = 'scrollbars=1,resizable=1,menubar=0';
  470:         options += ',width=700,height=500';
  471:         reseditbrowser = open(url,title,options,'1');
  472:         reseditbrowser.focus();
  473:     }
  474: // ]]>
  475: </script>
  476: ENDRESBRW
  477: }
  478: 
  479: sub selectstudent_link {
  480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  484:    if ($env{'request.course.id'}) {  
  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  487: 					'/'.$env{'request.course.sec'})) {
  488: 	   return '';
  489:        }
  490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  491:        if ($courseadvonly)  {
  492:            $callargs .= ",'',1,1";
  493:        }
  494:        return '<span class="LC_nobreak">'.
  495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  496:               &mt('Select User').'</a></span>';
  497:    }
  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  499:        $callargs .= ",'',1"; 
  500:        return '<span class="LC_nobreak">'.
  501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  502:               &mt('Select User').'</a></span>';
  503:    }
  504:    return '';
  505: }
  506: 
  507: sub selectresource_link {
  508:    my ($form,$reslink,$arg)=@_;
  509:    
  510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  512:    unless ($env{'request.course.id'}) { return $arg; }
  513:    return '<span class="LC_nobreak">'.
  514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  515:               $arg.'</a></span>';
  516: }
  517: 
  518: 
  519: 
  520: sub authorbrowser_javascript {
  521:     return <<"ENDAUTHORBRW";
  522: <script type="text/javascript" language="JavaScript">
  523: // <![CDATA[
  524: var stdeditbrowser;
  525: 
  526: function openauthorbrowser(formname,udom) {
  527:     var url = '/adm/pickauthor?';
  528:     url += 'form='+formname+'&roledom='+udom;
  529:     var title = 'Author_Browser';
  530:     var options = 'scrollbars=1,resizable=1,menubar=0';
  531:     options += ',width=700,height=600';
  532:     stdeditbrowser = open(url,title,options,'1');
  533:     stdeditbrowser.focus();
  534: }
  535: 
  536: // ]]>
  537: </script>
  538: ENDAUTHORBRW
  539: }
  540: 
  541: sub coursebrowser_javascript {
  542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  543:         $credits_element,$instcode) = @_;
  544:     my $wintitle = 'Course_Browser';
  545:     if ($crstype eq 'Community') {
  546:         $wintitle = 'Community_Browser';
  547:     }
  548:     my $id_functions = &javascript_index_functions();
  549:     my $output = '
  550: <script type="text/javascript" language="JavaScript">
  551: // <![CDATA[
  552:     var stdeditbrowser;'."\n";
  553: 
  554:     $output .= <<"ENDSTDBRW";
  555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  556:         var url = '/adm/pickcourse?';
  557:         var formid = getFormIdByName(formname);
  558:         var domainfilter = getDomainFromSelectbox(formname,udom);
  559:         if (domainfilter != null) {
  560:            if (domainfilter != '') {
  561:                url += 'domainfilter='+domainfilter+'&';
  562: 	   }
  563:         }
  564:         url += 'form=' + formname + '&cnumelement='+uname+
  565: 	                            '&cdomelement='+udom+
  566:                                     '&cnameelement='+desc;
  567:         if (extra_element !=null && extra_element != '') {
  568:             if (formname == 'rolechoice' || formname == 'studentform') {
  569:                 url += '&roleelement='+extra_element;
  570:                 if (domainfilter == null || domainfilter == '') {
  571:                     url += '&domainfilter='+extra_element;
  572:                 }
  573:             }
  574:             else {
  575:                 if (formname == 'portform') {
  576:                     url += '&setroles='+extra_element;
  577:                 } else {
  578:                     if (formname == 'rules') {
  579:                         url += '&fixeddom='+extra_element; 
  580:                     }
  581:                 }
  582:             }     
  583:         }
  584:         if (type != null && type != '') {
  585:             url += '&type='+type;
  586:         }
  587:         if (type_elem != null && type_elem != '') {
  588:             url += '&typeelement='+type_elem;
  589:         }
  590:         if (formname == 'ccrs') {
  591:             var ownername = document.forms[formid].ccuname.value;
  592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  593:             url += '&cloner='+ownername+':'+ownerdom;
  594:             if (type == 'Course') {
  595:                 url += '&crscode='+document.forms[formid].crscode.value;
  596:             }
  597:         }
  598:         if (formname == 'requestcrs') {
  599:             url += '&crsdom=$domainfilter&crscode=$instcode';
  600:         }
  601:         if (multflag !=null && multflag != '') {
  602:             url += '&multiple='+multflag;
  603:         }
  604:         var title = '$wintitle';
  605:         var options = 'scrollbars=1,resizable=1,menubar=0';
  606:         options += ',width=700,height=600';
  607:         stdeditbrowser = open(url,title,options,'1');
  608:         stdeditbrowser.focus();
  609:     }
  610: $id_functions
  611: ENDSTDBRW
  612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  614:                                       $credits_element);
  615:     }
  616:     $output .= '
  617: // ]]>
  618: </script>';
  619:     return $output;
  620: }
  621: 
  622: sub javascript_index_functions {
  623:     return <<"ENDJS";
  624: 
  625: function getFormIdByName(formname) {
  626:     for (var i=0;i<document.forms.length;i++) {
  627:         if (document.forms[i].name == formname) {
  628:             return i;
  629:         }
  630:     }
  631:     return -1;
  632: }
  633: 
  634: function getIndexByName(formid,item) {
  635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  636:         if (document.forms[formid].elements[i].name == item) {
  637:             return i;
  638:         }
  639:     }
  640:     return -1;
  641: }
  642: 
  643: function getDomainFromSelectbox(formname,udom) {
  644:     var userdom;
  645:     var formid = getFormIdByName(formname);
  646:     if (formid > -1) {
  647:         var domid = getIndexByName(formid,udom);
  648:         if (domid > -1) {
  649:             if (document.forms[formid].elements[domid].type == 'select-one') {
  650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  651:             }
  652:             if (document.forms[formid].elements[domid].type == 'hidden') {
  653:                 userdom=document.forms[formid].elements[domid].value;
  654:             }
  655:         }
  656:     }
  657:     return userdom;
  658: }
  659: 
  660: ENDJS
  661: 
  662: }
  663: 
  664: sub javascript_array_indexof {
  665:     return <<ENDJS;
  666: <script type="text/javascript" language="JavaScript">
  667: // <![CDATA[
  668: 
  669: if (!Array.prototype.indexOf) {
  670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  671:         "use strict";
  672:         if (this === void 0 || this === null) {
  673:             throw new TypeError();
  674:         }
  675:         var t = Object(this);
  676:         var len = t.length >>> 0;
  677:         if (len === 0) {
  678:             return -1;
  679:         }
  680:         var n = 0;
  681:         if (arguments.length > 0) {
  682:             n = Number(arguments[1]);
  683:             if (n !== n) { // shortcut for verifying if it is NaN
  684:                 n = 0;
  685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  687:             }
  688:         }
  689:         if (n >= len) {
  690:             return -1;
  691:         }
  692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  693:         for (; k < len; k++) {
  694:             if (k in t && t[k] === searchElement) {
  695:                 return k;
  696:             }
  697:         }
  698:         return -1;
  699:     }
  700: }
  701: 
  702: // ]]>
  703: </script>
  704: 
  705: ENDJS
  706: 
  707: }
  708: 
  709: sub userbrowser_javascript {
  710:     my $id_functions = &javascript_index_functions();
  711:     return <<"ENDUSERBRW";
  712: 
  713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  714:     var url = '/adm/pickuser?';
  715:     var userdom = getDomainFromSelectbox(formname,udom);
  716:     if (userdom != null) {
  717:        if (userdom != '') {
  718:            url += 'srchdom='+userdom+'&';
  719:        }
  720:     }
  721:     url += 'form=' + formname + '&unameelement='+uname+
  722:                                 '&udomelement='+udom+
  723:                                 '&ulastelement='+ulast+
  724:                                 '&ufirstelement='+ufirst+
  725:                                 '&uemailelement='+uemail+
  726:                                 '&hideudomelement='+hideudom+
  727:                                 '&coursedom='+crsdom;
  728:     if ((caller != null) && (caller != undefined)) {
  729:         url += '&caller='+caller;
  730:     }
  731:     var title = 'User_Browser';
  732:     var options = 'scrollbars=1,resizable=1,menubar=0';
  733:     options += ',width=700,height=600';
  734:     var stdeditbrowser = open(url,title,options,'1');
  735:     stdeditbrowser.focus();
  736: }
  737: 
  738: function fix_domain (formname,udom,origdom,uname) {
  739:     var formid = getFormIdByName(formname);
  740:     if (formid > -1) {
  741:         var unameid = getIndexByName(formid,uname);
  742:         var domid = getIndexByName(formid,udom);
  743:         var hidedomid = getIndexByName(formid,origdom);
  744:         if (hidedomid > -1) {
  745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  746:             var unameval = document.forms[formid].elements[unameid].value;
  747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  748:                 if (domid > -1) {
  749:                     var slct = document.forms[formid].elements[domid];
  750:                     if (slct.type == 'select-one') {
  751:                         var i;
  752:                         for (i=0;i<slct.length;i++) {
  753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  754:                         }
  755:                     }
  756:                     if (slct.type == 'hidden') {
  757:                         slct.value = fixeddom;
  758:                     }
  759:                 }
  760:             }
  761:         }
  762:     }
  763:     return;
  764: }
  765: 
  766: $id_functions
  767: ENDUSERBRW
  768: }
  769: 
  770: sub setsec_javascript {
  771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  773:         $communityrolestr);
  774:     if ($role_element ne '') {
  775:         my @allroles = ('st','ta','ep','in','ad');
  776:         foreach my $crstype ('Course','Community') {
  777:             if ($crstype eq 'Community') {
  778:                 foreach my $role (@allroles) {
  779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  780:                 }
  781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  782:             } else {
  783:                 foreach my $role (@allroles) {
  784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  785:                 }
  786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  787:             }
  788:         }
  789:         $rolestr = '"'.join('","',@allroles).'"';
  790:         $courserolestr = '"'.join('","',@courserolenames).'"';
  791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  792:     }
  793:     my $setsections = qq|
  794: function setSect(sectionlist) {
  795:     var sectionsArray = new Array();
  796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  797:         sectionsArray = sectionlist.split(",");
  798:     }
  799:     var numSections = sectionsArray.length;
  800:     document.$formname.$sec_element.length = 0;
  801:     if (numSections == 0) {
  802:         document.$formname.$sec_element.multiple=false;
  803:         document.$formname.$sec_element.size=1;
  804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  805:     } else {
  806:         if (numSections == 1) {
  807:             document.$formname.$sec_element.multiple=false;
  808:             document.$formname.$sec_element.size=1;
  809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  812:         } else {
  813:             for (var i=0; i<numSections; i++) {
  814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  815:             }
  816:             document.$formname.$sec_element.multiple=true
  817:             if (numSections < 3) {
  818:                 document.$formname.$sec_element.size=numSections;
  819:             } else {
  820:                 document.$formname.$sec_element.size=3;
  821:             }
  822:             document.$formname.$sec_element.options[0].selected = false
  823:         }
  824:     }
  825: }
  826: 
  827: function setRole(crstype) {
  828: |;
  829:     if ($role_element eq '') {
  830:         $setsections .= '    return;
  831: }
  832: ';
  833:     } else {
  834:         $setsections .= qq|
  835:     var elementLength = document.$formname.$role_element.length;
  836:     var allroles = Array($rolestr);
  837:     var courserolenames = Array($courserolestr);
  838:     var communityrolenames = Array($communityrolestr);
  839:     if (elementLength != undefined) {
  840:         if (document.$formname.$role_element.options[5].value == 'cc') {
  841:             if (crstype == 'Course') {
  842:                 return;
  843:             } else {
  844:                 allroles[5] = 'co';
  845:                 for (var i=0; i<6; i++) {
  846:                     document.$formname.$role_element.options[i].value = allroles[i];
  847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  848:                 }
  849:             }
  850:         } else {
  851:             if (crstype == 'Community') {
  852:                 return;
  853:             } else {
  854:                 allroles[5] = 'cc';
  855:                 for (var i=0; i<6; i++) {
  856:                     document.$formname.$role_element.options[i].value = allroles[i];
  857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  858:                 }
  859:             }
  860:         }
  861:     }
  862:     return;
  863: }
  864: |;
  865:     }
  866:     if ($credits_element) {
  867:         $setsections .= qq|
  868: function setCredits(defaultcredits) {
  869:     document.$formname.$credits_element.value = defaultcredits;
  870:     return;
  871: }
  872: |;
  873:     }
  874:     return $setsections;
  875: }
  876: 
  877: sub selectcourse_link {
  878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  879:        $typeelement) = @_;
  880:    my $type = $selecttype;
  881:    my $linktext = &mt('Select Course');
  882:    if ($selecttype eq 'Community') {
  883:        $linktext = &mt('Select Community');
  884:    } elsif ($selecttype eq 'Placement') {
  885:        $linktext = &mt('Select Placement Test'); 
  886:    } elsif ($selecttype eq 'Course/Community') {
  887:        $linktext = &mt('Select Course/Community');
  888:        $type = '';
  889:    } elsif ($selecttype eq 'Select') {
  890:        $linktext = &mt('Select');
  891:        $type = '';
  892:    }
  893:    return '<span class="LC_nobreak">'
  894:          ."<a href='"
  895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  898:          ."'>".$linktext.'</a>'
  899:          .'</span>';
  900: }
  901: 
  902: sub selectauthor_link {
  903:    my ($form,$udom)=@_;
  904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  905:           &mt('Select Author').'</a>';
  906: }
  907: 
  908: sub selectuser_link {
  909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  910:         $coursedom,$linktext,$caller) = @_;
  911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  913:            ');">'.$linktext.'</a>';
  914: }
  915: 
  916: sub check_uncheck_jscript {
  917:     my $jscript = <<"ENDSCRT";
  918: function checkAll(field) {
  919:     if (field.length > 0) {
  920:         for (i = 0; i < field.length; i++) {
  921:             if (!field[i].disabled) { 
  922:                 field[i].checked = true;
  923:             }
  924:         }
  925:     } else {
  926:         if (!field.disabled) { 
  927:             field.checked = true;
  928:         }
  929:     }
  930: }
  931:  
  932: function uncheckAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             field[i].checked = false ;
  936:         }
  937:     } else {
  938:         field.checked = false ;
  939:     }
  940: }
  941: ENDSCRT
  942:     return $jscript;
  943: }
  944: 
  945: sub select_timezone {
  946:    my ($name,$selected,$onchange,$includeempty)=@_;
  947:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  948:    if ($includeempty) {
  949:        $output .= '<option value=""';
  950:        if (($selected eq '') || ($selected eq 'local')) {
  951:            $output .= ' selected="selected" ';
  952:        }
  953:        $output .= '> </option>';
  954:    }
  955:    my @timezones = DateTime::TimeZone->all_names;
  956:    foreach my $tzone (@timezones) {
  957:        $output.= '<option value="'.$tzone.'"';
  958:        if ($tzone eq $selected) {
  959:            $output.=' selected="selected"';
  960:        }
  961:        $output.=">$tzone</option>\n";
  962:    }
  963:    $output.="</select>";
  964:    return $output;
  965: }
  966: 
  967: sub select_datelocale {
  968:     my ($name,$selected,$onchange,$includeempty)=@_;
  969:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  970:     if ($includeempty) {
  971:         $output .= '<option value=""';
  972:         if ($selected eq '') {
  973:             $output .= ' selected="selected" ';
  974:         }
  975:         $output .= '> </option>';
  976:     }
  977:     my (@possibles,%locale_names);
  978:     my @locales = DateTime::Locale::Catalog::Locales;
  979:     foreach my $locale (@locales) {
  980:         if (ref($locale) eq 'HASH') {
  981:             my $id = $locale->{'id'};
  982:             if ($id ne '') {
  983:                 my $en_terr = $locale->{'en_territory'};
  984:                 my $native_terr = $locale->{'native_territory'};
  985:                 my @languages = &Apache::lonlocal::preferred_languages();
  986:                 if (grep(/^en$/,@languages) || !@languages) {
  987:                     if ($en_terr ne '') {
  988:                         $locale_names{$id} = '('.$en_terr.')';
  989:                     } elsif ($native_terr ne '') {
  990:                         $locale_names{$id} = $native_terr;
  991:                     }
  992:                 } else {
  993:                     if ($native_terr ne '') {
  994:                         $locale_names{$id} = $native_terr.' ';
  995:                     } elsif ($en_terr ne '') {
  996:                         $locale_names{$id} = '('.$en_terr.')';
  997:                     }
  998:                 }
  999:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1000:                 push (@possibles,$id);
 1001:             }
 1002:         }
 1003:     }
 1004:     foreach my $item (sort(@possibles)) {
 1005:         $output.= '<option value="'.$item.'"';
 1006:         if ($item eq $selected) {
 1007:             $output.=' selected="selected"';
 1008:         }
 1009:         $output.=">$item";
 1010:         if ($locale_names{$item} ne '') {
 1011:             $output.='  '.$locale_names{$item};
 1012:         }
 1013:         $output.="</option>\n";
 1014:     }
 1015:     $output.="</select>";
 1016:     return $output;
 1017: }
 1018: 
 1019: sub select_language {
 1020:     my ($name,$selected,$includeempty) = @_;
 1021:     my %langchoices;
 1022:     if ($includeempty) {
 1023:         %langchoices = ('' => 'No language preference');
 1024:     }
 1025:     foreach my $id (&languageids()) {
 1026:         my $code = &supportedlanguagecode($id);
 1027:         if ($code) {
 1028:             $langchoices{$code} = &plainlanguagedescription($id);
 1029:         }
 1030:     }
 1031:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1032:     return &select_form($selected,$name,\%langchoices);
 1033: }
 1034: 
 1035: =pod
 1036: 
 1037: 
 1038: =item * &list_languages()
 1039: 
 1040: Returns an array reference that is suitable for use in language prompters.
 1041: Each array element is itself a two element array.  The first element
 1042: is the language code.  The second element a descsriptiuon of the 
 1043: language itself.  This is suitable for use in e.g.
 1044: &Apache::edit::select_arg (once dereferenced that is).
 1045: 
 1046: =cut 
 1047: 
 1048: sub list_languages {
 1049:     my @lang_choices;
 1050: 
 1051:     foreach my $id (&languageids()) {
 1052: 	my $code = &supportedlanguagecode($id);
 1053: 	if ($code) {
 1054: 	    my $selector    = $supported_codes{$id};
 1055: 	    my $description = &plainlanguagedescription($id);
 1056: 	    push (@lang_choices, [$selector, $description]);
 1057: 	}
 1058:     }
 1059:     return \@lang_choices;
 1060: }
 1061: 
 1062: =pod
 1063: 
 1064: =item * &linked_select_forms(...)
 1065: 
 1066: linked_select_forms returns a string containing a <script></script> block
 1067: and html for two <select> menus.  The select menus will be linked in that
 1068: changing the value of the first menu will result in new values being placed
 1069: in the second menu.  The values in the select menu will appear in alphabetical
 1070: order unless a defined order is provided.
 1071: 
 1072: linked_select_forms takes the following ordered inputs:
 1073: 
 1074: =over 4
 1075: 
 1076: =item * $formname, the name of the <form> tag
 1077: 
 1078: =item * $middletext, the text which appears between the <select> tags
 1079: 
 1080: =item * $firstdefault, the default value for the first menu
 1081: 
 1082: =item * $firstselectname, the name of the first <select> tag
 1083: 
 1084: =item * $secondselectname, the name of the second <select> tag
 1085: 
 1086: =item * $hashref, a reference to a hash containing the data for the menus.
 1087: 
 1088: =item * $menuorder, the order of values in the first menu
 1089: 
 1090: =item * $onchangefirst, additional javascript call to execute for an onchange
 1091:         event for the first <select> tag
 1092: 
 1093: =item * $onchangesecond, additional javascript call to execute for an onchange
 1094:         event for the second <select> tag
 1095: 
 1096: =back 
 1097: 
 1098: Below is an example of such a hash.  Only the 'text', 'default', and 
 1099: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1100: values for the first select menu.  The text that coincides with the 
 1101: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1102: and text for the second menu are given in the hash pointed to by 
 1103: $menu{$choice1}->{'select2'}.  
 1104: 
 1105:  my %menu = ( A1 => { text =>"Choice A1" ,
 1106:                        default => "B3",
 1107:                        select2 => { 
 1108:                            B1 => "Choice B1",
 1109:                            B2 => "Choice B2",
 1110:                            B3 => "Choice B3",
 1111:                            B4 => "Choice B4"
 1112:                            },
 1113:                        order => ['B4','B3','B1','B2'],
 1114:                    },
 1115:                A2 => { text =>"Choice A2" ,
 1116:                        default => "C2",
 1117:                        select2 => { 
 1118:                            C1 => "Choice C1",
 1119:                            C2 => "Choice C2",
 1120:                            C3 => "Choice C3"
 1121:                            },
 1122:                        order => ['C2','C1','C3'],
 1123:                    },
 1124:                A3 => { text =>"Choice A3" ,
 1125:                        default => "D6",
 1126:                        select2 => { 
 1127:                            D1 => "Choice D1",
 1128:                            D2 => "Choice D2",
 1129:                            D3 => "Choice D3",
 1130:                            D4 => "Choice D4",
 1131:                            D5 => "Choice D5",
 1132:                            D6 => "Choice D6",
 1133:                            D7 => "Choice D7"
 1134:                            },
 1135:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1136:                    }
 1137:                );
 1138: 
 1139: =cut
 1140: 
 1141: sub linked_select_forms {
 1142:     my ($formname,
 1143:         $middletext,
 1144:         $firstdefault,
 1145:         $firstselectname,
 1146:         $secondselectname, 
 1147:         $hashref,
 1148:         $menuorder,
 1149:         $onchangefirst,
 1150:         $onchangesecond
 1151:         ) = @_;
 1152:     my $second = "document.$formname.$secondselectname";
 1153:     my $first = "document.$formname.$firstselectname";
 1154:     # output the javascript to do the changing
 1155:     my $result = '';
 1156:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1157:     $result.="// <![CDATA[\n";
 1158:     $result.="var select2data = new Object();\n";
 1159:     $" = '","';
 1160:     my $debug = '';
 1161:     foreach my $s1 (sort(keys(%$hashref))) {
 1162:         $result.="select2data.d_$s1 = new Object();\n";        
 1163:         $result.="select2data.d_$s1.def = new String('".
 1164:             $hashref->{$s1}->{'default'}."');\n";
 1165:         $result.="select2data.d_$s1.values = new Array(";
 1166:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1167:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1168:             @s2values = @{$hashref->{$s1}->{'order'}};
 1169:         }
 1170:         $result.="\"@s2values\");\n";
 1171:         $result.="select2data.d_$s1.texts = new Array(";        
 1172:         my @s2texts;
 1173:         foreach my $value (@s2values) {
 1174:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1175:         }
 1176:         $result.="\"@s2texts\");\n";
 1177:     }
 1178:     $"=' ';
 1179:     $result.= <<"END";
 1180: 
 1181: function select1_changed() {
 1182:     // Determine new choice
 1183:     var newvalue = "d_" + $first.value;
 1184:     // update select2
 1185:     var values     = select2data[newvalue].values;
 1186:     var texts      = select2data[newvalue].texts;
 1187:     var select2def = select2data[newvalue].def;
 1188:     var i;
 1189:     // out with the old
 1190:     for (i = 0; i < $second.options.length; i++) {
 1191:         $second.options[i] = null;
 1192:     }
 1193:     // in with the nuclear
 1194:     for (i=0;i<values.length; i++) {
 1195:         $second.options[i] = new Option(values[i]);
 1196:         $second.options[i].value = values[i];
 1197:         $second.options[i].text = texts[i];
 1198:         if (values[i] == select2def) {
 1199:             $second.options[i].selected = true;
 1200:         }
 1201:     }
 1202: }
 1203: // ]]>
 1204: </script>
 1205: END
 1206:     # output the initial values for the selection lists
 1207:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1208:     my @order = sort(keys(%{$hashref}));
 1209:     if (ref($menuorder) eq 'ARRAY') {
 1210:         @order = @{$menuorder};
 1211:     }
 1212:     foreach my $value (@order) {
 1213:         $result.="    <option value=\"$value\" ";
 1214:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1215:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1216:     }
 1217:     $result .= "</select>\n";
 1218:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1219:     $result .= $middletext;
 1220:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1221:     if ($onchangesecond) {
 1222:         $result .= ' onchange="'.$onchangesecond.'"';
 1223:     }
 1224:     $result .= ">\n";
 1225:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1226:     
 1227:     my @secondorder = sort(keys(%select2));
 1228:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1229:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1230:     }
 1231:     foreach my $value (@secondorder) {
 1232:         $result.="    <option value=\"$value\" ";        
 1233:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1234:         $result.=">".&mt($select2{$value})."</option>\n";
 1235:     }
 1236:     $result .= "</select>\n";
 1237:     #    return $debug;
 1238:     return $result;
 1239: }   #  end of sub linked_select_forms {
 1240: 
 1241: =pod
 1242: 
 1243: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1244: 
 1245: Returns a string corresponding to an HTML link to the given help
 1246: $topic, where $topic corresponds to the name of a .tex file in
 1247: /home/httpd/html/adm/help/tex, with underscores replaced by
 1248: spaces. 
 1249: 
 1250: $text will optionally be linked to the same topic, allowing you to
 1251: link text in addition to the graphic. If you do not want to link
 1252: text, but wish to specify one of the later parameters, pass an
 1253: empty string. 
 1254: 
 1255: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1256: the link will not open a new window. If false, the link will open
 1257: a new window using Javascript. (Default is false.) 
 1258: 
 1259: $width and $height are optional numerical parameters that will
 1260: override the width and height of the popped up window, which may
 1261: be useful for certain help topics with big pictures included.
 1262: 
 1263: $imgid is the id of the img tag used for the help icon. This may be
 1264: used in a javascript call to switch the image src.  See 
 1265: lonhtmlcommon::htmlareaselectactive() for an example.
 1266: 
 1267: =cut
 1268: 
 1269: sub help_open_topic {
 1270:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1271:     $text = "" if (not defined $text);
 1272:     $stayOnPage = 0 if (not defined $stayOnPage);
 1273:     $width = 500 if (not defined $width);
 1274:     $height = 400 if (not defined $height);
 1275:     my $filename = $topic;
 1276:     $filename =~ s/ /_/g;
 1277: 
 1278:     my $template = "";
 1279:     my $link;
 1280:     
 1281:     $topic=~s/\W/\_/g;
 1282: 
 1283:     if (!$stayOnPage) {
 1284: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1285:     } elsif ($stayOnPage eq 'popup') {
 1286:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1287:     } else {
 1288: 	$link = "/adm/help/${filename}.hlp";
 1289:     }
 1290: 
 1291:     # Add the text
 1292:     if ($text ne "") {	
 1293: 	$template.='<span class="LC_help_open_topic">'
 1294:                   .'<a target="_top" href="'.$link.'">'
 1295:                   .$text.'</a>';
 1296:     }
 1297: 
 1298:     # (Always) Add the graphic
 1299:     my $title = &mt('Online Help');
 1300:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1301:     if ($imgid ne '') {
 1302:         $imgid = ' id="'.$imgid.'"';
 1303:     }
 1304:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1305:               .'<img src="'.$helpicon.'" border="0"'
 1306:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1307:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1308:               .' /></a>';
 1309:     if ($text ne "") {	
 1310:         $template.='</span>';
 1311:     }
 1312:     return $template;
 1313: 
 1314: }
 1315: 
 1316: # This is a quicky function for Latex cheatsheet editing, since it 
 1317: # appears in at least four places
 1318: sub helpLatexCheatsheet {
 1319:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1320:     my $out;
 1321:     my $addOther = '';
 1322:     if ($topic) {
 1323: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1324:     }
 1325:     $out = '<span>' # Start cheatsheet
 1326: 	  .$addOther
 1327:           .'<span>'
 1328: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1329: 	  .'</span> <span>'
 1330: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1331: 	  .'</span>';
 1332:     unless ($not_author) {
 1333:         $out .= '<span>'
 1334:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1335:                .'</span> <span>'
 1336:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1337: 	       .'</span>';
 1338:     }
 1339:     $out .= '</span>'; # End cheatsheet
 1340:     return $out;
 1341: }
 1342: 
 1343: sub general_help {
 1344:     my $helptopic='Student_Intro';
 1345:     if ($env{'request.role'}=~/^(ca|au)/) {
 1346: 	$helptopic='Authoring_Intro';
 1347:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1348: 	$helptopic='Course_Coordination_Intro';
 1349:     } elsif ($env{'request.role'}=~/^dc/) {
 1350:         $helptopic='Domain_Coordination_Intro';
 1351:     }
 1352:     return $helptopic;
 1353: }
 1354: 
 1355: sub update_help_link {
 1356:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1357:     my $origurl = $ENV{'REQUEST_URI'};
 1358:     $origurl=~s|^/~|/priv/|;
 1359:     my $timestamp = time;
 1360:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1361:         $$datum = &escape($$datum);
 1362:     }
 1363: 
 1364:     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";
 1365:     my $output .= <<"ENDOUTPUT";
 1366: <script type="text/javascript">
 1367: // <![CDATA[
 1368: banner_link = '$banner_link';
 1369: // ]]>
 1370: </script>
 1371: ENDOUTPUT
 1372:     return $output;
 1373: }
 1374: 
 1375: # now just updates the help link and generates a blue icon
 1376: sub help_open_menu {
 1377:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1378: 	= @_;    
 1379:     $stayOnPage = 1;
 1380:     my $output;
 1381:     if ($component_help) {
 1382: 	if (!$text) {
 1383: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1384: 				       $width,$height);
 1385: 	} else {
 1386: 	    my $help_text;
 1387: 	    $help_text=&unescape($topic);
 1388: 	    $output='<table><tr><td>'.
 1389: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1390: 				 $width,$height).'</td></tr></table>';
 1391: 	}
 1392:     }
 1393:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1394:     return $output.$banner_link;
 1395: }
 1396: 
 1397: sub top_nav_help {
 1398:     my ($text) = @_;
 1399:     $text = &mt($text);
 1400:     my $stay_on_page = 1;
 1401: 
 1402:     my ($link,$banner_link);
 1403:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1404:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1405: 	                         : "javascript:helpMenu('open')";
 1406:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1407:     }
 1408:     my $title = &mt('Get help');
 1409:     if ($link) {
 1410:         return <<"END";
 1411: $banner_link
 1412: <a href="$link" title="$title">$text</a>
 1413: END
 1414:     } else {
 1415:         return '&nbsp;'.$text.'&nbsp;';
 1416:     }
 1417: }
 1418: 
 1419: sub help_menu_js {
 1420:     my ($httphost) = @_;
 1421:     my $stayOnPage = 1;
 1422:     my $width = 620;
 1423:     my $height = 600;
 1424:     my $helptopic=&general_help();
 1425:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1426:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1427:     my $start_page =
 1428:         &Apache::loncommon::start_page('Help Menu', undef,
 1429: 				       {'frameset'    => 1,
 1430: 					'js_ready'    => 1,
 1431:                                         'use_absolute' => $httphost,
 1432: 					'add_entries' => {
 1433: 					    'border' => '0', 
 1434: 					    'rows'   => "110,*",},});
 1435:     my $end_page =
 1436:         &Apache::loncommon::end_page({'frameset' => 1,
 1437: 				      'js_ready' => 1,});
 1438: 
 1439:     my $template .= <<"ENDTEMPLATE";
 1440: <script type="text/javascript">
 1441: // <![CDATA[
 1442: // <!-- BEGIN LON-CAPA Internal
 1443: var banner_link = '';
 1444: function helpMenu(target) {
 1445:     var caller = this;
 1446:     if (target == 'open') {
 1447:         var newWindow = null;
 1448:         try {
 1449:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1450:         }
 1451:         catch(error) {
 1452:             writeHelp(caller);
 1453:             return;
 1454:         }
 1455:         if (newWindow) {
 1456:             caller = newWindow;
 1457:         }
 1458:     }
 1459:     writeHelp(caller);
 1460:     return;
 1461: }
 1462: function writeHelp(caller) {
 1463:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1464:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1465:     caller.document.close();
 1466:     caller.focus();
 1467: }
 1468: // END LON-CAPA Internal -->
 1469: // ]]>
 1470: </script>
 1471: ENDTEMPLATE
 1472:     return $template;
 1473: }
 1474: 
 1475: sub help_open_bug {
 1476:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1477:     unless ($env{'user.adv'}) { return ''; }
 1478:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1479:     $text = "" if (not defined $text);
 1480: 	$stayOnPage=1;
 1481:     $width = 600 if (not defined $width);
 1482:     $height = 600 if (not defined $height);
 1483: 
 1484:     $topic=~s/\W+/\+/g;
 1485:     my $link='';
 1486:     my $template='';
 1487:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1488: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1489:     if (!$stayOnPage)
 1490:     {
 1491: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1492:     }
 1493:     else
 1494:     {
 1495: 	$link = $url;
 1496:     }
 1497:     # Add the text
 1498:     if ($text ne "")
 1499:     {
 1500: 	$template .= 
 1501:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1502:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1503:     }
 1504: 
 1505:     # Add the graphic
 1506:     my $title = &mt('Report a Bug');
 1507:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1508:     $template .= <<"ENDTEMPLATE";
 1509:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1510: ENDTEMPLATE
 1511:     if ($text ne '') { $template.='</td></tr></table>' };
 1512:     return $template;
 1513: 
 1514: }
 1515: 
 1516: sub help_open_faq {
 1517:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1518:     unless ($env{'user.adv'}) { return ''; }
 1519:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1520:     $text = "" if (not defined $text);
 1521: 	$stayOnPage=1;
 1522:     $width = 350 if (not defined $width);
 1523:     $height = 400 if (not defined $height);
 1524: 
 1525:     $topic=~s/\W+/\+/g;
 1526:     my $link='';
 1527:     my $template='';
 1528:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1529:     if (!$stayOnPage)
 1530:     {
 1531: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1532:     }
 1533:     else
 1534:     {
 1535: 	$link = $url;
 1536:     }
 1537: 
 1538:     # Add the text
 1539:     if ($text ne "")
 1540:     {
 1541: 	$template .= 
 1542:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1543:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1544:     }
 1545: 
 1546:     # Add the graphic
 1547:     my $title = &mt('View the FAQ');
 1548:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1549:     $template .= <<"ENDTEMPLATE";
 1550:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1551: ENDTEMPLATE
 1552:     if ($text ne '') { $template.='</td></tr></table>' };
 1553:     return $template;
 1554: 
 1555: }
 1556: 
 1557: ###############################################################
 1558: ###############################################################
 1559: 
 1560: =pod
 1561: 
 1562: =item * &change_content_javascript():
 1563: 
 1564: This and the next function allow you to create small sections of an
 1565: otherwise static HTML page that you can update on the fly with
 1566: Javascript, even in Netscape 4.
 1567: 
 1568: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1569: must be written to the HTML page once. It will prove the Javascript
 1570: function "change(name, content)". Calling the change function with the
 1571: name of the section 
 1572: you want to update, matching the name passed to C<changable_area>, and
 1573: the new content you want to put in there, will put the content into
 1574: that area.
 1575: 
 1576: B<Note>: Netscape 4 only reserves enough space for the changable area
 1577: to contain room for the original contents. You need to "make space"
 1578: for whatever changes you wish to make, and be B<sure> to check your
 1579: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1580: it's adequate for updating a one-line status display, but little more.
 1581: This script will set the space to 100% width, so you only need to
 1582: worry about height in Netscape 4.
 1583: 
 1584: Modern browsers are much less limiting, and if you can commit to the
 1585: user not using Netscape 4, this feature may be used freely with
 1586: pretty much any HTML.
 1587: 
 1588: =cut
 1589: 
 1590: sub change_content_javascript {
 1591:     # If we're on Netscape 4, we need to use Layer-based code
 1592:     if ($env{'browser.type'} eq 'netscape' &&
 1593: 	$env{'browser.version'} =~ /^4\./) {
 1594: 	return (<<NETSCAPE4);
 1595: 	function change(name, content) {
 1596: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1597: 	    doc.open();
 1598: 	    doc.write(content);
 1599: 	    doc.close();
 1600: 	}
 1601: NETSCAPE4
 1602:     } else {
 1603: 	# Otherwise, we need to use semi-standards-compliant code
 1604: 	# (technically, "innerHTML" isn't standard but the equivalent
 1605: 	# is really scary, and every useful browser supports it
 1606: 	return (<<DOMBASED);
 1607: 	function change(name, content) {
 1608: 	    element = document.getElementById(name);
 1609: 	    element.innerHTML = content;
 1610: 	}
 1611: DOMBASED
 1612:     }
 1613: }
 1614: 
 1615: =pod
 1616: 
 1617: =item * &changable_area($name,$origContent):
 1618: 
 1619: This provides a "changable area" that can be modified on the fly via
 1620: the Javascript code provided in C<change_content_javascript>. $name is
 1621: the name you will use to reference the area later; do not repeat the
 1622: same name on a given HTML page more then once. $origContent is what
 1623: the area will originally contain, which can be left blank.
 1624: 
 1625: =cut
 1626: 
 1627: sub changable_area {
 1628:     my ($name, $origContent) = @_;
 1629: 
 1630:     if ($env{'browser.type'} eq 'netscape' &&
 1631: 	$env{'browser.version'} =~ /^4\./) {
 1632: 	# If this is netscape 4, we need to use the Layer tag
 1633: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1634:     } else {
 1635: 	return "<span id='$name'>$origContent</span>";
 1636:     }
 1637: }
 1638: 
 1639: =pod
 1640: 
 1641: =item * &viewport_geometry_js 
 1642: 
 1643: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1644: 
 1645: =cut
 1646: 
 1647: 
 1648: sub viewport_geometry_js { 
 1649:     return <<"GEOMETRY";
 1650: var Geometry = {};
 1651: function init_geometry() {
 1652:     if (Geometry.init) { return };
 1653:     Geometry.init=1;
 1654:     if (window.innerHeight) {
 1655:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1656:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1657:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1658:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1659:     }
 1660:     else if (document.documentElement && document.documentElement.clientHeight) {
 1661:         Geometry.getViewportHeight =
 1662:             function() { return document.documentElement.clientHeight; };
 1663:         Geometry.getViewportWidth =
 1664:             function() { return document.documentElement.clientWidth; };
 1665: 
 1666:         Geometry.getHorizontalScroll =
 1667:             function() { return document.documentElement.scrollLeft; };
 1668:         Geometry.getVerticalScroll =
 1669:             function() { return document.documentElement.scrollTop; };
 1670:     }
 1671:     else if (document.body.clientHeight) {
 1672:         Geometry.getViewportHeight =
 1673:             function() { return document.body.clientHeight; };
 1674:         Geometry.getViewportWidth =
 1675:             function() { return document.body.clientWidth; };
 1676:         Geometry.getHorizontalScroll =
 1677:             function() { return document.body.scrollLeft; };
 1678:         Geometry.getVerticalScroll =
 1679:             function() { return document.body.scrollTop; };
 1680:     }
 1681: }
 1682: 
 1683: GEOMETRY
 1684: }
 1685: 
 1686: =pod
 1687: 
 1688: =item * &viewport_size_js()
 1689: 
 1690: 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. 
 1691: 
 1692: =cut
 1693: 
 1694: sub viewport_size_js {
 1695:     my $geometry = &viewport_geometry_js();
 1696:     return <<"DIMS";
 1697: 
 1698: $geometry
 1699: 
 1700: function getViewportDims(width,height) {
 1701:     init_geometry();
 1702:     width.value = Geometry.getViewportWidth();
 1703:     height.value = Geometry.getViewportHeight();
 1704:     return;
 1705: }
 1706: 
 1707: DIMS
 1708: }
 1709: 
 1710: =pod
 1711: 
 1712: =item * &resize_textarea_js()
 1713: 
 1714: emits the needed javascript to resize a textarea to be as big as possible
 1715: 
 1716: creates a function resize_textrea that takes two IDs first should be
 1717: the id of the element to resize, second should be the id of a div that
 1718: surrounds everything that comes after the textarea, this routine needs
 1719: to be attached to the <body> for the onload and onresize events.
 1720: 
 1721: =back
 1722: 
 1723: =cut
 1724: 
 1725: sub resize_textarea_js {
 1726:     my $geometry = &viewport_geometry_js();
 1727:     return <<"RESIZE";
 1728:     <script type="text/javascript">
 1729: // <![CDATA[
 1730: $geometry
 1731: 
 1732: function getX(element) {
 1733:     var x = 0;
 1734:     while (element) {
 1735: 	x += element.offsetLeft;
 1736: 	element = element.offsetParent;
 1737:     }
 1738:     return x;
 1739: }
 1740: function getY(element) {
 1741:     var y = 0;
 1742:     while (element) {
 1743: 	y += element.offsetTop;
 1744: 	element = element.offsetParent;
 1745:     }
 1746:     return y;
 1747: }
 1748: 
 1749: 
 1750: function resize_textarea(textarea_id,bottom_id) {
 1751:     init_geometry();
 1752:     var textarea        = document.getElementById(textarea_id);
 1753:     //alert(textarea);
 1754: 
 1755:     var textarea_top    = getY(textarea);
 1756:     var textarea_height = textarea.offsetHeight;
 1757:     var bottom          = document.getElementById(bottom_id);
 1758:     var bottom_top      = getY(bottom);
 1759:     var bottom_height   = bottom.offsetHeight;
 1760:     var window_height   = Geometry.getViewportHeight();
 1761:     var fudge           = 23;
 1762:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1763:     if (new_height < 300) {
 1764: 	new_height = 300;
 1765:     }
 1766:     textarea.style.height=new_height+'px';
 1767: }
 1768: // ]]>
 1769: </script>
 1770: RESIZE
 1771: 
 1772: }
 1773: 
 1774: sub colorfuleditor_js {
 1775:     return <<"COLORFULEDIT"
 1776: <script type="text/javascript">
 1777: // <![CDATA[>
 1778:     function fold_box(curDepth, lastresource){
 1779: 
 1780:     // we need a list because there can be several blocks you need to fold in one tag
 1781:         var block = document.getElementsByName('foldblock_'+curDepth);
 1782:     // but there is only one folding button per tag
 1783:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1784: 
 1785:         if(block.item(0).style.display == 'none'){
 1786: 
 1787:             foldbutton.value = '@{[&mt("Hide")]}';
 1788:             for (i = 0; i < block.length; i++){
 1789:                 block.item(i).style.display = '';
 1790:             }
 1791:         }else{
 1792: 
 1793:             foldbutton.value = '@{[&mt("Show")]}';
 1794:             for (i = 0; i < block.length; i++){
 1795:                 // block.item(i).style.visibility = 'collapse';
 1796:                 block.item(i).style.display = 'none';
 1797:             }
 1798:         };
 1799:         saveState(lastresource);
 1800:     }
 1801: 
 1802:     function saveState (lastresource) {
 1803: 
 1804:         var tag_list = getTagList();
 1805:         if(tag_list != null){
 1806:             var timestamp = new Date().getTime();
 1807:             var key = lastresource;
 1808: 
 1809:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1810:             // starting with timestamp
 1811:             var value = timestamp+';';
 1812: 
 1813:             // building the list of key-value pairs
 1814:             for(var i = 0; i < tag_list.length; i++){
 1815:                 value += tag_list[i]+',';
 1816:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1817:             }
 1818: 
 1819:             // only iterate whole storage if nothing to override
 1820:             if(localStorage.getItem(key) == null){        
 1821: 
 1822:                 // prevent storage from growing large
 1823:                 if(localStorage.length > 50){
 1824:                     var regex_getTimestamp = /^(?:\d)+;/;
 1825:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1826:                     var oldest_key;
 1827:                     
 1828:                     for(var i = 1; i < localStorage.length; i++){
 1829:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1830:                             oldest_key = localStorage.key(i);
 1831:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1832:                         }
 1833:                     }
 1834:                     localStorage.removeItem(oldest_key);
 1835:                 }
 1836:             }
 1837:             localStorage.setItem(key,value);
 1838:         }
 1839:     }
 1840: 
 1841:     // restore folding status of blocks (on page load)
 1842:     function restoreState (lastresource) {
 1843:         if(localStorage.getItem(lastresource) != null){
 1844:             var key = lastresource;
 1845:             var value = localStorage.getItem(key);
 1846:             var regex_delTimestamp = /^\d+;/;
 1847: 
 1848:             value.replace(regex_delTimestamp, '');
 1849: 
 1850:             var valueArr = value.split(';');
 1851:             var pairs;
 1852:             var elements;
 1853:             for (var i = 0; i < valueArr.length; i++){
 1854:                 pairs = valueArr[i].split(',');
 1855:                 elements = document.getElementsByName(pairs[0]);
 1856: 
 1857:                 for (var j = 0; j < elements.length; j++){  
 1858:                     elements[j].style.display = pairs[1];
 1859:                     if (pairs[1] == "none"){
 1860:                         var regex_id = /([_\\d]+)\$/;
 1861:                         regex_id.exec(pairs[0]);
 1862:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1863:                     }
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868: 
 1869:     function getTagList () {
 1870:         
 1871:         var stringToSearch = document.lonhomework.innerHTML;
 1872: 
 1873:         var ret = new Array();
 1874:         var regex_findBlock = /(foldblock_.*?)"/g;
 1875:         var tag_list = stringToSearch.match(regex_findBlock);
 1876: 
 1877:         if(tag_list != null){
 1878:             for(var i = 0; i < tag_list.length; i++){            
 1879:                 ret.push(tag_list[i].replace(/"/, ''));
 1880:             }
 1881:         }
 1882:         return ret;
 1883:     }
 1884: 
 1885:     function saveScrollPosition (resource) {
 1886:         var tag_list = getTagList();
 1887: 
 1888:         // we dont always want to jump to the first block
 1889:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1890:         if(\$(window).scrollTop() > 170){
 1891:             if(tag_list != null){
 1892:                 var result;
 1893:                 for(var i = 0; i < tag_list.length; i++){
 1894:                     if(isElementInViewport(tag_list[i])){
 1895:                         result += tag_list[i]+';';
 1896:                     }
 1897:                 }
 1898:                 sessionStorage.setItem('anchor_'+resource, result);
 1899:             }
 1900:         } else {
 1901:             // we dont need to save zero, just delete the item to leave everything tidy
 1902:             sessionStorage.removeItem('anchor_'+resource);
 1903:         }
 1904:     }
 1905: 
 1906:     function restoreScrollPosition(resource){
 1907: 
 1908:         var elem = sessionStorage.getItem('anchor_'+resource);
 1909:         if(elem != null){
 1910:             var tag_list = elem.split(';');
 1911:             var elem_list;
 1912: 
 1913:             for(var i = 0; i < tag_list.length; i++){
 1914:                 elem_list = document.getElementsByName(tag_list[i]);
 1915:                 
 1916:                 if(elem_list.length > 0){
 1917:                     elem = elem_list[0];
 1918:                     break;
 1919:                 }
 1920:             }
 1921:             elem.scrollIntoView();
 1922:         }
 1923:     }
 1924: 
 1925:     function isElementInViewport(el) {
 1926: 
 1927:         // change to last element instead of first
 1928:         var elem = document.getElementsByName(el);
 1929:         var rect = elem[0].getBoundingClientRect();
 1930: 
 1931:         return (
 1932:             rect.top >= 0 &&
 1933:             rect.left >= 0 &&
 1934:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1935:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1936:         );
 1937:     }
 1938:     
 1939:     function autosize(depth){
 1940:         var cmInst = window['cm'+depth];
 1941:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1942: 
 1943:         // is fixed size, switching to dynamic
 1944:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1945:             cmInst.setSize("","auto");
 1946:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1947:             sessionStorage.setItem("autosized_"+depth, "yes");
 1948: 
 1949:         // is dynamic size, switching to fixed
 1950:         } else {
 1951:             cmInst.setSize("","300px");
 1952:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1953:             sessionStorage.removeItem("autosized_"+depth);
 1954:         }
 1955:     }
 1956: 
 1957: 
 1958: 
 1959: // ]]>
 1960: </script>
 1961: COLORFULEDIT
 1962: }
 1963: 
 1964: sub xmleditor_js {
 1965:     return <<XMLEDIT
 1966: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1967: <script type="text/javascript">
 1968: // <![CDATA[>
 1969: 
 1970:     function saveScrollPosition (resource) {
 1971: 
 1972:         var scrollPos = \$(window).scrollTop();
 1973:         sessionStorage.setItem(resource,scrollPos);
 1974:     }
 1975: 
 1976:     function restoreScrollPosition(resource){
 1977: 
 1978:         var scrollPos = sessionStorage.getItem(resource);
 1979:         \$(window).scrollTop(scrollPos);
 1980:     }
 1981: 
 1982:     // unless internet explorer
 1983:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1984: 
 1985:         \$(document).ready(function() {
 1986:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1987:         });
 1988:     }
 1989: 
 1990:     // inserts text at cursor position into codemirror (xml editor only)
 1991:     function insertText(text){
 1992:         cm.focus();
 1993:         var curPos = cm.getCursor();
 1994:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1995:     }
 1996: // ]]>
 1997: </script>
 1998: XMLEDIT
 1999: }
 2000: 
 2001: sub insert_folding_button {
 2002:     my $curDepth = $Apache::lonxml::curdepth;
 2003:     my $lastresource = $env{'request.ambiguous'};
 2004: 
 2005:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2006:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2007: }
 2008: 
 2009: =pod
 2010: 
 2011: =head1 Excel and CSV file utility routines
 2012: 
 2013: =cut
 2014: 
 2015: ###############################################################
 2016: ###############################################################
 2017: 
 2018: =pod
 2019: 
 2020: =over 4
 2021: 
 2022: =item * &csv_translate($text) 
 2023: 
 2024: Translate $text to allow it to be output as a 'comma separated values' 
 2025: format.
 2026: 
 2027: =cut
 2028: 
 2029: ###############################################################
 2030: ###############################################################
 2031: sub csv_translate {
 2032:     my $text = shift;
 2033:     $text =~ s/\"/\"\"/g;
 2034:     $text =~ s/\n/ /g;
 2035:     return $text;
 2036: }
 2037: 
 2038: ###############################################################
 2039: ###############################################################
 2040: 
 2041: =pod
 2042: 
 2043: =item * &define_excel_formats()
 2044: 
 2045: Define some commonly used Excel cell formats.
 2046: 
 2047: Currently supported formats:
 2048: 
 2049: =over 4
 2050: 
 2051: =item header
 2052: 
 2053: =item bold
 2054: 
 2055: =item h1
 2056: 
 2057: =item h2
 2058: 
 2059: =item h3
 2060: 
 2061: =item h4
 2062: 
 2063: =item i
 2064: 
 2065: =item date
 2066: 
 2067: =back
 2068: 
 2069: Inputs: $workbook
 2070: 
 2071: Returns: $format, a hash reference.
 2072: 
 2073: 
 2074: =cut
 2075: 
 2076: ###############################################################
 2077: ###############################################################
 2078: sub define_excel_formats {
 2079:     my ($workbook) = @_;
 2080:     my $format;
 2081:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2082:                                                 bottom    => 1,
 2083:                                                 align     => 'center');
 2084:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2085:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2086:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2087:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2088:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2089:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2090:     $format->{'date'} = $workbook->add_format(num_format=>
 2091:                                             'mm/dd/yyyy hh:mm:ss');
 2092:     return $format;
 2093: }
 2094: 
 2095: ###############################################################
 2096: ###############################################################
 2097: 
 2098: =pod
 2099: 
 2100: =item * &create_workbook()
 2101: 
 2102: Create an Excel worksheet.  If it fails, output message on the
 2103: request object and return undefs.
 2104: 
 2105: Inputs: Apache request object
 2106: 
 2107: Returns (undef) on failure, 
 2108:     Excel worksheet object, scalar with filename, and formats 
 2109:     from &Apache::loncommon::define_excel_formats on success
 2110: 
 2111: =cut
 2112: 
 2113: ###############################################################
 2114: ###############################################################
 2115: sub create_workbook {
 2116:     my ($r) = @_;
 2117:         #
 2118:     # Create the excel spreadsheet
 2119:     my $filename = '/prtspool/'.
 2120:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2121:         time.'_'.rand(1000000000).'.xls';
 2122:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2123:     if (! defined($workbook)) {
 2124:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2125:         $r->print(
 2126:             '<p class="LC_error">'
 2127:            .&mt('Problems occurred in creating the new Excel file.')
 2128:            .' '.&mt('This error has been logged.')
 2129:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2130:            .'</p>'
 2131:         );
 2132:         return (undef);
 2133:     }
 2134:     #
 2135:     $workbook->set_tempdir(LONCAPA::tempdir());
 2136:     #
 2137:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2138:     return ($workbook,$filename,$format);
 2139: }
 2140: 
 2141: ###############################################################
 2142: ###############################################################
 2143: 
 2144: =pod
 2145: 
 2146: =item * &create_text_file()
 2147: 
 2148: Create a file to write to and eventually make available to the user.
 2149: If file creation fails, outputs an error message on the request object and 
 2150: return undefs.
 2151: 
 2152: Inputs: Apache request object, and file suffix
 2153: 
 2154: Returns (undef) on failure, 
 2155:     Filehandle and filename on success.
 2156: 
 2157: =cut
 2158: 
 2159: ###############################################################
 2160: ###############################################################
 2161: sub create_text_file {
 2162:     my ($r,$suffix) = @_;
 2163:     if (! defined($suffix)) { $suffix = 'txt'; };
 2164:     my $fh;
 2165:     my $filename = '/prtspool/'.
 2166:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2167:         time.'_'.rand(1000000000).'.'.$suffix;
 2168:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2169:     if (! defined($fh)) {
 2170:         $r->log_error("Couldn't open $filename for output $!");
 2171:         $r->print(
 2172:             '<p class="LC_error">'
 2173:            .&mt('Problems occurred in creating the output file.')
 2174:            .' '.&mt('This error has been logged.')
 2175:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2176:            .'</p>'
 2177:         );
 2178:     }
 2179:     return ($fh,$filename)
 2180: }
 2181: 
 2182: 
 2183: =pod 
 2184: 
 2185: =back
 2186: 
 2187: =cut
 2188: 
 2189: ###############################################################
 2190: ##        Home server <option> list generating code          ##
 2191: ###############################################################
 2192: 
 2193: # ------------------------------------------
 2194: 
 2195: sub domain_select {
 2196:     my ($name,$value,$multiple)=@_;
 2197:     my %domains=map { 
 2198: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2199:     } &Apache::lonnet::all_domains();
 2200:     if ($multiple) {
 2201: 	$domains{''}=&mt('Any domain');
 2202: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2203: 	return &multiple_select_form($name,$value,4,\%domains);
 2204:     } else {
 2205: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2206: 	return &select_form($name,$value,\%domains);
 2207:     }
 2208: }
 2209: 
 2210: #-------------------------------------------
 2211: 
 2212: =pod
 2213: 
 2214: =head1 Routines for form select boxes
 2215: 
 2216: =over 4
 2217: 
 2218: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2219: 
 2220: Returns a string containing a <select> element int multiple mode
 2221: 
 2222: 
 2223: Args:
 2224:   $name - name of the <select> element
 2225:   $value - scalar or array ref of values that should already be selected
 2226:   $size - number of rows long the select element is
 2227:   $hash - the elements should be 'option' => 'shown text'
 2228:           (shown text should already have been &mt())
 2229:   $order - (optional) array ref of the order to show the elements in
 2230: 
 2231: =cut
 2232: 
 2233: #-------------------------------------------
 2234: sub multiple_select_form {
 2235:     my ($name,$value,$size,$hash,$order)=@_;
 2236:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2237:     my $output='';
 2238:     if (! defined($size)) {
 2239:         $size = 4;
 2240:         if (scalar(keys(%$hash))<4) {
 2241:             $size = scalar(keys(%$hash));
 2242:         }
 2243:     }
 2244:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2245:     my @order;
 2246:     if (ref($order) eq 'ARRAY')  {
 2247:         @order = @{$order};
 2248:     } else {
 2249:         @order = sort(keys(%$hash));
 2250:     }
 2251:     if (exists($$hash{'select_form_order'})) {
 2252:         @order = @{$$hash{'select_form_order'}};
 2253:     }
 2254:         
 2255:     foreach my $key (@order) {
 2256:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2257:         $output.='selected="selected" ' if ($selected{$key});
 2258:         $output.='>'.$hash->{$key}."</option>\n";
 2259:     }
 2260:     $output.="</select>\n";
 2261:     return $output;
 2262: }
 2263: 
 2264: #-------------------------------------------
 2265: 
 2266: =pod
 2267: 
 2268: =item * &select_form($defdom,$name,$hashref,$onchange)
 2269: 
 2270: Returns a string containing a <select name='$name' size='1'> form to 
 2271: allow a user to select options from a ref to a hash containing:
 2272: option_name => displayed text. An optional $onchange can include
 2273: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2274: 
 2275: See lonrights.pm for an example invocation and use.
 2276: 
 2277: =cut
 2278: 
 2279: #-------------------------------------------
 2280: sub select_form {
 2281:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2282:     return unless (ref($hashref) eq 'HASH');
 2283:     if ($onchange) {
 2284:         $onchange = ' onchange="'.$onchange.'"';
 2285:     }
 2286:     my $disabled;
 2287:     if ($readonly) {
 2288:         $disabled = ' disabled="disabled"';
 2289:     }
 2290:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2291:     my @keys;
 2292:     if (exists($hashref->{'select_form_order'})) {
 2293: 	@keys=@{$hashref->{'select_form_order'}};
 2294:     } else {
 2295: 	@keys=sort(keys(%{$hashref}));
 2296:     }
 2297:     foreach my $key (@keys) {
 2298:         $selectform.=
 2299: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2300:             ($key eq $def ? 'selected="selected" ' : '').
 2301:                 ">".$hashref->{$key}."</option>\n";
 2302:     }
 2303:     $selectform.="</select>";
 2304:     return $selectform;
 2305: }
 2306: 
 2307: # For display filters
 2308: 
 2309: sub display_filter {
 2310:     my ($context) = @_;
 2311:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2312:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2313:     my $phraseinput = 'hidden';
 2314:     my $includeinput = 'hidden';
 2315:     my ($checked,$includetypestext);
 2316:     if ($env{'form.displayfilter'} eq 'containing') {
 2317:         $phraseinput = 'text'; 
 2318:         if ($context eq 'parmslog') {
 2319:             $includeinput = 'checkbox';
 2320:             if ($env{'form.includetypes'}) {
 2321:                 $checked = ' checked="checked"';
 2322:             }
 2323:             $includetypestext = &mt('Include parameter types');
 2324:         }
 2325:     } else {
 2326:         $includetypestext = '&nbsp;';
 2327:     }
 2328:     my ($additional,$secondid,$thirdid);
 2329:     if ($context eq 'parmslog') {
 2330:         $additional = 
 2331:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2332:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2333:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2334:             '</label>';
 2335:         $secondid = 'includetypes';
 2336:         $thirdid = 'includetypestext';
 2337:     }
 2338:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2339:                                                     '$secondid','$thirdid')";
 2340:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2341: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2342: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2343: 	   '</label></span> <span class="LC_nobreak">'.
 2344:            &mt('Filter: [_1]',
 2345: 	   &select_form($env{'form.displayfilter'},
 2346: 			'displayfilter',
 2347: 			{'currentfolder' => 'Current folder/page',
 2348: 			 'containing' => 'Containing phrase',
 2349: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2350: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2351:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2352:                          '" />'.$additional;
 2353: }
 2354: 
 2355: sub display_filter_js {
 2356:     my $includetext = &mt('Include parameter types');
 2357:     return <<"ENDJS";
 2358:   
 2359: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2360:     var firstType = 'hidden';
 2361:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2362:         firstType = 'text';
 2363:     }
 2364:     firstObject = document.getElementById(firstid);
 2365:     if (typeof(firstObject) == 'object') {
 2366:         if (firstObject.type != firstType) {
 2367:             changeInputType(firstObject,firstType);
 2368:         }
 2369:     }
 2370:     if (context == 'parmslog') {
 2371:         var secondType = 'hidden';
 2372:         if (firstType == 'text') {
 2373:             secondType = 'checkbox';
 2374:         }
 2375:         secondObject = document.getElementById(secondid);  
 2376:         if (typeof(secondObject) == 'object') {
 2377:             if (secondObject.type != secondType) {
 2378:                 changeInputType(secondObject,secondType);
 2379:             }
 2380:         }
 2381:         var textItem = document.getElementById(thirdid);
 2382:         var currtext = textItem.innerHTML;
 2383:         var newtext;
 2384:         if (firstType == 'text') {
 2385:             newtext = '$includetext';
 2386:         } else {
 2387:             newtext = '&nbsp;';
 2388:         }
 2389:         if (currtext != newtext) {
 2390:             textItem.innerHTML = newtext;
 2391:         }
 2392:     }
 2393:     return;
 2394: }
 2395: 
 2396: function changeInputType(oldObject,newType) {
 2397:     var newObject = document.createElement('input');
 2398:     newObject.type = newType;
 2399:     if (oldObject.size) {
 2400:         newObject.size = oldObject.size;
 2401:     }
 2402:     if (oldObject.value) {
 2403:         newObject.value = oldObject.value;
 2404:     }
 2405:     if (oldObject.name) {
 2406:         newObject.name = oldObject.name;
 2407:     }
 2408:     if (oldObject.id) {
 2409:         newObject.id = oldObject.id;
 2410:     }
 2411:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2412:     return;
 2413: }
 2414: 
 2415: ENDJS
 2416: }
 2417: 
 2418: sub gradeleveldescription {
 2419:     my $gradelevel=shift;
 2420:     my %gradelevels=(0 => 'Not specified',
 2421: 		     1 => 'Grade 1',
 2422: 		     2 => 'Grade 2',
 2423: 		     3 => 'Grade 3',
 2424: 		     4 => 'Grade 4',
 2425: 		     5 => 'Grade 5',
 2426: 		     6 => 'Grade 6',
 2427: 		     7 => 'Grade 7',
 2428: 		     8 => 'Grade 8',
 2429: 		     9 => 'Grade 9',
 2430: 		     10 => 'Grade 10',
 2431: 		     11 => 'Grade 11',
 2432: 		     12 => 'Grade 12',
 2433: 		     13 => 'Grade 13',
 2434: 		     14 => '100 Level',
 2435: 		     15 => '200 Level',
 2436: 		     16 => '300 Level',
 2437: 		     17 => '400 Level',
 2438: 		     18 => 'Graduate Level');
 2439:     return &mt($gradelevels{$gradelevel});
 2440: }
 2441: 
 2442: sub select_level_form {
 2443:     my ($deflevel,$name)=@_;
 2444:     unless ($deflevel) { $deflevel=0; }
 2445:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2446:     for (my $i=0; $i<=18; $i++) {
 2447:         $selectform.="<option value=\"$i\" ".
 2448:             ($i==$deflevel ? 'selected="selected" ' : '').
 2449:                 ">".&gradeleveldescription($i)."</option>\n";
 2450:     }
 2451:     $selectform.="</select>";
 2452:     return $selectform;
 2453: }
 2454: 
 2455: #-------------------------------------------
 2456: 
 2457: =pod
 2458: 
 2459: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2460: 
 2461: Returns a string containing a <select name='$name' size='1'> form to 
 2462: allow a user to select the domain to preform an operation in.  
 2463: See loncreateuser.pm for an example invocation and use.
 2464: 
 2465: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2466: selected");
 2467: 
 2468: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2469: 
 2470: 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.
 2471: 
 2472: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2473: 
 2474: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2475: 
 2476: =cut
 2477: 
 2478: #-------------------------------------------
 2479: sub select_dom_form {
 2480:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2481:     if ($onchange) {
 2482:         $onchange = ' onchange="'.$onchange.'"';
 2483:     }
 2484:     my (@domains,%exclude);
 2485:     if (ref($incdoms) eq 'ARRAY') {
 2486:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2487:     } else {
 2488:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2489:     }
 2490:     if ($includeempty) { @domains=('',@domains); }
 2491:     if (ref($excdoms) eq 'ARRAY') {
 2492:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2493:     }
 2494:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2495:     foreach my $dom (@domains) {
 2496:         next if ($exclude{$dom});
 2497:         $selectdomain.="<option value=\"$dom\" ".
 2498:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2499:         if ($showdomdesc) {
 2500:             if ($dom ne '') {
 2501:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2502:                 if ($domdesc ne '') {
 2503:                     $selectdomain .= ' ('.$domdesc.')';
 2504:                 }
 2505:             } 
 2506:         }
 2507:         $selectdomain .= "</option>\n";
 2508:     }
 2509:     $selectdomain.="</select>";
 2510:     return $selectdomain;
 2511: }
 2512: 
 2513: #-------------------------------------------
 2514: 
 2515: =pod
 2516: 
 2517: =item * &home_server_form_item($domain,$name,$defaultflag)
 2518: 
 2519: input: 4 arguments (two required, two optional) - 
 2520:     $domain - domain of new user
 2521:     $name - name of form element
 2522:     $default - Value of 'default' causes a default item to be first 
 2523:                             option, and selected by default. 
 2524:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2525:                             if 1 server found, or default, if 0 found.
 2526: output: returns 2 items: 
 2527: (a) form element which contains either:
 2528:    (i) <select name="$name">
 2529:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2530:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2531:        </select>
 2532:        form item if there are multiple library servers in $domain, or
 2533:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2534:        if there is only one library server in $domain.
 2535: 
 2536: (b) number of library servers found.
 2537: 
 2538: See loncreateuser.pm for example of use.
 2539: 
 2540: =cut
 2541: 
 2542: #-------------------------------------------
 2543: sub home_server_form_item {
 2544:     my ($domain,$name,$default,$hide) = @_;
 2545:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2546:     my $result;
 2547:     my $numlib = keys(%servers);
 2548:     if ($numlib > 1) {
 2549:         $result .= '<select name="'.$name.'" />'."\n";
 2550:         if ($default) {
 2551:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2552:                        '</option>'."\n";
 2553:         }
 2554:         foreach my $hostid (sort(keys(%servers))) {
 2555:             $result.= '<option value="'.$hostid.'">'.
 2556: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2557:         }
 2558:         $result .= '</select>'."\n";
 2559:     } elsif ($numlib == 1) {
 2560:         my $hostid;
 2561:         foreach my $item (keys(%servers)) {
 2562:             $hostid = $item;
 2563:         }
 2564:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2565:                    $hostid.'" />';
 2566:                    if (!$hide) {
 2567:                        $result .= $hostid.' '.$servers{$hostid};
 2568:                    }
 2569:                    $result .= "\n";
 2570:     } elsif ($default) {
 2571:         $result .= '<input type="hidden" name="'.$name.
 2572:                    '" value="default" />';
 2573:                    if (!$hide) {
 2574:                        $result .= &mt('default');
 2575:                    }
 2576:                    $result .= "\n";
 2577:     }
 2578:     return ($result,$numlib);
 2579: }
 2580: 
 2581: =pod
 2582: 
 2583: =back 
 2584: 
 2585: =cut
 2586: 
 2587: ###############################################################
 2588: ##                  Decoding User Agent                      ##
 2589: ###############################################################
 2590: 
 2591: =pod
 2592: 
 2593: =head1 Decoding the User Agent
 2594: 
 2595: =over 4
 2596: 
 2597: =item * &decode_user_agent()
 2598: 
 2599: Inputs: $r
 2600: 
 2601: Outputs:
 2602: 
 2603: =over 4
 2604: 
 2605: =item * $httpbrowser
 2606: 
 2607: =item * $clientbrowser
 2608: 
 2609: =item * $clientversion
 2610: 
 2611: =item * $clientmathml
 2612: 
 2613: =item * $clientunicode
 2614: 
 2615: =item * $clientos
 2616: 
 2617: =item * $clientmobile
 2618: 
 2619: =item * $clientinfo
 2620: 
 2621: =item * $clientosversion
 2622: 
 2623: =back
 2624: 
 2625: =back 
 2626: 
 2627: =cut
 2628: 
 2629: ###############################################################
 2630: ###############################################################
 2631: sub decode_user_agent {
 2632:     my ($r)=@_;
 2633:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2634:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2635:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2636:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2637:     my $clientbrowser='unknown';
 2638:     my $clientversion='0';
 2639:     my $clientmathml='';
 2640:     my $clientunicode='0';
 2641:     my $clientmobile=0;
 2642:     my $clientosversion='';
 2643:     for (my $i=0;$i<=$#browsertype;$i++) {
 2644:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2645: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2646: 	    $clientbrowser=$bname;
 2647:             $httpbrowser=~/$vreg/i;
 2648: 	    $clientversion=$1;
 2649:             $clientmathml=($clientversion>=$minv);
 2650:             $clientunicode=($clientversion>=$univ);
 2651: 	}
 2652:     }
 2653:     my $clientos='unknown';
 2654:     my $clientinfo;
 2655:     if (($httpbrowser=~/linux/i) ||
 2656:         ($httpbrowser=~/unix/i) ||
 2657:         ($httpbrowser=~/ux/i) ||
 2658:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2659:     if (($httpbrowser=~/vax/i) ||
 2660:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2661:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2662:     if (($httpbrowser=~/mac/i) ||
 2663:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2664:     if ($httpbrowser=~/win/i) {
 2665:         $clientos='win';
 2666:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2667:             $clientosversion = $1;
 2668:         }
 2669:     }
 2670:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2671:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2672:         $clientmobile=lc($1);
 2673:     }
 2674:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2675:         $clientinfo = 'firefox-'.$1;
 2676:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2677:         $clientinfo = 'chromeframe-'.$1;
 2678:     }
 2679:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2680:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2681:             $clientosversion);
 2682: }
 2683: 
 2684: ###############################################################
 2685: ##    Authentication changing form generation subroutines    ##
 2686: ###############################################################
 2687: ##
 2688: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2689: ## hash, and have reasonable default values.
 2690: ##
 2691: ##    formname = the name given in the <form> tag.
 2692: #-------------------------------------------
 2693: 
 2694: =pod
 2695: 
 2696: =head1 Authentication Routines
 2697: 
 2698: =over 4
 2699: 
 2700: =item * &authform_xxxxxx()
 2701: 
 2702: The authform_xxxxxx subroutines provide javascript and html forms which 
 2703: handle some of the conveniences required for authentication forms.  
 2704: This is not an optimal method, but it works.  
 2705: 
 2706: =over 4
 2707: 
 2708: =item * authform_header
 2709: 
 2710: =item * authform_authorwarning
 2711: 
 2712: =item * authform_nochange
 2713: 
 2714: =item * authform_kerberos
 2715: 
 2716: =item * authform_internal
 2717: 
 2718: =item * authform_filesystem
 2719: 
 2720: =back
 2721: 
 2722: See loncreateuser.pm for invocation and use examples.
 2723: 
 2724: =cut
 2725: 
 2726: #-------------------------------------------
 2727: sub authform_header{  
 2728:     my %in = (
 2729:         formname => 'cu',
 2730:         kerb_def_dom => '',
 2731:         @_,
 2732:     );
 2733:     $in{'formname'} = 'document.' . $in{'formname'};
 2734:     my $result='';
 2735: 
 2736: #---------------------------------------------- Code for upper case translation
 2737:     my $Javascript_toUpperCase;
 2738:     unless ($in{kerb_def_dom}) {
 2739:         $Javascript_toUpperCase =<<"END";
 2740:         switch (choice) {
 2741:            case 'krb': currentform.elements[choicearg].value =
 2742:                currentform.elements[choicearg].value.toUpperCase();
 2743:                break;
 2744:            default:
 2745:         }
 2746: END
 2747:     } else {
 2748:         $Javascript_toUpperCase = "";
 2749:     }
 2750: 
 2751:     my $radioval = "'nochange'";
 2752:     if (defined($in{'curr_authtype'})) {
 2753:         if ($in{'curr_authtype'} ne '') {
 2754:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2755:         }
 2756:     }
 2757:     my $argfield = 'null';
 2758:     if (defined($in{'mode'})) {
 2759:         if ($in{'mode'} eq 'modifycourse')  {
 2760:             if (defined($in{'curr_autharg'})) {
 2761:                 if ($in{'curr_autharg'} ne '') {
 2762:                     $argfield = "'$in{'curr_autharg'}'";
 2763:                 }
 2764:             }
 2765:         }
 2766:     }
 2767: 
 2768:     $result.=<<"END";
 2769: var current = new Object();
 2770: current.radiovalue = $radioval;
 2771: current.argfield = $argfield;
 2772: 
 2773: function changed_radio(choice,currentform) {
 2774:     var choicearg = choice + 'arg';
 2775:     // If a radio button in changed, we need to change the argfield
 2776:     if (current.radiovalue != choice) {
 2777:         current.radiovalue = choice;
 2778:         if (current.argfield != null) {
 2779:             currentform.elements[current.argfield].value = '';
 2780:         }
 2781:         if (choice == 'nochange') {
 2782:             current.argfield = null;
 2783:         } else {
 2784:             current.argfield = choicearg;
 2785:             switch(choice) {
 2786:                 case 'krb': 
 2787:                     currentform.elements[current.argfield].value = 
 2788:                         "$in{'kerb_def_dom'}";
 2789:                 break;
 2790:               default:
 2791:                 break;
 2792:             }
 2793:         }
 2794:     }
 2795:     return;
 2796: }
 2797: 
 2798: function changed_text(choice,currentform) {
 2799:     var choicearg = choice + 'arg';
 2800:     if (currentform.elements[choicearg].value !='') {
 2801:         $Javascript_toUpperCase
 2802:         // clear old field
 2803:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2804:             currentform.elements[current.argfield].value = '';
 2805:         }
 2806:         current.argfield = choicearg;
 2807:     }
 2808:     set_auth_radio_buttons(choice,currentform);
 2809:     return;
 2810: }
 2811: 
 2812: function set_auth_radio_buttons(newvalue,currentform) {
 2813:     var numauthchoices = currentform.login.length;
 2814:     if (typeof numauthchoices  == "undefined") {
 2815:         return;
 2816:     } 
 2817:     var i=0;
 2818:     while (i < numauthchoices) {
 2819:         if (currentform.login[i].value == newvalue) { break; }
 2820:         i++;
 2821:     }
 2822:     if (i == numauthchoices) {
 2823:         return;
 2824:     }
 2825:     current.radiovalue = newvalue;
 2826:     currentform.login[i].checked = true;
 2827:     return;
 2828: }
 2829: END
 2830:     return $result;
 2831: }
 2832: 
 2833: sub authform_authorwarning {
 2834:     my $result='';
 2835:     $result='<i>'.
 2836:         &mt('As a general rule, only authors or co-authors should be '.
 2837:             'filesystem authenticated '.
 2838:             '(which allows access to the server filesystem).')."</i>\n";
 2839:     return $result;
 2840: }
 2841: 
 2842: sub authform_nochange {
 2843:     my %in = (
 2844:               formname => 'document.cu',
 2845:               kerb_def_dom => 'MSU.EDU',
 2846:               @_,
 2847:           );
 2848:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2849:     my $result;
 2850:     if (!$authnum) {
 2851:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2852:     } else {
 2853:         $result = '<label>'.&mt('[_1] Do not change login data',
 2854:                   '<input type="radio" name="login" value="nochange" '.
 2855:                   'checked="checked" onclick="'.
 2856:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2857: 	    '</label>';
 2858:     }
 2859:     return $result;
 2860: }
 2861: 
 2862: sub authform_kerberos {
 2863:     my %in = (
 2864:               formname => 'document.cu',
 2865:               kerb_def_dom => 'MSU.EDU',
 2866:               kerb_def_auth => 'krb4',
 2867:               @_,
 2868:               );
 2869:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2870:         $autharg,$jscall);
 2871:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2872:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2873:        $check5 = ' checked="checked"';
 2874:     } else {
 2875:        $check4 = ' checked="checked"';
 2876:     }
 2877:     $krbarg = $in{'kerb_def_dom'};
 2878:     if (defined($in{'curr_authtype'})) {
 2879:         if ($in{'curr_authtype'} eq 'krb') {
 2880:             $krbcheck = ' checked="checked"';
 2881:             if (defined($in{'mode'})) {
 2882:                 if ($in{'mode'} eq 'modifyuser') {
 2883:                     $krbcheck = '';
 2884:                 }
 2885:             }
 2886:             if (defined($in{'curr_kerb_ver'})) {
 2887:                 if ($in{'curr_krb_ver'} eq '5') {
 2888:                     $check5 = ' checked="checked"';
 2889:                     $check4 = '';
 2890:                 } else {
 2891:                     $check4 = ' checked="checked"';
 2892:                     $check5 = '';
 2893:                 }
 2894:             }
 2895:             if (defined($in{'curr_autharg'})) {
 2896:                 $krbarg = $in{'curr_autharg'};
 2897:             }
 2898:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2899:                 if (defined($in{'curr_autharg'})) {
 2900:                     $result = 
 2901:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2902:         $in{'curr_autharg'},$krbver);
 2903:                 } else {
 2904:                     $result =
 2905:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2906:                 }
 2907:                 return $result; 
 2908:             }
 2909:         }
 2910:     } else {
 2911:         if ($authnum == 1) {
 2912:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2913:         }
 2914:     }
 2915:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2916:         return;
 2917:     } elsif ($authtype eq '') {
 2918:         if (defined($in{'mode'})) {
 2919:             if ($in{'mode'} eq 'modifycourse') {
 2920:                 if ($authnum == 1) {
 2921:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2922:                 }
 2923:             }
 2924:         }
 2925:     }
 2926:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2927:     if ($authtype eq '') {
 2928:         $authtype = '<input type="radio" name="login" value="krb" '.
 2929:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2930:                     $krbcheck.' />';
 2931:     }
 2932:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2933:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2934:          $in{'curr_authtype'} eq 'krb5') ||
 2935:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2936:          $in{'curr_authtype'} eq 'krb4')) {
 2937:         $result .= &mt
 2938:         ('[_1] Kerberos authenticated with domain [_2] '.
 2939:          '[_3] Version 4 [_4] Version 5 [_5]',
 2940:          '<label>'.$authtype,
 2941:          '</label><input type="text" size="10" name="krbarg" '.
 2942:              'value="'.$krbarg.'" '.
 2943:              'onchange="'.$jscall.'" />',
 2944:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2945:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2946: 	 '</label>');
 2947:     } elsif ($can_assign{'krb4'}) {
 2948:         $result .= &mt
 2949:         ('[_1] Kerberos authenticated with domain [_2] '.
 2950:          '[_3] Version 4 [_4]',
 2951:          '<label>'.$authtype,
 2952:          '</label><input type="text" size="10" name="krbarg" '.
 2953:              'value="'.$krbarg.'" '.
 2954:              'onchange="'.$jscall.'" />',
 2955:          '<label><input type="hidden" name="krbver" value="4" />',
 2956:          '</label>');
 2957:     } elsif ($can_assign{'krb5'}) {
 2958:         $result .= &mt
 2959:         ('[_1] Kerberos authenticated with domain [_2] '.
 2960:          '[_3] Version 5 [_4]',
 2961:          '<label>'.$authtype,
 2962:          '</label><input type="text" size="10" name="krbarg" '.
 2963:              'value="'.$krbarg.'" '.
 2964:              'onchange="'.$jscall.'" />',
 2965:          '<label><input type="hidden" name="krbver" value="5" />',
 2966:          '</label>');
 2967:     }
 2968:     return $result;
 2969: }
 2970: 
 2971: sub authform_internal {
 2972:     my %in = (
 2973:                 formname => 'document.cu',
 2974:                 kerb_def_dom => 'MSU.EDU',
 2975:                 @_,
 2976:                 );
 2977:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2978:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2979:     if (defined($in{'curr_authtype'})) {
 2980:         if ($in{'curr_authtype'} eq 'int') {
 2981:             if ($can_assign{'int'}) {
 2982:                 $intcheck = 'checked="checked" ';
 2983:                 if (defined($in{'mode'})) {
 2984:                     if ($in{'mode'} eq 'modifyuser') {
 2985:                         $intcheck = '';
 2986:                     }
 2987:                 }
 2988:                 if (defined($in{'curr_autharg'})) {
 2989:                     $intarg = $in{'curr_autharg'};
 2990:                 }
 2991:             } else {
 2992:                 $result = &mt('Currently internally authenticated.');
 2993:                 return $result;
 2994:             }
 2995:         }
 2996:     } else {
 2997:         if ($authnum == 1) {
 2998:             $authtype = '<input type="hidden" name="login" value="int" />';
 2999:         }
 3000:     }
 3001:     if (!$can_assign{'int'}) {
 3002:         return;
 3003:     } elsif ($authtype eq '') {
 3004:         if (defined($in{'mode'})) {
 3005:             if ($in{'mode'} eq 'modifycourse') {
 3006:                 if ($authnum == 1) {
 3007:                     $authtype = '<input type="radio" name="login" value="int" />';
 3008:                 }
 3009:             }
 3010:         }
 3011:     }
 3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3013:     if ($authtype eq '') {
 3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 3016:     }
 3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3018:                $intarg.'" onchange="'.$jscall.'" />';
 3019:     $result = &mt
 3020:         ('[_1] Internally authenticated (with initial password [_2])',
 3021:          '<label>'.$authtype,'</label>'.$autharg);
 3022:     $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>';
 3023:     return $result;
 3024: }
 3025: 
 3026: sub authform_local {
 3027:     my %in = (
 3028:               formname => 'document.cu',
 3029:               kerb_def_dom => 'MSU.EDU',
 3030:               @_,
 3031:               );
 3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3034:     if (defined($in{'curr_authtype'})) {
 3035:         if ($in{'curr_authtype'} eq 'loc') {
 3036:             if ($can_assign{'loc'}) {
 3037:                 $loccheck = 'checked="checked" ';
 3038:                 if (defined($in{'mode'})) {
 3039:                     if ($in{'mode'} eq 'modifyuser') {
 3040:                         $loccheck = '';
 3041:                     }
 3042:                 }
 3043:                 if (defined($in{'curr_autharg'})) {
 3044:                     $locarg = $in{'curr_autharg'};
 3045:                 }
 3046:             } else {
 3047:                 $result = &mt('Currently using local (institutional) authentication.');
 3048:                 return $result;
 3049:             }
 3050:         }
 3051:     } else {
 3052:         if ($authnum == 1) {
 3053:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3054:         }
 3055:     }
 3056:     if (!$can_assign{'loc'}) {
 3057:         return;
 3058:     } elsif ($authtype eq '') {
 3059:         if (defined($in{'mode'})) {
 3060:             if ($in{'mode'} eq 'modifycourse') {
 3061:                 if ($authnum == 1) {
 3062:                     $authtype = '<input type="radio" name="login" value="loc" />';
 3063:                 }
 3064:             }
 3065:         }
 3066:     }
 3067:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3068:     if ($authtype eq '') {
 3069:         $authtype = '<input type="radio" name="login" value="loc" '.
 3070:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3071:                     $jscall.'" />';
 3072:     }
 3073:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3074:                $locarg.'" onchange="'.$jscall.'" />';
 3075:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3076:                   '<label>'.$authtype,'</label>'.$autharg);
 3077:     return $result;
 3078: }
 3079: 
 3080: sub authform_filesystem {
 3081:     my %in = (
 3082:               formname => 'document.cu',
 3083:               kerb_def_dom => 'MSU.EDU',
 3084:               @_,
 3085:               );
 3086:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 3087:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3088:     if (defined($in{'curr_authtype'})) {
 3089:         if ($in{'curr_authtype'} eq 'fsys') {
 3090:             if ($can_assign{'fsys'}) {
 3091:                 $fsyscheck = 'checked="checked" ';
 3092:                 if (defined($in{'mode'})) {
 3093:                     if ($in{'mode'} eq 'modifyuser') {
 3094:                         $fsyscheck = '';
 3095:                     }
 3096:                 }
 3097:             } else {
 3098:                 $result = &mt('Currently Filesystem Authenticated.');
 3099:                 return $result;
 3100:             }           
 3101:         }
 3102:     } else {
 3103:         if ($authnum == 1) {
 3104:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3105:         }
 3106:     }
 3107:     if (!$can_assign{'fsys'}) {
 3108:         return;
 3109:     } elsif ($authtype eq '') {
 3110:         if (defined($in{'mode'})) {
 3111:             if ($in{'mode'} eq 'modifycourse') {
 3112:                 if ($authnum == 1) {
 3113:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 3114:                 }
 3115:             }
 3116:         }
 3117:     }
 3118:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3119:     if ($authtype eq '') {
 3120:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3121:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3122:                     $jscall.'" />';
 3123:     }
 3124:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3125:                ' onchange="'.$jscall.'" />';
 3126:     $result = &mt
 3127:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3128:          '<label><input type="radio" name="login" value="fsys" '.
 3129:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 3130:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3131:                   'onchange="'.$jscall.'" />');
 3132:     return $result;
 3133: }
 3134: 
 3135: sub get_assignable_auth {
 3136:     my ($dom) = @_;
 3137:     if ($dom eq '') {
 3138:         $dom = $env{'request.role.domain'};
 3139:     }
 3140:     my %can_assign = (
 3141:                           krb4 => 1,
 3142:                           krb5 => 1,
 3143:                           int  => 1,
 3144:                           loc  => 1,
 3145:                      );
 3146:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3147:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3148:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3149:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3150:             my $context;
 3151:             if ($env{'request.role'} =~ /^au/) {
 3152:                 $context = 'author';
 3153:             } elsif ($env{'request.role'} =~ /^dc/) {
 3154:                 $context = 'domain';
 3155:             } elsif ($env{'request.course.id'}) {
 3156:                 $context = 'course';
 3157:             }
 3158:             if ($context) {
 3159:                 if (ref($authhash->{$context}) eq 'HASH') {
 3160:                    %can_assign = %{$authhash->{$context}}; 
 3161:                 }
 3162:             }
 3163:         }
 3164:     }
 3165:     my $authnum = 0;
 3166:     foreach my $key (keys(%can_assign)) {
 3167:         if ($can_assign{$key}) {
 3168:             $authnum ++;
 3169:         }
 3170:     }
 3171:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3172:         $authnum --;
 3173:     }
 3174:     return ($authnum,%can_assign);
 3175: }
 3176: 
 3177: ###############################################################
 3178: ##    Get Kerberos Defaults for Domain                 ##
 3179: ###############################################################
 3180: ##
 3181: ## Returns default kerberos version and an associated argument
 3182: ## as listed in file domain.tab. If not listed, provides
 3183: ## appropriate default domain and kerberos version.
 3184: ##
 3185: #-------------------------------------------
 3186: 
 3187: =pod
 3188: 
 3189: =item * &get_kerberos_defaults()
 3190: 
 3191: get_kerberos_defaults($target_domain) returns the default kerberos
 3192: version and domain. If not found, it defaults to version 4 and the 
 3193: domain of the server.
 3194: 
 3195: =over 4
 3196: 
 3197: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3198: 
 3199: =back
 3200: 
 3201: =back
 3202: 
 3203: =cut
 3204: 
 3205: #-------------------------------------------
 3206: sub get_kerberos_defaults {
 3207:     my $domain=shift;
 3208:     my ($krbdef,$krbdefdom);
 3209:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3210:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3211:         $krbdef = $domdefaults{'auth_def'};
 3212:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3213:     } else {
 3214:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3215:         my $krbdefdom=$1;
 3216:         $krbdefdom=~tr/a-z/A-Z/;
 3217:         $krbdef = "krb4";
 3218:     }
 3219:     return ($krbdef,$krbdefdom);
 3220: }
 3221: 
 3222: 
 3223: ###############################################################
 3224: ##                Thesaurus Functions                        ##
 3225: ###############################################################
 3226: 
 3227: =pod
 3228: 
 3229: =head1 Thesaurus Functions
 3230: 
 3231: =over 4
 3232: 
 3233: =item * &initialize_keywords()
 3234: 
 3235: Initializes the package variable %Keywords if it is empty.  Uses the
 3236: package variable $thesaurus_db_file.
 3237: 
 3238: =cut
 3239: 
 3240: ###################################################
 3241: 
 3242: sub initialize_keywords {
 3243:     return 1 if (scalar keys(%Keywords));
 3244:     # If we are here, %Keywords is empty, so fill it up
 3245:     #   Make sure the file we need exists...
 3246:     if (! -e $thesaurus_db_file) {
 3247:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3248:                                  " failed because it does not exist");
 3249:         return 0;
 3250:     }
 3251:     #   Set up the hash as a database
 3252:     my %thesaurus_db;
 3253:     if (! tie(%thesaurus_db,'GDBM_File',
 3254:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3255:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3256:                                  $thesaurus_db_file);
 3257:         return 0;
 3258:     } 
 3259:     #  Get the average number of appearances of a word.
 3260:     my $avecount = $thesaurus_db{'average.count'};
 3261:     #  Put keywords (those that appear > average) into %Keywords
 3262:     while (my ($word,$data)=each (%thesaurus_db)) {
 3263:         my ($count,undef) = split /:/,$data;
 3264:         $Keywords{$word}++ if ($count > $avecount);
 3265:     }
 3266:     untie %thesaurus_db;
 3267:     # Remove special values from %Keywords.
 3268:     foreach my $value ('total.count','average.count') {
 3269:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3270:   }
 3271:     return 1;
 3272: }
 3273: 
 3274: ###################################################
 3275: 
 3276: =pod
 3277: 
 3278: =item * &keyword($word)
 3279: 
 3280: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3281: than the average number of times in the thesaurus database.  Calls 
 3282: &initialize_keywords
 3283: 
 3284: =cut
 3285: 
 3286: ###################################################
 3287: 
 3288: sub keyword {
 3289:     return if (!&initialize_keywords());
 3290:     my $word=lc(shift());
 3291:     $word=~s/\W//g;
 3292:     return exists($Keywords{$word});
 3293: }
 3294: 
 3295: ###############################################################
 3296: 
 3297: =pod 
 3298: 
 3299: =item * &get_related_words()
 3300: 
 3301: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3302: an array of words.  If the keyword is not in the thesaurus, an empty array
 3303: will be returned.  The order of the words returned is determined by the
 3304: database which holds them.
 3305: 
 3306: Uses global $thesaurus_db_file.
 3307: 
 3308: 
 3309: =cut
 3310: 
 3311: ###############################################################
 3312: sub get_related_words {
 3313:     my $keyword = shift;
 3314:     my %thesaurus_db;
 3315:     if (! -e $thesaurus_db_file) {
 3316:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3317:                                  "failed because the file does not exist");
 3318:         return ();
 3319:     }
 3320:     if (! tie(%thesaurus_db,'GDBM_File',
 3321:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3322:         return ();
 3323:     } 
 3324:     my @Words=();
 3325:     my $count=0;
 3326:     if (exists($thesaurus_db{$keyword})) {
 3327: 	# The first element is the number of times
 3328: 	# the word appears.  We do not need it now.
 3329: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3330: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3331: 	my $threshold=$mostfrequentcount/10;
 3332:         foreach my $possibleword (@RelatedWords) {
 3333:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3334:             if ($wordcount>$threshold) {
 3335: 		push(@Words,$word);
 3336:                 $count++;
 3337:                 if ($count>10) { last; }
 3338: 	    }
 3339:         }
 3340:     }
 3341:     untie %thesaurus_db;
 3342:     return @Words;
 3343: }
 3344: ###############################################################
 3345: #
 3346: #  Spell checking
 3347: #
 3348: 
 3349: =pod
 3350: 
 3351: =back
 3352: 
 3353: =head1 Spell checking
 3354: 
 3355: =over 4
 3356: 
 3357: =item * &check_spelling($wordlist $language)
 3358: 
 3359: Takes a string containing words and feeds it to an external
 3360: spellcheck program via a pipeline. Returns a string containing
 3361: them mis-spelled words.
 3362: 
 3363: Parameters:
 3364: 
 3365: =over 4
 3366: 
 3367: =item - $wordlist
 3368: 
 3369: String that will be fed into the spellcheck program.
 3370: 
 3371: =item - $language
 3372: 
 3373: Language string that specifies the language for which the spell
 3374: check will be performed.
 3375: 
 3376: =back
 3377: 
 3378: =back
 3379: 
 3380: Note: This sub assumes that aspell is installed.
 3381: 
 3382: 
 3383: =cut
 3384: 
 3385: 
 3386: sub check_spelling {
 3387:     my ($wordlist, $language) = @_;
 3388:     my @misspellings;
 3389:     
 3390:     # Generate the speller and set the langauge.
 3391:     # if explicitly selected:
 3392: 
 3393:     my $speller = Text::Aspell->new;
 3394:     if ($language) {
 3395: 	$speller->set_option('lang', $language);
 3396:     }
 3397: 
 3398:     # Turn the word list into an array of words by splittingon whitespace
 3399: 
 3400:     my @words = split(/\s+/, $wordlist);
 3401: 
 3402:     foreach my $word (@words) {
 3403: 	if(! $speller->check($word)) {
 3404: 	    push(@misspellings, $word);
 3405: 	}
 3406:     }
 3407:     return join(' ', @misspellings);
 3408:     
 3409: }
 3410: 
 3411: # -------------------------------------------------------------- Plaintext name
 3412: =pod
 3413: 
 3414: =head1 User Name Functions
 3415: 
 3416: =over 4
 3417: 
 3418: =item * &plainname($uname,$udom,$first)
 3419: 
 3420: Takes a users logon name and returns it as a string in
 3421: "first middle last generation" form 
 3422: if $first is set to 'lastname' then it returns it as
 3423: 'lastname generation, firstname middlename' if their is a lastname
 3424: 
 3425: =cut
 3426: 
 3427: 
 3428: ###############################################################
 3429: sub plainname {
 3430:     my ($uname,$udom,$first)=@_;
 3431:     return if (!defined($uname) || !defined($udom));
 3432:     my %names=&getnames($uname,$udom);
 3433:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3434: 					  $names{'middlename'},
 3435: 					  $names{'lastname'},
 3436: 					  $names{'generation'},$first);
 3437:     $name=~s/^\s+//;
 3438:     $name=~s/\s+$//;
 3439:     $name=~s/\s+/ /g;
 3440:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3441:     return $name;
 3442: }
 3443: 
 3444: # -------------------------------------------------------------------- Nickname
 3445: =pod
 3446: 
 3447: =item * &nickname($uname,$udom)
 3448: 
 3449: Gets a users name and returns it as a string as
 3450: 
 3451: "&quot;nickname&quot;"
 3452: 
 3453: if the user has a nickname or
 3454: 
 3455: "first middle last generation"
 3456: 
 3457: if the user does not
 3458: 
 3459: =cut
 3460: 
 3461: sub nickname {
 3462:     my ($uname,$udom)=@_;
 3463:     return if (!defined($uname) || !defined($udom));
 3464:     my %names=&getnames($uname,$udom);
 3465:     my $name=$names{'nickname'};
 3466:     if ($name) {
 3467:        $name='&quot;'.$name.'&quot;'; 
 3468:     } else {
 3469:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3470: 	     $names{'lastname'}.' '.$names{'generation'};
 3471:        $name=~s/\s+$//;
 3472:        $name=~s/\s+/ /g;
 3473:     }
 3474:     return $name;
 3475: }
 3476: 
 3477: sub getnames {
 3478:     my ($uname,$udom)=@_;
 3479:     return if (!defined($uname) || !defined($udom));
 3480:     if ($udom eq 'public' && $uname eq 'public') {
 3481: 	return ('lastname' => &mt('Public'));
 3482:     }
 3483:     my $id=$uname.':'.$udom;
 3484:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3485:     if ($cached) {
 3486: 	return %{$names};
 3487:     } else {
 3488: 	my %loadnames=&Apache::lonnet::get('environment',
 3489:                     ['firstname','middlename','lastname','generation','nickname'],
 3490: 					 $udom,$uname);
 3491: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3492: 	return %loadnames;
 3493:     }
 3494: }
 3495: 
 3496: # -------------------------------------------------------------------- getemails
 3497: 
 3498: =pod
 3499: 
 3500: =item * &getemails($uname,$udom)
 3501: 
 3502: Gets a user's email information and returns it as a hash with keys:
 3503: notification, critnotification, permanentemail
 3504: 
 3505: For notification and critnotification, values are comma-separated lists 
 3506: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3507:  
 3508: 
 3509: =cut
 3510: 
 3511: 
 3512: sub getemails {
 3513:     my ($uname,$udom)=@_;
 3514:     if ($udom eq 'public' && $uname eq 'public') {
 3515: 	return;
 3516:     }
 3517:     if (!$udom) { $udom=$env{'user.domain'}; }
 3518:     if (!$uname) { $uname=$env{'user.name'}; }
 3519:     my $id=$uname.':'.$udom;
 3520:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3521:     if ($cached) {
 3522: 	return %{$names};
 3523:     } else {
 3524: 	my %loadnames=&Apache::lonnet::get('environment',
 3525:                     			   ['notification','critnotification',
 3526: 					    'permanentemail'],
 3527: 					   $udom,$uname);
 3528: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3529: 	return %loadnames;
 3530:     }
 3531: }
 3532: 
 3533: sub flush_email_cache {
 3534:     my ($uname,$udom)=@_;
 3535:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3536:     if (!$uname) { $uname=$env{'user.name'};   }
 3537:     return if ($udom eq 'public' && $uname eq 'public');
 3538:     my $id=$uname.':'.$udom;
 3539:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3540: }
 3541: 
 3542: # -------------------------------------------------------------------- getlangs
 3543: 
 3544: =pod
 3545: 
 3546: =item * &getlangs($uname,$udom)
 3547: 
 3548: Gets a user's language preference and returns it as a hash with key:
 3549: language.
 3550: 
 3551: =cut
 3552: 
 3553: 
 3554: sub getlangs {
 3555:     my ($uname,$udom) = @_;
 3556:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3557:     if (!$uname) { $uname=$env{'user.name'};   }
 3558:     my $id=$uname.':'.$udom;
 3559:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3560:     if ($cached) {
 3561:         return %{$langs};
 3562:     } else {
 3563:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3564:                                            $udom,$uname);
 3565:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3566:         return %loadlangs;
 3567:     }
 3568: }
 3569: 
 3570: sub flush_langs_cache {
 3571:     my ($uname,$udom)=@_;
 3572:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3573:     if (!$uname) { $uname=$env{'user.name'};   }
 3574:     return if ($udom eq 'public' && $uname eq 'public');
 3575:     my $id=$uname.':'.$udom;
 3576:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3577: }
 3578: 
 3579: # ------------------------------------------------------------------ Screenname
 3580: 
 3581: =pod
 3582: 
 3583: =item * &screenname($uname,$udom)
 3584: 
 3585: Gets a users screenname and returns it as a string
 3586: 
 3587: =cut
 3588: 
 3589: sub screenname {
 3590:     my ($uname,$udom)=@_;
 3591:     if ($uname eq $env{'user.name'} &&
 3592: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3593:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3594:     return $names{'screenname'};
 3595: }
 3596: 
 3597: 
 3598: # ------------------------------------------------------------- Confirm Wrapper
 3599: =pod
 3600: 
 3601: =item * &confirmwrapper($message)
 3602: 
 3603: Wrap messages about completion of operation in box
 3604: 
 3605: =cut
 3606: 
 3607: sub confirmwrapper {
 3608:     my ($message)=@_;
 3609:     if ($message) {
 3610:         return "\n".'<div class="LC_confirm_box">'."\n"
 3611:                .$message."\n"
 3612:                .'</div>'."\n";
 3613:     } else {
 3614:         return $message;
 3615:     }
 3616: }
 3617: 
 3618: # ------------------------------------------------------------- Message Wrapper
 3619: 
 3620: sub messagewrapper {
 3621:     my ($link,$username,$domain,$subject,$text)=@_;
 3622:     return 
 3623:         '<a href="/adm/email?compose=individual&amp;'.
 3624:         'recname='.$username.'&amp;recdom='.$domain.
 3625: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3626:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3627: }
 3628: 
 3629: # --------------------------------------------------------------- Notes Wrapper
 3630: 
 3631: sub noteswrapper {
 3632:     my ($link,$un,$do)=@_;
 3633:     return 
 3634: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3635: }
 3636: 
 3637: # ------------------------------------------------------------- Aboutme Wrapper
 3638: 
 3639: sub aboutmewrapper {
 3640:     my ($link,$username,$domain,$target,$class)=@_;
 3641:     if (!defined($username)  && !defined($domain)) {
 3642:         return;
 3643:     }
 3644:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3645: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3646: }
 3647: 
 3648: # ------------------------------------------------------------ Syllabus Wrapper
 3649: 
 3650: sub syllabuswrapper {
 3651:     my ($linktext,$coursedir,$domain)=@_;
 3652:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3653: }
 3654: 
 3655: # -----------------------------------------------------------------------------
 3656: 
 3657: sub track_student_link {
 3658:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3659:     my $link ="/adm/trackstudent?";
 3660:     my $title = 'View recent activity';
 3661:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3662:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3663:         $link .= "selected_student=$sname:$sdom";
 3664:         $title .= ' of this student';
 3665:     } 
 3666:     if (defined($target) && $target !~ /^\s*$/) {
 3667:         $target = qq{target="$target"};
 3668:     } else {
 3669:         $target = '';
 3670:     }
 3671:     if ($start) { $link.='&amp;start='.$start; }
 3672:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3673:     $title = &mt($title);
 3674:     $linktext = &mt($linktext);
 3675:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3676: 	&help_open_topic('View_recent_activity');
 3677: }
 3678: 
 3679: sub slot_reservations_link {
 3680:     my ($linktext,$sname,$sdom,$target) = @_;
 3681:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3682:     my $title = 'View slot reservation history';
 3683:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3684:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3685:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3686:         $title .= ' of this student';
 3687:     }
 3688:     if (defined($target) && $target !~ /^\s*$/) {
 3689:         $target = qq{target="$target"};
 3690:     } else {
 3691:         $target = '';
 3692:     }
 3693:     $title = &mt($title);
 3694:     $linktext = &mt($linktext);
 3695:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3696: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3697: 
 3698: }
 3699: 
 3700: # ===================================================== Display a student photo
 3701: 
 3702: 
 3703: sub student_image_tag {
 3704:     my ($domain,$user)=@_;
 3705:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3706:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3707: 	return '<img src="'.$imgsrc.'" align="right" />';
 3708:     } else {
 3709: 	return '';
 3710:     }
 3711: }
 3712: 
 3713: =pod
 3714: 
 3715: =back
 3716: 
 3717: =head1 Access .tab File Data
 3718: 
 3719: =over 4
 3720: 
 3721: =item * &languageids() 
 3722: 
 3723: returns list of all language ids
 3724: 
 3725: =cut
 3726: 
 3727: sub languageids {
 3728:     return sort(keys(%language));
 3729: }
 3730: 
 3731: =pod
 3732: 
 3733: =item * &languagedescription() 
 3734: 
 3735: returns description of a specified language id
 3736: 
 3737: =cut
 3738: 
 3739: sub languagedescription {
 3740:     my $code=shift;
 3741:     return  ($supported_language{$code}?'* ':'').
 3742:             $language{$code}.
 3743: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3744: }
 3745: 
 3746: =pod
 3747: 
 3748: =item * &plainlanguagedescription
 3749: 
 3750: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3751: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3752: 
 3753: =cut
 3754: 
 3755: sub plainlanguagedescription {
 3756:     my $code=shift;
 3757:     return $language{$code};
 3758: }
 3759: 
 3760: =pod
 3761: 
 3762: =item * &supportedlanguagecode
 3763: 
 3764: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3765: code.
 3766: 
 3767: =cut
 3768: 
 3769: sub supportedlanguagecode {
 3770:     my $code=shift;
 3771:     return $supported_language{$code};
 3772: }
 3773: 
 3774: =pod
 3775: 
 3776: =item * &latexlanguage()
 3777: 
 3778: Given a language key code returns the correspondnig language to use
 3779: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3780: is no supported hyphenation for the language code.
 3781: 
 3782: =cut
 3783: 
 3784: sub latexlanguage {
 3785:     my $code = shift;
 3786:     return $latex_language{$code};
 3787: }
 3788: 
 3789: =pod
 3790: 
 3791: =item * &latexhyphenation()
 3792: 
 3793: Same as above but what's supplied is the language as it might be stored
 3794: in the metadata.
 3795: 
 3796: =cut
 3797: 
 3798: sub latexhyphenation {
 3799:     my $key = shift;
 3800:     return $latex_language_bykey{$key};
 3801: }
 3802: 
 3803: =pod
 3804: 
 3805: =item * &copyrightids() 
 3806: 
 3807: returns list of all copyrights
 3808: 
 3809: =cut
 3810: 
 3811: sub copyrightids {
 3812:     return sort(keys(%cprtag));
 3813: }
 3814: 
 3815: =pod
 3816: 
 3817: =item * &copyrightdescription() 
 3818: 
 3819: returns description of a specified copyright id
 3820: 
 3821: =cut
 3822: 
 3823: sub copyrightdescription {
 3824:     return &mt($cprtag{shift(@_)});
 3825: }
 3826: 
 3827: =pod
 3828: 
 3829: =item * &source_copyrightids() 
 3830: 
 3831: returns list of all source copyrights
 3832: 
 3833: =cut
 3834: 
 3835: sub source_copyrightids {
 3836:     return sort(keys(%scprtag));
 3837: }
 3838: 
 3839: =pod
 3840: 
 3841: =item * &source_copyrightdescription() 
 3842: 
 3843: returns description of a specified source copyright id
 3844: 
 3845: =cut
 3846: 
 3847: sub source_copyrightdescription {
 3848:     return &mt($scprtag{shift(@_)});
 3849: }
 3850: 
 3851: =pod
 3852: 
 3853: =item * &filecategories() 
 3854: 
 3855: returns list of all file categories
 3856: 
 3857: =cut
 3858: 
 3859: sub filecategories {
 3860:     return sort(keys(%category_extensions));
 3861: }
 3862: 
 3863: =pod
 3864: 
 3865: =item * &filecategorytypes() 
 3866: 
 3867: returns list of file types belonging to a given file
 3868: category
 3869: 
 3870: =cut
 3871: 
 3872: sub filecategorytypes {
 3873:     my ($cat) = @_;
 3874:     return @{$category_extensions{lc($cat)}};
 3875: }
 3876: 
 3877: =pod
 3878: 
 3879: =item * &fileembstyle() 
 3880: 
 3881: returns embedding style for a specified file type
 3882: 
 3883: =cut
 3884: 
 3885: sub fileembstyle {
 3886:     return $fe{lc(shift(@_))};
 3887: }
 3888: 
 3889: sub filemimetype {
 3890:     return $fm{lc(shift(@_))};
 3891: }
 3892: 
 3893: 
 3894: sub filecategoryselect {
 3895:     my ($name,$value)=@_;
 3896:     return &select_form($value,$name,
 3897:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3898: }
 3899: 
 3900: =pod
 3901: 
 3902: =item * &filedescription() 
 3903: 
 3904: returns description for a specified file type
 3905: 
 3906: =cut
 3907: 
 3908: sub filedescription {
 3909:     my $file_description = $fd{lc(shift())};
 3910:     $file_description =~ s:([\[\]]):~$1:g;
 3911:     return &mt($file_description);
 3912: }
 3913: 
 3914: =pod
 3915: 
 3916: =item * &filedescriptionex() 
 3917: 
 3918: returns description for a specified file type with
 3919: extra formatting
 3920: 
 3921: =cut
 3922: 
 3923: sub filedescriptionex {
 3924:     my $ex=shift;
 3925:     my $file_description = $fd{lc($ex)};
 3926:     $file_description =~ s:([\[\]]):~$1:g;
 3927:     return '.'.$ex.' '.&mt($file_description);
 3928: }
 3929: 
 3930: # End of .tab access
 3931: =pod
 3932: 
 3933: =back
 3934: 
 3935: =cut
 3936: 
 3937: # ------------------------------------------------------------------ File Types
 3938: sub fileextensions {
 3939:     return sort(keys(%fe));
 3940: }
 3941: 
 3942: # ----------------------------------------------------------- Display Languages
 3943: # returns a hash with all desired display languages
 3944: #
 3945: 
 3946: sub display_languages {
 3947:     my %languages=();
 3948:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3949: 	$languages{$lang}=1;
 3950:     }
 3951:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3952:     if ($env{'form.displaylanguage'}) {
 3953: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3954: 	    $languages{$lang}=1;
 3955:         }
 3956:     }
 3957:     return %languages;
 3958: }
 3959: 
 3960: sub languages {
 3961:     my ($possible_langs) = @_;
 3962:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3963:     if (!ref($possible_langs)) {
 3964: 	if( wantarray ) {
 3965: 	    return @preferred_langs;
 3966: 	} else {
 3967: 	    return $preferred_langs[0];
 3968: 	}
 3969:     }
 3970:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3971:     my @preferred_possibilities;
 3972:     foreach my $preferred_lang (@preferred_langs) {
 3973: 	if (exists($possibilities{$preferred_lang})) {
 3974: 	    push(@preferred_possibilities, $preferred_lang);
 3975: 	}
 3976:     }
 3977:     if( wantarray ) {
 3978: 	return @preferred_possibilities;
 3979:     }
 3980:     return $preferred_possibilities[0];
 3981: }
 3982: 
 3983: sub user_lang {
 3984:     my ($touname,$toudom,$fromcid) = @_;
 3985:     my @userlangs;
 3986:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3987:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3988:                     $env{'course.'.$fromcid.'.languages'}));
 3989:     } else {
 3990:         my %langhash = &getlangs($touname,$toudom);
 3991:         if ($langhash{'languages'} ne '') {
 3992:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3993:         } else {
 3994:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3995:             if ($domdefs{'lang_def'} ne '') {
 3996:                 @userlangs = ($domdefs{'lang_def'});
 3997:             }
 3998:         }
 3999:     }
 4000:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4001:     my $user_lh = Apache::localize->get_handle(@languages);
 4002:     return $user_lh;
 4003: }
 4004: 
 4005: 
 4006: ###############################################################
 4007: ##               Student Answer Attempts                     ##
 4008: ###############################################################
 4009: 
 4010: =pod
 4011: 
 4012: =head1 Alternate Problem Views
 4013: 
 4014: =over 4
 4015: 
 4016: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4017:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4018: 
 4019: Return string with previous attempt on problem. Arguments:
 4020: 
 4021: =over 4
 4022: 
 4023: =item * $symb: Problem, including path
 4024: 
 4025: =item * $username: username of the desired student
 4026: 
 4027: =item * $domain: domain of the desired student
 4028: 
 4029: =item * $course: Course ID
 4030: 
 4031: =item * $getattempt: Leave blank for all attempts, otherwise put
 4032:     something
 4033: 
 4034: =item * $regexp: if string matches this regexp, the string will be
 4035:     sent to $gradesub
 4036: 
 4037: =item * $gradesub: routine that processes the string if it matches $regexp
 4038: 
 4039: =item * $usec: section of the desired student
 4040: 
 4041: =item * $identifier: counter for student (multiple students one problem) or 
 4042:     problem (one student; whole sequence).
 4043: 
 4044: =back
 4045: 
 4046: The output string is a table containing all desired attempts, if any.
 4047: 
 4048: =cut
 4049: 
 4050: sub get_previous_attempt {
 4051:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4052:   my $prevattempts='';
 4053:   no strict 'refs';
 4054:   if ($symb) {
 4055:     my (%returnhash)=
 4056:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4057:     if ($returnhash{'version'}) {
 4058:       my %lasthash=();
 4059:       my $version;
 4060:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4061:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4062:             if ($key =~ /\.rawrndseed$/) {
 4063:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4064:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4065:             } else {
 4066:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4067:             }
 4068:         }
 4069:       }
 4070:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4071:       $prevattempts.='<th>'.&mt('History').'</th>';
 4072:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4073:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4074:       foreach my $key (sort(keys(%lasthash))) {
 4075: 	my ($ign,@parts) = split(/\./,$key);
 4076: 	if ($#parts > 0) {
 4077: 	  my $data=$parts[-1];
 4078:           next if ($data eq 'foilorder');
 4079: 	  pop(@parts);
 4080:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4081:           if ($data eq 'type') {
 4082:               unless ($showsurv) {
 4083:                   my $id = join(',',@parts);
 4084:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4085:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4086:                       $lasthidden{$ign.'.'.$id} = 1;
 4087:                   }
 4088:               }
 4089:               if ($identifier ne '') {
 4090:                   my $id = join(',',@parts);
 4091:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4092:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4093:                       $hidestatus{$ign.'.'.$id} = 1;
 4094:                   }
 4095:               }
 4096:           } elsif ($data eq 'regrader') {
 4097:               if (($identifier ne '') && (@parts)) {
 4098:                   my $id = join(',',@parts);
 4099:                   $regraded{$ign.'.'.$id} = 1;
 4100:               }
 4101:           } 
 4102: 	} else {
 4103: 	  if ($#parts == 0) {
 4104: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4105: 	  } else {
 4106: 	    $prevattempts.='<th>'.$ign.'</th>';
 4107: 	  }
 4108: 	}
 4109:       }
 4110:       $prevattempts.=&end_data_table_header_row();
 4111:       if ($getattempt eq '') {
 4112:         my (%solved,%resets,%probstatus);
 4113:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4114:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4115:                 foreach my $id (keys(%regraded)) {
 4116:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4117:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4118:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4119:                         push(@{$resets{$id}},$version);
 4120:                     }
 4121:                 }
 4122:             }
 4123:         }
 4124: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4125:             my (@hidden,@unsolved);
 4126:             if (%typeparts) {
 4127:                 foreach my $id (keys(%typeparts)) {
 4128:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4129:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4130:                         push(@hidden,$id);
 4131:                     } elsif ($identifier ne '') {
 4132:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4133:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4134:                                 ($hidestatus{$id})) {
 4135:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4136:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4137:                                 push(@{$solved{$id}},$version);
 4138:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4139:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4140:                                 my $skip;
 4141:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4142:                                     foreach my $reset (@{$resets{$id}}) {
 4143:                                         if ($reset > $solved{$id}[-1]) {
 4144:                                             $skip=1;
 4145:                                             last;
 4146:                                         }
 4147:                                     }
 4148:                                 }
 4149:                                 unless ($skip) {
 4150:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4151:                                     push(@unsolved,$partslist);
 4152:                                 }
 4153:                             }
 4154:                         }
 4155:                     }
 4156:                 }
 4157:             }
 4158:             $prevattempts.=&start_data_table_row().
 4159:                            '<td>'.&mt('Transaction [_1]',$version);
 4160:             if (@unsolved) {
 4161:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4162:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4163:                                  &mt('Hide').'</label></span>';
 4164:             }
 4165:             $prevattempts .= '</td>';
 4166:             if (@hidden) {
 4167:                 foreach my $key (sort(keys(%lasthash))) {
 4168:                     next if ($key =~ /\.foilorder$/);
 4169:                     my $hide;
 4170:                     foreach my $id (@hidden) {
 4171:                         if ($key =~ /^\Q$id\E/) {
 4172:                             $hide = 1;
 4173:                             last;
 4174:                         }
 4175:                     }
 4176:                     if ($hide) {
 4177:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4178:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4179:                             my $value = &format_previous_attempt_value($key,
 4180:                                              $returnhash{$version.':'.$key});
 4181:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4182:                         } else {
 4183:                             $prevattempts.='<td>&nbsp;</td>';
 4184:                         }
 4185:                     } else {
 4186:                         if ($key =~ /\./) {
 4187:                             my $value = $returnhash{$version.':'.$key};
 4188:                             if ($key =~ /\.rndseed$/) {
 4189:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4190:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4191:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4192:                                 }
 4193:                             }
 4194:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4195:                                            '&nbsp;</td>';
 4196:                         } else {
 4197:                             $prevattempts.='<td>&nbsp;</td>';
 4198:                         }
 4199:                     }
 4200:                 }
 4201:             } else {
 4202: 	        foreach my $key (sort(keys(%lasthash))) {
 4203:                     next if ($key =~ /\.foilorder$/);
 4204:                     my $value = $returnhash{$version.':'.$key};
 4205:                     if ($key =~ /\.rndseed$/) {
 4206:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4207:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4208:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4209:                         }
 4210:                     }
 4211:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4212:                                    '&nbsp;</td>';
 4213: 	        }
 4214:             }
 4215: 	    $prevattempts.=&end_data_table_row();
 4216: 	 }
 4217:       }
 4218:       my @currhidden = keys(%lasthidden);
 4219:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4220:       foreach my $key (sort(keys(%lasthash))) {
 4221:           next if ($key =~ /\.foilorder$/);
 4222:           if (%typeparts) {
 4223:               my $hidden;
 4224:               foreach my $id (@currhidden) {
 4225:                   if ($key =~ /^\Q$id\E/) {
 4226:                       $hidden = 1;
 4227:                       last;
 4228:                   }
 4229:               }
 4230:               if ($hidden) {
 4231:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4232:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4233:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4234:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4235:                           $value = &$gradesub($value);
 4236:                       }
 4237:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4238:                   } else {
 4239:                       $prevattempts.='<td>&nbsp;</td>';
 4240:                   }
 4241:               } else {
 4242:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4243:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4244:                       $value = &$gradesub($value);
 4245:                   }
 4246:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4247:               }
 4248:           } else {
 4249: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4250: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4251:                   $value = &$gradesub($value);
 4252:               }
 4253: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4254:           }
 4255:       }
 4256:       $prevattempts.= &end_data_table_row().&end_data_table();
 4257:     } else {
 4258:       $prevattempts=
 4259: 	  &start_data_table().&start_data_table_row().
 4260: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4261: 	  &end_data_table_row().&end_data_table();
 4262:     }
 4263:   } else {
 4264:     $prevattempts=
 4265: 	  &start_data_table().&start_data_table_row().
 4266: 	  '<td>'.&mt('No data.').'</td>'.
 4267: 	  &end_data_table_row().&end_data_table();
 4268:   }
 4269: }
 4270: 
 4271: sub format_previous_attempt_value {
 4272:     my ($key,$value) = @_;
 4273:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4274:         $value = &Apache::lonlocal::locallocaltime($value);
 4275:     } elsif (ref($value) eq 'ARRAY') {
 4276:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4277:     } elsif ($key =~ /answerstring$/) {
 4278:         my %answers = &Apache::lonnet::str2hash($value);
 4279:         my @answer = %answers;
 4280:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4281:         my @anskeys = sort(keys(%answers));
 4282:         if (@anskeys == 1) {
 4283:             my $answer = $answers{$anskeys[0]};
 4284:             if ($answer =~ m{\0}) {
 4285:                 $answer =~ s{\0}{,}g;
 4286:             }
 4287:             my $tag_internal_answer_name = 'INTERNAL';
 4288:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4289:                 $value = $answer; 
 4290:             } else {
 4291:                 $value = $anskeys[0].'='.$answer;
 4292:             }
 4293:         } else {
 4294:             foreach my $ans (@anskeys) {
 4295:                 my $answer = $answers{$ans};
 4296:                 if ($answer =~ m{\0}) {
 4297:                     $answer =~ s{\0}{,}g;
 4298:                 }
 4299:                 $value .=  $ans.'='.$answer.'<br />';;
 4300:             } 
 4301:         }
 4302:     } else {
 4303:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4304:     }
 4305:     return $value;
 4306: }
 4307: 
 4308: 
 4309: sub relative_to_absolute {
 4310:     my ($url,$output)=@_;
 4311:     my $parser=HTML::TokeParser->new(\$output);
 4312:     my $token;
 4313:     my $thisdir=$url;
 4314:     my @rlinks=();
 4315:     while ($token=$parser->get_token) {
 4316: 	if ($token->[0] eq 'S') {
 4317: 	    if ($token->[1] eq 'a') {
 4318: 		if ($token->[2]->{'href'}) {
 4319: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4320: 		}
 4321: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4322: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4323: 	    } elsif ($token->[1] eq 'base') {
 4324: 		$thisdir=$token->[2]->{'href'};
 4325: 	    }
 4326: 	}
 4327:     }
 4328:     $thisdir=~s-/[^/]*$--;
 4329:     foreach my $link (@rlinks) {
 4330: 	unless (($link=~/^https?\:\/\//i) ||
 4331: 		($link=~/^\//) ||
 4332: 		($link=~/^javascript:/i) ||
 4333: 		($link=~/^mailto:/i) ||
 4334: 		($link=~/^\#/)) {
 4335: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4336: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4337: 	}
 4338:     }
 4339: # -------------------------------------------------- Deal with Applet codebases
 4340:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4341:     return $output;
 4342: }
 4343: 
 4344: =pod
 4345: 
 4346: =item * &get_student_view()
 4347: 
 4348: show a snapshot of what student was looking at
 4349: 
 4350: =cut
 4351: 
 4352: sub get_student_view {
 4353:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4354:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4355:   my (%form);
 4356:   my @elements=('symb','courseid','domain','username');
 4357:   foreach my $element (@elements) {
 4358:       $form{'grade_'.$element}=eval '$'.$element #'
 4359:   }
 4360:   if (defined($moreenv)) {
 4361:       %form=(%form,%{$moreenv});
 4362:   }
 4363:   if (defined($target)) { $form{'grade_target'} = $target; }
 4364:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4365:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4366:   $userview=~s/\<body[^\>]*\>//gi;
 4367:   $userview=~s/\<\/body\>//gi;
 4368:   $userview=~s/\<html\>//gi;
 4369:   $userview=~s/\<\/html\>//gi;
 4370:   $userview=~s/\<head\>//gi;
 4371:   $userview=~s/\<\/head\>//gi;
 4372:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4373:   $userview=&relative_to_absolute($feedurl,$userview);
 4374:   if (wantarray) {
 4375:      return ($userview,$response);
 4376:   } else {
 4377:      return $userview;
 4378:   }
 4379: }
 4380: 
 4381: sub get_student_view_with_retries {
 4382:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4383: 
 4384:     my $ok = 0;                 # True if we got a good response.
 4385:     my $content;
 4386:     my $response;
 4387: 
 4388:     # Try to get the student_view done. within the retries count:
 4389:     
 4390:     do {
 4391:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4392:          $ok      = $response->is_success;
 4393:          if (!$ok) {
 4394:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4395:          }
 4396:          $retries--;
 4397:     } while (!$ok && ($retries > 0));
 4398:     
 4399:     if (!$ok) {
 4400:        $content = '';          # On error return an empty content.
 4401:     }
 4402:     if (wantarray) {
 4403:        return ($content, $response);
 4404:     } else {
 4405:        return $content;
 4406:     }
 4407: }
 4408: 
 4409: =pod
 4410: 
 4411: =item * &get_student_answers() 
 4412: 
 4413: show a snapshot of how student was answering problem
 4414: 
 4415: =cut
 4416: 
 4417: sub get_student_answers {
 4418:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4419:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4420:   my (%moreenv);
 4421:   my @elements=('symb','courseid','domain','username');
 4422:   foreach my $element (@elements) {
 4423:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4424:   }
 4425:   $moreenv{'grade_target'}='answer';
 4426:   %moreenv=(%form,%moreenv);
 4427:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4428:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4429:   return $userview;
 4430: }
 4431: 
 4432: =pod
 4433: 
 4434: =item * &submlink()
 4435: 
 4436: Inputs: $text $uname $udom $symb $target
 4437: 
 4438: Returns: A link to grades.pm such as to see the SUBM view of a student
 4439: 
 4440: =cut
 4441: 
 4442: ###############################################
 4443: sub submlink {
 4444:     my ($text,$uname,$udom,$symb,$target)=@_;
 4445:     if (!($uname && $udom)) {
 4446: 	(my $cursymb, my $courseid,$udom,$uname)=
 4447: 	    &Apache::lonnet::whichuser($symb);
 4448: 	if (!$symb) { $symb=$cursymb; }
 4449:     }
 4450:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4451:     $symb=&escape($symb);
 4452:     if ($target) { $target=" target=\"$target\""; }
 4453:     return
 4454:         '<a href="/adm/grades?command=submission'.
 4455:         '&amp;symb='.$symb.
 4456:         '&amp;student='.$uname.
 4457:         '&amp;userdom='.$udom.'"'.
 4458:         $target.'>'.$text.'</a>';
 4459: }
 4460: ##############################################
 4461: 
 4462: =pod
 4463: 
 4464: =item * &pgrdlink()
 4465: 
 4466: Inputs: $text $uname $udom $symb $target
 4467: 
 4468: Returns: A link to grades.pm such as to see the PGRD view of a student
 4469: 
 4470: =cut
 4471: 
 4472: ###############################################
 4473: sub pgrdlink {
 4474:     my $link=&submlink(@_);
 4475:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4476:     return $link;
 4477: }
 4478: ##############################################
 4479: 
 4480: =pod
 4481: 
 4482: =item * &pprmlink()
 4483: 
 4484: Inputs: $text $uname $udom $symb $target
 4485: 
 4486: Returns: A link to parmset.pm such as to see the PPRM view of a
 4487: student and a specific resource
 4488: 
 4489: =cut
 4490: 
 4491: ###############################################
 4492: sub pprmlink {
 4493:     my ($text,$uname,$udom,$symb,$target)=@_;
 4494:     if (!($uname && $udom)) {
 4495: 	(my $cursymb, my $courseid,$udom,$uname)=
 4496: 	    &Apache::lonnet::whichuser($symb);
 4497: 	if (!$symb) { $symb=$cursymb; }
 4498:     }
 4499:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4500:     $symb=&escape($symb);
 4501:     if ($target) { $target="target=\"$target\""; }
 4502:     return '<a href="/adm/parmset?command=set&amp;'.
 4503: 	'symb='.$symb.'&amp;uname='.$uname.
 4504: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4505: }
 4506: ##############################################
 4507: 
 4508: =pod
 4509: 
 4510: =back
 4511: 
 4512: =cut
 4513: 
 4514: ###############################################
 4515: 
 4516: 
 4517: sub timehash {
 4518:     my ($thistime) = @_;
 4519:     my $timezone = &Apache::lonlocal::gettimezone();
 4520:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4521:                      ->set_time_zone($timezone);
 4522:     my $wday = $dt->day_of_week();
 4523:     if ($wday == 7) { $wday = 0; }
 4524:     return ( 'second' => $dt->second(),
 4525:              'minute' => $dt->minute(),
 4526:              'hour'   => $dt->hour(),
 4527:              'day'     => $dt->day_of_month(),
 4528:              'month'   => $dt->month(),
 4529:              'year'    => $dt->year(),
 4530:              'weekday' => $wday,
 4531:              'dayyear' => $dt->day_of_year(),
 4532:              'dlsav'   => $dt->is_dst() );
 4533: }
 4534: 
 4535: sub utc_string {
 4536:     my ($date)=@_;
 4537:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4538: }
 4539: 
 4540: sub maketime {
 4541:     my %th=@_;
 4542:     my ($epoch_time,$timezone,$dt);
 4543:     $timezone = &Apache::lonlocal::gettimezone();
 4544:     eval {
 4545:         $dt = DateTime->new( year   => $th{'year'},
 4546:                              month  => $th{'month'},
 4547:                              day    => $th{'day'},
 4548:                              hour   => $th{'hour'},
 4549:                              minute => $th{'minute'},
 4550:                              second => $th{'second'},
 4551:                              time_zone => $timezone,
 4552:                          );
 4553:     };
 4554:     if (!$@) {
 4555:         $epoch_time = $dt->epoch;
 4556:         if ($epoch_time) {
 4557:             return $epoch_time;
 4558:         }
 4559:     }
 4560:     return POSIX::mktime(
 4561:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4562:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4563: }
 4564: 
 4565: #########################################
 4566: 
 4567: sub findallcourses {
 4568:     my ($roles,$uname,$udom) = @_;
 4569:     my %roles;
 4570:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4571:     my %courses;
 4572:     my $now=time;
 4573:     if (!defined($uname)) {
 4574:         $uname = $env{'user.name'};
 4575:     }
 4576:     if (!defined($udom)) {
 4577:         $udom = $env{'user.domain'};
 4578:     }
 4579:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4580:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4581:         if (!%roles) {
 4582:             %roles = (
 4583:                        cc => 1,
 4584:                        co => 1,
 4585:                        in => 1,
 4586:                        ep => 1,
 4587:                        ta => 1,
 4588:                        cr => 1,
 4589:                        st => 1,
 4590:              );
 4591:         }
 4592:         foreach my $entry (keys(%roleshash)) {
 4593:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4594:             if ($trole =~ /^cr/) { 
 4595:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4596:             } else {
 4597:                 next if (!exists($roles{$trole}));
 4598:             }
 4599:             if ($tend) {
 4600:                 next if ($tend < $now);
 4601:             }
 4602:             if ($tstart) {
 4603:                 next if ($tstart > $now);
 4604:             }
 4605:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4606:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4607:             my $value = $trole.'/'.$cdom.'/';
 4608:             if ($secpart eq '') {
 4609:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4610:                 $sec = 'none';
 4611:                 $value .= $cnum.'/';
 4612:             } else {
 4613:                 $cnum = $cnumpart;
 4614:                 ($sec,$role) = split(/_/,$secpart);
 4615:                 $value .= $cnum.'/'.$sec;
 4616:             }
 4617:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4618:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4619:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4620:                 }
 4621:             } else {
 4622:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4623:             }
 4624:         }
 4625:     } else {
 4626:         foreach my $key (keys(%env)) {
 4627: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4628:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4629: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4630: 	        next if ($role eq 'ca' || $role eq 'aa');
 4631: 	        next if (%roles && !exists($roles{$role}));
 4632: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4633:                 my $active=1;
 4634:                 if ($starttime) {
 4635: 		    if ($now<$starttime) { $active=0; }
 4636:                 }
 4637:                 if ($endtime) {
 4638:                     if ($now>$endtime) { $active=0; }
 4639:                 }
 4640:                 if ($active) {
 4641:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4642:                     if ($sec eq '') {
 4643:                         $sec = 'none';
 4644:                     } else {
 4645:                         $value .= $sec;
 4646:                     }
 4647:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4648:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4649:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4650:                         }
 4651:                     } else {
 4652:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4653:                     }
 4654:                 }
 4655:             }
 4656:         }
 4657:     }
 4658:     return %courses;
 4659: }
 4660: 
 4661: ###############################################
 4662: 
 4663: sub blockcheck {
 4664:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4665: 
 4666:     if (defined($udom) && defined($uname)) {
 4667:         # If uname and udom are for a course, check for blocks in the course.
 4668:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4669:             my ($startblock,$endblock,$triggerblock) =
 4670:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4671:             return ($startblock,$endblock,$triggerblock);
 4672:         }
 4673:     } else {
 4674:         $udom = $env{'user.domain'};
 4675:         $uname = $env{'user.name'};
 4676:     }
 4677: 
 4678:     my $startblock = 0;
 4679:     my $endblock = 0;
 4680:     my $triggerblock = '';
 4681:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4682: 
 4683:     # If uname is for a user, and activity is course-specific, i.e.,
 4684:     # boards, chat or groups, check for blocking in current course only.
 4685: 
 4686:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4687:          $activity eq 'groups' || $activity eq 'printout') &&
 4688:         ($env{'request.course.id'})) {
 4689:         foreach my $key (keys(%live_courses)) {
 4690:             if ($key ne $env{'request.course.id'}) {
 4691:                 delete($live_courses{$key});
 4692:             }
 4693:         }
 4694:     }
 4695: 
 4696:     my $otheruser = 0;
 4697:     my %own_courses;
 4698:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4699:         # Resource belongs to user other than current user.
 4700:         $otheruser = 1;
 4701:         # Gather courses for current user
 4702:         %own_courses = 
 4703:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4704:     }
 4705: 
 4706:     # Gather active course roles - course coordinator, instructor, 
 4707:     # exam proctor, ta, student, or custom role.
 4708: 
 4709:     foreach my $course (keys(%live_courses)) {
 4710:         my ($cdom,$cnum);
 4711:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4712:             $cdom = $env{'course.'.$course.'.domain'};
 4713:             $cnum = $env{'course.'.$course.'.num'};
 4714:         } else {
 4715:             ($cdom,$cnum) = split(/_/,$course); 
 4716:         }
 4717:         my $no_ownblock = 0;
 4718:         my $no_userblock = 0;
 4719:         if ($otheruser && $activity ne 'com') {
 4720:             # Check if current user has 'evb' priv for this
 4721:             if (defined($own_courses{$course})) {
 4722:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4723:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4724:                     if ($sec ne 'none') {
 4725:                         $checkrole .= '/'.$sec;
 4726:                     }
 4727:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4728:                         $no_ownblock = 1;
 4729:                         last;
 4730:                     }
 4731:                 }
 4732:             }
 4733:             # if they have 'evb' priv and are currently not playing student
 4734:             next if (($no_ownblock) &&
 4735:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4736:         }
 4737:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4738:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4739:             if ($sec ne 'none') {
 4740:                 $checkrole .= '/'.$sec;
 4741:             }
 4742:             if ($otheruser) {
 4743:                 # Resource belongs to user other than current user.
 4744:                 # Assemble privs for that user, and check for 'evb' priv.
 4745:                 my (%allroles,%userroles);
 4746:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4747:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4748:                         my ($trole,$tdom,$tnum,$tsec);
 4749:                         if ($entry =~ /^cr/) {
 4750:                             ($trole,$tdom,$tnum,$tsec) = 
 4751:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4752:                         } else {
 4753:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4754:                         }
 4755:                         my ($spec,$area,$trest);
 4756:                         $area = '/'.$tdom.'/'.$tnum;
 4757:                         $trest = $tnum;
 4758:                         if ($tsec ne '') {
 4759:                             $area .= '/'.$tsec;
 4760:                             $trest .= '/'.$tsec;
 4761:                         }
 4762:                         $spec = $trole.'.'.$area;
 4763:                         if ($trole =~ /^cr/) {
 4764:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4765:                                                               $tdom,$spec,$trest,$area);
 4766:                         } else {
 4767:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4768:                                                                 $tdom,$spec,$trest,$area);
 4769:                         }
 4770:                     }
 4771:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4772:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4773:                         if ($1) {
 4774:                             $no_userblock = 1;
 4775:                             last;
 4776:                         }
 4777:                     }
 4778:                 }
 4779:             } else {
 4780:                 # Resource belongs to current user
 4781:                 # Check for 'evb' priv via lonnet::allowed().
 4782:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4783:                     $no_ownblock = 1;
 4784:                     last;
 4785:                 }
 4786:             }
 4787:         }
 4788:         # if they have the evb priv and are currently not playing student
 4789:         next if (($no_ownblock) &&
 4790:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4791:         next if ($no_userblock);
 4792: 
 4793:         # Retrieve blocking times and identity of locker for course
 4794:         # of specified user, unless user has 'evb' privilege.
 4795:         
 4796:         my ($start,$end,$trigger) = 
 4797:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4798:         if (($start != 0) && 
 4799:             (($startblock == 0) || ($startblock > $start))) {
 4800:             $startblock = $start;
 4801:             if ($trigger ne '') {
 4802:                 $triggerblock = $trigger;
 4803:             }
 4804:         }
 4805:         if (($end != 0)  &&
 4806:             (($endblock == 0) || ($endblock < $end))) {
 4807:             $endblock = $end;
 4808:             if ($trigger ne '') {
 4809:                 $triggerblock = $trigger;
 4810:             }
 4811:         }
 4812:     }
 4813:     return ($startblock,$endblock,$triggerblock);
 4814: }
 4815: 
 4816: sub get_blocks {
 4817:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4818:     my $startblock = 0;
 4819:     my $endblock = 0;
 4820:     my $triggerblock = '';
 4821:     my $course = $cdom.'_'.$cnum;
 4822:     $setters->{$course} = {};
 4823:     $setters->{$course}{'staff'} = [];
 4824:     $setters->{$course}{'times'} = [];
 4825:     $setters->{$course}{'triggers'} = [];
 4826:     my (@blockers,%triggered);
 4827:     my $now = time;
 4828:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4829:     if ($activity eq 'docs') {
 4830:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4831:         foreach my $block (@blockers) {
 4832:             if ($block =~ /^firstaccess____(.+)$/) {
 4833:                 my $item = $1;
 4834:                 my $type = 'map';
 4835:                 my $timersymb = $item;
 4836:                 if ($item eq 'course') {
 4837:                     $type = 'course';
 4838:                 } elsif ($item =~ /___\d+___/) {
 4839:                     $type = 'resource';
 4840:                 } else {
 4841:                     $timersymb = &Apache::lonnet::symbread($item);
 4842:                 }
 4843:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4844:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4845:                 $triggered{$block} = {
 4846:                                        start => $start,
 4847:                                        end   => $end,
 4848:                                        type  => $type,
 4849:                                      };
 4850:             }
 4851:         }
 4852:     } else {
 4853:         foreach my $block (keys(%commblocks)) {
 4854:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4855:                 my ($start,$end) = ($1,$2);
 4856:                 if ($start <= time && $end >= time) {
 4857:                     if (ref($commblocks{$block}) eq 'HASH') {
 4858:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4859:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4860:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4861:                                     push(@blockers,$block);
 4862:                                 }
 4863:                             }
 4864:                         }
 4865:                     }
 4866:                 }
 4867:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4868:                 my $item = $1;
 4869:                 my $timersymb = $item; 
 4870:                 my $type = 'map';
 4871:                 if ($item eq 'course') {
 4872:                     $type = 'course';
 4873:                 } elsif ($item =~ /___\d+___/) {
 4874:                     $type = 'resource';
 4875:                 } else {
 4876:                     $timersymb = &Apache::lonnet::symbread($item);
 4877:                 }
 4878:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4879:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4880:                 if ($start && $end) {
 4881:                     if (($start <= time) && ($end >= time)) {
 4882:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4883:                             push(@blockers,$block);
 4884:                             $triggered{$block} = {
 4885:                                                    start => $start,
 4886:                                                    end   => $end,
 4887:                                                    type  => $type,
 4888:                                                  };
 4889:                         }
 4890:                     }
 4891:                 }
 4892:             }
 4893:         }
 4894:     }
 4895:     foreach my $blocker (@blockers) {
 4896:         my ($staff_name,$staff_dom,$title,$blocks) =
 4897:             &parse_block_record($commblocks{$blocker});
 4898:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4899:         my ($start,$end,$triggertype);
 4900:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4901:             ($start,$end) = ($1,$2);
 4902:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4903:             $start = $triggered{$blocker}{'start'};
 4904:             $end = $triggered{$blocker}{'end'};
 4905:             $triggertype = $triggered{$blocker}{'type'};
 4906:         }
 4907:         if ($start) {
 4908:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4909:             if ($triggertype) {
 4910:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4911:             } else {
 4912:                 push(@{$$setters{$course}{'triggers'}},0);
 4913:             }
 4914:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4915:                 $startblock = $start;
 4916:                 if ($triggertype) {
 4917:                     $triggerblock = $blocker;
 4918:                 }
 4919:             }
 4920:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4921:                $endblock = $end;
 4922:                if ($triggertype) {
 4923:                    $triggerblock = $blocker;
 4924:                }
 4925:             }
 4926:         }
 4927:     }
 4928:     return ($startblock,$endblock,$triggerblock);
 4929: }
 4930: 
 4931: sub parse_block_record {
 4932:     my ($record) = @_;
 4933:     my ($setuname,$setudom,$title,$blocks);
 4934:     if (ref($record) eq 'HASH') {
 4935:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4936:         $title = &unescape($record->{'event'});
 4937:         $blocks = $record->{'blocks'};
 4938:     } else {
 4939:         my @data = split(/:/,$record,3);
 4940:         if (scalar(@data) eq 2) {
 4941:             $title = $data[1];
 4942:             ($setuname,$setudom) = split(/@/,$data[0]);
 4943:         } else {
 4944:             ($setuname,$setudom,$title) = @data;
 4945:         }
 4946:         $blocks = { 'com' => 'on' };
 4947:     }
 4948:     return ($setuname,$setudom,$title,$blocks);
 4949: }
 4950: 
 4951: sub blocking_status {
 4952:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4953:     my %setters;
 4954: 
 4955: # check for active blocking
 4956:     my ($startblock,$endblock,$triggerblock) = 
 4957:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4958:     my $blocked = 0;
 4959:     if ($startblock && $endblock) {
 4960:         $blocked = 1;
 4961:     }
 4962: 
 4963: # caller just wants to know whether a block is active
 4964:     if (!wantarray) { return $blocked; }
 4965: 
 4966: # build a link to a popup window containing the details
 4967:     my $querystring  = "?activity=$activity";
 4968: # $uname and $udom decide whose portfolio the user is trying to look at
 4969:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4970:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 4971:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4972:     } elsif ($activity eq 'docs') {
 4973:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4974:     }
 4975: 
 4976:     my $output .= <<'END_MYBLOCK';
 4977: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4978:     var options = "width=" + w + ",height=" + h + ",";
 4979:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4980:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4981:     var newWin = window.open(url, wdwName, options);
 4982:     newWin.focus();
 4983: }
 4984: END_MYBLOCK
 4985: 
 4986:     $output = Apache::lonhtmlcommon::scripttag($output);
 4987:   
 4988:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4989:     my $text = &mt('Communication Blocked');
 4990:     my $class = 'LC_comblock';
 4991:     if ($activity eq 'docs') {
 4992:         $text = &mt('Content Access Blocked');
 4993:         $class = '';
 4994:     } elsif ($activity eq 'printout') {
 4995:         $text = &mt('Printing Blocked');
 4996:     } elsif ($activity eq 'passwd') {
 4997:         $text = &mt('Password Changing Blocked');
 4998:     }
 4999:     $output .= <<"END_BLOCK";
 5000: <div class='$class'>
 5001:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5002:   title='$text'>
 5003:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5004:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5005:   title='$text'>$text</a>
 5006: </div>
 5007: 
 5008: END_BLOCK
 5009: 
 5010:     return ($blocked, $output);
 5011: }
 5012: 
 5013: ###############################################
 5014: 
 5015: sub check_ip_acc {
 5016:     my ($acc,$clientip)=@_;
 5017:     &Apache::lonxml::debug("acc is $acc");
 5018:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5019:         return 1;
 5020:     }
 5021:     my $allowed;
 5022:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5023: 
 5024:     my $name;
 5025:     my %access = (
 5026:                      allowfrom => 1,
 5027:                      denyfrom  => 0,
 5028:                  );
 5029:     my @allows;
 5030:     my @denies;
 5031:     foreach my $item (split(',',$acc)) {
 5032:         $item =~ s/^\s*//;
 5033:         $item =~ s/\s*$//;
 5034:         my $pattern;
 5035:         if ($item =~ /^\!(.+)$/) {
 5036:             push(@denies,$1);
 5037:         } else {
 5038:             push(@allows,$item);
 5039:         }
 5040:    }
 5041:    my $numdenies = scalar(@denies);
 5042:    my $numallows = scalar(@allows);
 5043:    my $count = 0;
 5044:    foreach my $pattern (@denies,@allows) {
 5045:         $count ++; 
 5046:         my $acctype = 'allowfrom';
 5047:         if ($count <= $numdenies) {
 5048:             $acctype = 'denyfrom';
 5049:         }
 5050:         if ($pattern =~ /\*$/) {
 5051:             #35.8.*
 5052:             $pattern=~s/\*//;
 5053:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5054:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5055:             #35.8.3.[34-56]
 5056:             my $low=$2;
 5057:             my $high=$3;
 5058:             $pattern=$1;
 5059:             if ($ip =~ /^\Q$pattern\E/) {
 5060:                 my $last=(split(/\./,$ip))[3];
 5061:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5062:             }
 5063:         } elsif ($pattern =~ /^\*/) {
 5064:             #*.msu.edu
 5065:             $pattern=~s/\*//;
 5066:             if (!defined($name)) {
 5067:                 use Socket;
 5068:                 my $netaddr=inet_aton($ip);
 5069:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5070:             }
 5071:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5072:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5073:             #127.0.0.1
 5074:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5075:         } else {
 5076:             #some.name.com
 5077:             if (!defined($name)) {
 5078:                 use Socket;
 5079:                 my $netaddr=inet_aton($ip);
 5080:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5081:             }
 5082:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5083:         }
 5084:         if ($allowed =~ /^(0|1)$/) { last; }
 5085:     }
 5086:     if ($allowed eq '') {
 5087:         if ($numdenies && !$numallows) {
 5088:             $allowed = 1;
 5089:         } else {
 5090:             $allowed = 0;
 5091:         }
 5092:     }
 5093:     return $allowed;
 5094: }
 5095: 
 5096: ###############################################
 5097: 
 5098: =pod
 5099: 
 5100: =head1 Domain Template Functions
 5101: 
 5102: =over 4
 5103: 
 5104: =item * &determinedomain()
 5105: 
 5106: Inputs: $domain (usually will be undef)
 5107: 
 5108: Returns: Determines which domain should be used for designs
 5109: 
 5110: =cut
 5111: 
 5112: ###############################################
 5113: sub determinedomain {
 5114:     my $domain=shift;
 5115:     if (! $domain) {
 5116:         # Determine domain if we have not been given one
 5117:         $domain = &Apache::lonnet::default_login_domain();
 5118:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5119:         if ($env{'request.role.domain'}) { 
 5120:             $domain=$env{'request.role.domain'}; 
 5121:         }
 5122:     }
 5123:     return $domain;
 5124: }
 5125: ###############################################
 5126: 
 5127: sub devalidate_domconfig_cache {
 5128:     my ($udom)=@_;
 5129:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5130: }
 5131: 
 5132: # ---------------------- Get domain configuration for a domain
 5133: sub get_domainconf {
 5134:     my ($udom) = @_;
 5135:     my $cachetime=1800;
 5136:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5137:     if (defined($cached)) { return %{$result}; }
 5138: 
 5139:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5140: 					     ['login','rolecolors','autoenroll'],$udom);
 5141:     my (%designhash,%legacy);
 5142:     if (keys(%domconfig) > 0) {
 5143:         if (ref($domconfig{'login'}) eq 'HASH') {
 5144:             if (keys(%{$domconfig{'login'}})) {
 5145:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5146:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5147:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5148:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5149:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5150:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5151:                                         if ($key eq 'loginvia') {
 5152:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5153:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5154:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5155:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5156: 
 5157:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5158:                                                 } else {
 5159:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5160:                                                 }
 5161:                                             }
 5162:                                         } elsif ($key eq 'headtag') {
 5163:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5164:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5165:                                             }
 5166:                                         }
 5167:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5168:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5169:                                         }
 5170:                                     }
 5171:                                 }
 5172:                             }
 5173:                         } else {
 5174:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5175:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5176:                                     $domconfig{'login'}{$key}{$img};
 5177:                             }
 5178:                         }
 5179:                     } else {
 5180:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5181:                     }
 5182:                 }
 5183:             } else {
 5184:                 $legacy{'login'} = 1;
 5185:             }
 5186:         } else {
 5187:             $legacy{'login'} = 1;
 5188:         }
 5189:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5190:             if (keys(%{$domconfig{'rolecolors'}})) {
 5191:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5192:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5193:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5194:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5195:                         }
 5196:                     }
 5197:                 }
 5198:             } else {
 5199:                 $legacy{'rolecolors'} = 1;
 5200:             }
 5201:         } else {
 5202:             $legacy{'rolecolors'} = 1;
 5203:         }
 5204:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5205:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5206:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5207:             }
 5208:         }
 5209:         if (keys(%legacy) > 0) {
 5210:             my %legacyhash = &get_legacy_domconf($udom);
 5211:             foreach my $item (keys(%legacyhash)) {
 5212:                 if ($item =~ /^\Q$udom\E\.login/) {
 5213:                     if ($legacy{'login'}) { 
 5214:                         $designhash{$item} = $legacyhash{$item};
 5215:                     }
 5216:                 } else {
 5217:                     if ($legacy{'rolecolors'}) {
 5218:                         $designhash{$item} = $legacyhash{$item};
 5219:                     }
 5220:                 }
 5221:             }
 5222:         }
 5223:     } else {
 5224:         %designhash = &get_legacy_domconf($udom); 
 5225:     }
 5226:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5227: 				  $cachetime);
 5228:     return %designhash;
 5229: }
 5230: 
 5231: sub get_legacy_domconf {
 5232:     my ($udom) = @_;
 5233:     my %legacyhash;
 5234:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5235:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5236:     if (-e $designfile) {
 5237:         if ( open (my $fh,"<$designfile") ) {
 5238:             while (my $line = <$fh>) {
 5239:                 next if ($line =~ /^\#/);
 5240:                 chomp($line);
 5241:                 my ($key,$val)=(split(/\=/,$line));
 5242:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5243:             }
 5244:             close($fh);
 5245:         }
 5246:     }
 5247:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5248:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5249:     }
 5250:     return %legacyhash;
 5251: }
 5252: 
 5253: =pod
 5254: 
 5255: =item * &domainlogo()
 5256: 
 5257: Inputs: $domain (usually will be undef)
 5258: 
 5259: Returns: A link to a domain logo, if the domain logo exists.
 5260: If the domain logo does not exist, a description of the domain.
 5261: 
 5262: =cut
 5263: 
 5264: ###############################################
 5265: sub domainlogo {
 5266:     my $domain = &determinedomain(shift);
 5267:     my %designhash = &get_domainconf($domain);    
 5268:     # See if there is a logo
 5269:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5270:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5271:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5272: 	    if ($imgsrc =~ m{^/res/}) {
 5273: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5274: 		&Apache::lonnet::repcopy($local_name);
 5275: 	    }
 5276: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5277:         } 
 5278:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5279:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5280:         return &Apache::lonnet::domain($domain,'description');
 5281:     } else {
 5282:         return '';
 5283:     }
 5284: }
 5285: ##############################################
 5286: 
 5287: =pod
 5288: 
 5289: =item * &designparm()
 5290: 
 5291: Inputs: $which parameter; $domain (usually will be undef)
 5292: 
 5293: Returns: value of designparamter $which
 5294: 
 5295: =cut
 5296: 
 5297: 
 5298: ##############################################
 5299: sub designparm {
 5300:     my ($which,$domain)=@_;
 5301:     if (exists($env{'environment.color.'.$which})) {
 5302:         return $env{'environment.color.'.$which};
 5303:     }
 5304:     $domain=&determinedomain($domain);
 5305:     my %domdesign;
 5306:     unless ($domain eq 'public') {
 5307:         %domdesign = &get_domainconf($domain);
 5308:     }
 5309:     my $output;
 5310:     if ($domdesign{$domain.'.'.$which} ne '') {
 5311:         $output = $domdesign{$domain.'.'.$which};
 5312:     } else {
 5313:         $output = $defaultdesign{$which};
 5314:     }
 5315:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5316:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5317:         if ($output =~ m{^/(adm|res)/}) {
 5318:             if ($output =~ m{^/res/}) {
 5319:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5320:                 &Apache::lonnet::repcopy($local_name);
 5321:             }
 5322:             $output = &lonhttpdurl($output);
 5323:         }
 5324:     }
 5325:     return $output;
 5326: }
 5327: 
 5328: ##############################################
 5329: =pod
 5330: 
 5331: =item * &authorspace()
 5332: 
 5333: Inputs: $url (usually will be undef).
 5334: 
 5335: Returns: Path to Authoring Space containing the resource or 
 5336:          directory being viewed (or for which action is being taken). 
 5337:          If $url is provided, and begins /priv/<domain>/<uname>
 5338:          the path will be that portion of the $context argument.
 5339:          Otherwise the path will be for the author space of the current
 5340:          user when the current role is author, or for that of the 
 5341:          co-author/assistant co-author space when the current role 
 5342:          is co-author or assistant co-author.
 5343: 
 5344: =cut
 5345: 
 5346: sub authorspace {
 5347:     my ($url) = @_;
 5348:     if ($url ne '') {
 5349:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5350:            return $1;
 5351:         }
 5352:     }
 5353:     my $caname = '';
 5354:     my $cadom = '';
 5355:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5356:         ($cadom,$caname) =
 5357:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5358:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5359:         $caname = $env{'user.name'};
 5360:         $cadom = $env{'user.domain'};
 5361:     }
 5362:     if (($caname ne '') && ($cadom ne '')) {
 5363:         return "/priv/$cadom/$caname/";
 5364:     }
 5365:     return;
 5366: }
 5367: 
 5368: ##############################################
 5369: =pod
 5370: 
 5371: =item * &head_subbox()
 5372: 
 5373: Inputs: $content (contains HTML code with page functions, etc.)
 5374: 
 5375: Returns: HTML div with $content
 5376:          To be included in page header
 5377: 
 5378: =cut
 5379: 
 5380: sub head_subbox {
 5381:     my ($content)=@_;
 5382:     my $output =
 5383:         '<div class="LC_head_subbox">'
 5384:        .$content
 5385:        .'</div>'
 5386: }
 5387: 
 5388: ##############################################
 5389: =pod
 5390: 
 5391: =item * &CSTR_pageheader()
 5392: 
 5393: Input: (optional) filename from which breadcrumb trail is built.
 5394:        In most cases no input as needed, as $env{'request.filename'}
 5395:        is appropriate for use in building the breadcrumb trail.
 5396: 
 5397: Returns: HTML div with CSTR path and recent box
 5398:          To be included on Authoring Space pages
 5399: 
 5400: =cut
 5401: 
 5402: sub CSTR_pageheader {
 5403:     my ($trailfile) = @_;
 5404:     if ($trailfile eq '') {
 5405:         $trailfile = $env{'request.filename'};
 5406:     }
 5407: 
 5408: # this is for resources; directories have customtitle, and crumbs
 5409: # and select recent are created in lonpubdir.pm
 5410: 
 5411:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5412:     my ($udom,$uname,$thisdisfn)=
 5413:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5414:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5415:     $formaction =~ s{/+}{/}g;
 5416: 
 5417:     my $parentpath = '';
 5418:     my $lastitem = '';
 5419:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5420:         $parentpath = $1;
 5421:         $lastitem = $2;
 5422:     } else {
 5423:         $lastitem = $thisdisfn;
 5424:     }
 5425: 
 5426:     my $output =
 5427:          '<div>'
 5428:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5429:         .'<b>'.&mt('Authoring Space:').'</b> '
 5430:         .'<form name="dirs" method="post" action="'.$formaction
 5431:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5432:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5433: 
 5434:     if ($lastitem) {
 5435:         $output .=
 5436:              '<span class="LC_filename">'
 5437:             .$lastitem
 5438:             .'</span>';
 5439:     }
 5440:     $output .=
 5441:          '<br />'
 5442:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5443:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5444:         .'</form>'
 5445:         .&Apache::lonmenu::constspaceform()
 5446:         .'</div>';
 5447: 
 5448:     return $output;
 5449: }
 5450: 
 5451: ###############################################
 5452: ###############################################
 5453: 
 5454: =pod
 5455: 
 5456: =back
 5457: 
 5458: =head1 HTML Helpers
 5459: 
 5460: =over 4
 5461: 
 5462: =item * &bodytag()
 5463: 
 5464: Returns a uniform header for LON-CAPA web pages.
 5465: 
 5466: Inputs: 
 5467: 
 5468: =over 4
 5469: 
 5470: =item * $title, A title to be displayed on the page.
 5471: 
 5472: =item * $function, the current role (can be undef).
 5473: 
 5474: =item * $addentries, extra parameters for the <body> tag.
 5475: 
 5476: =item * $bodyonly, if defined, only return the <body> tag.
 5477: 
 5478: =item * $domain, if defined, force a given domain.
 5479: 
 5480: =item * $forcereg, if page should register as content page (relevant for 
 5481:             text interface only)
 5482: 
 5483: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5484:                      navigational links
 5485: 
 5486: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5487: 
 5488: =item * $args, optional argument valid values are
 5489:             no_auto_mt_title -> prevents &mt()ing the title arg
 5490: 
 5491: =item * $advtoolsref, optional argument, ref to an array containing
 5492:             inlineremote items to be added in "Functions" menu below
 5493:             breadcrumbs.
 5494: 
 5495: =back
 5496: 
 5497: Returns: A uniform header for LON-CAPA web pages.  
 5498: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5499: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5500: other decorations will be returned.
 5501: 
 5502: =cut
 5503: 
 5504: sub bodytag {
 5505:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5506:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5507: 
 5508:     my $public;
 5509:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5510:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5511:         $public = 1;
 5512:     }
 5513:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5514:     my $httphost = $args->{'use_absolute'};
 5515: 
 5516:     $function = &get_users_function() if (!$function);
 5517:     my $img =    &designparm($function.'.img',$domain);
 5518:     my $font =   &designparm($function.'.font',$domain);
 5519:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5520: 
 5521:     my %design = ( 'style'   => 'margin-top: 0',
 5522: 		   'bgcolor' => $pgbg,
 5523: 		   'text'    => $font,
 5524:                    'alink'   => &designparm($function.'.alink',$domain),
 5525: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5526: 		   'link'    => &designparm($function.'.link',$domain),);
 5527:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5528: 
 5529:  # role and realm
 5530:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5531:     if ($realm) {
 5532:         $realm = '/'.$realm;
 5533:     }
 5534:     if ($role  eq 'ca') {
 5535:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5536:         $realm = &plainname($rname,$rdom);
 5537:     } 
 5538: # realm
 5539:     if ($env{'request.course.id'}) {
 5540:         if ($env{'request.role'} !~ /^cr/) {
 5541:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5542:         }
 5543:         if ($env{'request.course.sec'}) {
 5544:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5545:         }   
 5546: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5547:     } else {
 5548:         $role = &Apache::lonnet::plaintext($role);
 5549:     }
 5550: 
 5551:     if (!$realm) { $realm='&nbsp;'; }
 5552: 
 5553:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5554: 
 5555: # construct main body tag
 5556:     my $bodytag = "<body $extra_body_attr>".
 5557: 	&Apache::lontexconvert::init_math_support();
 5558: 
 5559:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5560: 
 5561:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5562:         return $bodytag;
 5563:     }
 5564: 
 5565:     if ($public) {
 5566: 	undef($role);
 5567:     }
 5568:     
 5569:     my $titleinfo = '<h1>'.$title.'</h1>';
 5570:     #
 5571:     # Extra info if you are the DC
 5572:     my $dc_info = '';
 5573:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5574:                         $env{'course.'.$env{'request.course.id'}.
 5575:                                  '.domain'}.'/'})) {
 5576:         my $cid = $env{'request.course.id'};
 5577:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5578:         $dc_info =~ s/\s+$//;
 5579:     }
 5580: 
 5581:     my $crstype;
 5582:     if ($env{'request.course.id'}) {
 5583:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 5584:     } elsif ($args->{'crstype'}) {
 5585:         $crstype = $args->{'crstype'};
 5586:     }
 5587:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 5588:         undef($role);
 5589:     } else {
 5590:         $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5591:     }
 5592: 
 5593:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5594: 
 5595:         #    if ($env{'request.state'} eq 'construct') {
 5596:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5597:         #    }
 5598: 
 5599:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5600:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5601: 
 5602:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
 5603: 
 5604:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5605:              if ($dc_info) {
 5606:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5607:              }
 5608:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5609:                 <em>$realm</em> $dc_info</div>|;
 5610:             return $bodytag;
 5611:         }
 5612: 
 5613:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5614:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5615:         }
 5616: 
 5617:         $bodytag .= $right;
 5618: 
 5619:         if ($dc_info) {
 5620:             $dc_info = &dc_courseid_toggle($dc_info);
 5621:         }
 5622:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5623: 
 5624:         #if directed to not display the secondary menu, don't.  
 5625:         if ($args->{'no_secondary_menu'}) {
 5626:             return $bodytag;
 5627:         }
 5628:         #don't show menus for public users
 5629:         if (!$public){
 5630:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5631:             $bodytag .= Apache::lonmenu::serverform();
 5632:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5633:             if ($env{'request.state'} eq 'construct') {
 5634:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5635:                                 $args->{'bread_crumbs'});
 5636:             } elsif ($forcereg) {
 5637:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5638:                                                             $args->{'group'});
 5639:             } else {
 5640:                 $bodytag .= 
 5641:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5642:                                                         $forcereg,$args->{'group'},
 5643:                                                         $args->{'bread_crumbs'},
 5644:                                                         $advtoolsref);
 5645:             }
 5646:         }else{
 5647:             # this is to seperate menu from content when there's no secondary
 5648:             # menu. Especially needed for public accessible ressources.
 5649:             $bodytag .= '<hr style="clear:both" />';
 5650:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5651:         }
 5652: 
 5653:         return $bodytag;
 5654: }
 5655: 
 5656: sub dc_courseid_toggle {
 5657:     my ($dc_info) = @_;
 5658:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5659:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5660:            &mt('(More ...)').'</a></span>'.
 5661:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5662: }
 5663: 
 5664: sub make_attr_string {
 5665:     my ($register,$attr_ref) = @_;
 5666: 
 5667:     if ($attr_ref && !ref($attr_ref)) {
 5668: 	die("addentries Must be a hash ref ".
 5669: 	    join(':',caller(1))." ".
 5670: 	    join(':',caller(0))." ");
 5671:     }
 5672: 
 5673:     if ($register) {
 5674: 	my ($on_load,$on_unload);
 5675: 	foreach my $key (keys(%{$attr_ref})) {
 5676: 	    if      (lc($key) eq 'onload') {
 5677: 		$on_load.=$attr_ref->{$key}.';';
 5678: 		delete($attr_ref->{$key});
 5679: 
 5680: 	    } elsif (lc($key) eq 'onunload') {
 5681: 		$on_unload.=$attr_ref->{$key}.';';
 5682: 		delete($attr_ref->{$key});
 5683: 	    }
 5684: 	}
 5685: 	$attr_ref->{'onload'}  = $on_load;
 5686: 	$attr_ref->{'onunload'}= $on_unload;
 5687:     }
 5688: 
 5689:     my $attr_string;
 5690:     foreach my $attr (sort(keys(%$attr_ref))) {
 5691: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5692:     }
 5693:     return $attr_string;
 5694: }
 5695: 
 5696: 
 5697: ###############################################
 5698: ###############################################
 5699: 
 5700: =pod
 5701: 
 5702: =item * &endbodytag()
 5703: 
 5704: Returns a uniform footer for LON-CAPA web pages.
 5705: 
 5706: Inputs: 1 - optional reference to an args hash
 5707: If in the hash, key for noredirectlink has a value which evaluates to true,
 5708: a 'Continue' link is not displayed if the page contains an
 5709: internal redirect in the <head></head> section,
 5710: i.e., $env{'internal.head.redirect'} exists   
 5711: 
 5712: =cut
 5713: 
 5714: sub endbodytag {
 5715:     my ($args) = @_;
 5716:     my $endbodytag;
 5717:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5718:         $endbodytag='</body>';
 5719:     }
 5720:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5721:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5722: 	    $endbodytag=
 5723: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5724: 	        &mt('Continue').'</a>'.
 5725: 	        $endbodytag;
 5726:         }
 5727:     }
 5728:     return $endbodytag;
 5729: }
 5730: 
 5731: =pod
 5732: 
 5733: =item * &standard_css()
 5734: 
 5735: Returns a style sheet
 5736: 
 5737: Inputs: (all optional)
 5738:             domain         -> force to color decorate a page for a specific
 5739:                                domain
 5740:             function       -> force usage of a specific rolish color scheme
 5741:             bgcolor        -> override the default page bgcolor
 5742: 
 5743: =cut
 5744: 
 5745: sub standard_css {
 5746:     my ($function,$domain,$bgcolor) = @_;
 5747:     $function  = &get_users_function() if (!$function);
 5748:     my $img    = &designparm($function.'.img',   $domain);
 5749:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5750:     my $font   = &designparm($function.'.font',  $domain);
 5751:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5752: #second colour for later usage
 5753:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5754:     my $pgbg_or_bgcolor =
 5755: 	         $bgcolor ||
 5756: 	         &designparm($function.'.pgbg',  $domain);
 5757:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5758:     my $alink  = &designparm($function.'.alink', $domain);
 5759:     my $vlink  = &designparm($function.'.vlink', $domain);
 5760:     my $link   = &designparm($function.'.link',  $domain);
 5761: 
 5762:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5763:     my $mono                 = 'monospace';
 5764:     my $data_table_head      = $sidebg;
 5765:     my $data_table_light     = '#FAFAFA';
 5766:     my $data_table_dark      = '#E0E0E0';
 5767:     my $data_table_darker    = '#CCCCCC';
 5768:     my $data_table_highlight = '#FFFF00';
 5769:     my $mail_new             = '#FFBB77';
 5770:     my $mail_new_hover       = '#DD9955';
 5771:     my $mail_read            = '#BBBB77';
 5772:     my $mail_read_hover      = '#999944';
 5773:     my $mail_replied         = '#AAAA88';
 5774:     my $mail_replied_hover   = '#888855';
 5775:     my $mail_other           = '#99BBBB';
 5776:     my $mail_other_hover     = '#669999';
 5777:     my $table_header         = '#DDDDDD';
 5778:     my $feedback_link_bg     = '#BBBBBB';
 5779:     my $lg_border_color      = '#C8C8C8';
 5780:     my $button_hover         = '#BF2317';
 5781: 
 5782:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5783:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5784:                                              : '0 3px 0 4px';
 5785: 
 5786: 
 5787:     return <<END;
 5788: 
 5789: /* needed for iframe to allow 100% height in FF */
 5790: body, html { 
 5791:     margin: 0;
 5792:     padding: 0 0.5%;
 5793:     height: 99%; /* to avoid scrollbars */
 5794: }
 5795: 
 5796: body {
 5797:   font-family: $sans;
 5798:   line-height:130%;
 5799:   font-size:0.83em;
 5800:   color:$font;
 5801: }
 5802: 
 5803: a:focus,
 5804: a:focus img {
 5805:   color: red;
 5806: }
 5807: 
 5808: form, .inline {
 5809:   display: inline;
 5810: }
 5811: 
 5812: .LC_right {
 5813:   text-align:right;
 5814: }
 5815: 
 5816: .LC_middle {
 5817:   vertical-align:middle;
 5818: }
 5819: 
 5820: .LC_floatleft {
 5821:   float: left;
 5822: }
 5823: 
 5824: .LC_floatright {
 5825:   float: right;
 5826: }
 5827: 
 5828: .LC_400Box {
 5829:   width:400px;
 5830: }
 5831: 
 5832: .LC_iframecontainer {
 5833:     width: 98%;
 5834:     margin: 0;
 5835:     position: fixed;
 5836:     top: 8.5em;
 5837:     bottom: 0;
 5838: }
 5839: 
 5840: .LC_iframecontainer iframe{
 5841:     border: none;
 5842:     width: 100%;
 5843:     height: 100%;
 5844: }
 5845: 
 5846: .LC_filename {
 5847:   font-family: $mono;
 5848:   white-space:pre;
 5849:   font-size: 120%;
 5850: }
 5851: 
 5852: .LC_fileicon {
 5853:   border: none;
 5854:   height: 1.3em;
 5855:   vertical-align: text-bottom;
 5856:   margin-right: 0.3em;
 5857:   text-decoration:none;
 5858: }
 5859: 
 5860: .LC_setting {
 5861:   text-decoration:underline;
 5862: }
 5863: 
 5864: .LC_error {
 5865:   color: red;
 5866: }
 5867: 
 5868: .LC_warning {
 5869:   color: darkorange;
 5870: }
 5871: 
 5872: .LC_diff_removed {
 5873:   color: red;
 5874: }
 5875: 
 5876: .LC_info,
 5877: .LC_success,
 5878: .LC_diff_added {
 5879:   color: green;
 5880: }
 5881: 
 5882: div.LC_confirm_box {
 5883:   background-color: #FAFAFA;
 5884:   border: 1px solid $lg_border_color;
 5885:   margin-right: 0;
 5886:   padding: 5px;
 5887: }
 5888: 
 5889: div.LC_confirm_box .LC_error img,
 5890: div.LC_confirm_box .LC_success img {
 5891:   vertical-align: middle;
 5892: }
 5893: 
 5894: .LC_icon {
 5895:   border: none;
 5896:   vertical-align: middle;
 5897: }
 5898: 
 5899: .LC_docs_spacer {
 5900:   width: 25px;
 5901:   height: 1px;
 5902:   border: none;
 5903: }
 5904: 
 5905: .LC_internal_info {
 5906:   color: #999999;
 5907: }
 5908: 
 5909: .LC_discussion {
 5910:   background: $data_table_dark;
 5911:   border: 1px solid black;
 5912:   margin: 2px;
 5913: }
 5914: 
 5915: .LC_disc_action_left {
 5916:   background: $sidebg;
 5917:   text-align: left;
 5918:   padding: 4px;
 5919:   margin: 2px;
 5920: }
 5921: 
 5922: .LC_disc_action_right {
 5923:   background: $sidebg;
 5924:   text-align: right;
 5925:   padding: 4px;
 5926:   margin: 2px;
 5927: }
 5928: 
 5929: .LC_disc_new_item {
 5930:   background: white;
 5931:   border: 2px solid red;
 5932:   margin: 4px;
 5933:   padding: 4px;
 5934: }
 5935: 
 5936: .LC_disc_old_item {
 5937:   background: white;
 5938:   margin: 4px;
 5939:   padding: 4px;
 5940: }
 5941: 
 5942: table.LC_pastsubmission {
 5943:   border: 1px solid black;
 5944:   margin: 2px;
 5945: }
 5946: 
 5947: table#LC_menubuttons {
 5948:   width: 100%;
 5949:   background: $pgbg;
 5950:   border: 2px;
 5951:   border-collapse: separate;
 5952:   padding: 0;
 5953: }
 5954: 
 5955: table#LC_title_bar a {
 5956:   color: $fontmenu;
 5957: }
 5958: 
 5959: table#LC_title_bar {
 5960:   clear: both;
 5961:   display: none;
 5962: }
 5963: 
 5964: table#LC_title_bar,
 5965: table.LC_breadcrumbs, /* obsolete? */
 5966: table#LC_title_bar.LC_with_remote {
 5967:   width: 100%;
 5968:   border-color: $pgbg;
 5969:   border-style: solid;
 5970:   border-width: $border;
 5971:   background: $pgbg;
 5972:   color: $fontmenu;
 5973:   border-collapse: collapse;
 5974:   padding: 0;
 5975:   margin: 0;
 5976: }
 5977: 
 5978: ul.LC_breadcrumb_tools_outerlist {
 5979:     margin: 0;
 5980:     padding: 0;
 5981:     position: relative;
 5982:     list-style: none;
 5983: }
 5984: ul.LC_breadcrumb_tools_outerlist li {
 5985:     display: inline;
 5986: }
 5987: 
 5988: .LC_breadcrumb_tools_navigation {
 5989:     padding: 0;
 5990:     margin: 0;
 5991:     float: left;
 5992: }
 5993: .LC_breadcrumb_tools_tools {
 5994:     padding: 0;
 5995:     margin: 0;
 5996:     float: right;
 5997: }
 5998: 
 5999: .LC_placement_prog {
 6000:     padding-right: 20px;
 6001:     font-weight: bold;
 6002:     font-size: 90%;
 6003: }
 6004: 
 6005: table#LC_title_bar td {
 6006:   background: $tabbg;
 6007: }
 6008: 
 6009: table#LC_menubuttons img {
 6010:   border: none;
 6011: }
 6012: 
 6013: .LC_breadcrumbs_component {
 6014:   float: right;
 6015:   margin: 0 1em;
 6016: }
 6017: .LC_breadcrumbs_component img {
 6018:   vertical-align: middle;
 6019: }
 6020: 
 6021: td.LC_table_cell_checkbox {
 6022:   text-align: center;
 6023: }
 6024: 
 6025: .LC_fontsize_small {
 6026:   font-size: 70%;
 6027: }
 6028: 
 6029: #LC_breadcrumbs {
 6030:   clear:both;
 6031:   background: $sidebg;
 6032:   border-bottom: 1px solid $lg_border_color;
 6033:   line-height: 2.5em;
 6034:   overflow: hidden;
 6035:   margin: 0;
 6036:   padding: 0;
 6037:   text-align: left;
 6038: }
 6039: 
 6040: .LC_head_subbox, .LC_actionbox {
 6041:   clear:both;
 6042:   background: #F8F8F8; /* $sidebg; */
 6043:   border: 1px solid $sidebg;
 6044:   margin: 0 0 10px 0;
 6045:   padding: 3px;
 6046:   text-align: left;
 6047: }
 6048: 
 6049: .LC_fontsize_medium {
 6050:   font-size: 85%;
 6051: }
 6052: 
 6053: .LC_fontsize_large {
 6054:   font-size: 120%;
 6055: }
 6056: 
 6057: .LC_menubuttons_inline_text {
 6058:   color: $font;
 6059:   font-size: 90%;
 6060:   padding-left:3px;
 6061: }
 6062: 
 6063: .LC_menubuttons_inline_text img{
 6064:   vertical-align: middle;
 6065: }
 6066: 
 6067: li.LC_menubuttons_inline_text img {
 6068:   cursor:pointer;
 6069:   text-decoration: none;
 6070: }
 6071: 
 6072: .LC_menubuttons_link {
 6073:   text-decoration: none;
 6074: }
 6075: 
 6076: .LC_menubuttons_category {
 6077:   color: $font;
 6078:   background: $pgbg;
 6079:   font-size: larger;
 6080:   font-weight: bold;
 6081: }
 6082: 
 6083: td.LC_menubuttons_text {
 6084:   color: $font;
 6085: }
 6086: 
 6087: .LC_current_location {
 6088:   background: $tabbg;
 6089: }
 6090: 
 6091: table.LC_data_table {
 6092:   border: 1px solid #000000;
 6093:   border-collapse: separate;
 6094:   border-spacing: 1px;
 6095:   background: $pgbg;
 6096: }
 6097: 
 6098: .LC_data_table_dense {
 6099:   font-size: small;
 6100: }
 6101: 
 6102: table.LC_nested_outer {
 6103:   border: 1px solid #000000;
 6104:   border-collapse: collapse;
 6105:   border-spacing: 0;
 6106:   width: 100%;
 6107: }
 6108: 
 6109: table.LC_innerpickbox,
 6110: table.LC_nested {
 6111:   border: none;
 6112:   border-collapse: collapse;
 6113:   border-spacing: 0;
 6114:   width: 100%;
 6115: }
 6116: 
 6117: table.LC_data_table tr th,
 6118: table.LC_calendar tr th,
 6119: table.LC_prior_tries tr th,
 6120: table.LC_innerpickbox tr th {
 6121:   font-weight: bold;
 6122:   background-color: $data_table_head;
 6123:   color:$fontmenu;
 6124:   font-size:90%;
 6125: }
 6126: 
 6127: table.LC_innerpickbox tr th,
 6128: table.LC_innerpickbox tr td {
 6129:   vertical-align: top;
 6130: }
 6131: 
 6132: table.LC_data_table tr.LC_info_row > td {
 6133:   background-color: #CCCCCC;
 6134:   font-weight: bold;
 6135:   text-align: left;
 6136: }
 6137: 
 6138: table.LC_data_table tr.LC_odd_row > td {
 6139:   background-color: $data_table_light;
 6140:   padding: 2px;
 6141:   vertical-align: top;
 6142: }
 6143: 
 6144: table.LC_pick_box tr > td.LC_odd_row {
 6145:   background-color: $data_table_light;
 6146:   vertical-align: top;
 6147: }
 6148: 
 6149: table.LC_data_table tr.LC_even_row > td {
 6150:   background-color: $data_table_dark;
 6151:   padding: 2px;
 6152:   vertical-align: top;
 6153: }
 6154: 
 6155: table.LC_pick_box tr > td.LC_even_row {
 6156:   background-color: $data_table_dark;
 6157:   vertical-align: top;
 6158: }
 6159: 
 6160: table.LC_data_table tr.LC_data_table_highlight td {
 6161:   background-color: $data_table_darker;
 6162: }
 6163: 
 6164: table.LC_data_table tr td.LC_leftcol_header {
 6165:   background-color: $data_table_head;
 6166:   font-weight: bold;
 6167: }
 6168: 
 6169: table.LC_data_table tr.LC_empty_row td,
 6170: table.LC_nested tr.LC_empty_row td {
 6171:   font-weight: bold;
 6172:   font-style: italic;
 6173:   text-align: center;
 6174:   padding: 8px;
 6175: }
 6176: 
 6177: table.LC_data_table tr.LC_empty_row td,
 6178: table.LC_data_table tr.LC_footer_row td {
 6179:   background-color: $sidebg;
 6180: }
 6181: 
 6182: table.LC_nested tr.LC_empty_row td {
 6183:   background-color: #FFFFFF;
 6184: }
 6185: 
 6186: table.LC_caption {
 6187: }
 6188: 
 6189: table.LC_nested tr.LC_empty_row td {
 6190:   padding: 4ex
 6191: }
 6192: 
 6193: table.LC_nested_outer tr th {
 6194:   font-weight: bold;
 6195:   color:$fontmenu;
 6196:   background-color: $data_table_head;
 6197:   font-size: small;
 6198:   border-bottom: 1px solid #000000;
 6199: }
 6200: 
 6201: table.LC_nested_outer tr td.LC_subheader {
 6202:   background-color: $data_table_head;
 6203:   font-weight: bold;
 6204:   font-size: small;
 6205:   border-bottom: 1px solid #000000;
 6206:   text-align: right;
 6207: }
 6208: 
 6209: table.LC_nested tr.LC_info_row td {
 6210:   background-color: #CCCCCC;
 6211:   font-weight: bold;
 6212:   font-size: small;
 6213:   text-align: center;
 6214: }
 6215: 
 6216: table.LC_nested tr.LC_info_row td.LC_left_item,
 6217: table.LC_nested_outer tr th.LC_left_item {
 6218:   text-align: left;
 6219: }
 6220: 
 6221: table.LC_nested td {
 6222:   background-color: #FFFFFF;
 6223:   font-size: small;
 6224: }
 6225: 
 6226: table.LC_nested_outer tr th.LC_right_item,
 6227: table.LC_nested tr.LC_info_row td.LC_right_item,
 6228: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6229: table.LC_nested tr td.LC_right_item {
 6230:   text-align: right;
 6231: }
 6232: 
 6233: table.LC_nested tr.LC_odd_row td {
 6234:   background-color: #EEEEEE;
 6235: }
 6236: 
 6237: table.LC_createuser {
 6238: }
 6239: 
 6240: table.LC_createuser tr.LC_section_row td {
 6241:   font-size: small;
 6242: }
 6243: 
 6244: table.LC_createuser tr.LC_info_row td  {
 6245:   background-color: #CCCCCC;
 6246:   font-weight: bold;
 6247:   text-align: center;
 6248: }
 6249: 
 6250: table.LC_calendar {
 6251:   border: 1px solid #000000;
 6252:   border-collapse: collapse;
 6253:   width: 98%;
 6254: }
 6255: 
 6256: table.LC_calendar_pickdate {
 6257:   font-size: xx-small;
 6258: }
 6259: 
 6260: table.LC_calendar tr td {
 6261:   border: 1px solid #000000;
 6262:   vertical-align: top;
 6263:   width: 14%;
 6264: }
 6265: 
 6266: table.LC_calendar tr td.LC_calendar_day_empty {
 6267:   background-color: $data_table_dark;
 6268: }
 6269: 
 6270: table.LC_calendar tr td.LC_calendar_day_current {
 6271:   background-color: $data_table_highlight;
 6272: }
 6273: 
 6274: table.LC_data_table tr td.LC_mail_new {
 6275:   background-color: $mail_new;
 6276: }
 6277: 
 6278: table.LC_data_table tr.LC_mail_new:hover {
 6279:   background-color: $mail_new_hover;
 6280: }
 6281: 
 6282: table.LC_data_table tr td.LC_mail_read {
 6283:   background-color: $mail_read;
 6284: }
 6285: 
 6286: /*
 6287: table.LC_data_table tr.LC_mail_read:hover {
 6288:   background-color: $mail_read_hover;
 6289: }
 6290: */
 6291: 
 6292: table.LC_data_table tr td.LC_mail_replied {
 6293:   background-color: $mail_replied;
 6294: }
 6295: 
 6296: /*
 6297: table.LC_data_table tr.LC_mail_replied:hover {
 6298:   background-color: $mail_replied_hover;
 6299: }
 6300: */
 6301: 
 6302: table.LC_data_table tr td.LC_mail_other {
 6303:   background-color: $mail_other;
 6304: }
 6305: 
 6306: /*
 6307: table.LC_data_table tr.LC_mail_other:hover {
 6308:   background-color: $mail_other_hover;
 6309: }
 6310: */
 6311: 
 6312: table.LC_data_table tr > td.LC_browser_file,
 6313: table.LC_data_table tr > td.LC_browser_file_published {
 6314:   background: #AAEE77;
 6315: }
 6316: 
 6317: table.LC_data_table tr > td.LC_browser_file_locked,
 6318: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6319:   background: #FFAA99;
 6320: }
 6321: 
 6322: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6323:   background: #888888;
 6324: }
 6325: 
 6326: table.LC_data_table tr > td.LC_browser_file_modified,
 6327: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6328:   background: #F8F866;
 6329: }
 6330: 
 6331: table.LC_data_table tr.LC_browser_folder > td {
 6332:   background: #E0E8FF;
 6333: }
 6334: 
 6335: table.LC_data_table tr > td.LC_roles_is {
 6336:   /* background: #77FF77; */
 6337: }
 6338: 
 6339: table.LC_data_table tr > td.LC_roles_future {
 6340:   border-right: 8px solid #FFFF77;
 6341: }
 6342: 
 6343: table.LC_data_table tr > td.LC_roles_will {
 6344:   border-right: 8px solid #FFAA77;
 6345: }
 6346: 
 6347: table.LC_data_table tr > td.LC_roles_expired {
 6348:   border-right: 8px solid #FF7777;
 6349: }
 6350: 
 6351: table.LC_data_table tr > td.LC_roles_will_not {
 6352:   border-right: 8px solid #AAFF77;
 6353: }
 6354: 
 6355: table.LC_data_table tr > td.LC_roles_selected {
 6356:   border-right: 8px solid #11CC55;
 6357: }
 6358: 
 6359: span.LC_current_location {
 6360:   font-size:larger;
 6361:   background: $pgbg;
 6362: }
 6363: 
 6364: span.LC_current_nav_location {
 6365:   font-weight:bold;
 6366:   background: $sidebg;
 6367: }
 6368: 
 6369: span.LC_parm_menu_item {
 6370:   font-size: larger;
 6371: }
 6372: 
 6373: span.LC_parm_scope_all {
 6374:   color: red;
 6375: }
 6376: 
 6377: span.LC_parm_scope_folder {
 6378:   color: green;
 6379: }
 6380: 
 6381: span.LC_parm_scope_resource {
 6382:   color: orange;
 6383: }
 6384: 
 6385: span.LC_parm_part {
 6386:   color: blue;
 6387: }
 6388: 
 6389: span.LC_parm_folder,
 6390: span.LC_parm_symb {
 6391:   font-size: x-small;
 6392:   font-family: $mono;
 6393:   color: #AAAAAA;
 6394: }
 6395: 
 6396: ul.LC_parm_parmlist li {
 6397:   display: inline-block;
 6398:   padding: 0.3em 0.8em;
 6399:   vertical-align: top;
 6400:   width: 150px;
 6401:   border-top:1px solid $lg_border_color;
 6402: }
 6403: 
 6404: td.LC_parm_overview_level_menu,
 6405: td.LC_parm_overview_map_menu,
 6406: td.LC_parm_overview_parm_selectors,
 6407: td.LC_parm_overview_restrictions  {
 6408:   border: 1px solid black;
 6409:   border-collapse: collapse;
 6410: }
 6411: 
 6412: table.LC_parm_overview_restrictions td {
 6413:   border-width: 1px 4px 1px 4px;
 6414:   border-style: solid;
 6415:   border-color: $pgbg;
 6416:   text-align: center;
 6417: }
 6418: 
 6419: table.LC_parm_overview_restrictions th {
 6420:   background: $tabbg;
 6421:   border-width: 1px 4px 1px 4px;
 6422:   border-style: solid;
 6423:   border-color: $pgbg;
 6424: }
 6425: 
 6426: table#LC_helpmenu {
 6427:   border: none;
 6428:   height: 55px;
 6429:   border-spacing: 0;
 6430: }
 6431: 
 6432: table#LC_helpmenu fieldset legend {
 6433:   font-size: larger;
 6434: }
 6435: 
 6436: table#LC_helpmenu_links {
 6437:   width: 100%;
 6438:   border: 1px solid black;
 6439:   background: $pgbg;
 6440:   padding: 0;
 6441:   border-spacing: 1px;
 6442: }
 6443: 
 6444: table#LC_helpmenu_links tr td {
 6445:   padding: 1px;
 6446:   background: $tabbg;
 6447:   text-align: center;
 6448:   font-weight: bold;
 6449: }
 6450: 
 6451: table#LC_helpmenu_links a:link,
 6452: table#LC_helpmenu_links a:visited,
 6453: table#LC_helpmenu_links a:active {
 6454:   text-decoration: none;
 6455:   color: $font;
 6456: }
 6457: 
 6458: table#LC_helpmenu_links a:hover {
 6459:   text-decoration: underline;
 6460:   color: $vlink;
 6461: }
 6462: 
 6463: .LC_chrt_popup_exists {
 6464:   border: 1px solid #339933;
 6465:   margin: -1px;
 6466: }
 6467: 
 6468: .LC_chrt_popup_up {
 6469:   border: 1px solid yellow;
 6470:   margin: -1px;
 6471: }
 6472: 
 6473: .LC_chrt_popup {
 6474:   border: 1px solid #8888FF;
 6475:   background: #CCCCFF;
 6476: }
 6477: 
 6478: table.LC_pick_box {
 6479:   border-collapse: separate;
 6480:   background: white;
 6481:   border: 1px solid black;
 6482:   border-spacing: 1px;
 6483: }
 6484: 
 6485: table.LC_pick_box td.LC_pick_box_title {
 6486:   background: $sidebg;
 6487:   font-weight: bold;
 6488:   text-align: left;
 6489:   vertical-align: top;
 6490:   width: 184px;
 6491:   padding: 8px;
 6492: }
 6493: 
 6494: table.LC_pick_box td.LC_pick_box_value {
 6495:   text-align: left;
 6496:   padding: 8px;
 6497: }
 6498: 
 6499: table.LC_pick_box td.LC_pick_box_select {
 6500:   text-align: left;
 6501:   padding: 8px;
 6502: }
 6503: 
 6504: table.LC_pick_box td.LC_pick_box_separator {
 6505:   padding: 0;
 6506:   height: 1px;
 6507:   background: black;
 6508: }
 6509: 
 6510: table.LC_pick_box td.LC_pick_box_submit {
 6511:   text-align: right;
 6512: }
 6513: 
 6514: table.LC_pick_box td.LC_evenrow_value {
 6515:   text-align: left;
 6516:   padding: 8px;
 6517:   background-color: $data_table_light;
 6518: }
 6519: 
 6520: table.LC_pick_box td.LC_oddrow_value {
 6521:   text-align: left;
 6522:   padding: 8px;
 6523:   background-color: $data_table_light;
 6524: }
 6525: 
 6526: span.LC_helpform_receipt_cat {
 6527:   font-weight: bold;
 6528: }
 6529: 
 6530: table.LC_group_priv_box {
 6531:   background: white;
 6532:   border: 1px solid black;
 6533:   border-spacing: 1px;
 6534: }
 6535: 
 6536: table.LC_group_priv_box td.LC_pick_box_title {
 6537:   background: $tabbg;
 6538:   font-weight: bold;
 6539:   text-align: right;
 6540:   width: 184px;
 6541: }
 6542: 
 6543: table.LC_group_priv_box td.LC_groups_fixed {
 6544:   background: $data_table_light;
 6545:   text-align: center;
 6546: }
 6547: 
 6548: table.LC_group_priv_box td.LC_groups_optional {
 6549:   background: $data_table_dark;
 6550:   text-align: center;
 6551: }
 6552: 
 6553: table.LC_group_priv_box td.LC_groups_functionality {
 6554:   background: $data_table_darker;
 6555:   text-align: center;
 6556:   font-weight: bold;
 6557: }
 6558: 
 6559: table.LC_group_priv td {
 6560:   text-align: left;
 6561:   padding: 0;
 6562: }
 6563: 
 6564: .LC_navbuttons {
 6565:   margin: 2ex 0ex 2ex 0ex;
 6566: }
 6567: 
 6568: .LC_topic_bar {
 6569:   font-weight: bold;
 6570:   background: $tabbg;
 6571:   margin: 1em 0em 1em 2em;
 6572:   padding: 3px;
 6573:   font-size: 1.2em;
 6574: }
 6575: 
 6576: .LC_topic_bar span {
 6577:   left: 0.5em;
 6578:   position: absolute;
 6579:   vertical-align: middle;
 6580:   font-size: 1.2em;
 6581: }
 6582: 
 6583: table.LC_course_group_status {
 6584:   margin: 20px;
 6585: }
 6586: 
 6587: table.LC_status_selector td {
 6588:   vertical-align: top;
 6589:   text-align: center;
 6590:   padding: 4px;
 6591: }
 6592: 
 6593: div.LC_feedback_link {
 6594:   clear: both;
 6595:   background: $sidebg;
 6596:   width: 100%;
 6597:   padding-bottom: 10px;
 6598:   border: 1px $tabbg solid;
 6599:   height: 22px;
 6600:   line-height: 22px;
 6601:   padding-top: 5px;
 6602: }
 6603: 
 6604: div.LC_feedback_link img {
 6605:   height: 22px;
 6606:   vertical-align:middle;
 6607: }
 6608: 
 6609: div.LC_feedback_link a {
 6610:   text-decoration: none;
 6611: }
 6612: 
 6613: div.LC_comblock {
 6614:   display:inline;
 6615:   color:$font;
 6616:   font-size:90%;
 6617: }
 6618: 
 6619: div.LC_feedback_link div.LC_comblock {
 6620:   padding-left:5px;
 6621: }
 6622: 
 6623: div.LC_feedback_link div.LC_comblock a {
 6624:   color:$font;
 6625: }
 6626: 
 6627: span.LC_feedback_link {
 6628:   /* background: $feedback_link_bg; */
 6629:   font-size: larger;
 6630: }
 6631: 
 6632: span.LC_message_link {
 6633:   /* background: $feedback_link_bg; */
 6634:   font-size: larger;
 6635:   position: absolute;
 6636:   right: 1em;
 6637: }
 6638: 
 6639: table.LC_prior_tries {
 6640:   border: 1px solid #000000;
 6641:   border-collapse: separate;
 6642:   border-spacing: 1px;
 6643: }
 6644: 
 6645: table.LC_prior_tries td {
 6646:   padding: 2px;
 6647: }
 6648: 
 6649: .LC_answer_correct {
 6650:   background: lightgreen;
 6651:   color: darkgreen;
 6652:   padding: 6px;
 6653: }
 6654: 
 6655: .LC_answer_charged_try {
 6656:   background: #FFAAAA;
 6657:   color: darkred;
 6658:   padding: 6px;
 6659: }
 6660: 
 6661: .LC_answer_not_charged_try,
 6662: .LC_answer_no_grade,
 6663: .LC_answer_late {
 6664:   background: lightyellow;
 6665:   color: black;
 6666:   padding: 6px;
 6667: }
 6668: 
 6669: .LC_answer_previous {
 6670:   background: lightblue;
 6671:   color: darkblue;
 6672:   padding: 6px;
 6673: }
 6674: 
 6675: .LC_answer_no_message {
 6676:   background: #FFFFFF;
 6677:   color: black;
 6678:   padding: 6px;
 6679: }
 6680: 
 6681: .LC_answer_unknown {
 6682:   background: orange;
 6683:   color: black;
 6684:   padding: 6px;
 6685: }
 6686: 
 6687: span.LC_prior_numerical,
 6688: span.LC_prior_string,
 6689: span.LC_prior_custom,
 6690: span.LC_prior_reaction,
 6691: span.LC_prior_math {
 6692:   font-family: $mono;
 6693:   white-space: pre;
 6694: }
 6695: 
 6696: span.LC_prior_string {
 6697:   font-family: $mono;
 6698:   white-space: pre;
 6699: }
 6700: 
 6701: table.LC_prior_option {
 6702:   width: 100%;
 6703:   border-collapse: collapse;
 6704: }
 6705: 
 6706: table.LC_prior_rank,
 6707: table.LC_prior_match {
 6708:   border-collapse: collapse;
 6709: }
 6710: 
 6711: table.LC_prior_option tr td,
 6712: table.LC_prior_rank tr td,
 6713: table.LC_prior_match tr td {
 6714:   border: 1px solid #000000;
 6715: }
 6716: 
 6717: .LC_nobreak {
 6718:   white-space: nowrap;
 6719: }
 6720: 
 6721: span.LC_cusr_emph {
 6722:   font-style: italic;
 6723: }
 6724: 
 6725: span.LC_cusr_subheading {
 6726:   font-weight: normal;
 6727:   font-size: 85%;
 6728: }
 6729: 
 6730: div.LC_docs_entry_move {
 6731:   border: 1px solid #BBBBBB;
 6732:   background: #DDDDDD;
 6733:   width: 22px;
 6734:   padding: 1px;
 6735:   margin: 0;
 6736: }
 6737: 
 6738: table.LC_data_table tr > td.LC_docs_entry_commands,
 6739: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6740:   font-size: x-small;
 6741: }
 6742: 
 6743: .LC_docs_entry_parameter {
 6744:   white-space: nowrap;
 6745: }
 6746: 
 6747: .LC_docs_copy {
 6748:   color: #000099;
 6749: }
 6750: 
 6751: .LC_docs_cut {
 6752:   color: #550044;
 6753: }
 6754: 
 6755: .LC_docs_rename {
 6756:   color: #009900;
 6757: }
 6758: 
 6759: .LC_docs_remove {
 6760:   color: #990000;
 6761: }
 6762: 
 6763: .LC_docs_reinit_warn,
 6764: .LC_docs_ext_edit {
 6765:   font-size: x-small;
 6766: }
 6767: 
 6768: table.LC_docs_adddocs td,
 6769: table.LC_docs_adddocs th {
 6770:   border: 1px solid #BBBBBB;
 6771:   padding: 4px;
 6772:   background: #DDDDDD;
 6773: }
 6774: 
 6775: table.LC_sty_begin {
 6776:   background: #BBFFBB;
 6777: }
 6778: 
 6779: table.LC_sty_end {
 6780:   background: #FFBBBB;
 6781: }
 6782: 
 6783: table.LC_double_column {
 6784:   border-width: 0;
 6785:   border-collapse: collapse;
 6786:   width: 100%;
 6787:   padding: 2px;
 6788: }
 6789: 
 6790: table.LC_double_column tr td.LC_left_col {
 6791:   top: 2px;
 6792:   left: 2px;
 6793:   width: 47%;
 6794:   vertical-align: top;
 6795: }
 6796: 
 6797: table.LC_double_column tr td.LC_right_col {
 6798:   top: 2px;
 6799:   right: 2px;
 6800:   width: 47%;
 6801:   vertical-align: top;
 6802: }
 6803: 
 6804: div.LC_left_float {
 6805:   float: left;
 6806:   padding-right: 5%;
 6807:   padding-bottom: 4px;
 6808: }
 6809: 
 6810: div.LC_clear_float_header {
 6811:   padding-bottom: 2px;
 6812: }
 6813: 
 6814: div.LC_clear_float_footer {
 6815:   padding-top: 10px;
 6816:   clear: both;
 6817: }
 6818: 
 6819: div.LC_grade_show_user {
 6820: /*  border-left: 5px solid $sidebg; */
 6821:   border-top: 5px solid #000000;
 6822:   margin: 50px 0 0 0;
 6823:   padding: 15px 0 5px 10px;
 6824: }
 6825: 
 6826: div.LC_grade_show_user_odd_row {
 6827: /*  border-left: 5px solid #000000; */
 6828: }
 6829: 
 6830: div.LC_grade_show_user div.LC_Box {
 6831:   margin-right: 50px;
 6832: }
 6833: 
 6834: div.LC_grade_submissions,
 6835: div.LC_grade_message_center,
 6836: div.LC_grade_info_links {
 6837:   margin: 5px;
 6838:   width: 99%;
 6839:   background: #FFFFFF;
 6840: }
 6841: 
 6842: div.LC_grade_submissions_header,
 6843: div.LC_grade_message_center_header {
 6844:   font-weight: bold;
 6845:   font-size: large;
 6846: }
 6847: 
 6848: div.LC_grade_submissions_body,
 6849: div.LC_grade_message_center_body {
 6850:   border: 1px solid black;
 6851:   width: 99%;
 6852:   background: #FFFFFF;
 6853: }
 6854: 
 6855: table.LC_scantron_action {
 6856:   width: 100%;
 6857: }
 6858: 
 6859: table.LC_scantron_action tr th {
 6860:   font-weight:bold;
 6861:   font-style:normal;
 6862: }
 6863: 
 6864: .LC_edit_problem_header,
 6865: div.LC_edit_problem_footer {
 6866:   font-weight: normal;
 6867:   font-size:  medium;
 6868:   margin: 2px;
 6869:   background-color: $sidebg;
 6870: }
 6871: 
 6872: div.LC_edit_problem_header,
 6873: div.LC_edit_problem_header div,
 6874: div.LC_edit_problem_footer,
 6875: div.LC_edit_problem_footer div,
 6876: div.LC_edit_problem_editxml_header,
 6877: div.LC_edit_problem_editxml_header div {
 6878:   z-index: 100;
 6879: }
 6880: 
 6881: div.LC_edit_problem_header_title {
 6882:   font-weight: bold;
 6883:   font-size: larger;
 6884:   background: $tabbg;
 6885:   padding: 3px;
 6886:   margin: 0 0 5px 0;
 6887: }
 6888: 
 6889: table.LC_edit_problem_header_title {
 6890:   width: 100%;
 6891:   background: $tabbg;
 6892: }
 6893: 
 6894: div.LC_edit_actionbar {
 6895:     background-color: $sidebg;
 6896:     margin: 0;
 6897:     padding: 0;
 6898:     line-height: 200%;
 6899: }
 6900: 
 6901: div.LC_edit_actionbar div{
 6902:     padding: 0;
 6903:     margin: 0;
 6904:     display: inline-block;
 6905: }
 6906: 
 6907: .LC_edit_opt {
 6908:   padding-left: 1em;
 6909:   white-space: nowrap;
 6910: }
 6911: 
 6912: .LC_edit_problem_latexhelper{
 6913:     text-align: right;
 6914: }
 6915: 
 6916: #LC_edit_problem_colorful div{
 6917:     margin-left: 40px;
 6918: }
 6919: 
 6920: #LC_edit_problem_codemirror div{
 6921:     margin-left: 0px;
 6922: }
 6923: 
 6924: img.stift {
 6925:   border-width: 0;
 6926:   vertical-align: middle;
 6927: }
 6928: 
 6929: table td.LC_mainmenu_col_fieldset {
 6930:   vertical-align: top;
 6931: }
 6932: 
 6933: div.LC_createcourse {
 6934:   margin: 10px 10px 10px 10px;
 6935: }
 6936: 
 6937: .LC_dccid {
 6938:   float: right;
 6939:   margin: 0.2em 0 0 0;
 6940:   padding: 0;
 6941:   font-size: 90%;
 6942:   display:none;
 6943: }
 6944: 
 6945: ol.LC_primary_menu a:hover,
 6946: ol#LC_MenuBreadcrumbs a:hover,
 6947: ol#LC_PathBreadcrumbs a:hover,
 6948: ul#LC_secondary_menu a:hover,
 6949: .LC_FormSectionClearButton input:hover
 6950: ul.LC_TabContent   li:hover a {
 6951:   color:$button_hover;
 6952:   text-decoration:none;
 6953: }
 6954: 
 6955: h1 {
 6956:   padding: 0;
 6957:   line-height:130%;
 6958: }
 6959: 
 6960: h2,
 6961: h3,
 6962: h4,
 6963: h5,
 6964: h6 {
 6965:   margin: 5px 0 5px 0;
 6966:   padding: 0;
 6967:   line-height:130%;
 6968: }
 6969: 
 6970: .LC_hcell {
 6971:   padding:3px 15px 3px 15px;
 6972:   margin: 0;
 6973:   background-color:$tabbg;
 6974:   color:$fontmenu;
 6975:   border-bottom:solid 1px $lg_border_color;
 6976: }
 6977: 
 6978: .LC_Box > .LC_hcell {
 6979:   margin: 0 -10px 10px -10px;
 6980: }
 6981: 
 6982: .LC_noBorder {
 6983:   border: 0;
 6984: }
 6985: 
 6986: .LC_FormSectionClearButton input {
 6987:   background-color:transparent;
 6988:   border: none;
 6989:   cursor:pointer;
 6990:   text-decoration:underline;
 6991: }
 6992: 
 6993: .LC_help_open_topic {
 6994:   color: #FFFFFF;
 6995:   background-color: #EEEEFF;
 6996:   margin: 1px;
 6997:   padding: 4px;
 6998:   border: 1px solid #000033;
 6999:   white-space: nowrap;
 7000:   /* vertical-align: middle; */
 7001: }
 7002: 
 7003: dl,
 7004: ul,
 7005: div,
 7006: fieldset {
 7007:   margin: 10px 10px 10px 0;
 7008:   /* overflow: hidden; */
 7009: }
 7010: 
 7011: article.geogebraweb div {
 7012:     margin: 0;
 7013: }
 7014: 
 7015: fieldset > legend {
 7016:   font-weight: bold;
 7017:   padding: 0 5px 0 5px;
 7018: }
 7019: 
 7020: #LC_nav_bar {
 7021:   float: left;
 7022:   background-color: $pgbg_or_bgcolor;
 7023:   margin: 0 0 2px 0;
 7024: }
 7025: 
 7026: #LC_realm {
 7027:   margin: 0.2em 0 0 0;
 7028:   padding: 0;
 7029:   font-weight: bold;
 7030:   text-align: center;
 7031:   background-color: $pgbg_or_bgcolor;
 7032: }
 7033: 
 7034: #LC_nav_bar em {
 7035:   font-weight: bold;
 7036:   font-style: normal;
 7037: }
 7038: 
 7039: ol.LC_primary_menu {
 7040:   margin: 0;
 7041:   padding: 0;
 7042: }
 7043: 
 7044: ol#LC_PathBreadcrumbs {
 7045:   margin: 0;
 7046: }
 7047: 
 7048: ol.LC_primary_menu li {
 7049:   color: RGB(80, 80, 80);
 7050:   vertical-align: middle;
 7051:   text-align: left;
 7052:   list-style: none;
 7053:   position: relative;
 7054:   float: left;
 7055:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7056:   line-height: 1.5em;
 7057: }
 7058: 
 7059: ol.LC_primary_menu li a,
 7060: ol.LC_primary_menu li p {
 7061:   display: block;
 7062:   margin: 0;
 7063:   padding: 0 5px 0 10px;
 7064:   text-decoration: none;
 7065: }
 7066: 
 7067: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7068:   display: inline-block;
 7069:   width: 95%;
 7070:   text-align: left;
 7071: }
 7072: 
 7073: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7074:   display: inline-block;	
 7075:   width: 5%;
 7076:   float: right;
 7077:   text-align: right;
 7078:   font-size: 70%;
 7079: }
 7080: 
 7081: ol.LC_primary_menu ul {
 7082:   display: none;
 7083:   width: 15em;
 7084:   background-color: $data_table_light;
 7085:   position: absolute;
 7086:   top: 100%;
 7087: }
 7088: 
 7089: ol.LC_primary_menu ul ul {
 7090:   left: 100%;
 7091:   top: 0;
 7092: }
 7093: 
 7094: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7095:   display: block;
 7096:   position: absolute;
 7097:   margin: 0;
 7098:   padding: 0;
 7099:   z-index: 2;
 7100: }
 7101: 
 7102: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7103: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7104:   font-size: 90%;
 7105:   vertical-align: top;
 7106:   float: none;
 7107:   border-left: 1px solid black;
 7108:   border-right: 1px solid black;
 7109: /* A dark bottom border to visualize different menu options; 
 7110: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7111:   border-bottom: 1px solid $data_table_dark; 
 7112: }
 7113: 
 7114: ol.LC_primary_menu li li p:hover {
 7115:   color:$button_hover;
 7116:   text-decoration:none;
 7117:   background-color:$data_table_dark;
 7118: }
 7119: 
 7120: ol.LC_primary_menu li li a:hover {
 7121:    color:$button_hover;
 7122:    background-color:$data_table_dark;
 7123: }
 7124: 
 7125: /* Font-size equal to the size of the predecessors*/
 7126: ol.LC_primary_menu li:hover li li {
 7127:   font-size: 100%;
 7128: }
 7129: 
 7130: ol.LC_primary_menu li img {
 7131:   vertical-align: bottom;
 7132:   height: 1.1em;
 7133:   margin: 0.2em 0 0 0;
 7134: }
 7135: 
 7136: ol.LC_primary_menu a {
 7137:   color: RGB(80, 80, 80);
 7138:   text-decoration: none;
 7139: }
 7140: 
 7141: ol.LC_primary_menu a.LC_new_message {
 7142:   font-weight:bold;
 7143:   color: darkred;
 7144: }
 7145: 
 7146: ol.LC_docs_parameters {
 7147:   margin-left: 0;
 7148:   padding: 0;
 7149:   list-style: none;
 7150: }
 7151: 
 7152: ol.LC_docs_parameters li {
 7153:   margin: 0;
 7154:   padding-right: 20px;
 7155:   display: inline;
 7156: }
 7157: 
 7158: ol.LC_docs_parameters li:before {
 7159:   content: "\\002022 \\0020";
 7160: }
 7161: 
 7162: li.LC_docs_parameters_title {
 7163:   font-weight: bold;
 7164: }
 7165: 
 7166: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7167:   content: "";
 7168: }
 7169: 
 7170: ul#LC_secondary_menu {
 7171:   clear: right;
 7172:   color: $fontmenu;
 7173:   background: $tabbg;
 7174:   list-style: none;
 7175:   padding: 0;
 7176:   margin: 0;
 7177:   width: 100%;
 7178:   text-align: left;
 7179:   float: left;
 7180: }
 7181: 
 7182: ul#LC_secondary_menu li {
 7183:   font-weight: bold;
 7184:   line-height: 1.8em;
 7185:   border-right: 1px solid black;
 7186:   float: left;
 7187: }
 7188: 
 7189: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7190:   background-color: $data_table_light;
 7191: }
 7192: 
 7193: ul#LC_secondary_menu li a {
 7194:   padding: 0 0.8em;
 7195: }
 7196: 
 7197: ul#LC_secondary_menu li ul {
 7198:   display: none;
 7199: }
 7200: 
 7201: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7202:   display: block;
 7203:   position: absolute;
 7204:   margin: 0;
 7205:   padding: 0;
 7206:   list-style:none;
 7207:   float: none;
 7208:   background-color: $data_table_light;
 7209:   z-index: 2;
 7210:   margin-left: -1px;
 7211: }
 7212: 
 7213: ul#LC_secondary_menu li ul li {
 7214:   font-size: 90%;
 7215:   vertical-align: top;
 7216:   border-left: 1px solid black;
 7217:   border-right: 1px solid black;
 7218:   background-color: $data_table_light;
 7219:   list-style:none;
 7220:   float: none;
 7221: }
 7222: 
 7223: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7224:   background-color: $data_table_dark;
 7225: }
 7226: 
 7227: ul.LC_TabContent {
 7228:   display:block;
 7229:   background: $sidebg;
 7230:   border-bottom: solid 1px $lg_border_color;
 7231:   list-style:none;
 7232:   margin: -1px -10px 0 -10px;
 7233:   padding: 0;
 7234: }
 7235: 
 7236: ul.LC_TabContent li,
 7237: ul.LC_TabContentBigger li {
 7238:   float:left;
 7239: }
 7240: 
 7241: ul#LC_secondary_menu li a {
 7242:   color: $fontmenu;
 7243:   text-decoration: none;
 7244: }
 7245: 
 7246: ul.LC_TabContent {
 7247:   min-height:20px;
 7248: }
 7249: 
 7250: ul.LC_TabContent li {
 7251:   vertical-align:middle;
 7252:   padding: 0 16px 0 10px;
 7253:   background-color:$tabbg;
 7254:   border-bottom:solid 1px $lg_border_color;
 7255:   border-left: solid 1px $font;
 7256: }
 7257: 
 7258: ul.LC_TabContent .right {
 7259:   float:right;
 7260: }
 7261: 
 7262: ul.LC_TabContent li a,
 7263: ul.LC_TabContent li {
 7264:   color:rgb(47,47,47);
 7265:   text-decoration:none;
 7266:   font-size:95%;
 7267:   font-weight:bold;
 7268:   min-height:20px;
 7269: }
 7270: 
 7271: ul.LC_TabContent li a:hover,
 7272: ul.LC_TabContent li a:focus {
 7273:   color: $button_hover;
 7274:   background:none;
 7275:   outline:none;
 7276: }
 7277: 
 7278: ul.LC_TabContent li:hover {
 7279:   color: $button_hover;
 7280:   cursor:pointer;
 7281: }
 7282: 
 7283: ul.LC_TabContent li.active {
 7284:   color: $font;
 7285:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7286:   border-bottom:solid 1px #FFFFFF;
 7287:   cursor: default;
 7288: }
 7289: 
 7290: ul.LC_TabContent li.active a {
 7291:   color:$font;
 7292:   background:#FFFFFF;
 7293:   outline: none;
 7294: }
 7295: 
 7296: ul.LC_TabContent li.goback {
 7297:   float: left;
 7298:   border-left: none;
 7299: }
 7300: 
 7301: #maincoursedoc {
 7302:   clear:both;
 7303: }
 7304: 
 7305: ul.LC_TabContentBigger {
 7306:   display:block;
 7307:   list-style:none;
 7308:   padding: 0;
 7309: }
 7310: 
 7311: ul.LC_TabContentBigger li {
 7312:   vertical-align:bottom;
 7313:   height: 30px;
 7314:   font-size:110%;
 7315:   font-weight:bold;
 7316:   color: #737373;
 7317: }
 7318: 
 7319: ul.LC_TabContentBigger li.active {
 7320:   position: relative;
 7321:   top: 1px;
 7322: }
 7323: 
 7324: ul.LC_TabContentBigger li a {
 7325:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7326:   height: 30px;
 7327:   line-height: 30px;
 7328:   text-align: center;
 7329:   display: block;
 7330:   text-decoration: none;
 7331:   outline: none;  
 7332: }
 7333: 
 7334: ul.LC_TabContentBigger li.active a {
 7335:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7336:   color:$font;
 7337: }
 7338: 
 7339: ul.LC_TabContentBigger li b {
 7340:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7341:   display: block;
 7342:   float: left;
 7343:   padding: 0 30px;
 7344:   border-bottom: 1px solid $lg_border_color;
 7345: }
 7346: 
 7347: ul.LC_TabContentBigger li:hover b {
 7348:   color:$button_hover;
 7349: }
 7350: 
 7351: ul.LC_TabContentBigger li.active b {
 7352:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7353:   color:$font;
 7354:   border: 0;
 7355: }
 7356: 
 7357: 
 7358: ul.LC_CourseBreadcrumbs {
 7359:   background: $sidebg;
 7360:   height: 2em;
 7361:   padding-left: 10px;
 7362:   margin: 0;
 7363:   list-style-position: inside;
 7364: }
 7365: 
 7366: ol#LC_MenuBreadcrumbs,
 7367: ol#LC_PathBreadcrumbs {
 7368:   padding-left: 10px;
 7369:   margin: 0;
 7370:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7371: }
 7372: 
 7373: ol#LC_MenuBreadcrumbs li,
 7374: ol#LC_PathBreadcrumbs li,
 7375: ul.LC_CourseBreadcrumbs li {
 7376:   display: inline;
 7377:   white-space: normal;  
 7378: }
 7379: 
 7380: ol#LC_MenuBreadcrumbs li a,
 7381: ul.LC_CourseBreadcrumbs li a {
 7382:   text-decoration: none;
 7383:   font-size:90%;
 7384: }
 7385: 
 7386: ol#LC_MenuBreadcrumbs h1 {
 7387:   display: inline;
 7388:   font-size: 90%;
 7389:   line-height: 2.5em;
 7390:   margin: 0;
 7391:   padding: 0;
 7392: }
 7393: 
 7394: ol#LC_PathBreadcrumbs li a {
 7395:   text-decoration:none;
 7396:   font-size:100%;
 7397:   font-weight:bold;
 7398: }
 7399: 
 7400: .LC_Box {
 7401:   border: solid 1px $lg_border_color;
 7402:   padding: 0 10px 10px 10px;
 7403: }
 7404: 
 7405: .LC_DocsBox {
 7406:   border: solid 1px $lg_border_color;
 7407:   padding: 0 0 10px 10px;
 7408: }
 7409: 
 7410: .LC_AboutMe_Image {
 7411:   float:left;
 7412:   margin-right:10px;
 7413: }
 7414: 
 7415: .LC_Clear_AboutMe_Image {
 7416:   clear:left;
 7417: }
 7418: 
 7419: dl.LC_ListStyleClean dt {
 7420:   padding-right: 5px;
 7421:   display: table-header-group;
 7422: }
 7423: 
 7424: dl.LC_ListStyleClean dd {
 7425:   display: table-row;
 7426: }
 7427: 
 7428: .LC_ListStyleClean,
 7429: .LC_ListStyleSimple,
 7430: .LC_ListStyleNormal,
 7431: .LC_ListStyleSpecial {
 7432:   /* display:block; */
 7433:   list-style-position: inside;
 7434:   list-style-type: none;
 7435:   overflow: hidden;
 7436:   padding: 0;
 7437: }
 7438: 
 7439: .LC_ListStyleSimple li,
 7440: .LC_ListStyleSimple dd,
 7441: .LC_ListStyleNormal li,
 7442: .LC_ListStyleNormal dd,
 7443: .LC_ListStyleSpecial li,
 7444: .LC_ListStyleSpecial dd {
 7445:   margin: 0;
 7446:   padding: 5px 5px 5px 10px;
 7447:   clear: both;
 7448: }
 7449: 
 7450: .LC_ListStyleClean li,
 7451: .LC_ListStyleClean dd {
 7452:   padding-top: 0;
 7453:   padding-bottom: 0;
 7454: }
 7455: 
 7456: .LC_ListStyleSimple dd,
 7457: .LC_ListStyleSimple li {
 7458:   border-bottom: solid 1px $lg_border_color;
 7459: }
 7460: 
 7461: .LC_ListStyleSpecial li,
 7462: .LC_ListStyleSpecial dd {
 7463:   list-style-type: none;
 7464:   background-color: RGB(220, 220, 220);
 7465:   margin-bottom: 4px;
 7466: }
 7467: 
 7468: table.LC_SimpleTable {
 7469:   margin:5px;
 7470:   border:solid 1px $lg_border_color;
 7471: }
 7472: 
 7473: table.LC_SimpleTable tr {
 7474:   padding: 0;
 7475:   border:solid 1px $lg_border_color;
 7476: }
 7477: 
 7478: table.LC_SimpleTable thead {
 7479:   background:rgb(220,220,220);
 7480: }
 7481: 
 7482: div.LC_columnSection {
 7483:   display: block;
 7484:   clear: both;
 7485:   overflow: hidden;
 7486:   margin: 0;
 7487: }
 7488: 
 7489: div.LC_columnSection>* {
 7490:   float: left;
 7491:   margin: 10px 20px 10px 0;
 7492:   overflow:hidden;
 7493: }
 7494: 
 7495: table em {
 7496:   font-weight: bold;
 7497:   font-style: normal;
 7498: }
 7499: 
 7500: table.LC_tableBrowseRes,
 7501: table.LC_tableOfContent {
 7502:   border:none;
 7503:   border-spacing: 1px;
 7504:   padding: 3px;
 7505:   background-color: #FFFFFF;
 7506:   font-size: 90%;
 7507: }
 7508: 
 7509: table.LC_tableOfContent {
 7510:   border-collapse: collapse;
 7511: }
 7512: 
 7513: table.LC_tableBrowseRes a,
 7514: table.LC_tableOfContent a {
 7515:   background-color: transparent;
 7516:   text-decoration: none;
 7517: }
 7518: 
 7519: table.LC_tableOfContent img {
 7520:   border: none;
 7521:   height: 1.3em;
 7522:   vertical-align: text-bottom;
 7523:   margin-right: 0.3em;
 7524: }
 7525: 
 7526: a#LC_content_toolbar_firsthomework {
 7527:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7528: }
 7529: 
 7530: a#LC_content_toolbar_everything {
 7531:   background-image:url(/res/adm/pages/show-all.gif);
 7532: }
 7533: 
 7534: a#LC_content_toolbar_uncompleted {
 7535:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7536: }
 7537: 
 7538: #LC_content_toolbar_clearbubbles {
 7539:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7540: }
 7541: 
 7542: a#LC_content_toolbar_changefolder {
 7543:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7544: }
 7545: 
 7546: a#LC_content_toolbar_changefolder_toggled {
 7547:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7548: }
 7549: 
 7550: a#LC_content_toolbar_edittoplevel {
 7551:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7552: }
 7553: 
 7554: ul#LC_toolbar li a:hover {
 7555:   background-position: bottom center;
 7556: }
 7557: 
 7558: ul#LC_toolbar {
 7559:   padding: 0;
 7560:   margin: 2px;
 7561:   list-style:none;
 7562:   position:relative;
 7563:   background-color:white;
 7564:   overflow: auto;
 7565: }
 7566: 
 7567: ul#LC_toolbar li {
 7568:   border:1px solid white;
 7569:   padding: 0;
 7570:   margin: 0;
 7571:   float: left;
 7572:   display:inline;
 7573:   vertical-align:middle;
 7574:   white-space: nowrap;
 7575: }
 7576: 
 7577: 
 7578: a.LC_toolbarItem {
 7579:   display:block;
 7580:   padding: 0;
 7581:   margin: 0;
 7582:   height: 32px;
 7583:   width: 32px;
 7584:   color:white;
 7585:   border: none;
 7586:   background-repeat:no-repeat;
 7587:   background-color:transparent;
 7588: }
 7589: 
 7590: ul.LC_funclist {
 7591:     margin: 0;
 7592:     padding: 0.5em 1em 0.5em 0;
 7593: }
 7594: 
 7595: ul.LC_funclist > li:first-child {
 7596:     font-weight:bold; 
 7597:     margin-left:0.8em;
 7598: }
 7599: 
 7600: ul.LC_funclist + ul.LC_funclist {
 7601:     /* 
 7602:        left border as a seperator if we have more than
 7603:        one list 
 7604:     */
 7605:     border-left: 1px solid $sidebg;
 7606:     /* 
 7607:        this hides the left border behind the border of the 
 7608:        outer box if element is wrapped to the next 'line' 
 7609:     */
 7610:     margin-left: -1px;
 7611: }
 7612: 
 7613: ul.LC_funclist li {
 7614:   display: inline;
 7615:   white-space: nowrap;
 7616:   margin: 0 0 0 25px;
 7617:   line-height: 150%;
 7618: }
 7619: 
 7620: .LC_hidden {
 7621:   display: none;
 7622: }
 7623: 
 7624: .LCmodal-overlay {
 7625: 		position:fixed;
 7626: 		top:0;
 7627: 		right:0;
 7628: 		bottom:0;
 7629: 		left:0;
 7630: 		height:100%;
 7631: 		width:100%;
 7632: 		margin:0;
 7633: 		padding:0;
 7634: 		background:#999;
 7635: 		opacity:.75;
 7636: 		filter: alpha(opacity=75);
 7637: 		-moz-opacity: 0.75;
 7638: 		z-index:101;
 7639: }
 7640: 
 7641: * html .LCmodal-overlay {   
 7642: 		position: absolute;
 7643: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7644: }
 7645: 
 7646: .LCmodal-window {
 7647: 		position:fixed;
 7648: 		top:50%;
 7649: 		left:50%;
 7650: 		margin:0;
 7651: 		padding:0;
 7652: 		z-index:102;
 7653: 	}
 7654: 
 7655: * html .LCmodal-window {
 7656: 		position:absolute;
 7657: }
 7658: 
 7659: .LCclose-window {
 7660: 		position:absolute;
 7661: 		width:32px;
 7662: 		height:32px;
 7663: 		right:8px;
 7664: 		top:8px;
 7665: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7666: 		text-indent:-99999px;
 7667: 		overflow:hidden;
 7668: 		cursor:pointer;
 7669: }
 7670: 
 7671: /*
 7672:   styles used for response display
 7673: */
 7674: div.LC_radiofoil, div.LC_rankfoil {
 7675:   margin: .5em 0em .5em 0em;
 7676: }
 7677: table.LC_itemgroup {
 7678:   margin-top: 1em;
 7679: }
 7680: 
 7681: /*
 7682:   styles used by TTH when "Default set of options to pass to tth/m
 7683:   when converting TeX" in course settings has been set
 7684: 
 7685:   option passed: -t
 7686: 
 7687: */
 7688: 
 7689: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7690: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7691: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7692: td div.norm {line-height:normal;}
 7693: 
 7694: /*
 7695:   option passed -y3
 7696: */
 7697: 
 7698: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7699: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7700: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7701: 
 7702: /*
 7703:   sections with roles, for content only
 7704: */
 7705: section[class^="role-"] {
 7706:   padding-left: 10px;
 7707:   padding-right: 5px;
 7708:   margin-top: 8px;
 7709:   margin-bottom: 8px;
 7710:   border: 1px solid #2A4;
 7711:   border-radius: 5px;
 7712:   box-shadow: 0px 1px 1px #BBB;
 7713: }
 7714: section[class^="role-"]>h1 {
 7715:   position: relative;
 7716:   margin: 0px;
 7717:   padding-top: 10px;
 7718:   padding-left: 40px;
 7719: }
 7720: section[class^="role-"]>h1:before {
 7721:   position: absolute;
 7722:   left: -5px;
 7723:   top: 5px;
 7724: }
 7725: section.role-activity>h1:before {
 7726:   content:url('/adm/daxe/images/section_icons/activity.png');
 7727: }
 7728: section.role-advice>h1:before {
 7729:   content:url('/adm/daxe/images/section_icons/advice.png');
 7730: }
 7731: section.role-bibliography>h1:before {
 7732:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 7733: }
 7734: section.role-citation>h1:before {
 7735:   content:url('/adm/daxe/images/section_icons/citation.png');
 7736: }
 7737: section.role-conclusion>h1:before {
 7738:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 7739: }
 7740: section.role-definition>h1:before {
 7741:   content:url('/adm/daxe/images/section_icons/definition.png');
 7742: }
 7743: section.role-demonstration>h1:before {
 7744:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 7745: }
 7746: section.role-example>h1:before {
 7747:   content:url('/adm/daxe/images/section_icons/example.png');
 7748: }
 7749: section.role-explanation>h1:before {
 7750:   content:url('/adm/daxe/images/section_icons/explanation.png');
 7751: }
 7752: section.role-introduction>h1:before {
 7753:   content:url('/adm/daxe/images/section_icons/introduction.png');
 7754: }
 7755: section.role-method>h1:before {
 7756:   content:url('/adm/daxe/images/section_icons/method.png');
 7757: }
 7758: section.role-more_information>h1:before {
 7759:   content:url('/adm/daxe/images/section_icons/more_information.png');
 7760: }
 7761: section.role-objectives>h1:before {
 7762:   content:url('/adm/daxe/images/section_icons/objectives.png');
 7763: }
 7764: section.role-prerequisites>h1:before {
 7765:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 7766: }
 7767: section.role-remark>h1:before {
 7768:   content:url('/adm/daxe/images/section_icons/remark.png');
 7769: }
 7770: section.role-reminder>h1:before {
 7771:   content:url('/adm/daxe/images/section_icons/reminder.png');
 7772: }
 7773: section.role-summary>h1:before {
 7774:   content:url('/adm/daxe/images/section_icons/summary.png');
 7775: }
 7776: section.role-syntax>h1:before {
 7777:   content:url('/adm/daxe/images/section_icons/syntax.png');
 7778: }
 7779: section.role-warning>h1:before {
 7780:   content:url('/adm/daxe/images/section_icons/warning.png');
 7781: }
 7782: 
 7783: END
 7784: }
 7785: 
 7786: =pod
 7787: 
 7788: =item * &headtag()
 7789: 
 7790: Returns a uniform footer for LON-CAPA web pages.
 7791: 
 7792: Inputs: $title - optional title for the head
 7793:         $head_extra - optional extra HTML to put inside the <head>
 7794:         $args - optional arguments
 7795:             force_register - if is true call registerurl so the remote is 
 7796:                              informed
 7797:             redirect       -> array ref of
 7798:                                    1- seconds before redirect occurs
 7799:                                    2- url to redirect to
 7800:                                    3- whether the side effect should occur
 7801:                            (side effect of setting 
 7802:                                $env{'internal.head.redirect'} to the url 
 7803:                                redirected too)
 7804:             domain         -> force to color decorate a page for a specific
 7805:                                domain
 7806:             function       -> force usage of a specific rolish color scheme
 7807:             bgcolor        -> override the default page bgcolor
 7808:             no_auto_mt_title
 7809:                            -> prevent &mt()ing the title arg
 7810: 
 7811: =cut
 7812: 
 7813: sub headtag {
 7814:     my ($title,$head_extra,$args) = @_;
 7815:     
 7816:     my $function = $args->{'function'} || &get_users_function();
 7817:     my $domain   = $args->{'domain'}   || &determinedomain();
 7818:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7819:     my $httphost = $args->{'use_absolute'};
 7820:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7821: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7822: 		   #time(),
 7823: 		   $env{'environment.color.timestamp'},
 7824: 		   $function,$domain,$bgcolor);
 7825: 
 7826:     $url = '/adm/css/'.&escape($url).'.css';
 7827: 
 7828:     my $result =
 7829: 	'<head>'.
 7830: 	&font_settings($args);
 7831: 
 7832:     my $inhibitprint;
 7833:     if ($args->{'print_suppress'}) {
 7834:         $inhibitprint = &print_suppression();
 7835:     }
 7836: 
 7837:     if (!$args->{'frameset'}) {
 7838: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7839:     }
 7840:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7841:         $result .= Apache::lonxml::display_title();
 7842:     }
 7843:     if (!$args->{'no_nav_bar'} 
 7844: 	&& !$args->{'only_body'}
 7845: 	&& !$args->{'frameset'}) {
 7846: 	$result .= &help_menu_js($httphost);
 7847:         $result.=&modal_window();
 7848:         $result.=&togglebox_script();
 7849:         $result.=&wishlist_window();
 7850:         $result.=&LCprogressbarUpdate_script();
 7851:     } else {
 7852:         if ($args->{'add_modal'}) {
 7853:            $result.=&modal_window();
 7854:         }
 7855:         if ($args->{'add_wishlist'}) {
 7856:            $result.=&wishlist_window();
 7857:         }
 7858:         if ($args->{'add_togglebox'}) {
 7859:            $result.=&togglebox_script();
 7860:         }
 7861:         if ($args->{'add_progressbar'}) {
 7862:            $result.=&LCprogressbarUpdate_script();
 7863:         }
 7864:     }
 7865:     if (ref($args->{'redirect'})) {
 7866: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7867: 	$url = &Apache::lonenc::check_encrypt($url);
 7868: 	if (!$inhibit_continue) {
 7869: 	    $env{'internal.head.redirect'} = $url;
 7870: 	}
 7871: 	$result.=<<ADDMETA
 7872: <meta http-equiv="pragma" content="no-cache" />
 7873: <meta http-equiv="Refresh" content="$time; url=$url" />
 7874: ADDMETA
 7875:     } else {
 7876:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7877:             my $requrl = $env{'request.uri'};
 7878:             if ($requrl eq '') {
 7879:                 $requrl = $ENV{'REQUEST_URI'};
 7880:                 $requrl =~ s/\?.+$//;
 7881:             }
 7882:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7883:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7884:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7885:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7886:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7887:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7888:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7889:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7890:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7891:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7892:                             if (($newserver) && ($newserver ne $lonhost)) {
 7893:                                 my $numsec = 5;
 7894:                                 my $timeout = $numsec * 1000;
 7895:                                 my ($newurl,$locknum,%locks,$msg);
 7896:                                 if ($env{'request.role.adv'}) {
 7897:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7898:                                 }
 7899:                                 my $disable_submit = 0;
 7900:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7901:                                     $disable_submit = 1;
 7902:                                 }
 7903:                                 if ($locknum) {
 7904:                                     my @lockinfo = sort(values(%locks));
 7905:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7906:                                            join(", ",sort(values(%locks)))."\\n".
 7907:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7908:                                 } else {
 7909:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7910:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7911:                                     }
 7912:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7913:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7914:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7915:                                         $newurl .= '&role='.$env{'request.role'};
 7916:                                     }
 7917:                                     if ($env{'request.symb'}) {
 7918:                                         $newurl .= '&symb='.$env{'request.symb'};
 7919:                                     } else {
 7920:                                         $newurl .= '&origurl='.$requrl;
 7921:                                     }
 7922:                                 }
 7923:                                 &js_escape(\$msg);
 7924:                                 $result.=<<OFFLOAD
 7925: <meta http-equiv="pragma" content="no-cache" />
 7926: <script type="text/javascript">
 7927: // <![CDATA[
 7928: function LC_Offload_Now() {
 7929:     var dest = "$newurl";
 7930:     if (dest != '') {
 7931:         window.location.href="$newurl";
 7932:     }
 7933: }
 7934: \$(document).ready(function () {
 7935:     window.alert('$msg');
 7936:     if ($disable_submit) {
 7937:         \$(".LC_hwk_submit").prop("disabled", true);
 7938:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7939:     }
 7940:     setTimeout('LC_Offload_Now()', $timeout);
 7941: });
 7942: // ]]>
 7943: </script>
 7944: OFFLOAD
 7945:                             }
 7946:                         }
 7947:                     }
 7948:                 }
 7949:             }
 7950:         }
 7951:     }
 7952:     if (!defined($title)) {
 7953: 	$title = 'The LearningOnline Network with CAPA';
 7954:     }
 7955:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7956:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7957: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7958:     if (!$args->{'frameset'}) {
 7959:         $result .= ' /';
 7960:     }
 7961:     $result .= '>' 
 7962:         .$inhibitprint
 7963: 	.$head_extra;
 7964:     if ($env{'browser.mobile'}) {
 7965:         $result .= '
 7966: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7967: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7968:     }
 7969:     return $result.'</head>';
 7970: }
 7971: 
 7972: =pod
 7973: 
 7974: =item * &font_settings()
 7975: 
 7976: Returns neccessary <meta> to set the proper encoding
 7977: 
 7978: Inputs: optional reference to HASH -- $args passed to &headtag()
 7979: 
 7980: =cut
 7981: 
 7982: sub font_settings {
 7983:     my ($args) = @_;
 7984:     my $headerstring='';
 7985:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7986:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7987:         $headerstring.=
 7988:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7989:         if (!$args->{'frameset'}) {
 7990: 	    $headerstring.= ' /';
 7991:         }
 7992: 	$headerstring .= '>'."\n";
 7993:     }
 7994:     return $headerstring;
 7995: }
 7996: 
 7997: =pod
 7998: 
 7999: =item * &print_suppression()
 8000: 
 8001: In course context returns css which causes the body to be blank when media="print",
 8002: if printout generation is unavailable for the current resource.
 8003: 
 8004: This could be because:
 8005: 
 8006: (a) printstartdate is in the future
 8007: 
 8008: (b) printenddate is in the past
 8009: 
 8010: (c) there is an active exam block with "printout"
 8011: functionality blocked
 8012: 
 8013: Users with pav, pfo or evb privileges are exempt.
 8014: 
 8015: Inputs: none
 8016: 
 8017: =cut
 8018: 
 8019: 
 8020: sub print_suppression {
 8021:     my $noprint;
 8022:     if ($env{'request.course.id'}) {
 8023:         my $scope = $env{'request.course.id'};
 8024:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8025:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8026:             return;
 8027:         }
 8028:         if ($env{'request.course.sec'} ne '') {
 8029:             $scope .= "/$env{'request.course.sec'}";
 8030:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8031:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8032:                 return;
 8033:             }
 8034:         }
 8035:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8036:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8037:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8038:         if ($blocked) {
 8039:             my $checkrole = "cm./$cdom/$cnum";
 8040:             if ($env{'request.course.sec'} ne '') {
 8041:                 $checkrole .= "/$env{'request.course.sec'}";
 8042:             }
 8043:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8044:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8045:                 $noprint = 1;
 8046:             }
 8047:         }
 8048:         unless ($noprint) {
 8049:             my $symb = &Apache::lonnet::symbread();
 8050:             if ($symb ne '') {
 8051:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8052:                 if (ref($navmap)) {
 8053:                     my $res = $navmap->getBySymb($symb);
 8054:                     if (ref($res)) {
 8055:                         if (!$res->resprintable()) {
 8056:                             $noprint = 1;
 8057:                         }
 8058:                     }
 8059:                 }
 8060:             }
 8061:         }
 8062:         if ($noprint) {
 8063:             return <<"ENDSTYLE";
 8064: <style type="text/css" media="print">
 8065:     body { display:none }
 8066: </style>
 8067: ENDSTYLE
 8068:         }
 8069:     }
 8070:     return;
 8071: }
 8072: 
 8073: =pod
 8074: 
 8075: =item * &xml_begin()
 8076: 
 8077: Returns the needed doctype and <html>
 8078: 
 8079: Inputs: none
 8080: 
 8081: =cut
 8082: 
 8083: sub xml_begin {
 8084:     my ($is_frameset) = @_;
 8085:     my $output='';
 8086: 
 8087:     if ($env{'browser.mathml'}) {
 8088: 	$output='<?xml version="1.0"?>'
 8089:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8090: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8091:             
 8092: #	    .'<!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">] >'
 8093: 	    .'<!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">'
 8094:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8095: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8096:     } elsif ($is_frameset) {
 8097:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8098:                 '<html>'."\n";
 8099:     } else {
 8100: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8101:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8102:     }
 8103:     return $output;
 8104: }
 8105: 
 8106: =pod
 8107: 
 8108: =item * &start_page()
 8109: 
 8110: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8111: 
 8112: Inputs:
 8113: 
 8114: =over 4
 8115: 
 8116: $title - optional title for the page
 8117: 
 8118: $head_extra - optional extra HTML to incude inside the <head>
 8119: 
 8120: $args - additional optional args supported are:
 8121: 
 8122: =over 8
 8123: 
 8124:              only_body      -> is true will set &bodytag() onlybodytag
 8125:                                     arg on
 8126:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8127:              add_entries    -> additional attributes to add to the  <body>
 8128:              domain         -> force to color decorate a page for a 
 8129:                                     specific domain
 8130:              function       -> force usage of a specific rolish color
 8131:                                     scheme
 8132:              redirect       -> see &headtag()
 8133:              bgcolor        -> override the default page bg color
 8134:              js_ready       -> return a string ready for being used in 
 8135:                                     a javascript writeln
 8136:              html_encode    -> return a string ready for being used in 
 8137:                                     a html attribute
 8138:              force_register -> if is true will turn on the &bodytag()
 8139:                                     $forcereg arg
 8140:              frameset       -> if true will start with a <frameset>
 8141:                                     rather than <body>
 8142:              skip_phases    -> hash ref of 
 8143:                                     head -> skip the <html><head> generation
 8144:                                     body -> skip all <body> generation
 8145:              no_auto_mt_title -> prevent &mt()ing the title arg
 8146:              bread_crumbs ->             Array containing breadcrumbs
 8147:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8148:              group          -> includes the current group, if page is for a 
 8149:                                specific group  
 8150: 
 8151: =back
 8152: 
 8153: =back
 8154: 
 8155: =cut
 8156: 
 8157: sub start_page {
 8158:     my ($title,$head_extra,$args) = @_;
 8159:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8160: 
 8161:     $env{'internal.start_page'}++;
 8162:     my ($result,@advtools);
 8163: 
 8164:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8165:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8166:     }
 8167:     
 8168:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8169: 	if ($args->{'frameset'}) {
 8170: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8171: 						$args->{'add_entries'});
 8172: 	    $result .= "\n<frameset $attr_string>\n";
 8173:         } else {
 8174:             $result .=
 8175:                 &bodytag($title, 
 8176:                          $args->{'function'},       $args->{'add_entries'},
 8177:                          $args->{'only_body'},      $args->{'domain'},
 8178:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8179:                          $args->{'bgcolor'},        $args,
 8180:                          \@advtools);
 8181:         }
 8182:     }
 8183: 
 8184:     if ($args->{'js_ready'}) {
 8185: 		$result = &js_ready($result);
 8186:     }
 8187:     if ($args->{'html_encode'}) {
 8188: 		$result = &html_encode($result);
 8189:     }
 8190: 
 8191:     # Preparation for new and consistent functionlist at top of screen
 8192:     # if ($args->{'functionlist'}) {
 8193:     #            $result .= &build_functionlist();
 8194:     #}
 8195: 
 8196:     # Don't add anything more if only_body wanted or in const space
 8197:     return $result if    $args->{'only_body'} 
 8198:                       || $env{'request.state'} eq 'construct';
 8199: 
 8200:     #Breadcrumbs
 8201:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8202: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8203: 		#if any br links exists, add them to the breadcrumbs
 8204: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8205: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8206: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8207: 			}
 8208: 		}
 8209:                 # if @advtools array contains items add then to the breadcrumbs
 8210:                 if (@advtools > 0) {
 8211:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8212:                 }
 8213: 
 8214: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8215: 		if(exists($args->{'bread_crumbs_component'})){
 8216: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 8217: 		} elsif ($args->{'crstype'} eq 'Placement') {
 8218: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
 8219:                                                                        $args->{'crstype'});
 8220:                 } else {
 8221: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 8222: 		}
 8223:     }
 8224:     return $result;
 8225: }
 8226: 
 8227: sub end_page {
 8228:     my ($args) = @_;
 8229:     $env{'internal.end_page'}++;
 8230:     my $result;
 8231:     if ($args->{'discussion'}) {
 8232: 	my ($target,$parser);
 8233: 	if (ref($args->{'discussion'})) {
 8234: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8235: 				$args->{'discussion'}{'parser'});
 8236: 	}
 8237: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8238:     }
 8239:     if ($args->{'frameset'}) {
 8240: 	$result .= '</frameset>';
 8241:     } else {
 8242: 	$result .= &endbodytag($args);
 8243:     }
 8244:     unless ($args->{'notbody'}) {
 8245:         $result .= "\n</html>";
 8246:     }
 8247: 
 8248:     if ($args->{'js_ready'}) {
 8249: 	$result = &js_ready($result);
 8250:     }
 8251: 
 8252:     if ($args->{'html_encode'}) {
 8253: 	$result = &html_encode($result);
 8254:     }
 8255: 
 8256:     return $result;
 8257: }
 8258: 
 8259: sub wishlist_window {
 8260:     return(<<'ENDWISHLIST');
 8261: <script type="text/javascript">
 8262: // <![CDATA[
 8263: // <!-- BEGIN LON-CAPA Internal
 8264: function set_wishlistlink(title, path) {
 8265:     if (!title) {
 8266:         title = document.title;
 8267:         title = title.replace(/^LON-CAPA /,'');
 8268:     }
 8269:     title = encodeURIComponent(title);
 8270:     title = title.replace("'","\\\'");
 8271:     if (!path) {
 8272:         path = location.pathname;
 8273:     }
 8274:     path = encodeURIComponent(path);
 8275:     path = path.replace("'","\\\'");
 8276:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8277:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8278: }
 8279: // END LON-CAPA Internal -->
 8280: // ]]>
 8281: </script>
 8282: ENDWISHLIST
 8283: }
 8284: 
 8285: sub modal_window {
 8286:     return(<<'ENDMODAL');
 8287: <script type="text/javascript">
 8288: // <![CDATA[
 8289: // <!-- BEGIN LON-CAPA Internal
 8290: var modalWindow = {
 8291: 	parent:"body",
 8292: 	windowId:null,
 8293: 	content:null,
 8294: 	width:null,
 8295: 	height:null,
 8296: 	close:function()
 8297: 	{
 8298: 	        $(".LCmodal-window").remove();
 8299: 	        $(".LCmodal-overlay").remove();
 8300: 	},
 8301: 	open:function()
 8302: 	{
 8303: 		var modal = "";
 8304: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8305: 		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;\">";
 8306: 		modal += this.content;
 8307: 		modal += "</div>";	
 8308: 
 8309: 		$(this.parent).append(modal);
 8310: 
 8311: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8312: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8313: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8314: 	}
 8315: };
 8316: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8317: 	{
 8318:                 source = source.replace("'","&#39;");
 8319: 		modalWindow.windowId = "myModal";
 8320: 		modalWindow.width = width;
 8321: 		modalWindow.height = height;
 8322: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8323: 		modalWindow.open();
 8324: 	};
 8325: // END LON-CAPA Internal -->
 8326: // ]]>
 8327: </script>
 8328: ENDMODAL
 8329: }
 8330: 
 8331: sub modal_link {
 8332:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8333:     unless ($width) { $width=480; }
 8334:     unless ($height) { $height=400; }
 8335:     unless ($scrolling) { $scrolling='yes'; }
 8336:     unless ($transparency) { $transparency='true'; }
 8337: 
 8338:     my $target_attr;
 8339:     if (defined($target)) {
 8340:         $target_attr = 'target="'.$target.'"';
 8341:     }
 8342:     return <<"ENDLINK";
 8343: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8344:            $linktext</a>
 8345: ENDLINK
 8346: }
 8347: 
 8348: sub modal_adhoc_script {
 8349:     my ($funcname,$width,$height,$content)=@_;
 8350:     return (<<ENDADHOC);
 8351: <script type="text/javascript">
 8352: // <![CDATA[
 8353:         var $funcname = function()
 8354:         {
 8355:                 modalWindow.windowId = "myModal";
 8356:                 modalWindow.width = $width;
 8357:                 modalWindow.height = $height;
 8358:                 modalWindow.content = '$content';
 8359:                 modalWindow.open();
 8360:         };  
 8361: // ]]>
 8362: </script>
 8363: ENDADHOC
 8364: }
 8365: 
 8366: sub modal_adhoc_inner {
 8367:     my ($funcname,$width,$height,$content)=@_;
 8368:     my $innerwidth=$width-20;
 8369:     $content=&js_ready(
 8370:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8371:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8372:                  $content.
 8373:                  &end_scrollbox().
 8374:                  &end_page()
 8375:              );
 8376:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8377: }
 8378: 
 8379: sub modal_adhoc_window {
 8380:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8381:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8382:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8383: }
 8384: 
 8385: sub modal_adhoc_launch {
 8386:     my ($funcname,$width,$height,$content)=@_;
 8387:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8388: <script type="text/javascript">
 8389: // <![CDATA[
 8390: $funcname();
 8391: // ]]>
 8392: </script>
 8393: ENDLAUNCH
 8394: }
 8395: 
 8396: sub modal_adhoc_close {
 8397:     return (<<ENDCLOSE);
 8398: <script type="text/javascript">
 8399: // <![CDATA[
 8400: modalWindow.close();
 8401: // ]]>
 8402: </script>
 8403: ENDCLOSE
 8404: }
 8405: 
 8406: sub togglebox_script {
 8407:    return(<<ENDTOGGLE);
 8408: <script type="text/javascript"> 
 8409: // <![CDATA[
 8410: function LCtoggleDisplay(id,hidetext,showtext) {
 8411:    link = document.getElementById(id + "link").childNodes[0];
 8412:    with (document.getElementById(id).style) {
 8413:       if (display == "none" ) {
 8414:           display = "inline";
 8415:           link.nodeValue = hidetext;
 8416:         } else {
 8417:           display = "none";
 8418:           link.nodeValue = showtext;
 8419:        }
 8420:    }
 8421: }
 8422: // ]]>
 8423: </script>
 8424: ENDTOGGLE
 8425: }
 8426: 
 8427: sub start_togglebox {
 8428:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8429:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8430:     unless ($showtext) { $showtext=&mt('show'); }
 8431:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8432:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8433:     return &start_data_table().
 8434:            &start_data_table_header_row().
 8435:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8436:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8437:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8438:            &end_data_table_header_row().
 8439:            '<tr id="'.$id.'" style="display:none""><td>';
 8440: }
 8441: 
 8442: sub end_togglebox {
 8443:     return '</td></tr>'.&end_data_table();
 8444: }
 8445: 
 8446: sub LCprogressbar_script {
 8447:    my ($id)=@_;
 8448:    return(<<ENDPROGRESS);
 8449: <script type="text/javascript">
 8450: // <![CDATA[
 8451: \$('#progressbar$id').progressbar({
 8452:   value: 0,
 8453:   change: function(event, ui) {
 8454:     var newVal = \$(this).progressbar('option', 'value');
 8455:     \$('.pblabel', this).text(LCprogressTxt);
 8456:   }
 8457: });
 8458: // ]]>
 8459: </script>
 8460: ENDPROGRESS
 8461: }
 8462: 
 8463: sub LCprogressbarUpdate_script {
 8464:    return(<<ENDPROGRESSUPDATE);
 8465: <style type="text/css">
 8466: .ui-progressbar { position:relative; }
 8467: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8468: </style>
 8469: <script type="text/javascript">
 8470: // <![CDATA[
 8471: var LCprogressTxt='---';
 8472: 
 8473: function LCupdateProgress(percent,progresstext,id) {
 8474:    LCprogressTxt=progresstext;
 8475:    \$('#progressbar'+id).progressbar('value',percent);
 8476: }
 8477: // ]]>
 8478: </script>
 8479: ENDPROGRESSUPDATE
 8480: }
 8481: 
 8482: my $LClastpercent;
 8483: my $LCidcnt;
 8484: my $LCcurrentid;
 8485: 
 8486: sub LCprogressbar {
 8487:     my ($r)=(@_);
 8488:     $LClastpercent=0;
 8489:     $LCidcnt++;
 8490:     $LCcurrentid=$$.'_'.$LCidcnt;
 8491:     my $starting=&mt('Starting');
 8492:     my $content=(<<ENDPROGBAR);
 8493:   <div id="progressbar$LCcurrentid">
 8494:     <span class="pblabel">$starting</span>
 8495:   </div>
 8496: ENDPROGBAR
 8497:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8498: }
 8499: 
 8500: sub LCprogressbarUpdate {
 8501:     my ($r,$val,$text)=@_;
 8502:     unless ($val) { 
 8503:        if ($LClastpercent) {
 8504:            $val=$LClastpercent;
 8505:        } else {
 8506:            $val=0;
 8507:        }
 8508:     }
 8509:     if ($val<0) { $val=0; }
 8510:     if ($val>100) { $val=0; }
 8511:     $LClastpercent=$val;
 8512:     unless ($text) { $text=$val.'%'; }
 8513:     $text=&js_ready($text);
 8514:     &r_print($r,<<ENDUPDATE);
 8515: <script type="text/javascript">
 8516: // <![CDATA[
 8517: LCupdateProgress($val,'$text','$LCcurrentid');
 8518: // ]]>
 8519: </script>
 8520: ENDUPDATE
 8521: }
 8522: 
 8523: sub LCprogressbarClose {
 8524:     my ($r)=@_;
 8525:     $LClastpercent=0;
 8526:     &r_print($r,<<ENDCLOSE);
 8527: <script type="text/javascript">
 8528: // <![CDATA[
 8529: \$("#progressbar$LCcurrentid").hide('slow'); 
 8530: // ]]>
 8531: </script>
 8532: ENDCLOSE
 8533: }
 8534: 
 8535: sub r_print {
 8536:     my ($r,$to_print)=@_;
 8537:     if ($r) {
 8538:       $r->print($to_print);
 8539:       $r->rflush();
 8540:     } else {
 8541:       print($to_print);
 8542:     }
 8543: }
 8544: 
 8545: sub html_encode {
 8546:     my ($result) = @_;
 8547: 
 8548:     $result = &HTML::Entities::encode($result,'<>&"');
 8549:     
 8550:     return $result;
 8551: }
 8552: 
 8553: sub js_ready {
 8554:     my ($result) = @_;
 8555: 
 8556:     $result =~ s/[\n\r]/ /xmsg;
 8557:     $result =~ s/\\/\\\\/xmsg;
 8558:     $result =~ s/'/\\'/xmsg;
 8559:     $result =~ s{</}{<\\/}xmsg;
 8560:     
 8561:     return $result;
 8562: }
 8563: 
 8564: sub validate_page {
 8565:     if (  exists($env{'internal.start_page'})
 8566: 	  &&     $env{'internal.start_page'} > 1) {
 8567: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8568: 				 $env{'internal.start_page'}.' '.
 8569: 				 $ENV{'request.filename'});
 8570:     }
 8571:     if (  exists($env{'internal.end_page'})
 8572: 	  &&     $env{'internal.end_page'} > 1) {
 8573: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8574: 				 $env{'internal.end_page'}.' '.
 8575: 				 $env{'request.filename'});
 8576:     }
 8577:     if (     exists($env{'internal.start_page'})
 8578: 	&& ! exists($env{'internal.end_page'})) {
 8579: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8580: 				 $env{'request.filename'});
 8581:     }
 8582:     if (   ! exists($env{'internal.start_page'})
 8583: 	&&   exists($env{'internal.end_page'})) {
 8584: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8585: 				 $env{'request.filename'});
 8586:     }
 8587: }
 8588: 
 8589: 
 8590: sub start_scrollbox {
 8591:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8592:     unless ($outerwidth) { $outerwidth='520px'; }
 8593:     unless ($width) { $width='500px'; }
 8594:     unless ($height) { $height='200px'; }
 8595:     my ($table_id,$div_id,$tdcol);
 8596:     if ($id ne '') {
 8597:         $table_id = ' id="table_'.$id.'"';
 8598:         $div_id = ' id="div_'.$id.'"';
 8599:     }
 8600:     if ($bgcolor ne '') {
 8601:         $tdcol = "background-color: $bgcolor;";
 8602:     }
 8603:     my $nicescroll_js;
 8604:     if ($env{'browser.mobile'}) {
 8605:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8606:     }
 8607:     return <<"END";
 8608: $nicescroll_js
 8609: 
 8610: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8611: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8612: END
 8613: }
 8614: 
 8615: sub end_scrollbox {
 8616:     return '</div></td></tr></table>';
 8617: }
 8618: 
 8619: sub nicescroll_javascript {
 8620:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8621:     my %options;
 8622:     if (ref($cursor) eq 'HASH') {
 8623:         %options = %{$cursor};
 8624:     }
 8625:     unless ($options{'railalign'} =~ /^left|right$/) {
 8626:         $options{'railalign'} = 'left';
 8627:     }
 8628:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8629:         my $function  = &get_users_function();
 8630:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8631:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8632:             $options{'cursorcolor'} = '#00F';
 8633:         }
 8634:     }
 8635:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8636:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8637:             $options{'cursoropacity'}='1.0';
 8638:         }
 8639:     } else {
 8640:         $options{'cursoropacity'}='1.0';
 8641:     }
 8642:     if ($options{'cursorfixedheight'} eq 'none') {
 8643:         delete($options{'cursorfixedheight'});
 8644:     } else {
 8645:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8646:     }
 8647:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8648:         delete($options{'railoffset'});
 8649:     }
 8650:     my @niceoptions;
 8651:     while (my($key,$value) = each(%options)) {
 8652:         if ($value =~ /^\{.+\}$/) {
 8653:             push(@niceoptions,$key.':'.$value);
 8654:         } else {
 8655:             push(@niceoptions,$key.':"'.$value.'"');
 8656:         }
 8657:     }
 8658:     my $nicescroll_js = '
 8659: $(document).ready(
 8660:       function() {
 8661:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8662:       }
 8663: );
 8664: ';
 8665:     if ($framecheck) {
 8666:         $nicescroll_js .= '
 8667: function expand_div(caller) {
 8668:     if (top === self) {
 8669:         document.getElementById("'.$id.'").style.width = "auto";
 8670:         document.getElementById("'.$id.'").style.height = "auto";
 8671:     } else {
 8672:         try {
 8673:             if (parent.frames) {
 8674:                 if (parent.frames.length > 1) {
 8675:                     var framesrc = parent.frames[1].location.href;
 8676:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8677:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8678:                         document.getElementById("'.$id.'").style.width = "auto";
 8679:                         document.getElementById("'.$id.'").style.height = "auto";
 8680:                     }
 8681:                 }
 8682:             }
 8683:         } catch (e) {
 8684:             return;
 8685:         }
 8686:     }
 8687:     return;
 8688: }
 8689: ';
 8690:     }
 8691:     if ($needjsready) {
 8692:         $nicescroll_js = '
 8693: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8694:     } else {
 8695:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8696:     }
 8697:     return $nicescroll_js;
 8698: }
 8699: 
 8700: sub simple_error_page {
 8701:     my ($r,$title,$msg,$args) = @_;
 8702:     if (ref($args) eq 'HASH') {
 8703:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8704:     } else {
 8705:         $msg = &mt($msg);
 8706:     }
 8707: 
 8708:     my $page =
 8709: 	&Apache::loncommon::start_page($title).
 8710: 	'<p class="LC_error">'.$msg.'</p>'.
 8711: 	&Apache::loncommon::end_page();
 8712:     if (ref($r)) {
 8713: 	$r->print($page);
 8714: 	return;
 8715:     }
 8716:     return $page;
 8717: }
 8718: 
 8719: {
 8720:     my @row_count;
 8721: 
 8722:     sub start_data_table_count {
 8723:         unshift(@row_count, 0);
 8724:         return;
 8725:     }
 8726: 
 8727:     sub end_data_table_count {
 8728:         shift(@row_count);
 8729:         return;
 8730:     }
 8731: 
 8732:     sub start_data_table {
 8733: 	my ($add_class,$id) = @_;
 8734: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8735:         my $table_id;
 8736:         if (defined($id)) {
 8737:             $table_id = ' id="'.$id.'"';
 8738:         }
 8739: 	&start_data_table_count();
 8740: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8741:     }
 8742: 
 8743:     sub end_data_table {
 8744: 	&end_data_table_count();
 8745: 	return '</table>'."\n";;
 8746:     }
 8747: 
 8748:     sub start_data_table_row {
 8749: 	my ($add_class, $id) = @_;
 8750: 	$row_count[0]++;
 8751: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8752: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8753:         $id = (' id="'.$id.'"') unless ($id eq '');
 8754:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8755:     }
 8756:     
 8757:     sub continue_data_table_row {
 8758: 	my ($add_class, $id) = @_;
 8759: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8760: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8761:         $id = (' id="'.$id.'"') unless ($id eq '');
 8762:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8763:     }
 8764: 
 8765:     sub end_data_table_row {
 8766: 	return '</tr>'."\n";;
 8767:     }
 8768: 
 8769:     sub start_data_table_empty_row {
 8770: #	$row_count[0]++;
 8771: 	return  '<tr class="LC_empty_row" >'."\n";;
 8772:     }
 8773: 
 8774:     sub end_data_table_empty_row {
 8775: 	return '</tr>'."\n";;
 8776:     }
 8777: 
 8778:     sub start_data_table_header_row {
 8779: 	return  '<tr class="LC_header_row">'."\n";;
 8780:     }
 8781: 
 8782:     sub end_data_table_header_row {
 8783: 	return '</tr>'."\n";;
 8784:     }
 8785: 
 8786:     sub data_table_caption {
 8787:         my $caption = shift;
 8788:         return "<caption class=\"LC_caption\">$caption</caption>";
 8789:     }
 8790: }
 8791: 
 8792: =pod
 8793: 
 8794: =item * &inhibit_menu_check($arg)
 8795: 
 8796: Checks for a inhibitmenu state and generates output to preserve it
 8797: 
 8798: Inputs:         $arg - can be any of
 8799:                      - undef - in which case the return value is a string 
 8800:                                to add  into arguments list of a uri
 8801:                      - 'input' - in which case the return value is a HTML
 8802:                                  <form> <input> field of type hidden to
 8803:                                  preserve the value
 8804:                      - a url - in which case the return value is the url with
 8805:                                the neccesary cgi args added to preserve the
 8806:                                inhibitmenu state
 8807:                      - a ref to a url - no return value, but the string is
 8808:                                         updated to include the neccessary cgi
 8809:                                         args to preserve the inhibitmenu state
 8810: 
 8811: =cut
 8812: 
 8813: sub inhibit_menu_check {
 8814:     my ($arg) = @_;
 8815:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8816:     if ($arg eq 'input') {
 8817: 	if ($env{'form.inhibitmenu'}) {
 8818: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8819: 	} else {
 8820: 	    return
 8821: 	}
 8822:     }
 8823:     if ($env{'form.inhibitmenu'}) {
 8824: 	if (ref($arg)) {
 8825: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8826: 	} elsif ($arg eq '') {
 8827: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8828: 	} else {
 8829: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8830: 	}
 8831:     }
 8832:     if (!ref($arg)) {
 8833: 	return $arg;
 8834:     }
 8835: }
 8836: 
 8837: ###############################################
 8838: 
 8839: =pod
 8840: 
 8841: =back
 8842: 
 8843: =head1 User Information Routines
 8844: 
 8845: =over 4
 8846: 
 8847: =item * &get_users_function()
 8848: 
 8849: Used by &bodytag to determine the current users primary role.
 8850: Returns either 'student','coordinator','admin', or 'author'.
 8851: 
 8852: =cut
 8853: 
 8854: ###############################################
 8855: sub get_users_function {
 8856:     my $function = 'norole';
 8857:     if ($env{'request.role'}=~/^(st)/) {
 8858:         $function='student';
 8859:     }
 8860:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8861:         $function='coordinator';
 8862:     }
 8863:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8864:         $function='admin';
 8865:     }
 8866:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8867:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8868:         $function='author';
 8869:     }
 8870:     return $function;
 8871: }
 8872: 
 8873: ###############################################
 8874: 
 8875: =pod
 8876: 
 8877: =item * &show_course()
 8878: 
 8879: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8880: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8881: 
 8882: Inputs:
 8883: None
 8884: 
 8885: Outputs:
 8886: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8887: 
 8888: =cut
 8889: 
 8890: ###############################################
 8891: sub show_course {
 8892:     my $course = !$env{'user.adv'};
 8893:     if (!$env{'user.adv'}) {
 8894:         foreach my $env (keys(%env)) {
 8895:             next if ($env !~ m/^user\.priv\./);
 8896:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8897:                 $course = 0;
 8898:                 last;
 8899:             }
 8900:         }
 8901:     }
 8902:     return $course;
 8903: }
 8904: 
 8905: ###############################################
 8906: 
 8907: =pod
 8908: 
 8909: =item * &check_user_status()
 8910: 
 8911: Determines current status of supplied role for a
 8912: specific user. Roles can be active, previous or future.
 8913: 
 8914: Inputs: 
 8915: user's domain, user's username, course's domain,
 8916: course's number, optional section ID.
 8917: 
 8918: Outputs:
 8919: role status: active, previous or future. 
 8920: 
 8921: =cut
 8922: 
 8923: sub check_user_status {
 8924:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8925:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8926:     my @uroles = keys(%userinfo);
 8927:     my $srchstr;
 8928:     my $active_chk = 'none';
 8929:     my $now = time;
 8930:     if (@uroles > 0) {
 8931:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8932:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8933:         } else {
 8934:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8935:         }
 8936:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8937:             my $role_end = 0;
 8938:             my $role_start = 0;
 8939:             $active_chk = 'active';
 8940:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8941:                 $role_end = $1;
 8942:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8943:                     $role_start = $1;
 8944:                 }
 8945:             }
 8946:             if ($role_start > 0) {
 8947:                 if ($now < $role_start) {
 8948:                     $active_chk = 'future';
 8949:                 }
 8950:             }
 8951:             if ($role_end > 0) {
 8952:                 if ($now > $role_end) {
 8953:                     $active_chk = 'previous';
 8954:                 }
 8955:             }
 8956:         }
 8957:     }
 8958:     return $active_chk;
 8959: }
 8960: 
 8961: ###############################################
 8962: 
 8963: =pod
 8964: 
 8965: =item * &get_sections()
 8966: 
 8967: Determines all the sections for a course including
 8968: sections with students and sections containing other roles.
 8969: Incoming parameters: 
 8970: 
 8971: 1. domain
 8972: 2. course number 
 8973: 3. reference to array containing roles for which sections should 
 8974: be gathered (optional).
 8975: 4. reference to array containing status types for which sections 
 8976: should be gathered (optional).
 8977: 
 8978: If the third argument is undefined, sections are gathered for any role. 
 8979: If the fourth argument is undefined, sections are gathered for any status.
 8980: Permissible values are 'active' or 'future' or 'previous'.
 8981:  
 8982: Returns section hash (keys are section IDs, values are
 8983: number of users in each section), subject to the
 8984: optional roles filter, optional status filter 
 8985: 
 8986: =cut
 8987: 
 8988: ###############################################
 8989: sub get_sections {
 8990:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8991:     if (!defined($cdom) || !defined($cnum)) {
 8992:         my $cid =  $env{'request.course.id'};
 8993: 
 8994: 	return if (!defined($cid));
 8995: 
 8996:         $cdom = $env{'course.'.$cid.'.domain'};
 8997:         $cnum = $env{'course.'.$cid.'.num'};
 8998:     }
 8999: 
 9000:     my %sectioncount;
 9001:     my $now = time;
 9002: 
 9003:     my $check_students = 1;
 9004:     my $only_students = 0;
 9005:     if (ref($possible_roles) eq 'ARRAY') {
 9006:         if (grep(/^st$/,@{$possible_roles})) {
 9007:             if (@{$possible_roles} == 1) {
 9008:                 $only_students = 1;
 9009:             }
 9010:         } else {
 9011:             $check_students = 0;
 9012:         }
 9013:     }
 9014: 
 9015:     if ($check_students) { 
 9016: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9017: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9018: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9019:         my $start_index = &Apache::loncoursedata::CL_START();
 9020:         my $end_index = &Apache::loncoursedata::CL_END();
 9021:         my $status;
 9022: 	while (my ($student,$data) = each(%$classlist)) {
 9023: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9024: 				                     $data->[$status_index],
 9025:                                                      $data->[$start_index],
 9026:                                                      $data->[$end_index]);
 9027:             if ($stu_status eq 'Active') {
 9028:                 $status = 'active';
 9029:             } elsif ($end < $now) {
 9030:                 $status = 'previous';
 9031:             } elsif ($start > $now) {
 9032:                 $status = 'future';
 9033:             } 
 9034: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9035:                 if ((!defined($possible_status)) || (($status ne '') && 
 9036:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9037: 		    $sectioncount{$section}++;
 9038:                 }
 9039: 	    }
 9040: 	}
 9041:     }
 9042:     if ($only_students) {
 9043:         return %sectioncount;
 9044:     }
 9045:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9046:     foreach my $user (sort(keys(%courseroles))) {
 9047: 	if ($user !~ /^(\w{2})/) { next; }
 9048: 	my ($role) = ($user =~ /^(\w{2})/);
 9049: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9050: 	my ($section,$status);
 9051: 	if ($role eq 'cr' &&
 9052: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9053: 	    $section=$1;
 9054: 	}
 9055: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9056: 	if (!defined($section) || $section eq '-1') { next; }
 9057:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9058:         if ($end == -1 && $start == -1) {
 9059:             next; #deleted role
 9060:         }
 9061:         if (!defined($possible_status)) { 
 9062:             $sectioncount{$section}++;
 9063:         } else {
 9064:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9065:                 $status = 'active';
 9066:             } elsif ($end < $now) {
 9067:                 $status = 'future';
 9068:             } elsif ($start > $now) {
 9069:                 $status = 'previous';
 9070:             }
 9071:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9072:                 $sectioncount{$section}++;
 9073:             }
 9074:         }
 9075:     }
 9076:     return %sectioncount;
 9077: }
 9078: 
 9079: ###############################################
 9080: 
 9081: =pod
 9082: 
 9083: =item * &get_course_users()
 9084: 
 9085: Retrieves usernames:domains for users in the specified course
 9086: with specific role(s), and access status. 
 9087: 
 9088: Incoming parameters:
 9089: 1. course domain
 9090: 2. course number
 9091: 3. access status: users must have - either active, 
 9092: previous, future, or all.
 9093: 4. reference to array of permissible roles
 9094: 5. reference to array of section restrictions (optional)
 9095: 6. reference to results object (hash of hashes).
 9096: 7. reference to optional userdata hash
 9097: 8. reference to optional statushash
 9098: 9. flag if privileged users (except those set to unhide in
 9099:    course settings) should be excluded    
 9100: Keys of top level results hash are roles.
 9101: Keys of inner hashes are username:domain, with 
 9102: values set to access type.
 9103: Optional userdata hash returns an array with arguments in the 
 9104: same order as loncoursedata::get_classlist() for student data.
 9105: 
 9106: Optional statushash returns
 9107: 
 9108: Entries for end, start, section and status are blank because
 9109: of the possibility of multiple values for non-student roles.
 9110: 
 9111: =cut
 9112: 
 9113: ###############################################
 9114: 
 9115: sub get_course_users {
 9116:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9117:     my %idx = ();
 9118:     my %seclists;
 9119: 
 9120:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9121:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9122:     $idx{end} = &Apache::loncoursedata::CL_END();
 9123:     $idx{start} = &Apache::loncoursedata::CL_START();
 9124:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9125:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9126:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9127:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9128: 
 9129:     if (grep(/^st$/,@{$roles})) {
 9130:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9131:         my $now = time;
 9132:         foreach my $student (keys(%{$classlist})) {
 9133:             my $match = 0;
 9134:             my $secmatch = 0;
 9135:             my $section = $$classlist{$student}[$idx{section}];
 9136:             my $status = $$classlist{$student}[$idx{status}];
 9137:             if ($section eq '') {
 9138:                 $section = 'none';
 9139:             }
 9140:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9141:                 if (grep(/^all$/,@{$sections})) {
 9142:                     $secmatch = 1;
 9143:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9144:                     if (grep(/^none$/,@{$sections})) {
 9145:                         $secmatch = 1;
 9146:                     }
 9147:                 } else {  
 9148: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9149: 		        $secmatch = 1;
 9150:                     }
 9151: 		}
 9152:                 if (!$secmatch) {
 9153:                     next;
 9154:                 }
 9155:             }
 9156:             if (defined($$types{'active'})) {
 9157:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9158:                     push(@{$$users{st}{$student}},'active');
 9159:                     $match = 1;
 9160:                 }
 9161:             }
 9162:             if (defined($$types{'previous'})) {
 9163:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9164:                     push(@{$$users{st}{$student}},'previous');
 9165:                     $match = 1;
 9166:                 }
 9167:             }
 9168:             if (defined($$types{'future'})) {
 9169:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9170:                     push(@{$$users{st}{$student}},'future');
 9171:                     $match = 1;
 9172:                 }
 9173:             }
 9174:             if ($match) {
 9175:                 push(@{$seclists{$student}},$section);
 9176:                 if (ref($userdata) eq 'HASH') {
 9177:                     $$userdata{$student} = $$classlist{$student};
 9178:                 }
 9179:                 if (ref($statushash) eq 'HASH') {
 9180:                     $statushash->{$student}{'st'}{$section} = $status;
 9181:                 }
 9182:             }
 9183:         }
 9184:     }
 9185:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9186:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9187:         my $now = time;
 9188:         my %displaystatus = ( previous => 'Expired',
 9189:                               active   => 'Active',
 9190:                               future   => 'Future',
 9191:                             );
 9192:         my (%nothide,@possdoms);
 9193:         if ($hidepriv) {
 9194:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9195:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9196:                 if ($user !~ /:/) {
 9197:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9198:                 } else {
 9199:                     $nothide{$user} = 1;
 9200:                 }
 9201:             }
 9202:             my @possdoms = ($cdom);
 9203:             if ($coursehash{'checkforpriv'}) {
 9204:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9205:             }
 9206:         }
 9207:         foreach my $person (sort(keys(%coursepersonnel))) {
 9208:             my $match = 0;
 9209:             my $secmatch = 0;
 9210:             my $status;
 9211:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9212:             $user =~ s/:$//;
 9213:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9214:             if ($end == -1 || $start == -1) {
 9215:                 next;
 9216:             }
 9217:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9218:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9219:                 my ($uname,$udom) = split(/:/,$user);
 9220:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9221:                     if (grep(/^all$/,@{$sections})) {
 9222:                         $secmatch = 1;
 9223:                     } elsif ($usec eq '') {
 9224:                         if (grep(/^none$/,@{$sections})) {
 9225:                             $secmatch = 1;
 9226:                         }
 9227:                     } else {
 9228:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9229:                             $secmatch = 1;
 9230:                         }
 9231:                     }
 9232:                     if (!$secmatch) {
 9233:                         next;
 9234:                     }
 9235:                 }
 9236:                 if ($usec eq '') {
 9237:                     $usec = 'none';
 9238:                 }
 9239:                 if ($uname ne '' && $udom ne '') {
 9240:                     if ($hidepriv) {
 9241:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9242:                             (!$nothide{$uname.':'.$udom})) {
 9243:                             next;
 9244:                         }
 9245:                     }
 9246:                     if ($end > 0 && $end < $now) {
 9247:                         $status = 'previous';
 9248:                     } elsif ($start > $now) {
 9249:                         $status = 'future';
 9250:                     } else {
 9251:                         $status = 'active';
 9252:                     }
 9253:                     foreach my $type (keys(%{$types})) { 
 9254:                         if ($status eq $type) {
 9255:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9256:                                 push(@{$$users{$role}{$user}},$type);
 9257:                             }
 9258:                             $match = 1;
 9259:                         }
 9260:                     }
 9261:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9262:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9263: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9264:                         }
 9265:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9266:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9267:                         }
 9268:                         if (ref($statushash) eq 'HASH') {
 9269:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9270:                         }
 9271:                     }
 9272:                 }
 9273:             }
 9274:         }
 9275:         if (grep(/^ow$/,@{$roles})) {
 9276:             if ((defined($cdom)) && (defined($cnum))) {
 9277:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9278:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9279:                     my $owner = $csettings{'internal.courseowner'};
 9280:                     next if ($owner eq '');
 9281:                     my ($ownername,$ownerdom);
 9282:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9283:                         $ownername = $1;
 9284:                         $ownerdom = $2;
 9285:                     } else {
 9286:                         $ownername = $owner;
 9287:                         $ownerdom = $cdom;
 9288:                         $owner = $ownername.':'.$ownerdom;
 9289:                     }
 9290:                     @{$$users{'ow'}{$owner}} = 'any';
 9291:                     if (defined($userdata) && 
 9292: 			!exists($$userdata{$owner})) {
 9293: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9294:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9295:                             push(@{$seclists{$owner}},'none');
 9296:                         }
 9297:                         if (ref($statushash) eq 'HASH') {
 9298:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9299:                         }
 9300: 		    }
 9301:                 }
 9302:             }
 9303:         }
 9304:         foreach my $user (keys(%seclists)) {
 9305:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9306:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9307:         }
 9308:     }
 9309:     return;
 9310: }
 9311: 
 9312: sub get_user_info {
 9313:     my ($udom,$uname,$idx,$userdata) = @_;
 9314:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9315: 	&plainname($uname,$udom,'lastname');
 9316:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9317:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9318:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9319:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9320:     return;
 9321: }
 9322: 
 9323: ###############################################
 9324: 
 9325: =pod
 9326: 
 9327: =item * &get_user_quota()
 9328: 
 9329: Retrieves quota assigned for storage of user files.
 9330: Default is to report quota for portfolio files.
 9331: 
 9332: Incoming parameters:
 9333: 1. user's username
 9334: 2. user's domain
 9335: 3. quota name - portfolio, author, or course
 9336:    (if no quota name provided, defaults to portfolio).
 9337: 4. crstype - official, unofficial, textbook, placement or community, 
 9338:    if quota name is course
 9339: 
 9340: Returns:
 9341: 1. Disk quota (in MB) assigned to student.
 9342: 2. (Optional) Type of setting: custom or default
 9343:    (individually assigned or default for user's 
 9344:    institutional status).
 9345: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9346:    or student - types as defined in localenroll::inst_usertypes 
 9347:    for user's domain, which determines default quota for user.
 9348: 4. (Optional) - Default quota which would apply to the user.
 9349: 
 9350: If a value has been stored in the user's environment, 
 9351: it will return that, otherwise it returns the maximal default
 9352: defined for the user's institutional status(es) in the domain.
 9353: 
 9354: =cut
 9355: 
 9356: ###############################################
 9357: 
 9358: 
 9359: sub get_user_quota {
 9360:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9361:     my ($quota,$quotatype,$settingstatus,$defquota);
 9362:     if (!defined($udom)) {
 9363:         $udom = $env{'user.domain'};
 9364:     }
 9365:     if (!defined($uname)) {
 9366:         $uname = $env{'user.name'};
 9367:     }
 9368:     if (($udom eq '' || $uname eq '') ||
 9369:         ($udom eq 'public') && ($uname eq 'public')) {
 9370:         $quota = 0;
 9371:         $quotatype = 'default';
 9372:         $defquota = 0; 
 9373:     } else {
 9374:         my $inststatus;
 9375:         if ($quotaname eq 'course') {
 9376:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9377:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9378:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9379:             } else {
 9380:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9381:                 $quota = $cenv{'internal.uploadquota'};
 9382:             }
 9383:         } else {
 9384:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9385:                 if ($quotaname eq 'author') {
 9386:                     $quota = $env{'environment.authorquota'};
 9387:                 } else {
 9388:                     $quota = $env{'environment.portfolioquota'};
 9389:                 }
 9390:                 $inststatus = $env{'environment.inststatus'};
 9391:             } else {
 9392:                 my %userenv = 
 9393:                     &Apache::lonnet::get('environment',['portfolioquota',
 9394:                                          'authorquota','inststatus'],$udom,$uname);
 9395:                 my ($tmp) = keys(%userenv);
 9396:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9397:                     if ($quotaname eq 'author') {
 9398:                         $quota = $userenv{'authorquota'};
 9399:                     } else {
 9400:                         $quota = $userenv{'portfolioquota'};
 9401:                     }
 9402:                     $inststatus = $userenv{'inststatus'};
 9403:                 } else {
 9404:                     undef(%userenv);
 9405:                 }
 9406:             }
 9407:         }
 9408:         if ($quota eq '' || wantarray) {
 9409:             if ($quotaname eq 'course') {
 9410:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9411:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9412:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
 9413:                     ($crstype eq 'placement')) { 
 9414:                     $defquota = $domdefs{$crstype.'quota'};
 9415:                 }
 9416:                 if ($defquota eq '') {
 9417:                     $defquota = 500;
 9418:                 }
 9419:             } else {
 9420:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9421:             }
 9422:             if ($quota eq '') {
 9423:                 $quota = $defquota;
 9424:                 $quotatype = 'default';
 9425:             } else {
 9426:                 $quotatype = 'custom';
 9427:             }
 9428:         }
 9429:     }
 9430:     if (wantarray) {
 9431:         return ($quota,$quotatype,$settingstatus,$defquota);
 9432:     } else {
 9433:         return $quota;
 9434:     }
 9435: }
 9436: 
 9437: ###############################################
 9438: 
 9439: =pod
 9440: 
 9441: =item * &default_quota()
 9442: 
 9443: Retrieves default quota assigned for storage of user portfolio files,
 9444: given an (optional) user's institutional status.
 9445: 
 9446: Incoming parameters:
 9447: 
 9448: 1. domain
 9449: 2. (Optional) institutional status(es).  This is a : separated list of 
 9450:    status types (e.g., faculty, staff, student etc.)
 9451:    which apply to the user for whom the default is being retrieved.
 9452:    If the institutional status string in undefined, the domain
 9453:    default quota will be returned.
 9454: 3.  quota name - portfolio, author, or course
 9455:    (if no quota name provided, defaults to portfolio).
 9456: 
 9457: Returns:
 9458: 
 9459: 1. Default disk quota (in MB) for user portfolios in the domain.
 9460: 2. (Optional) institutional type which determined the value of the
 9461:    default quota.
 9462: 
 9463: If a value has been stored in the domain's configuration db,
 9464: it will return that, otherwise it returns 20 (for backwards 
 9465: compatibility with domains which have not set up a configuration
 9466: db file; the original statically defined portfolio quota was 20 MB). 
 9467: 
 9468: If the user's status includes multiple types (e.g., staff and student),
 9469: the largest default quota which applies to the user determines the
 9470: default quota returned.
 9471: 
 9472: =cut
 9473: 
 9474: ###############################################
 9475: 
 9476: 
 9477: sub default_quota {
 9478:     my ($udom,$inststatus,$quotaname) = @_;
 9479:     my ($defquota,$settingstatus);
 9480:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9481:                                             ['quotas'],$udom);
 9482:     my $key = 'defaultquota';
 9483:     if ($quotaname eq 'author') {
 9484:         $key = 'authorquota';
 9485:     }
 9486:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9487:         if ($inststatus ne '') {
 9488:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9489:             foreach my $item (@statuses) {
 9490:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9491:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9492:                         if ($defquota eq '') {
 9493:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9494:                             $settingstatus = $item;
 9495:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9496:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9497:                             $settingstatus = $item;
 9498:                         }
 9499:                     }
 9500:                 } elsif ($key eq 'defaultquota') {
 9501:                     if ($quotahash{'quotas'}{$item} ne '') {
 9502:                         if ($defquota eq '') {
 9503:                             $defquota = $quotahash{'quotas'}{$item};
 9504:                             $settingstatus = $item;
 9505:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9506:                             $defquota = $quotahash{'quotas'}{$item};
 9507:                             $settingstatus = $item;
 9508:                         }
 9509:                     }
 9510:                 }
 9511:             }
 9512:         }
 9513:         if ($defquota eq '') {
 9514:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9515:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9516:             } elsif ($key eq 'defaultquota') {
 9517:                 $defquota = $quotahash{'quotas'}{'default'};
 9518:             }
 9519:             $settingstatus = 'default';
 9520:             if ($defquota eq '') {
 9521:                 if ($quotaname eq 'author') {
 9522:                     $defquota = 500;
 9523:                 }
 9524:             }
 9525:         }
 9526:     } else {
 9527:         $settingstatus = 'default';
 9528:         if ($quotaname eq 'author') {
 9529:             $defquota = 500;
 9530:         } else {
 9531:             $defquota = 20;
 9532:         }
 9533:     }
 9534:     if (wantarray) {
 9535:         return ($defquota,$settingstatus);
 9536:     } else {
 9537:         return $defquota;
 9538:     }
 9539: }
 9540: 
 9541: ###############################################
 9542: 
 9543: =pod
 9544: 
 9545: =item * &excess_filesize_warning()
 9546: 
 9547: Returns warning message if upload of file to authoring space, or copying
 9548: of existing file within authoring space will cause quota for the authoring
 9549: space to be exceeded.
 9550: 
 9551: Same, if upload of a file directly to a course/community via Course Editor
 9552: will cause quota for uploaded content for the course to be exceeded.
 9553: 
 9554: Inputs: 7 
 9555: 1. username or coursenum
 9556: 2. domain
 9557: 3. context ('author' or 'course')
 9558: 4. filename of file for which action is being requested
 9559: 5. filesize (kB) of file
 9560: 6. action being taken: copy or upload.
 9561: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
 9562: 
 9563: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9564:          otherwise return null.
 9565: 
 9566: =back
 9567: 
 9568: =cut
 9569: 
 9570: sub excess_filesize_warning {
 9571:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9572:     my $current_disk_usage = 0;
 9573:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9574:     if ($context eq 'author') {
 9575:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9576:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9577:     } else {
 9578:         foreach my $subdir ('docs','supplemental') {
 9579:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9580:         }
 9581:     }
 9582:     $disk_quota = int($disk_quota * 1000);
 9583:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9584:         return '<p class="LC_warning">'.
 9585:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9586:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9587:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9588:                             $disk_quota,$current_disk_usage).
 9589:                '</p>';
 9590:     }
 9591:     return;
 9592: }
 9593: 
 9594: ###############################################
 9595: 
 9596: 
 9597: 
 9598: 
 9599: sub get_secgrprole_info {
 9600:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9601:     my %sections_count = &get_sections($cdom,$cnum);
 9602:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9603:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9604:     my @groups = sort(keys(%curr_groups));
 9605:     my $allroles = [];
 9606:     my $rolehash;
 9607:     my $accesshash = {
 9608:                      active => 'Currently has access',
 9609:                      future => 'Will have future access',
 9610:                      previous => 'Previously had access',
 9611:                   };
 9612:     if ($needroles) {
 9613:         $rolehash = {'all' => 'all'};
 9614:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9615: 	if (&Apache::lonnet::error(%user_roles)) {
 9616: 	    undef(%user_roles);
 9617: 	}
 9618:         foreach my $item (keys(%user_roles)) {
 9619:             my ($role)=split(/\:/,$item,2);
 9620:             if ($role eq 'cr') { next; }
 9621:             if ($role =~ /^cr/) {
 9622:                 $$rolehash{$role} = (split('/',$role))[3];
 9623:             } else {
 9624:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9625:             }
 9626:         }
 9627:         foreach my $key (sort(keys(%{$rolehash}))) {
 9628:             push(@{$allroles},$key);
 9629:         }
 9630:         push (@{$allroles},'st');
 9631:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9632:     }
 9633:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9634: }
 9635: 
 9636: sub user_picker {
 9637:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9638:     my $currdom = $dom;
 9639:     my %curr_selected = (
 9640:                         srchin => 'dom',
 9641:                         srchby => 'lastname',
 9642:                       );
 9643:     my $srchterm;
 9644:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9645:         if ($srch->{'srchby'} ne '') {
 9646:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9647:         }
 9648:         if ($srch->{'srchin'} ne '') {
 9649:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9650:         }
 9651:         if ($srch->{'srchtype'} ne '') {
 9652:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9653:         }
 9654:         if ($srch->{'srchdomain'} ne '') {
 9655:             $currdom = $srch->{'srchdomain'};
 9656:         }
 9657:         $srchterm = $srch->{'srchterm'};
 9658:     }
 9659:     my %html_lt=&Apache::lonlocal::texthash(
 9660:                     'usr'       => 'Search criteria',
 9661:                     'doma'      => 'Domain/institution to search',
 9662:                     'uname'     => 'username',
 9663:                     'lastname'  => 'last name',
 9664:                     'lastfirst' => 'last name, first name',
 9665:                     'crs'       => 'in this course',
 9666:                     'dom'       => 'in selected LON-CAPA domain', 
 9667:                     'alc'       => 'all LON-CAPA',
 9668:                     'instd'     => 'in institutional directory for selected domain',
 9669:                     'exact'     => 'is',
 9670:                     'contains'  => 'contains',
 9671:                     'begins'    => 'begins with',
 9672:                                        );
 9673:     my %js_lt=&Apache::lonlocal::texthash(
 9674:                     'youm'      => "You must include some text to search for.",
 9675:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9676:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9677:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9678:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9679:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9680:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9681:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9682:                                        );
 9683:     &html_escape(\%html_lt);
 9684:     &js_escape(\%js_lt);
 9685:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9686:     my $srchinsel = ' <select name="srchin">';
 9687: 
 9688:     my @srchins = ('crs','dom','alc','instd');
 9689: 
 9690:     foreach my $option (@srchins) {
 9691:         # FIXME 'alc' option unavailable until 
 9692:         #       loncreateuser::print_user_query_page()
 9693:         #       has been completed.
 9694:         next if ($option eq 'alc');
 9695:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9696:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9697:         if ($curr_selected{'srchin'} eq $option) {
 9698:             $srchinsel .= ' 
 9699:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9700:         } else {
 9701:             $srchinsel .= '
 9702:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9703:         }
 9704:     }
 9705:     $srchinsel .= "\n  </select>\n";
 9706: 
 9707:     my $srchbysel =  ' <select name="srchby">';
 9708:     foreach my $option ('lastname','lastfirst','uname') {
 9709:         if ($curr_selected{'srchby'} eq $option) {
 9710:             $srchbysel .= '
 9711:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9712:         } else {
 9713:             $srchbysel .= '
 9714:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9715:          }
 9716:     }
 9717:     $srchbysel .= "\n  </select>\n";
 9718: 
 9719:     my $srchtypesel = ' <select name="srchtype">';
 9720:     foreach my $option ('begins','contains','exact') {
 9721:         if ($curr_selected{'srchtype'} eq $option) {
 9722:             $srchtypesel .= '
 9723:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9724:         } else {
 9725:             $srchtypesel .= '
 9726:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9727:         }
 9728:     }
 9729:     $srchtypesel .= "\n  </select>\n";
 9730: 
 9731:     my ($newuserscript,$new_user_create);
 9732:     my $context_dom = $env{'request.role.domain'};
 9733:     if ($context eq 'requestcrs') {
 9734:         if ($env{'form.coursedom'} ne '') { 
 9735:             $context_dom = $env{'form.coursedom'};
 9736:         }
 9737:     }
 9738:     if ($forcenewuser) {
 9739:         if (ref($srch) eq 'HASH') {
 9740:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9741:                 if ($cancreate) {
 9742:                     $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>';
 9743:                 } else {
 9744:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9745:                     my %usertypetext = (
 9746:                         official   => 'institutional',
 9747:                         unofficial => 'non-institutional',
 9748:                     );
 9749:                     $new_user_create = '<p class="LC_warning">'
 9750:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9751:                                       .' '
 9752:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9753:                                           ,'<a href="'.$helplink.'">','</a>')
 9754:                                       .'</p><br />';
 9755:                 }
 9756:             }
 9757:         }
 9758: 
 9759:         $newuserscript = <<"ENDSCRIPT";
 9760: 
 9761: function setSearch(createnew,callingForm) {
 9762:     if (createnew == 1) {
 9763:         for (var i=0; i<callingForm.srchby.length; i++) {
 9764:             if (callingForm.srchby.options[i].value == 'uname') {
 9765:                 callingForm.srchby.selectedIndex = i;
 9766:             }
 9767:         }
 9768:         for (var i=0; i<callingForm.srchin.length; i++) {
 9769:             if ( callingForm.srchin.options[i].value == 'dom') {
 9770: 		callingForm.srchin.selectedIndex = i;
 9771:             }
 9772:         }
 9773:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9774:             if (callingForm.srchtype.options[i].value == 'exact') {
 9775:                 callingForm.srchtype.selectedIndex = i;
 9776:             }
 9777:         }
 9778:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9779:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9780:                 callingForm.srchdomain.selectedIndex = i;
 9781:             }
 9782:         }
 9783:     }
 9784: }
 9785: ENDSCRIPT
 9786: 
 9787:     }
 9788: 
 9789:     my $output = <<"END_BLOCK";
 9790: <script type="text/javascript">
 9791: // <![CDATA[
 9792: function validateEntry(callingForm) {
 9793: 
 9794:     var checkok = 1;
 9795:     var srchin;
 9796:     for (var i=0; i<callingForm.srchin.length; i++) {
 9797: 	if ( callingForm.srchin[i].checked ) {
 9798: 	    srchin = callingForm.srchin[i].value;
 9799: 	}
 9800:     }
 9801: 
 9802:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9803:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9804:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9805:     var srchterm =  callingForm.srchterm.value;
 9806:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9807:     var msg = "";
 9808: 
 9809:     if (srchterm == "") {
 9810:         checkok = 0;
 9811:         msg += "$js_lt{'youm'}\\n";
 9812:     }
 9813: 
 9814:     if (srchtype== 'begins') {
 9815:         if (srchterm.length < 2) {
 9816:             checkok = 0;
 9817:             msg += "$js_lt{'thte'}\\n";
 9818:         }
 9819:     }
 9820: 
 9821:     if (srchtype== 'contains') {
 9822:         if (srchterm.length < 3) {
 9823:             checkok = 0;
 9824:             msg += "$js_lt{'thet'}\\n";
 9825:         }
 9826:     }
 9827:     if (srchin == 'instd') {
 9828:         if (srchdomain == '') {
 9829:             checkok = 0;
 9830:             msg += "$js_lt{'yomc'}\\n";
 9831:         }
 9832:     }
 9833:     if (srchin == 'dom') {
 9834:         if (srchdomain == '') {
 9835:             checkok = 0;
 9836:             msg += "$js_lt{'ymcd'}\\n";
 9837:         }
 9838:     }
 9839:     if (srchby == 'lastfirst') {
 9840:         if (srchterm.indexOf(",") == -1) {
 9841:             checkok = 0;
 9842:             msg += "$js_lt{'whus'}\\n";
 9843:         }
 9844:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9845:             checkok = 0;
 9846:             msg += "$js_lt{'whse'}\\n";
 9847:         }
 9848:     }
 9849:     if (checkok == 0) {
 9850:         alert("$js_lt{'thfo'}\\n"+msg);
 9851:         return;
 9852:     }
 9853:     if (checkok == 1) {
 9854:         callingForm.submit();
 9855:     }
 9856: }
 9857: 
 9858: $newuserscript
 9859: 
 9860: // ]]>
 9861: </script>
 9862: 
 9863: $new_user_create
 9864: 
 9865: END_BLOCK
 9866: 
 9867:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9868:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9869:                $domform.
 9870:                &Apache::lonhtmlcommon::row_closure().
 9871:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9872:                $srchbysel.
 9873:                $srchtypesel. 
 9874:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9875:                $srchinsel.
 9876:                &Apache::lonhtmlcommon::row_closure(1). 
 9877:                &Apache::lonhtmlcommon::end_pick_box().
 9878:                '<br />';
 9879:     return $output;
 9880: }
 9881: 
 9882: sub user_rule_check {
 9883:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9884:     my ($response,%inst_response);
 9885:     if (ref($usershash) eq 'HASH') {
 9886:         if (keys(%{$usershash}) > 1) {
 9887:             my (%by_username,%by_id,%userdoms);
 9888:             my $checkid; 
 9889:             if (ref($checks) eq 'HASH') {
 9890:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9891:                     $checkid = 1;
 9892:                 }
 9893:             }
 9894:             foreach my $user (keys(%{$usershash})) {
 9895:                 my ($uname,$udom) = split(/:/,$user);
 9896:                 if ($checkid) {
 9897:                     if (ref($usershash->{$user}) eq 'HASH') {
 9898:                         if ($usershash->{$user}->{'id'} ne '') {
 9899:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
 9900:                             $userdoms{$udom} = 1;
 9901:                             if (ref($inst_results) eq 'HASH') {
 9902:                                 $inst_results->{$uname.':'.$udom} = {};
 9903:                             }
 9904:                         }
 9905:                     }
 9906:                 } else {
 9907:                     $by_username{$udom}{$uname} = 1;
 9908:                     $userdoms{$udom} = 1;
 9909:                     if (ref($inst_results) eq 'HASH') {
 9910:                         $inst_results->{$uname.':'.$udom} = {};
 9911:                     }
 9912:                 }
 9913:             }
 9914:             foreach my $udom (keys(%userdoms)) {
 9915:                 if (!$got_rules->{$udom}) {
 9916:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9917:                                                              ['usercreation'],$udom);
 9918:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9919:                         foreach my $item ('username','id') {
 9920:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9921:                                 $$curr_rules{$udom}{$item} =
 9922:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9923:                             }
 9924:                         }
 9925:                     }
 9926:                     $got_rules->{$udom} = 1;
 9927:                 }
 9928:             }
 9929:             if ($checkid) {
 9930:                 foreach my $udom (keys(%by_id)) {
 9931:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9932:                     if ($outcome eq 'ok') {
 9933:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9934:                             my $uname = $by_id{$udom}{$id};
 9935:                             $inst_response{$uname.':'.$udom} = $outcome;
 9936:                         }
 9937:                         if (ref($results) eq 'HASH') {
 9938:                             foreach my $uname (keys(%{$results})) {
 9939:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9940:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9941:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9942:                                 }
 9943:                             }
 9944:                         }
 9945:                     }
 9946:                 }
 9947:             } else {
 9948:                 foreach my $udom (keys(%by_username)) {
 9949:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9950:                     if ($outcome eq 'ok') {
 9951:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9952:                             $inst_response{$uname.':'.$udom} = $outcome;
 9953:                         }
 9954:                         if (ref($results) eq 'HASH') {
 9955:                             foreach my $uname (keys(%{$results})) {
 9956:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9957:                             }
 9958:                         }
 9959:                     }
 9960:                 }
 9961:             }
 9962:         } elsif (keys(%{$usershash}) == 1) {
 9963:             my $user = (keys(%{$usershash}))[0];
 9964:             my ($uname,$udom) = split(/:/,$user);
 9965:             if (($udom ne '') && ($uname ne '')) {
 9966:                 if (ref($usershash->{$user}) eq 'HASH') {
 9967:                     if (ref($checks) eq 'HASH') {
 9968:                         if (defined($checks->{'username'})) {
 9969:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
 9970:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9971:                         } elsif (defined($checks->{'id'})) {
 9972:                             if ($usershash->{$user}->{'id'} ne '') {
 9973:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9974:                                     &Apache::lonnet::get_instuser($udom,undef,
 9975:                                                                   $usershash->{$user}->{'id'});
 9976:                             } else {
 9977:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9978:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9979:                             }
 9980:                         }
 9981:                     } else {
 9982:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9983:                             &Apache::lonnet::get_instuser($udom,$uname);
 9984:                        return;
 9985:                     }
 9986:                     if (!$got_rules->{$udom}) {
 9987:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9988:                                                                  ['usercreation'],$udom);
 9989:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9990:                             foreach my $item ('username','id') {
 9991:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9992:                                    $$curr_rules{$udom}{$item} = 
 9993:                                        $domconfig{'usercreation'}{$item.'_rule'};
 9994:                                 }
 9995:                             }
 9996:                         }
 9997:                         $got_rules->{$udom} = 1;
 9998:                     }
 9999:                 }
10000:             } else {
10001:                 return;
10002:             }
10003:         } else {
10004:             return;
10005:         }
10006:         foreach my $user (keys(%{$usershash})) {
10007:             my ($uname,$udom) = split(/:/,$user);
10008:             next if (($udom eq '') || ($uname eq ''));
10009:             my $id;
10010:             if (ref($inst_results) eq 'HASH') {
10011:                 if (ref($inst_results->{$user}) eq 'HASH') {
10012:                     $id = $inst_results->{$user}->{'id'};
10013:                 }
10014:             }
10015:             if ($id eq '') { 
10016:                 if (ref($usershash->{$user})) {
10017:                     $id = $usershash->{$user}->{'id'};
10018:                 }
10019:             }
10020:             foreach my $item (keys(%{$checks})) {
10021:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10022:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10023:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10024:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10025:                                                                              $$curr_rules{$udom}{$item});
10026:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10027:                                 if ($rule_check{$rule}) {
10028:                                     $$rulematch{$user}{$item} = $rule;
10029:                                     if ($inst_response{$user} eq 'ok') {
10030:                                         if (ref($inst_results) eq 'HASH') {
10031:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10032:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10033:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10034:                                                 } elsif ($item eq 'id') {
10035:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10036:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10037:                                                     }
10038:                                                 }
10039:                                             }
10040:                                         }
10041:                                     }
10042:                                     last;
10043:                                 }
10044:                             }
10045:                         }
10046:                     }
10047:                 }
10048:             }
10049:         }
10050:     }
10051:     return;
10052: }
10053: 
10054: sub user_rule_formats {
10055:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10056:     my %text = ( 
10057:                  'username' => 'Usernames',
10058:                  'id'       => 'IDs',
10059:                );
10060:     my $output;
10061:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10062:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10063:         if (@{$ruleorder} > 0) {
10064:             $output = '<br />'.
10065:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10066:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10067:                       ' <ul>';
10068:             foreach my $rule (@{$ruleorder}) {
10069:                 if (ref($curr_rules) eq 'ARRAY') {
10070:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10071:                         if (ref($rules->{$rule}) eq 'HASH') {
10072:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10073:                                         $rules->{$rule}{'desc'}.'</li>';
10074:                         }
10075:                     }
10076:                 }
10077:             }
10078:             $output .= '</ul>';
10079:         }
10080:     }
10081:     return $output;
10082: }
10083: 
10084: sub instrule_disallow_msg {
10085:     my ($checkitem,$domdesc,$count,$mode) = @_;
10086:     my $response;
10087:     my %text = (
10088:                   item   => 'username',
10089:                   items  => 'usernames',
10090:                   match  => 'matches',
10091:                   do     => 'does',
10092:                   action => 'a username',
10093:                   one    => 'one',
10094:                );
10095:     if ($count > 1) {
10096:         $text{'item'} = 'usernames';
10097:         $text{'match'} ='match';
10098:         $text{'do'} = 'do';
10099:         $text{'action'} = 'usernames',
10100:         $text{'one'} = 'ones';
10101:     }
10102:     if ($checkitem eq 'id') {
10103:         $text{'items'} = 'IDs';
10104:         $text{'item'} = 'ID';
10105:         $text{'action'} = 'an ID';
10106:         if ($count > 1) {
10107:             $text{'item'} = 'IDs';
10108:             $text{'action'} = 'IDs';
10109:         }
10110:     }
10111:     $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 />';
10112:     if ($mode eq 'upload') {
10113:         if ($checkitem eq 'username') {
10114:             $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'}.");
10115:         } elsif ($checkitem eq 'id') {
10116:             $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.");
10117:         }
10118:     } elsif ($mode eq 'selfcreate') {
10119:         if ($checkitem eq 'id') {
10120:             $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.");
10121:         }
10122:     } else {
10123:         if ($checkitem eq 'username') {
10124:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10125:         } elsif ($checkitem eq 'id') {
10126:             $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.");
10127:         }
10128:     }
10129:     return $response;
10130: }
10131: 
10132: sub personal_data_fieldtitles {
10133:     my %fieldtitles = &Apache::lonlocal::texthash (
10134:                         id => 'Student/Employee ID',
10135:                         permanentemail => 'E-mail address',
10136:                         lastname => 'Last Name',
10137:                         firstname => 'First Name',
10138:                         middlename => 'Middle Name',
10139:                         generation => 'Generation',
10140:                         gen => 'Generation',
10141:                         inststatus => 'Affiliation',
10142:                    );
10143:     return %fieldtitles;
10144: }
10145: 
10146: sub sorted_inst_types {
10147:     my ($dom) = @_;
10148:     my ($usertypes,$order);
10149:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10150:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10151:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10152:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10153:     } else {
10154:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10155:     }
10156:     my $othertitle = &mt('All users');
10157:     if ($env{'request.course.id'}) {
10158:         $othertitle  = &mt('Any users');
10159:     }
10160:     my @types;
10161:     if (ref($order) eq 'ARRAY') {
10162:         @types = @{$order};
10163:     }
10164:     if (@types == 0) {
10165:         if (ref($usertypes) eq 'HASH') {
10166:             @types = sort(keys(%{$usertypes}));
10167:         }
10168:     }
10169:     if (keys(%{$usertypes}) > 0) {
10170:         $othertitle = &mt('Other users');
10171:     }
10172:     return ($othertitle,$usertypes,\@types);
10173: }
10174: 
10175: sub get_institutional_codes {
10176:     my ($settings,$allcourses,$LC_code) = @_;
10177: # Get complete list of course sections to update
10178:     my @currsections = ();
10179:     my @currxlists = ();
10180:     my $coursecode = $$settings{'internal.coursecode'};
10181: 
10182:     if ($$settings{'internal.sectionnums'} ne '') {
10183:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10184:     }
10185: 
10186:     if ($$settings{'internal.crosslistings'} ne '') {
10187:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10188:     }
10189: 
10190:     if (@currxlists > 0) {
10191:         foreach (@currxlists) {
10192:             if (m/^([^:]+):(\w*)$/) {
10193:                 unless (grep/^$1$/,@{$allcourses}) {
10194:                     push @{$allcourses},$1;
10195:                     $$LC_code{$1} = $2;
10196:                 }
10197:             }
10198:         }
10199:     }
10200:  
10201:     if (@currsections > 0) {
10202:         foreach (@currsections) {
10203:             if (m/^(\w+):(\w*)$/) {
10204:                 my $sec = $coursecode.$1;
10205:                 my $lc_sec = $2;
10206:                 unless (grep/^$sec$/,@{$allcourses}) {
10207:                     push @{$allcourses},$sec;
10208:                     $$LC_code{$sec} = $lc_sec;
10209:                 }
10210:             }
10211:         }
10212:     }
10213:     return;
10214: }
10215: 
10216: sub get_standard_codeitems {
10217:     return ('Year','Semester','Department','Number','Section');
10218: }
10219: 
10220: =pod
10221: 
10222: =head1 Slot Helpers
10223: 
10224: =over 4
10225: 
10226: =item * sorted_slots()
10227: 
10228: Sorts an array of slot names in order of an optional sort key,
10229: default sort is by slot start time (earliest first). 
10230: 
10231: Inputs:
10232: 
10233: =over 4
10234: 
10235: slotsarr  - Reference to array of unsorted slot names.
10236: 
10237: slots     - Reference to hash of hash, where outer hash keys are slot names.
10238: 
10239: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10240: 
10241: =back
10242: 
10243: Returns:
10244: 
10245: =over 4
10246: 
10247: sorted   - An array of slot names sorted by a specified sort key 
10248:            (default sort key is start time of the slot).
10249: 
10250: =back
10251: 
10252: =cut
10253: 
10254: 
10255: sub sorted_slots {
10256:     my ($slotsarr,$slots,$sortkey) = @_;
10257:     if ($sortkey eq '') {
10258:         $sortkey = 'starttime';
10259:     }
10260:     my @sorted;
10261:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10262:         @sorted =
10263:             sort {
10264:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10265:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10266:                      }
10267:                      if (ref($slots->{$a})) { return -1;}
10268:                      if (ref($slots->{$b})) { return 1;}
10269:                      return 0;
10270:                  } @{$slotsarr};
10271:     }
10272:     return @sorted;
10273: }
10274: 
10275: =pod
10276: 
10277: =item * get_future_slots()
10278: 
10279: Inputs:
10280: 
10281: =over 4
10282: 
10283: cnum - course number
10284: 
10285: cdom - course domain
10286: 
10287: now - current UNIX time
10288: 
10289: symb - optional symb
10290: 
10291: =back
10292: 
10293: Returns:
10294: 
10295: =over 4
10296: 
10297: sorted_reservable - ref to array of student_schedulable slots currently 
10298:                     reservable, ordered by end date of reservation period.
10299: 
10300: reservable_now - ref to hash of student_schedulable slots currently
10301:                  reservable.
10302: 
10303:     Keys in inner hash are:
10304:     (a) symb: either blank or symb to which slot use is restricted.
10305:     (b) endreserve: end date of reservation period. 
10306: 
10307: sorted_future - ref to array of student_schedulable slots reservable in
10308:                 the future, ordered by start date of reservation period.
10309: 
10310: future_reservable - ref to hash of student_schedulable slots reservable
10311:                     in the future.
10312: 
10313:     Keys in inner hash are:
10314:     (a) symb: either blank or symb to which slot use is restricted.
10315:     (b) startreserve:  start date of reservation period.
10316: 
10317: =back
10318: 
10319: =cut
10320: 
10321: sub get_future_slots {
10322:     my ($cnum,$cdom,$now,$symb) = @_;
10323:     my $map;
10324:     if ($symb) {
10325:         ($map) = &Apache::lonnet::decode_symb($symb);
10326:     }
10327:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10328:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10329:     foreach my $slot (keys(%slots)) {
10330:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10331:         if ($symb) {
10332:             if ($slots{$slot}->{'symb'} ne '') {
10333:                 my $canuse;
10334:                 my %oksymbs;
10335:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10336:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10337:                 if ($oksymbs{$symb}) {
10338:                     $canuse = 1;
10339:                 } else {
10340:                     foreach my $item (@slotsymbs) {
10341:                         if ($item =~ /\.(page|sequence)$/) {
10342:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10343:                             if (($map ne '') && ($map eq $sloturl)) {
10344:                                 $canuse = 1;
10345:                                 last;
10346:                             }
10347:                         }
10348:                     }
10349:                 }
10350:                 next unless ($canuse);
10351:             }
10352:         }
10353:         if (($slots{$slot}->{'starttime'} > $now) &&
10354:             ($slots{$slot}->{'endtime'} > $now)) {
10355:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10356:                 my $userallowed = 0;
10357:                 if ($slots{$slot}->{'allowedsections'}) {
10358:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10359:                     if (!defined($env{'request.role.sec'})
10360:                         && grep(/^No section assigned$/,@allowed_sec)) {
10361:                         $userallowed=1;
10362:                     } else {
10363:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10364:                             $userallowed=1;
10365:                         }
10366:                     }
10367:                     unless ($userallowed) {
10368:                         if (defined($env{'request.course.groups'})) {
10369:                             my @groups = split(/:/,$env{'request.course.groups'});
10370:                             foreach my $group (@groups) {
10371:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10372:                                     $userallowed=1;
10373:                                     last;
10374:                                 }
10375:                             }
10376:                         }
10377:                     }
10378:                 }
10379:                 if ($slots{$slot}->{'allowedusers'}) {
10380:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10381:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10382:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10383:                         $userallowed = 1;
10384:                     }
10385:                 }
10386:                 next unless($userallowed);
10387:             }
10388:             my $startreserve = $slots{$slot}->{'startreserve'};
10389:             my $endreserve = $slots{$slot}->{'endreserve'};
10390:             my $symb = $slots{$slot}->{'symb'};
10391:             if (($startreserve < $now) &&
10392:                 (!$endreserve || $endreserve > $now)) {
10393:                 my $lastres = $endreserve;
10394:                 if (!$lastres) {
10395:                     $lastres = $slots{$slot}->{'starttime'};
10396:                 }
10397:                 $reservable_now{$slot} = {
10398:                                            symb       => $symb,
10399:                                            endreserve => $lastres
10400:                                          };
10401:             } elsif (($startreserve > $now) &&
10402:                      (!$endreserve || $endreserve > $startreserve)) {
10403:                 $future_reservable{$slot} = {
10404:                                               symb         => $symb,
10405:                                               startreserve => $startreserve
10406:                                             };
10407:             }
10408:         }
10409:     }
10410:     my @unsorted_reservable = keys(%reservable_now);
10411:     if (@unsorted_reservable > 0) {
10412:         @sorted_reservable = 
10413:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10414:     }
10415:     my @unsorted_future = keys(%future_reservable);
10416:     if (@unsorted_future > 0) {
10417:         @sorted_future =
10418:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10419:     }
10420:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10421: }
10422: 
10423: =pod
10424: 
10425: =back
10426: 
10427: =head1 HTTP Helpers
10428: 
10429: =over 4
10430: 
10431: =item * &get_unprocessed_cgi($query,$possible_names)
10432: 
10433: Modify the %env hash to contain unprocessed CGI form parameters held in
10434: $query.  The parameters listed in $possible_names (an array reference),
10435: will be set in $env{'form.name'} if they do not already exist.
10436: 
10437: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10438: $possible_names is an ref to an array of form element names.  As an example:
10439: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10440: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10441: 
10442: =cut
10443: 
10444: sub get_unprocessed_cgi {
10445:   my ($query,$possible_names)= @_;
10446:   # $Apache::lonxml::debug=1;
10447:   foreach my $pair (split(/&/,$query)) {
10448:     my ($name, $value) = split(/=/,$pair);
10449:     $name = &unescape($name);
10450:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10451:       $value =~ tr/+/ /;
10452:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10453:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10454:     }
10455:   }
10456: }
10457: 
10458: =pod
10459: 
10460: =item * &cacheheader() 
10461: 
10462: returns cache-controlling header code
10463: 
10464: =cut
10465: 
10466: sub cacheheader {
10467:     unless ($env{'request.method'} eq 'GET') { return ''; }
10468:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10469:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10470:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10471:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10472:     return $output;
10473: }
10474: 
10475: =pod
10476: 
10477: =item * &no_cache($r) 
10478: 
10479: specifies header code to not have cache
10480: 
10481: =cut
10482: 
10483: sub no_cache {
10484:     my ($r) = @_;
10485:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10486: 	$env{'request.method'} ne 'GET') { return ''; }
10487:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10488:     $r->no_cache(1);
10489:     $r->header_out("Expires" => $date);
10490:     $r->header_out("Pragma" => "no-cache");
10491: }
10492: 
10493: sub content_type {
10494:     my ($r,$type,$charset) = @_;
10495:     if ($r) {
10496: 	#  Note that printout.pl calls this with undef for $r.
10497: 	&no_cache($r);
10498:     }
10499:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10500:     unless ($charset) {
10501: 	$charset=&Apache::lonlocal::current_encoding;
10502:     }
10503:     if ($charset) { $type.='; charset='.$charset; }
10504:     if ($r) {
10505: 	$r->content_type($type);
10506:     } else {
10507: 	print("Content-type: $type\n\n");
10508:     }
10509: }
10510: 
10511: =pod
10512: 
10513: =item * &add_to_env($name,$value) 
10514: 
10515: adds $name to the %env hash with value
10516: $value, if $name already exists, the entry is converted to an array
10517: reference and $value is added to the array.
10518: 
10519: =cut
10520: 
10521: sub add_to_env {
10522:   my ($name,$value)=@_;
10523:   if (defined($env{$name})) {
10524:     if (ref($env{$name})) {
10525:       #already have multiple values
10526:       push(@{ $env{$name} },$value);
10527:     } else {
10528:       #first time seeing multiple values, convert hash entry to an arrayref
10529:       my $first=$env{$name};
10530:       undef($env{$name});
10531:       push(@{ $env{$name} },$first,$value);
10532:     }
10533:   } else {
10534:     $env{$name}=$value;
10535:   }
10536: }
10537: 
10538: =pod
10539: 
10540: =item * &get_env_multiple($name) 
10541: 
10542: gets $name from the %env hash, it seemlessly handles the cases where multiple
10543: values may be defined and end up as an array ref.
10544: 
10545: returns an array of values
10546: 
10547: =cut
10548: 
10549: sub get_env_multiple {
10550:     my ($name) = @_;
10551:     my @values;
10552:     if (defined($env{$name})) {
10553:         # exists is it an array
10554:         if (ref($env{$name})) {
10555:             @values=@{ $env{$name} };
10556:         } else {
10557:             $values[0]=$env{$name};
10558:         }
10559:     }
10560:     return(@values);
10561: }
10562: 
10563: sub ask_for_embedded_content {
10564:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10565:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10566:         %currsubfile,%unused,$rem);
10567:     my $counter = 0;
10568:     my $numnew = 0;
10569:     my $numremref = 0;
10570:     my $numinvalid = 0;
10571:     my $numpathchg = 0;
10572:     my $numexisting = 0;
10573:     my $numunused = 0;
10574:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10575:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10576:     my $heading = &mt('Upload embedded files');
10577:     my $buttontext = &mt('Upload');
10578: 
10579:     if ($env{'request.course.id'}) {
10580:         if ($actionurl eq '/adm/dependencies') {
10581:             $navmap = Apache::lonnavmaps::navmap->new();
10582:         }
10583:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10584:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10585:     }
10586:     if (($actionurl eq '/adm/portfolio') || 
10587:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10588:         my $current_path='/';
10589:         if ($env{'form.currentpath'}) {
10590:             $current_path = $env{'form.currentpath'};
10591:         }
10592:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10593:             $udom = $cdom;
10594:             $uname = $cnum;
10595:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10596:         } else {
10597:             $udom = $env{'user.domain'};
10598:             $uname = $env{'user.name'};
10599:             $url = '/userfiles/portfolio';
10600:         }
10601:         $toplevel = $url.'/';
10602:         $url .= $current_path;
10603:         $getpropath = 1;
10604:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10605:              ($actionurl eq '/adm/imsimport')) { 
10606:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10607:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10608:         $toplevel = $url;
10609:         if ($rest ne '') {
10610:             $url .= $rest;
10611:         }
10612:     } elsif ($actionurl eq '/adm/coursedocs') {
10613:         if (ref($args) eq 'HASH') {
10614:             $url = $args->{'docs_url'};
10615:             $toplevel = $url;
10616:             if ($args->{'context'} eq 'paste') {
10617:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10618:                 ($path) = 
10619:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10620:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10621:                 $fileloc =~ s{^/}{};
10622:             }
10623:         }
10624:     } elsif ($actionurl eq '/adm/dependencies')  {
10625:         if ($env{'request.course.id'} ne '') {
10626:             if (ref($args) eq 'HASH') {
10627:                 $url = $args->{'docs_url'};
10628:                 $title = $args->{'docs_title'};
10629:                 $toplevel = $url; 
10630:                 unless ($toplevel =~ m{^/}) {
10631:                     $toplevel = "/$url";
10632:                 }
10633:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10634:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10635:                     $path = $1;
10636:                 } else {
10637:                     ($path) =
10638:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10639:                 }
10640:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10641:                     $fileloc = $toplevel;
10642:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10643:                     my ($udom,$uname,$fname) =
10644:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10645:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10646:                 } else {
10647:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10648:                 }
10649:                 $fileloc =~ s{^/}{};
10650:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10651:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10652:             }
10653:         }
10654:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10655:         $udom = $cdom;
10656:         $uname = $cnum;
10657:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10658:         $toplevel = $url;
10659:         $path = $url;
10660:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10661:         $fileloc =~ s{^/}{};
10662:     }
10663:     foreach my $file (keys(%{$allfiles})) {
10664:         my $embed_file;
10665:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10666:             $embed_file = $1;
10667:         } else {
10668:             $embed_file = $file;
10669:         }
10670:         my ($absolutepath,$cleaned_file);
10671:         if ($embed_file =~ m{^\w+://}) {
10672:             $cleaned_file = $embed_file;
10673:             $newfiles{$cleaned_file} = 1;
10674:             $mapping{$cleaned_file} = $embed_file;
10675:         } else {
10676:             $cleaned_file = &clean_path($embed_file);
10677:             if ($embed_file =~ m{^/}) {
10678:                 $absolutepath = $embed_file;
10679:             }
10680:             if ($cleaned_file =~ m{/}) {
10681:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10682:                 $path = &check_for_traversal($path,$url,$toplevel);
10683:                 my $item = $fname;
10684:                 if ($path ne '') {
10685:                     $item = $path.'/'.$fname;
10686:                     $subdependencies{$path}{$fname} = 1;
10687:                 } else {
10688:                     $dependencies{$item} = 1;
10689:                 }
10690:                 if ($absolutepath) {
10691:                     $mapping{$item} = $absolutepath;
10692:                 } else {
10693:                     $mapping{$item} = $embed_file;
10694:                 }
10695:             } else {
10696:                 $dependencies{$embed_file} = 1;
10697:                 if ($absolutepath) {
10698:                     $mapping{$cleaned_file} = $absolutepath;
10699:                 } else {
10700:                     $mapping{$cleaned_file} = $embed_file;
10701:                 }
10702:             }
10703:         }
10704:     }
10705:     my $dirptr = 16384;
10706:     foreach my $path (keys(%subdependencies)) {
10707:         $currsubfile{$path} = {};
10708:         if (($actionurl eq '/adm/portfolio') || 
10709:             ($actionurl eq '/adm/coursegrp_portfolio')) {
10710:             my ($sublistref,$listerror) =
10711:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10712:             if (ref($sublistref) eq 'ARRAY') {
10713:                 foreach my $line (@{$sublistref}) {
10714:                     my ($file_name,$rest) = split(/\&/,$line,2);
10715:                     $currsubfile{$path}{$file_name} = 1;
10716:                 }
10717:             }
10718:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10719:             if (opendir(my $dir,$url.'/'.$path)) {
10720:                 my @subdir_list = grep(!/^\./,readdir($dir));
10721:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10722:             }
10723:         } elsif (($actionurl eq '/adm/dependencies') ||
10724:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10725:                   ($args->{'context'} eq 'paste')) ||
10726:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10727:             if ($env{'request.course.id'} ne '') {
10728:                 my $dir;
10729:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10730:                     $dir = $fileloc;
10731:                 } else {
10732:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10733:                 }
10734:                 if ($dir ne '') {
10735:                     my ($sublistref,$listerror) =
10736:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10737:                     if (ref($sublistref) eq 'ARRAY') {
10738:                         foreach my $line (@{$sublistref}) {
10739:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10740:                                 undef,$mtime)=split(/\&/,$line,12);
10741:                             unless (($testdir&$dirptr) ||
10742:                                     ($file_name =~ /^\.\.?$/)) {
10743:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10744:                             }
10745:                         }
10746:                     }
10747:                 }
10748:             }
10749:         }
10750:         foreach my $file (keys(%{$subdependencies{$path}})) {
10751:             if (exists($currsubfile{$path}{$file})) {
10752:                 my $item = $path.'/'.$file;
10753:                 unless ($mapping{$item} eq $item) {
10754:                     $pathchanges{$item} = 1;
10755:                 }
10756:                 $existing{$item} = 1;
10757:                 $numexisting ++;
10758:             } else {
10759:                 $newfiles{$path.'/'.$file} = 1;
10760:             }
10761:         }
10762:         if ($actionurl eq '/adm/dependencies') {
10763:             foreach my $path (keys(%currsubfile)) {
10764:                 if (ref($currsubfile{$path}) eq 'HASH') {
10765:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10766:                          unless ($subdependencies{$path}{$file}) {
10767:                              next if (($rem ne '') &&
10768:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10769:                                        (ref($navmap) &&
10770:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10771:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10772:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10773:                              $unused{$path.'/'.$file} = 1; 
10774:                          }
10775:                     }
10776:                 }
10777:             }
10778:         }
10779:     }
10780:     my %currfile;
10781:     if (($actionurl eq '/adm/portfolio') ||
10782:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10783:         my ($dirlistref,$listerror) =
10784:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10785:         if (ref($dirlistref) eq 'ARRAY') {
10786:             foreach my $line (@{$dirlistref}) {
10787:                 my ($file_name,$rest) = split(/\&/,$line,2);
10788:                 $currfile{$file_name} = 1;
10789:             }
10790:         }
10791:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10792:         if (opendir(my $dir,$url)) {
10793:             my @dir_list = grep(!/^\./,readdir($dir));
10794:             map {$currfile{$_} = 1;} @dir_list;
10795:         }
10796:     } elsif (($actionurl eq '/adm/dependencies') ||
10797:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10798:               ($args->{'context'} eq 'paste')) ||
10799:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10800:         if ($env{'request.course.id'} ne '') {
10801:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10802:             if ($dir ne '') {
10803:                 my ($dirlistref,$listerror) =
10804:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10805:                 if (ref($dirlistref) eq 'ARRAY') {
10806:                     foreach my $line (@{$dirlistref}) {
10807:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10808:                             $size,undef,$mtime)=split(/\&/,$line,12);
10809:                         unless (($testdir&$dirptr) ||
10810:                                 ($file_name =~ /^\.\.?$/)) {
10811:                             $currfile{$file_name} = [$size,$mtime];
10812:                         }
10813:                     }
10814:                 }
10815:             }
10816:         }
10817:     }
10818:     foreach my $file (keys(%dependencies)) {
10819:         if (exists($currfile{$file})) {
10820:             unless ($mapping{$file} eq $file) {
10821:                 $pathchanges{$file} = 1;
10822:             }
10823:             $existing{$file} = 1;
10824:             $numexisting ++;
10825:         } else {
10826:             $newfiles{$file} = 1;
10827:         }
10828:     }
10829:     foreach my $file (keys(%currfile)) {
10830:         unless (($file eq $filename) ||
10831:                 ($file eq $filename.'.bak') ||
10832:                 ($dependencies{$file})) {
10833:             if ($actionurl eq '/adm/dependencies') {
10834:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10835:                     next if (($rem ne '') &&
10836:                              (($env{"httpref.$rem".$file} ne '') ||
10837:                               (ref($navmap) &&
10838:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10839:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10840:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10841:                 }
10842:             }
10843:             $unused{$file} = 1;
10844:         }
10845:     }
10846:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10847:         ($args->{'context'} eq 'paste')) {
10848:         $counter = scalar(keys(%existing));
10849:         $numpathchg = scalar(keys(%pathchanges));
10850:         return ($output,$counter,$numpathchg,\%existing);
10851:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
10852:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10853:         $counter = scalar(keys(%existing));
10854:         $numpathchg = scalar(keys(%pathchanges));
10855:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10856:     }
10857:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10858:         if ($actionurl eq '/adm/dependencies') {
10859:             next if ($embed_file =~ m{^\w+://});
10860:         }
10861:         $upload_output .= &start_data_table_row().
10862:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10863:                           '<span class="LC_filename">'.$embed_file.'</span>';
10864:         unless ($mapping{$embed_file} eq $embed_file) {
10865:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10866:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10867:         }
10868:         $upload_output .= '</td>';
10869:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10870:             $upload_output.='<td align="right">'.
10871:                             '<span class="LC_info LC_fontsize_medium">'.
10872:                             &mt("URL points to web address").'</span>';
10873:             $numremref++;
10874:         } elsif ($args->{'error_on_invalid_names'}
10875:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10876:             $upload_output.='<td align="right"><span class="LC_warning">'.
10877:                             &mt('Invalid characters').'</span>';
10878:             $numinvalid++;
10879:         } else {
10880:             $upload_output .= '<td>'.
10881:                               &embedded_file_element('upload_embedded',$counter,
10882:                                                      $embed_file,\%mapping,
10883:                                                      $allfiles,$codebase,'upload');
10884:             $counter ++;
10885:             $numnew ++;
10886:         }
10887:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10888:     }
10889:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10890:         if ($actionurl eq '/adm/dependencies') {
10891:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10892:             $modify_output .= &start_data_table_row().
10893:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10894:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10895:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10896:                               '<td>'.$size.'</td>'.
10897:                               '<td>'.$mtime.'</td>'.
10898:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10899:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10900:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10901:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10902:                               &embedded_file_element('upload_embedded',$counter,
10903:                                                      $embed_file,\%mapping,
10904:                                                      $allfiles,$codebase,'modify').
10905:                               '</div></td>'.
10906:                               &end_data_table_row()."\n";
10907:             $counter ++;
10908:         } else {
10909:             $upload_output .= &start_data_table_row().
10910:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10911:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10912:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10913:                               &Apache::loncommon::end_data_table_row()."\n";
10914:         }
10915:     }
10916:     my $delidx = $counter;
10917:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10918:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10919:         $delete_output .= &start_data_table_row().
10920:                           '<td><img src="'.&icon($oldfile).'" />'.
10921:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10922:                           '<td>'.$size.'</td>'.
10923:                           '<td>'.$mtime.'</td>'.
10924:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10925:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10926:                           &embedded_file_element('upload_embedded',$delidx,
10927:                                                  $oldfile,\%mapping,$allfiles,
10928:                                                  $codebase,'delete').'</td>'.
10929:                           &end_data_table_row()."\n"; 
10930:         $numunused ++;
10931:         $delidx ++;
10932:     }
10933:     if ($upload_output) {
10934:         $upload_output = &start_data_table().
10935:                          $upload_output.
10936:                          &end_data_table()."\n";
10937:     }
10938:     if ($modify_output) {
10939:         $modify_output = &start_data_table().
10940:                          &start_data_table_header_row().
10941:                          '<th>'.&mt('File').'</th>'.
10942:                          '<th>'.&mt('Size (KB)').'</th>'.
10943:                          '<th>'.&mt('Modified').'</th>'.
10944:                          '<th>'.&mt('Upload replacement?').'</th>'.
10945:                          &end_data_table_header_row().
10946:                          $modify_output.
10947:                          &end_data_table()."\n";
10948:     }
10949:     if ($delete_output) {
10950:         $delete_output = &start_data_table().
10951:                          &start_data_table_header_row().
10952:                          '<th>'.&mt('File').'</th>'.
10953:                          '<th>'.&mt('Size (KB)').'</th>'.
10954:                          '<th>'.&mt('Modified').'</th>'.
10955:                          '<th>'.&mt('Delete?').'</th>'.
10956:                          &end_data_table_header_row().
10957:                          $delete_output.
10958:                          &end_data_table()."\n";
10959:     }
10960:     my $applies = 0;
10961:     if ($numremref) {
10962:         $applies ++;
10963:     }
10964:     if ($numinvalid) {
10965:         $applies ++;
10966:     }
10967:     if ($numexisting) {
10968:         $applies ++;
10969:     }
10970:     if ($counter || $numunused) {
10971:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10972:                   ' method="post" enctype="multipart/form-data">'."\n".
10973:                   $state.'<h3>'.$heading.'</h3>'; 
10974:         if ($actionurl eq '/adm/dependencies') {
10975:             if ($numnew) {
10976:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10977:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10978:                            $upload_output.'<br />'."\n";
10979:             }
10980:             if ($numexisting) {
10981:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10982:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10983:                            $modify_output.'<br />'."\n";
10984:                            $buttontext = &mt('Save changes');
10985:             }
10986:             if ($numunused) {
10987:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10988:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10989:                            $delete_output.'<br />'."\n";
10990:                            $buttontext = &mt('Save changes');
10991:             }
10992:         } else {
10993:             $output .= $upload_output.'<br />'."\n";
10994:         }
10995:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10996:                    $counter.'" />'."\n";
10997:         if ($actionurl eq '/adm/dependencies') { 
10998:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10999:                        $numnew.'" />'."\n";
11000:         } elsif ($actionurl eq '') {
11001:             $output .=  '<input type="hidden" name="phase" value="three" />';
11002:         }
11003:     } elsif ($applies) {
11004:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11005:         if ($applies > 1) {
11006:             $output .=  
11007:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11008:             if ($numremref) {
11009:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11010:             }
11011:             if ($numinvalid) {
11012:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11013:             }
11014:             if ($numexisting) {
11015:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11016:             }
11017:             $output .= '</ul><br />';
11018:         } elsif ($numremref) {
11019:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11020:         } elsif ($numinvalid) {
11021:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11022:         } elsif ($numexisting) {
11023:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11024:         }
11025:         $output .= $upload_output.'<br />';
11026:     }
11027:     my ($pathchange_output,$chgcount);
11028:     $chgcount = $counter;
11029:     if (keys(%pathchanges) > 0) {
11030:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11031:             if ($counter) {
11032:                 $output .= &embedded_file_element('pathchange',$chgcount,
11033:                                                   $embed_file,\%mapping,
11034:                                                   $allfiles,$codebase,'change');
11035:             } else {
11036:                 $pathchange_output .= 
11037:                     &start_data_table_row().
11038:                     '<td><input type ="checkbox" name="namechange" value="'.
11039:                     $chgcount.'" checked="checked" /></td>'.
11040:                     '<td>'.$mapping{$embed_file}.'</td>'.
11041:                     '<td>'.$embed_file.
11042:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11043:                                            \%mapping,$allfiles,$codebase,'change').
11044:                     '</td>'.&end_data_table_row();
11045:             }
11046:             $numpathchg ++;
11047:             $chgcount ++;
11048:         }
11049:     }
11050:     if (($counter) || ($numunused)) {
11051:         if ($numpathchg) {
11052:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11053:                        $numpathchg.'" />'."\n";
11054:         }
11055:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11056:             ($actionurl eq '/adm/imsimport')) {
11057:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11058:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11059:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11060:         } elsif ($actionurl eq '/adm/dependencies') {
11061:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11062:         }
11063:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11064:     } elsif ($numpathchg) {
11065:         my %pathchange = ();
11066:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11067:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11068:             $output .= '<p>'.&mt('or').'</p>'; 
11069:         }
11070:     }
11071:     return ($output,$counter,$numpathchg);
11072: }
11073: 
11074: =pod
11075: 
11076: =item * clean_path($name)
11077: 
11078: Performs clean-up of directories, subdirectories and filename in an
11079: embedded object, referenced in an HTML file which is being uploaded
11080: to a course or portfolio, where 
11081: "Upload embedded images/multimedia files if HTML file" checkbox was
11082: checked.
11083: 
11084: Clean-up is similar to replacements in lonnet::clean_filename()
11085: except each / between sub-directory and next level is preserved.
11086: 
11087: =cut
11088: 
11089: sub clean_path {
11090:     my ($embed_file) = @_;
11091:     $embed_file =~s{^/+}{};
11092:     my @contents;
11093:     if ($embed_file =~ m{/}) {
11094:         @contents = split(/\//,$embed_file);
11095:     } else {
11096:         @contents = ($embed_file);
11097:     }
11098:     my $lastidx = scalar(@contents)-1;
11099:     for (my $i=0; $i<=$lastidx; $i++) { 
11100:         $contents[$i]=~s{\\}{/}g;
11101:         $contents[$i]=~s/\s+/\_/g;
11102:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11103:         if ($i == $lastidx) {
11104:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11105:         }
11106:     }
11107:     if ($lastidx > 0) {
11108:         return join('/',@contents);
11109:     } else {
11110:         return $contents[0];
11111:     }
11112: }
11113: 
11114: sub embedded_file_element {
11115:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11116:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11117:                    (ref($codebase) eq 'HASH'));
11118:     my $output;
11119:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11120:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11121:     }
11122:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11123:                &escape($embed_file).'" />';
11124:     unless (($context eq 'upload_embedded') && 
11125:             ($mapping->{$embed_file} eq $embed_file)) {
11126:         $output .='
11127:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11128:     }
11129:     my $attrib;
11130:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11131:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11132:     }
11133:     $output .=
11134:         "\n\t\t".
11135:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11136:         $attrib.'" />';
11137:     if (exists($codebase->{$mapping->{$embed_file}})) {
11138:         $output .=
11139:             "\n\t\t".
11140:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11141:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11142:     }
11143:     return $output;
11144: }
11145: 
11146: sub get_dependency_details {
11147:     my ($currfile,$currsubfile,$embed_file) = @_;
11148:     my ($size,$mtime,$showsize,$showmtime);
11149:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11150:         if ($embed_file =~ m{/}) {
11151:             my ($path,$fname) = split(/\//,$embed_file);
11152:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11153:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11154:             }
11155:         } else {
11156:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11157:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11158:             }
11159:         }
11160:         $showsize = $size/1024.0;
11161:         $showsize = sprintf("%.1f",$showsize);
11162:         if ($mtime > 0) {
11163:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11164:         }
11165:     }
11166:     return ($showsize,$showmtime);
11167: }
11168: 
11169: sub ask_embedded_js {
11170:     return <<"END";
11171: <script type="text/javascript"">
11172: // <![CDATA[
11173: function toggleBrowse(counter) {
11174:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11175:     var fileid = document.getElementById('embedded_item_'+counter);
11176:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11177:     if (chkboxid.checked == true) {
11178:         uploaddivid.style.display='block';
11179:     } else {
11180:         uploaddivid.style.display='none';
11181:         fileid.value = '';
11182:     }
11183: }
11184: // ]]>
11185: </script>
11186: 
11187: END
11188: }
11189: 
11190: sub upload_embedded {
11191:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11192:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11193:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11194:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11195:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11196:         my $orig_uploaded_filename =
11197:             $env{'form.embedded_item_'.$i.'.filename'};
11198:         foreach my $type ('orig','ref','attrib','codebase') {
11199:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11200:                 $env{'form.embedded_'.$type.'_'.$i} =
11201:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11202:             }
11203:         }
11204:         my ($path,$fname) =
11205:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11206:         # no path, whole string is fname
11207:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11208:         $fname = &Apache::lonnet::clean_filename($fname);
11209:         # See if there is anything left
11210:         next if ($fname eq '');
11211: 
11212:         # Check if file already exists as a file or directory.
11213:         my ($state,$msg);
11214:         if ($context eq 'portfolio') {
11215:             my $port_path = $dirpath;
11216:             if ($group ne '') {
11217:                 $port_path = "groups/$group/$port_path";
11218:             }
11219:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11220:                                               $fname,$group,'embedded_item_'.$i,
11221:                                               $dir_root,$port_path,$disk_quota,
11222:                                               $current_disk_usage,$uname,$udom);
11223:             if ($state eq 'will_exceed_quota'
11224:                 || $state eq 'file_locked') {
11225:                 $output .= $msg;
11226:                 next;
11227:             }
11228:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11229:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11230:             if ($state eq 'exists') {
11231:                 $output .= $msg;
11232:                 next;
11233:             }
11234:         }
11235:         # Check if extension is valid
11236:         if (($fname =~ /\.(\w+)$/) &&
11237:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11238:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11239:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11240:             next;
11241:         } elsif (($fname =~ /\.(\w+)$/) &&
11242:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11243:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11244:             next;
11245:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11246:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11247:             next;
11248:         }
11249:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11250:         my $subdir = $path;
11251:         $subdir =~ s{/+$}{};
11252:         if ($context eq 'portfolio') {
11253:             my $result;
11254:             if ($state eq 'existingfile') {
11255:                 $result=
11256:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11257:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11258:             } else {
11259:                 $result=
11260:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11261:                                                     $dirpath.
11262:                                                     $env{'form.currentpath'}.$subdir);
11263:                 if ($result !~ m|^/uploaded/|) {
11264:                     $output .= '<span class="LC_error">'
11265:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11266:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11267:                                .'</span><br />';
11268:                     next;
11269:                 } else {
11270:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11271:                                $path.$fname.'</span>').'<br />';     
11272:                 }
11273:             }
11274:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11275:             my $extendedsubdir = $dirpath.'/'.$subdir;
11276:             $extendedsubdir =~ s{/+$}{};
11277:             my $result =
11278:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11279:             if ($result !~ m|^/uploaded/|) {
11280:                 $output .= '<span class="LC_error">'
11281:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11282:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11283:                            .'</span><br />';
11284:                     next;
11285:             } else {
11286:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11287:                            $path.$fname.'</span>').'<br />';
11288:                 if ($context eq 'syllabus') {
11289:                     &Apache::lonnet::make_public_indefinitely($result);
11290:                 }
11291:             }
11292:         } else {
11293: # Save the file
11294:             my $target = $env{'form.embedded_item_'.$i};
11295:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11296:             my $dest = $fullpath.$fname;
11297:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11298:             my @parts=split(/\//,"$dirpath/$path");
11299:             my $count;
11300:             my $filepath = $dir_root;
11301:             foreach my $subdir (@parts) {
11302:                 $filepath .= "/$subdir";
11303:                 if (!-e $filepath) {
11304:                     mkdir($filepath,0770);
11305:                 }
11306:             }
11307:             my $fh;
11308:             if (!open($fh,'>'.$dest)) {
11309:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11310:                 $output .= '<span class="LC_error">'.
11311:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11312:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11313:                            '</span><br />';
11314:             } else {
11315:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11316:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11317:                     $output .= '<span class="LC_error">'.
11318:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11319:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11320:                               '</span><br />';
11321:                 } else {
11322:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11323:                                $url.'</span>').'<br />';
11324:                     unless ($context eq 'testbank') {
11325:                         $footer .= &mt('View embedded file: [_1]',
11326:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11327:                     }
11328:                 }
11329:                 close($fh);
11330:             }
11331:         }
11332:         if ($env{'form.embedded_ref_'.$i}) {
11333:             $pathchange{$i} = 1;
11334:         }
11335:     }
11336:     if ($output) {
11337:         $output = '<p>'.$output.'</p>';
11338:     }
11339:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11340:     $returnflag = 'ok';
11341:     my $numpathchgs = scalar(keys(%pathchange));
11342:     if ($numpathchgs > 0) {
11343:         if ($context eq 'portfolio') {
11344:             $output .= '<p>'.&mt('or').'</p>';
11345:         } elsif ($context eq 'testbank') {
11346:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11347:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11348:             $returnflag = 'modify_orightml';
11349:         }
11350:     }
11351:     return ($output.$footer,$returnflag,$numpathchgs);
11352: }
11353: 
11354: sub modify_html_form {
11355:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11356:     my $end = 0;
11357:     my $modifyform;
11358:     if ($context eq 'upload_embedded') {
11359:         return unless (ref($pathchange) eq 'HASH');
11360:         if ($env{'form.number_embedded_items'}) {
11361:             $end += $env{'form.number_embedded_items'};
11362:         }
11363:         if ($env{'form.number_pathchange_items'}) {
11364:             $end += $env{'form.number_pathchange_items'};
11365:         }
11366:         if ($end) {
11367:             for (my $i=0; $i<$end; $i++) {
11368:                 if ($i < $env{'form.number_embedded_items'}) {
11369:                     next unless($pathchange->{$i});
11370:                 }
11371:                 $modifyform .=
11372:                     &start_data_table_row().
11373:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11374:                     'checked="checked" /></td>'.
11375:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11376:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11377:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11378:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11379:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11380:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11381:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11382:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11383:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11384:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11385:                     &end_data_table_row();
11386:             }
11387:         }
11388:     } else {
11389:         $modifyform = $pathchgtable;
11390:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11391:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11392:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11393:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11394:         }
11395:     }
11396:     if ($modifyform) {
11397:         if ($actionurl eq '/adm/dependencies') {
11398:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11399:         }
11400:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11401:                '<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".
11402:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11403:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11404:                '</ol></p>'."\n".'<p>'.
11405:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11406:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11407:                &start_data_table()."\n".
11408:                &start_data_table_header_row().
11409:                '<th>'.&mt('Change?').'</th>'.
11410:                '<th>'.&mt('Current reference').'</th>'.
11411:                '<th>'.&mt('Required reference').'</th>'.
11412:                &end_data_table_header_row()."\n".
11413:                $modifyform.
11414:                &end_data_table().'<br />'."\n".$hiddenstate.
11415:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11416:                '</form>'."\n";
11417:     }
11418:     return;
11419: }
11420: 
11421: sub modify_html_refs {
11422:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11423:     my $container;
11424:     if ($context eq 'portfolio') {
11425:         $container = $env{'form.container'};
11426:     } elsif ($context eq 'coursedoc') {
11427:         $container = $env{'form.primaryurl'};
11428:     } elsif ($context eq 'manage_dependencies') {
11429:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11430:         $container = "/$container";
11431:     } elsif ($context eq 'syllabus') {
11432:         $container = $url;
11433:     } else {
11434:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11435:     }
11436:     my (%allfiles,%codebase,$output,$content);
11437:     my @changes = &get_env_multiple('form.namechange');
11438:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11439:         if (wantarray) {
11440:             return ('',0,0); 
11441:         } else {
11442:             return;
11443:         }
11444:     }
11445:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11446:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11447:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11448:             if (wantarray) {
11449:                 return ('',0,0);
11450:             } else {
11451:                 return;
11452:             }
11453:         } 
11454:         $content = &Apache::lonnet::getfile($container);
11455:         if ($content eq '-1') {
11456:             if (wantarray) {
11457:                 return ('',0,0);
11458:             } else {
11459:                 return;
11460:             }
11461:         }
11462:     } else {
11463:         unless ($container =~ /^\Q$dir_root\E/) {
11464:             if (wantarray) {
11465:                 return ('',0,0);
11466:             } else {
11467:                 return;
11468:             }
11469:         } 
11470:         if (open(my $fh,"<$container")) {
11471:             $content = join('', <$fh>);
11472:             close($fh);
11473:         } else {
11474:             if (wantarray) {
11475:                 return ('',0,0);
11476:             } else {
11477:                 return;
11478:             }
11479:         }
11480:     }
11481:     my ($count,$codebasecount) = (0,0);
11482:     my $mm = new File::MMagic;
11483:     my $mime_type = $mm->checktype_contents($content);
11484:     if ($mime_type eq 'text/html') {
11485:         my $parse_result = 
11486:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11487:                                                     \%codebase,\$content);
11488:         if ($parse_result eq 'ok') {
11489:             foreach my $i (@changes) {
11490:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11491:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11492:                 if ($allfiles{$ref}) {
11493:                     my $newname =  $orig;
11494:                     my ($attrib_regexp,$codebase);
11495:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11496:                     if ($attrib_regexp =~ /:/) {
11497:                         $attrib_regexp =~ s/\:/|/g;
11498:                     }
11499:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11500:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11501:                         $count += $numchg;
11502:                         $allfiles{$newname} = $allfiles{$ref};
11503:                         delete($allfiles{$ref});
11504:                     }
11505:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11506:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11507:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11508:                         $codebasecount ++;
11509:                     }
11510:                 }
11511:             }
11512:             my $skiprewrites;
11513:             if ($count || $codebasecount) {
11514:                 my $saveresult;
11515:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11516:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11517:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11518:                     if ($url eq $container) {
11519:                         my ($fname) = ($container =~ m{/([^/]+)$});
11520:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11521:                                             $count,'<span class="LC_filename">'.
11522:                                             $fname.'</span>').'</p>';
11523:                     } else {
11524:                          $output = '<p class="LC_error">'.
11525:                                    &mt('Error: update failed for: [_1].',
11526:                                    '<span class="LC_filename">'.
11527:                                    $container.'</span>').'</p>';
11528:                     }
11529:                     if ($context eq 'syllabus') {
11530:                         unless ($saveresult eq 'ok') {
11531:                             $skiprewrites = 1;
11532:                         }
11533:                     }
11534:                 } else {
11535:                     if (open(my $fh,">$container")) {
11536:                         print $fh $content;
11537:                         close($fh);
11538:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11539:                                   $count,'<span class="LC_filename">'.
11540:                                   $container.'</span>').'</p>';
11541:                     } else {
11542:                          $output = '<p class="LC_error">'.
11543:                                    &mt('Error: could not update [_1].',
11544:                                    '<span class="LC_filename">'.
11545:                                    $container.'</span>').'</p>';
11546:                     }
11547:                 }
11548:             }
11549:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11550:                 my ($actionurl,$state);
11551:                 $actionurl = "/public/$udom/$uname/syllabus";
11552:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11553:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11554:                                               \%codebase,
11555:                                               {'context' => 'rewrites',
11556:                                                'ignore_remote_references' => 1,});
11557:                 if (ref($mapping) eq 'HASH') {
11558:                     my $rewrites = 0;
11559:                     foreach my $key (keys(%{$mapping})) {
11560:                         next if ($key =~ m{^https?://});
11561:                         my $ref = $mapping->{$key};
11562:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11563:                         my $attrib;
11564:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11565:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11566:                         }
11567:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11568:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11569:                             $rewrites += $numchg;
11570:                         }
11571:                     }
11572:                     if ($rewrites) {
11573:                         my $saveresult; 
11574:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11575:                         if ($url eq $container) {
11576:                             my ($fname) = ($container =~ m{/([^/]+)$});
11577:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11578:                                             $count,'<span class="LC_filename">'.
11579:                                             $fname.'</span>').'</p>';
11580:                         } else {
11581:                             $output .= '<p class="LC_error">'.
11582:                                        &mt('Error: could not update links in [_1].',
11583:                                        '<span class="LC_filename">'.
11584:                                        $container.'</span>').'</p>';
11585: 
11586:                         }
11587:                     }
11588:                 }
11589:             }
11590:         } else {
11591:             &logthis('Failed to parse '.$container.
11592:                      ' to modify references: '.$parse_result);
11593:         }
11594:     }
11595:     if (wantarray) {
11596:         return ($output,$count,$codebasecount);
11597:     } else {
11598:         return $output;
11599:     }
11600: }
11601: 
11602: sub check_for_existing {
11603:     my ($path,$fname,$element) = @_;
11604:     my ($state,$msg);
11605:     if (-d $path.'/'.$fname) {
11606:         $state = 'exists';
11607:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11608:     } elsif (-e $path.'/'.$fname) {
11609:         $state = 'exists';
11610:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11611:     }
11612:     if ($state eq 'exists') {
11613:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11614:     }
11615:     return ($state,$msg);
11616: }
11617: 
11618: sub check_for_upload {
11619:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11620:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11621:     my $filesize = length($env{'form.'.$element});
11622:     if (!$filesize) {
11623:         my $msg = '<span class="LC_error">'.
11624:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11625:                       '<span class="LC_filename">'.$fname.'</span>',
11626:                       $filesize).'<br />'.
11627:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11628:                   '</span>';
11629:         return ('zero_bytes',$msg);
11630:     }
11631:     $filesize =  $filesize/1000; #express in k (1024?)
11632:     my $getpropath = 1;
11633:     my ($dirlistref,$listerror) =
11634:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11635:     my $found_file = 0;
11636:     my $locked_file = 0;
11637:     my @lockers;
11638:     my $navmap;
11639:     if ($env{'request.course.id'}) {
11640:         $navmap = Apache::lonnavmaps::navmap->new();
11641:     }
11642:     if (ref($dirlistref) eq 'ARRAY') {
11643:         foreach my $line (@{$dirlistref}) {
11644:             my ($file_name,$rest)=split(/\&/,$line,2);
11645:             if ($file_name eq $fname){
11646:                 $file_name = $path.$file_name;
11647:                 if ($group ne '') {
11648:                     $file_name = $group.$file_name;
11649:                 }
11650:                 $found_file = 1;
11651:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11652:                     foreach my $lock (@lockers) {
11653:                         if (ref($lock) eq 'ARRAY') {
11654:                             my ($symb,$crsid) = @{$lock};
11655:                             if ($crsid eq $env{'request.course.id'}) {
11656:                                 if (ref($navmap)) {
11657:                                     my $res = $navmap->getBySymb($symb);
11658:                                     foreach my $part (@{$res->parts()}) { 
11659:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11660:                                         unless (($slot_status == $res->RESERVED) ||
11661:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11662:                                             $locked_file = 1;
11663:                                         }
11664:                                     }
11665:                                 } else {
11666:                                     $locked_file = 1;
11667:                                 }
11668:                             } else {
11669:                                 $locked_file = 1;
11670:                             }
11671:                         }
11672:                    }
11673:                 } else {
11674:                     my @info = split(/\&/,$rest);
11675:                     my $currsize = $info[6]/1000;
11676:                     if ($currsize < $filesize) {
11677:                         my $extra = $filesize - $currsize;
11678:                         if (($current_disk_usage + $extra) > $disk_quota) {
11679:                             my $msg = '<p class="LC_warning">'.
11680:                                       &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.',
11681:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11682:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11683:                                                    $disk_quota,$current_disk_usage).'</p>';
11684:                             return ('will_exceed_quota',$msg);
11685:                         }
11686:                     }
11687:                 }
11688:             }
11689:         }
11690:     }
11691:     if (($current_disk_usage + $filesize) > $disk_quota){
11692:         my $msg = '<p class="LC_warning">'.
11693:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11694:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11695:         return ('will_exceed_quota',$msg);
11696:     } elsif ($found_file) {
11697:         if ($locked_file) {
11698:             my $msg = '<p class="LC_warning">';
11699:             $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>');
11700:             $msg .= '</p>';
11701:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11702:             return ('file_locked',$msg);
11703:         } else {
11704:             my $msg = '<p class="LC_error">';
11705:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11706:             $msg .= '</p>';
11707:             return ('existingfile',$msg);
11708:         }
11709:     }
11710: }
11711: 
11712: sub check_for_traversal {
11713:     my ($path,$url,$toplevel) = @_;
11714:     my @parts=split(/\//,$path);
11715:     my $cleanpath;
11716:     my $fullpath = $url;
11717:     for (my $i=0;$i<@parts;$i++) {
11718:         next if ($parts[$i] eq '.');
11719:         if ($parts[$i] eq '..') {
11720:             $fullpath =~ s{([^/]+/)$}{};
11721:         } else {
11722:             $fullpath .= $parts[$i].'/';
11723:         }
11724:     }
11725:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11726:         $cleanpath = $1;
11727:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11728:         my $curr_toprel = $1;
11729:         my @parts = split(/\//,$curr_toprel);
11730:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11731:         my @urlparts = split(/\//,$url_toprel);
11732:         my $doubledots;
11733:         my $startdiff = -1;
11734:         for (my $i=0; $i<@urlparts; $i++) {
11735:             if ($startdiff == -1) {
11736:                 unless ($urlparts[$i] eq $parts[$i]) {
11737:                     $startdiff = $i;
11738:                     $doubledots .= '../';
11739:                 }
11740:             } else {
11741:                 $doubledots .= '../';
11742:             }
11743:         }
11744:         if ($startdiff > -1) {
11745:             $cleanpath = $doubledots;
11746:             for (my $i=$startdiff; $i<@parts; $i++) {
11747:                 $cleanpath .= $parts[$i].'/';
11748:             }
11749:         }
11750:     }
11751:     $cleanpath =~ s{(/)$}{};
11752:     return $cleanpath;
11753: }
11754: 
11755: sub is_archive_file {
11756:     my ($mimetype) = @_;
11757:     if (($mimetype eq 'application/octet-stream') ||
11758:         ($mimetype eq 'application/x-stuffit') ||
11759:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11760:         return 1;
11761:     }
11762:     return;
11763: }
11764: 
11765: sub decompress_form {
11766:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11767:     my %lt = &Apache::lonlocal::texthash (
11768:         this => 'This file is an archive file.',
11769:         camt => 'This file is a Camtasia archive file.',
11770:         itsc => 'Its contents are as follows:',
11771:         youm => 'You may wish to extract its contents.',
11772:         extr => 'Extract contents',
11773:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11774:         proa => 'Process automatically?',
11775:         yes  => 'Yes',
11776:         no   => 'No',
11777:         fold => 'Title for folder containing movie',
11778:         movi => 'Title for page containing embedded movie', 
11779:     );
11780:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11781:     my ($is_camtasia,$topdir,%toplevel,@paths);
11782:     my $info = &list_archive_contents($fileloc,\@paths);
11783:     if (@paths) {
11784:         foreach my $path (@paths) {
11785:             $path =~ s{^/}{};
11786:             if ($path =~ m{^([^/]+)/$}) {
11787:                 $topdir = $1;
11788:             }
11789:             if ($path =~ m{^([^/]+)/}) {
11790:                 $toplevel{$1} = $path;
11791:             } else {
11792:                 $toplevel{$path} = $path;
11793:             }
11794:         }
11795:     }
11796:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11797:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11798:                         "$topdir/media/",
11799:                         "$topdir/media/$topdir.mp4",
11800:                         "$topdir/media/FirstFrame.png",
11801:                         "$topdir/media/player.swf",
11802:                         "$topdir/media/swfobject.js",
11803:                         "$topdir/media/expressInstall.swf");
11804:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11805:                          "$topdir/$topdir.mp4",
11806:                          "$topdir/$topdir\_config.xml",
11807:                          "$topdir/$topdir\_controller.swf",
11808:                          "$topdir/$topdir\_embed.css",
11809:                          "$topdir/$topdir\_First_Frame.png",
11810:                          "$topdir/$topdir\_player.html",
11811:                          "$topdir/$topdir\_Thumbnails.png",
11812:                          "$topdir/playerProductInstall.swf",
11813:                          "$topdir/scripts/",
11814:                          "$topdir/scripts/config_xml.js",
11815:                          "$topdir/scripts/handlebars.js",
11816:                          "$topdir/scripts/jquery-1.7.1.min.js",
11817:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11818:                          "$topdir/scripts/modernizr.js",
11819:                          "$topdir/scripts/player-min.js",
11820:                          "$topdir/scripts/swfobject.js",
11821:                          "$topdir/skins/",
11822:                          "$topdir/skins/configuration_express.xml",
11823:                          "$topdir/skins/express_show/",
11824:                          "$topdir/skins/express_show/player-min.css",
11825:                          "$topdir/skins/express_show/spritesheet.png");
11826:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11827:                          "$topdir/$topdir.mp4",
11828:                          "$topdir/$topdir\_config.xml",
11829:                          "$topdir/$topdir\_controller.swf",
11830:                          "$topdir/$topdir\_embed.css",
11831:                          "$topdir/$topdir\_First_Frame.png",
11832:                          "$topdir/$topdir\_player.html",
11833:                          "$topdir/$topdir\_Thumbnails.png",
11834:                          "$topdir/playerProductInstall.swf",
11835:                          "$topdir/scripts/",
11836:                          "$topdir/scripts/config_xml.js",
11837:                          "$topdir/scripts/techsmith-smart-player.min.js",
11838:                          "$topdir/skins/",
11839:                          "$topdir/skins/configuration_express.xml",
11840:                          "$topdir/skins/express_show/",
11841:                          "$topdir/skins/express_show/spritesheet.min.css",
11842:                          "$topdir/skins/express_show/spritesheet.png",
11843:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11844:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11845:         if (@diffs == 0) {
11846:             $is_camtasia = 6;
11847:         } else {
11848:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11849:             if (@diffs == 0) {
11850:                 $is_camtasia = 8;
11851:             } else {
11852:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11853:                 if (@diffs == 0) {
11854:                     $is_camtasia = 8;
11855:                 }
11856:             }
11857:         }
11858:     }
11859:     my $output;
11860:     if ($is_camtasia) {
11861:         $output = <<"ENDCAM";
11862: <script type="text/javascript" language="Javascript">
11863: // <![CDATA[
11864: 
11865: function camtasiaToggle() {
11866:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11867:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11868:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11869:                 document.getElementById('camtasia_titles').style.display='block';
11870:             } else {
11871:                 document.getElementById('camtasia_titles').style.display='none';
11872:             }
11873:         }
11874:     }
11875:     return;
11876: }
11877: 
11878: // ]]>
11879: </script>
11880: <p>$lt{'camt'}</p>
11881: ENDCAM
11882:     } else {
11883:         $output = '<p>'.$lt{'this'};
11884:         if ($info eq '') {
11885:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11886:         } else {
11887:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11888:                        '<div><pre>'.$info.'</pre></div>';
11889:         }
11890:     }
11891:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11892:     my $duplicates;
11893:     my $num = 0;
11894:     if (ref($dirlist) eq 'ARRAY') {
11895:         foreach my $item (@{$dirlist}) {
11896:             if (ref($item) eq 'ARRAY') {
11897:                 if (exists($toplevel{$item->[0]})) {
11898:                     $duplicates .= 
11899:                         &start_data_table_row().
11900:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11901:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11902:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11903:                         'value="1" />'.&mt('Yes').'</label>'.
11904:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11905:                         '<td>'.$item->[0].'</td>';
11906:                     if ($item->[2]) {
11907:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11908:                     } else {
11909:                         $duplicates .= '<td>'.&mt('File').'</td>';
11910:                     }
11911:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11912:                                    '<td>'.
11913:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11914:                                    '</td>'.
11915:                                    &end_data_table_row();
11916:                     $num ++;
11917:                 }
11918:             }
11919:         }
11920:     }
11921:     my $itemcount;
11922:     if (@paths > 0) {
11923:         $itemcount = scalar(@paths);
11924:     } else {
11925:         $itemcount = 1;
11926:     }
11927:     if ($is_camtasia) {
11928:         $output .= $lt{'auto'}.'<br />'.
11929:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11930:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11931:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11932:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11933:                    $lt{'no'}.'</label></span><br />'.
11934:                    '<div id="camtasia_titles" style="display:block">'.
11935:                    &Apache::lonhtmlcommon::start_pick_box().
11936:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11937:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11938:                    &Apache::lonhtmlcommon::row_closure().
11939:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11940:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11941:                    &Apache::lonhtmlcommon::row_closure(1).
11942:                    &Apache::lonhtmlcommon::end_pick_box().
11943:                    '</div>';
11944:     }
11945:     $output .= 
11946:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11947:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11948:         "\n";
11949:     if ($duplicates ne '') {
11950:         $output .= '<p><span class="LC_warning">'.
11951:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11952:                    &start_data_table().
11953:                    &start_data_table_header_row().
11954:                    '<th>'.&mt('Overwrite?').'</th>'.
11955:                    '<th>'.&mt('Name').'</th>'.
11956:                    '<th>'.&mt('Type').'</th>'.
11957:                    '<th>'.&mt('Size').'</th>'.
11958:                    '<th>'.&mt('Last modified').'</th>'.
11959:                    &end_data_table_header_row().
11960:                    $duplicates.
11961:                    &end_data_table().
11962:                    '</p>';
11963:     }
11964:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11965:     if (ref($hiddenelements) eq 'HASH') {
11966:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11967:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11968:         }
11969:     }
11970:     $output .= <<"END";
11971: <br />
11972: <input type="submit" name="decompress" value="$lt{'extr'}" />
11973: </form>
11974: $noextract
11975: END
11976:     return $output;
11977: }
11978: 
11979: sub decompression_utility {
11980:     my ($program) = @_;
11981:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11982:     my $location;
11983:     if (grep(/^\Q$program\E$/,@utilities)) { 
11984:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11985:                          '/usr/sbin/') {
11986:             if (-x $dir.$program) {
11987:                 $location = $dir.$program;
11988:                 last;
11989:             }
11990:         }
11991:     }
11992:     return $location;
11993: }
11994: 
11995: sub list_archive_contents {
11996:     my ($file,$pathsref) = @_;
11997:     my (@cmd,$output);
11998:     my $needsregexp;
11999:     if ($file =~ /\.zip$/) {
12000:         @cmd = (&decompression_utility('unzip'),"-l");
12001:         $needsregexp = 1;
12002:     } elsif (($file =~ m/\.tar\.gz$/) ||
12003:              ($file =~ /\.tgz$/)) {
12004:         @cmd = (&decompression_utility('tar'),"-ztf");
12005:     } elsif ($file =~ /\.tar\.bz2$/) {
12006:         @cmd = (&decompression_utility('tar'),"-jtf");
12007:     } elsif ($file =~ m|\.tar$|) {
12008:         @cmd = (&decompression_utility('tar'),"-tf");
12009:     }
12010:     if (@cmd) {
12011:         undef($!);
12012:         undef($@);
12013:         if (open(my $fh,"-|", @cmd, $file)) {
12014:             while (my $line = <$fh>) {
12015:                 $output .= $line;
12016:                 chomp($line);
12017:                 my $item;
12018:                 if ($needsregexp) {
12019:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12020:                 } else {
12021:                     $item = $line;
12022:                 }
12023:                 if ($item ne '') {
12024:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12025:                         push(@{$pathsref},$item);
12026:                     } 
12027:                 }
12028:             }
12029:             close($fh);
12030:         }
12031:     }
12032:     return $output;
12033: }
12034: 
12035: sub decompress_uploaded_file {
12036:     my ($file,$dir) = @_;
12037:     &Apache::lonnet::appenv({'cgi.file' => $file});
12038:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12039:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12040:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12041:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12042:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12043:     my $decompressed = $env{'cgi.decompressed'};
12044:     &Apache::lonnet::delenv('cgi.file');
12045:     &Apache::lonnet::delenv('cgi.dir');
12046:     &Apache::lonnet::delenv('cgi.decompressed');
12047:     return ($decompressed,$result);
12048: }
12049: 
12050: sub process_decompression {
12051:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12052:     my ($dir,$error,$warning,$output);
12053:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12054:         $error = &mt('Filename not a supported archive file type.').
12055:                  '<br />'.&mt('Filename should end with one of: [_1].',
12056:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12057:     } else {
12058:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12059:         if ($docuhome eq 'no_host') {
12060:             $error = &mt('Could not determine home server for course.');
12061:         } else {
12062:             my @ids=&Apache::lonnet::current_machine_ids();
12063:             my $currdir = "$dir_root/$destination";
12064:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12065:                 $dir = &LONCAPA::propath($docudom,$docuname).
12066:                        "$dir_root/$destination";
12067:             } else {
12068:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12069:                        "$dir_root/$docudom/$docuname/$destination";
12070:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12071:                     $error = &mt('Archive file not found.');
12072:                 }
12073:             }
12074:             my (@to_overwrite,@to_skip);
12075:             if ($env{'form.archive_overwrite_total'} > 0) {
12076:                 my $total = $env{'form.archive_overwrite_total'};
12077:                 for (my $i=0; $i<$total; $i++) {
12078:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12079:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12080:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12081:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12082:                     }
12083:                 }
12084:             }
12085:             my $numskip = scalar(@to_skip);
12086:             if (($numskip > 0) && 
12087:                 ($numskip == $env{'form.archive_itemcount'})) {
12088:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12089:             } elsif ($dir eq '') {
12090:                 $error = &mt('Directory containing archive file unavailable.');
12091:             } elsif (!$error) {
12092:                 my ($decompressed,$display);
12093:                 if ($numskip > 0) {
12094:                     my $tempdir = time.'_'.$$.int(rand(10000));
12095:                     mkdir("$dir/$tempdir",0755);
12096:                     system("mv $dir/$file $dir/$tempdir/$file");
12097:                     ($decompressed,$display) = 
12098:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12099:                     foreach my $item (@to_skip) {
12100:                         if (($item ne '') && ($item !~ /\.\./)) {
12101:                             if (-f "$dir/$tempdir/$item") { 
12102:                                 unlink("$dir/$tempdir/$item");
12103:                             } elsif (-d "$dir/$tempdir/$item") {
12104:                                 system("rm -rf $dir/$tempdir/$item");
12105:                             }
12106:                         }
12107:                     }
12108:                     system("mv $dir/$tempdir/* $dir");
12109:                     rmdir("$dir/$tempdir");   
12110:                 } else {
12111:                     ($decompressed,$display) = 
12112:                         &decompress_uploaded_file($file,$dir);
12113:                 }
12114:                 if ($decompressed eq 'ok') {
12115:                     $output = '<p class="LC_info">'.
12116:                               &mt('Files extracted successfully from archive.').
12117:                               '</p>'."\n";
12118:                     my ($warning,$result,@contents);
12119:                     my ($newdirlistref,$newlisterror) =
12120:                         &Apache::lonnet::dirlist($currdir,$docudom,
12121:                                                  $docuname,1);
12122:                     my (%is_dir,%changes,@newitems);
12123:                     my $dirptr = 16384;
12124:                     if (ref($newdirlistref) eq 'ARRAY') {
12125:                         foreach my $dir_line (@{$newdirlistref}) {
12126:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12127:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12128:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12129:                                 push(@newitems,$item);
12130:                                 if ($dirptr&$testdir) {
12131:                                     $is_dir{$item} = 1;
12132:                                 }
12133:                                 $changes{$item} = 1;
12134:                             }
12135:                         }
12136:                     }
12137:                     if (keys(%changes) > 0) {
12138:                         foreach my $item (sort(@newitems)) {
12139:                             if ($changes{$item}) {
12140:                                 push(@contents,$item);
12141:                             }
12142:                         }
12143:                     }
12144:                     if (@contents > 0) {
12145:                         my $wantform;
12146:                         unless ($env{'form.autoextract_camtasia'}) {
12147:                             $wantform = 1;
12148:                         }
12149:                         my (%children,%parent,%dirorder,%titles);
12150:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12151:                                                                 $currdir,\%is_dir,
12152:                                                                 \%children,\%parent,
12153:                                                                 \@contents,\%dirorder,
12154:                                                                 \%titles,$wantform);
12155:                         if ($datatable ne '') {
12156:                             $output .= &archive_options_form('decompressed',$datatable,
12157:                                                              $count,$hiddenelem);
12158:                             my $startcount = 6;
12159:                             $output .= &archive_javascript($startcount,$count,
12160:                                                            \%titles,\%children);
12161:                         }
12162:                         if ($env{'form.autoextract_camtasia'}) {
12163:                             my $version = $env{'form.autoextract_camtasia'};
12164:                             my %displayed;
12165:                             my $total = 1;
12166:                             $env{'form.archive_directory'} = [];
12167:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12168:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12169:                                 $path =~ s{/$}{};
12170:                                 my $item;
12171:                                 if ($path ne '') {
12172:                                     $item = "$path/$titles{$i}";
12173:                                 } else {
12174:                                     $item = $titles{$i};
12175:                                 }
12176:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12177:                                 if ($item eq $contents[0]) {
12178:                                     push(@{$env{'form.archive_directory'}},$i);
12179:                                     $env{'form.archive_'.$i} = 'display';
12180:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12181:                                     $displayed{'folder'} = $i;
12182:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12183:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12184:                                     $env{'form.archive_'.$i} = 'display';
12185:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12186:                                     $displayed{'web'} = $i;
12187:                                 } else {
12188:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12189:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12190:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12191:                                         push(@{$env{'form.archive_directory'}},$i);
12192:                                     }
12193:                                     $env{'form.archive_'.$i} = 'dependency';
12194:                                 }
12195:                                 $total ++;
12196:                             }
12197:                             for (my $i=1; $i<$total; $i++) {
12198:                                 next if ($i == $displayed{'web'});
12199:                                 next if ($i == $displayed{'folder'});
12200:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12201:                             }
12202:                             $env{'form.phase'} = 'decompress_cleanup';
12203:                             $env{'form.archivedelete'} = 1;
12204:                             $env{'form.archive_count'} = $total-1;
12205:                             $output .=
12206:                                 &process_extracted_files('coursedocs',$docudom,
12207:                                                          $docuname,$destination,
12208:                                                          $dir_root,$hiddenelem);
12209:                         }
12210:                     } else {
12211:                         $warning = &mt('No new items extracted from archive file.');
12212:                     }
12213:                 } else {
12214:                     $output = $display;
12215:                     $error = &mt('An error occurred during extraction from the archive file.');
12216:                 }
12217:             }
12218:         }
12219:     }
12220:     if ($error) {
12221:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12222:                    $error.'</p>'."\n";
12223:     }
12224:     if ($warning) {
12225:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12226:     }
12227:     return $output;
12228: }
12229: 
12230: sub get_extracted {
12231:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12232:         $titles,$wantform) = @_;
12233:     my $count = 0;
12234:     my $depth = 0;
12235:     my $datatable;
12236:     my @hierarchy;
12237:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12238:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12239:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12240:     foreach my $item (@{$contents}) {
12241:         $count ++;
12242:         @{$dirorder->{$count}} = @hierarchy;
12243:         $titles->{$count} = $item;
12244:         &archive_hierarchy($depth,$count,$parent,$children);
12245:         if ($wantform) {
12246:             $datatable .= &archive_row($is_dir->{$item},$item,
12247:                                        $currdir,$depth,$count);
12248:         }
12249:         if ($is_dir->{$item}) {
12250:             $depth ++;
12251:             push(@hierarchy,$count);
12252:             $parent->{$depth} = $count;
12253:             $datatable .=
12254:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12255:                                            \$depth,\$count,\@hierarchy,$dirorder,
12256:                                            $children,$parent,$titles,$wantform);
12257:             $depth --;
12258:             pop(@hierarchy);
12259:         }
12260:     }
12261:     return ($count,$datatable);
12262: }
12263: 
12264: sub recurse_extracted_archive {
12265:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12266:         $children,$parent,$titles,$wantform) = @_;
12267:     my $result='';
12268:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12269:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12270:             (ref($dirorder) eq 'HASH')) {
12271:         return $result;
12272:     }
12273:     my $dirptr = 16384;
12274:     my ($newdirlistref,$newlisterror) =
12275:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12276:     if (ref($newdirlistref) eq 'ARRAY') {
12277:         foreach my $dir_line (@{$newdirlistref}) {
12278:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12279:             unless ($item =~ /^\.+$/) {
12280:                 $$count ++;
12281:                 @{$dirorder->{$$count}} = @{$hierarchy};
12282:                 $titles->{$$count} = $item;
12283:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12284: 
12285:                 my $is_dir;
12286:                 if ($dirptr&$testdir) {
12287:                     $is_dir = 1;
12288:                 }
12289:                 if ($wantform) {
12290:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12291:                 }
12292:                 if ($is_dir) {
12293:                     $$depth ++;
12294:                     push(@{$hierarchy},$$count);
12295:                     $parent->{$$depth} = $$count;
12296:                     $result .=
12297:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12298:                                                    $docuname,$depth,$count,
12299:                                                    $hierarchy,$dirorder,$children,
12300:                                                    $parent,$titles,$wantform);
12301:                     $$depth --;
12302:                     pop(@{$hierarchy});
12303:                 }
12304:             }
12305:         }
12306:     }
12307:     return $result;
12308: }
12309: 
12310: sub archive_hierarchy {
12311:     my ($depth,$count,$parent,$children) =@_;
12312:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12313:         if (exists($parent->{$depth})) {
12314:              $children->{$parent->{$depth}} .= $count.':';
12315:         }
12316:     }
12317:     return;
12318: }
12319: 
12320: sub archive_row {
12321:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12322:     my ($name) = ($item =~ m{([^/]+)$});
12323:     my %choices = &Apache::lonlocal::texthash (
12324:                                        'display'    => 'Add as file',
12325:                                        'dependency' => 'Include as dependency',
12326:                                        'discard'    => 'Discard',
12327:                                       );
12328:     if ($is_dir) {
12329:         $choices{'display'} = &mt('Add as folder'); 
12330:     }
12331:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12332:     my $offset = 0;
12333:     foreach my $action ('display','dependency','discard') {
12334:         $offset ++;
12335:         if ($action ne 'display') {
12336:             $offset ++;
12337:         }  
12338:         $output .= '<td><span class="LC_nobreak">'.
12339:                    '<label><input type="radio" name="archive_'.$count.
12340:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12341:         my $text = $choices{$action};
12342:         if ($is_dir) {
12343:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12344:             if ($action eq 'display') {
12345:                 $text = &mt('Add as folder');
12346:             }
12347:         } else {
12348:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12349: 
12350:         }
12351:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12352:         if ($action eq 'dependency') {
12353:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12354:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12355:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12356:                        '<option value=""></option>'."\n".
12357:                        '</select>'."\n".
12358:                        '</div>';
12359:         } elsif ($action eq 'display') {
12360:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12361:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12362:                        '</div>';
12363:         }
12364:         $output .= '</td>';
12365:     }
12366:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12367:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12368:     for (my $i=0; $i<$depth; $i++) {
12369:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12370:     }
12371:     if ($is_dir) {
12372:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12373:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12374:     } else {
12375:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12376:     }
12377:     $output .= '&nbsp;'.$name.'</td>'."\n".
12378:                &end_data_table_row();
12379:     return $output;
12380: }
12381: 
12382: sub archive_options_form {
12383:     my ($form,$display,$count,$hiddenelem) = @_;
12384:     my %lt = &Apache::lonlocal::texthash(
12385:                perm => 'Permanently remove archive file?',
12386:                hows => 'How should each extracted item be incorporated in the course?',
12387:                cont => 'Content actions for all',
12388:                addf => 'Add as folder/file',
12389:                incd => 'Include as dependency for a displayed file',
12390:                disc => 'Discard',
12391:                no   => 'No',
12392:                yes  => 'Yes',
12393:                save => 'Save',
12394:     );
12395:     my $output = <<"END";
12396: <form name="$form" method="post" action="">
12397: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12398: <label>
12399:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12400: </label>
12401: &nbsp;
12402: <label>
12403:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12404: </span>
12405: </p>
12406: <input type="hidden" name="phase" value="decompress_cleanup" />
12407: <br />$lt{'hows'}
12408: <div class="LC_columnSection">
12409:   <fieldset>
12410:     <legend>$lt{'cont'}</legend>
12411:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12412:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12413:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12414:   </fieldset>
12415: </div>
12416: END
12417:     return $output.
12418:            &start_data_table()."\n".
12419:            $display."\n".
12420:            &end_data_table()."\n".
12421:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12422:            $hiddenelem.
12423:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12424:            '</form>';
12425: }
12426: 
12427: sub archive_javascript {
12428:     my ($startcount,$numitems,$titles,$children) = @_;
12429:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12430:     my $maintitle = $env{'form.comment'};
12431:     my $scripttag = <<START;
12432: <script type="text/javascript">
12433: // <![CDATA[
12434: 
12435: function checkAll(form,prefix) {
12436:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12437:     for (var i=0; i < form.elements.length; i++) {
12438:         var id = form.elements[i].id;
12439:         if ((id != '') && (id != undefined)) {
12440:             if (idstr.test(id)) {
12441:                 if (form.elements[i].type == 'radio') {
12442:                     form.elements[i].checked = true;
12443:                     var nostart = i-$startcount;
12444:                     var offset = nostart%7;
12445:                     var count = (nostart-offset)/7;    
12446:                     dependencyCheck(form,count,offset);
12447:                 }
12448:             }
12449:         }
12450:     }
12451: }
12452: 
12453: function propagateCheck(form,count) {
12454:     if (count > 0) {
12455:         var startelement = $startcount + ((count-1) * 7);
12456:         for (var j=1; j<6; j++) {
12457:             if ((j != 2) && (j != 4)) {
12458:                 var item = startelement + j; 
12459:                 if (form.elements[item].type == 'radio') {
12460:                     if (form.elements[item].checked) {
12461:                         containerCheck(form,count,j);
12462:                         break;
12463:                     }
12464:                 }
12465:             }
12466:         }
12467:     }
12468: }
12469: 
12470: numitems = $numitems
12471: var titles = new Array(numitems);
12472: var parents = new Array(numitems);
12473: for (var i=0; i<numitems; i++) {
12474:     parents[i] = new Array;
12475: }
12476: var maintitle = '$maintitle';
12477: 
12478: START
12479: 
12480:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12481:         my @contents = split(/:/,$children->{$container});
12482:         for (my $i=0; $i<@contents; $i ++) {
12483:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12484:         }
12485:     }
12486: 
12487:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12488:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12489:     }
12490: 
12491:     $scripttag .= <<END;
12492: 
12493: function containerCheck(form,count,offset) {
12494:     if (count > 0) {
12495:         dependencyCheck(form,count,offset);
12496:         var item = (offset+$startcount)+7*(count-1);
12497:         form.elements[item].checked = true;
12498:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12499:             if (parents[count].length > 0) {
12500:                 for (var j=0; j<parents[count].length; j++) {
12501:                     containerCheck(form,parents[count][j],offset);
12502:                 }
12503:             }
12504:         }
12505:     }
12506: }
12507: 
12508: function dependencyCheck(form,count,offset) {
12509:     if (count > 0) {
12510:         var chosen = (offset+$startcount)+7*(count-1);
12511:         var depitem = $startcount + ((count-1) * 7) + 4;
12512:         var currtype = form.elements[depitem].type;
12513:         if (form.elements[chosen].value == 'dependency') {
12514:             document.getElementById('arc_depon_'+count).style.display='block'; 
12515:             form.elements[depitem].options.length = 0;
12516:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12517:             for (var i=1; i<=numitems; i++) {
12518:                 if (i == count) {
12519:                     continue;
12520:                 }
12521:                 var startelement = $startcount + (i-1) * 7;
12522:                 for (var j=1; j<6; j++) {
12523:                     if ((j != 2) && (j!= 4)) {
12524:                         var item = startelement + j;
12525:                         if (form.elements[item].type == 'radio') {
12526:                             if (form.elements[item].checked) {
12527:                                 if (form.elements[item].value == 'display') {
12528:                                     var n = form.elements[depitem].options.length;
12529:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12530:                                 }
12531:                             }
12532:                         }
12533:                     }
12534:                 }
12535:             }
12536:         } else {
12537:             document.getElementById('arc_depon_'+count).style.display='none';
12538:             form.elements[depitem].options.length = 0;
12539:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12540:         }
12541:         titleCheck(form,count,offset);
12542:     }
12543: }
12544: 
12545: function propagateSelect(form,count,offset) {
12546:     if (count > 0) {
12547:         var item = (1+offset+$startcount)+7*(count-1);
12548:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12549:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12550:             if (parents[count].length > 0) {
12551:                 for (var j=0; j<parents[count].length; j++) {
12552:                     containerSelect(form,parents[count][j],offset,picked);
12553:                 }
12554:             }
12555:         }
12556:     }
12557: }
12558: 
12559: function containerSelect(form,count,offset,picked) {
12560:     if (count > 0) {
12561:         var item = (offset+$startcount)+7*(count-1);
12562:         if (form.elements[item].type == 'radio') {
12563:             if (form.elements[item].value == 'dependency') {
12564:                 if (form.elements[item+1].type == 'select-one') {
12565:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12566:                         if (form.elements[item+1].options[i].value == picked) {
12567:                             form.elements[item+1].selectedIndex = i;
12568:                             break;
12569:                         }
12570:                     }
12571:                 }
12572:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12573:                     if (parents[count].length > 0) {
12574:                         for (var j=0; j<parents[count].length; j++) {
12575:                             containerSelect(form,parents[count][j],offset,picked);
12576:                         }
12577:                     }
12578:                 }
12579:             }
12580:         }
12581:     }
12582: }
12583: 
12584: function titleCheck(form,count,offset) {
12585:     if (count > 0) {
12586:         var chosen = (offset+$startcount)+7*(count-1);
12587:         var depitem = $startcount + ((count-1) * 7) + 2;
12588:         var currtype = form.elements[depitem].type;
12589:         if (form.elements[chosen].value == 'display') {
12590:             document.getElementById('arc_title_'+count).style.display='block';
12591:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12592:                 document.getElementById('archive_title_'+count).value=maintitle;
12593:             }
12594:         } else {
12595:             document.getElementById('arc_title_'+count).style.display='none';
12596:             if (currtype == 'text') { 
12597:                 document.getElementById('archive_title_'+count).value='';
12598:             }
12599:         }
12600:     }
12601:     return;
12602: }
12603: 
12604: // ]]>
12605: </script>
12606: END
12607:     return $scripttag;
12608: }
12609: 
12610: sub process_extracted_files {
12611:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12612:     my $numitems = $env{'form.archive_count'};
12613:     return unless ($numitems);
12614:     my @ids=&Apache::lonnet::current_machine_ids();
12615:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12616:         %folders,%containers,%mapinner,%prompttofetch);
12617:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12618:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12619:         $prefix = &LONCAPA::propath($docudom,$docuname);
12620:         $pathtocheck = "$dir_root/$destination";
12621:         $dir = $dir_root;
12622:         $ishome = 1;
12623:     } else {
12624:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12625:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12626:         $dir = "$dir_root/$docudom/$docuname";    
12627:     }
12628:     my $currdir = "$dir_root/$destination";
12629:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12630:     if ($env{'form.folderpath'}) {
12631:         my @items = split('&',$env{'form.folderpath'});
12632:         $folders{'0'} = $items[-2];
12633:         if ($env{'form.folderpath'} =~ /\:1$/) {
12634:             $containers{'0'}='page';
12635:         } else {  
12636:             $containers{'0'}='sequence';
12637:         }
12638:     }
12639:     my @archdirs = &get_env_multiple('form.archive_directory');
12640:     if ($numitems) {
12641:         for (my $i=1; $i<=$numitems; $i++) {
12642:             my $path = $env{'form.archive_content_'.$i};
12643:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12644:                 my $item = $1;
12645:                 $toplevelitems{$item} = $i;
12646:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12647:                     $is_dir{$item} = 1;
12648:                 }
12649:             }
12650:         }
12651:     }
12652:     my ($output,%children,%parent,%titles,%dirorder,$result);
12653:     if (keys(%toplevelitems) > 0) {
12654:         my @contents = sort(keys(%toplevelitems));
12655:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12656:                                            \%parent,\@contents,\%dirorder,\%titles);
12657:     }
12658:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12659:     if ($numitems) {
12660:         for (my $i=1; $i<=$numitems; $i++) {
12661:             next if ($env{'form.archive_'.$i} eq 'dependency');
12662:             my $path = $env{'form.archive_content_'.$i};
12663:             if ($path =~ /^\Q$pathtocheck\E/) {
12664:                 if ($env{'form.archive_'.$i} eq 'discard') {
12665:                     if ($prefix ne '' && $path ne '') {
12666:                         if (-e $prefix.$path) {
12667:                             if ((@archdirs > 0) && 
12668:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12669:                                 $todeletedir{$prefix.$path} = 1;
12670:                             } else {
12671:                                 $todelete{$prefix.$path} = 1;
12672:                             }
12673:                         }
12674:                     }
12675:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12676:                     my ($docstitle,$title,$url,$outer);
12677:                     ($title) = ($path =~ m{/([^/]+)$});
12678:                     $docstitle = $env{'form.archive_title_'.$i};
12679:                     if ($docstitle eq '') {
12680:                         $docstitle = $title;
12681:                     }
12682:                     $outer = 0;
12683:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12684:                         if (@{$dirorder{$i}} > 0) {
12685:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12686:                                 if ($env{'form.archive_'.$item} eq 'display') {
12687:                                     $outer = $item;
12688:                                     last;
12689:                                 }
12690:                             }
12691:                         }
12692:                     }
12693:                     my ($errtext,$fatal) = 
12694:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12695:                                                '/'.$folders{$outer}.'.'.
12696:                                                $containers{$outer});
12697:                     next if ($fatal);
12698:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12699:                         if ($context eq 'coursedocs') {
12700:                             $mapinner{$i} = time;
12701:                             $folders{$i} = 'default_'.$mapinner{$i};
12702:                             $containers{$i} = 'sequence';
12703:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12704:                                       $folders{$i}.'.'.$containers{$i};
12705:                             my $newidx = &LONCAPA::map::getresidx();
12706:                             $LONCAPA::map::resources[$newidx]=
12707:                                 $docstitle.':'.$url.':false:normal:res';
12708:                             push(@LONCAPA::map::order,$newidx);
12709:                             my ($outtext,$errtext) =
12710:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12711:                                                         $docuname.'/'.$folders{$outer}.
12712:                                                         '.'.$containers{$outer},1,1);
12713:                             $newseqid{$i} = $newidx;
12714:                             unless ($errtext) {
12715:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12716:                             }
12717:                         }
12718:                     } else {
12719:                         if ($context eq 'coursedocs') {
12720:                             my $newidx=&LONCAPA::map::getresidx();
12721:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12722:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12723:                                       $title;
12724:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12725:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12726:                             }
12727:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12728:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12729:                             }
12730:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12731:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12732:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12733:                                 unless ($ishome) {
12734:                                     my $fetch = "$newdest{$i}/$title";
12735:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12736:                                     $prompttofetch{$fetch} = 1;
12737:                                 }
12738:                             }
12739:                             $LONCAPA::map::resources[$newidx]=
12740:                                 $docstitle.':'.$url.':false:normal:res';
12741:                             push(@LONCAPA::map::order, $newidx);
12742:                             my ($outtext,$errtext)=
12743:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12744:                                                         $docuname.'/'.$folders{$outer}.
12745:                                                         '.'.$containers{$outer},1,1);
12746:                             unless ($errtext) {
12747:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12748:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12749:                                 }
12750:                             }
12751:                         }
12752:                     }
12753:                 }
12754:             } else {
12755:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12756:             }
12757:         }
12758:         for (my $i=1; $i<=$numitems; $i++) {
12759:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12760:             my $path = $env{'form.archive_content_'.$i};
12761:             if ($path =~ /^\Q$pathtocheck\E/) {
12762:                 my ($title) = ($path =~ m{/([^/]+)$});
12763:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12764:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12765:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12766:                         my ($itemidx,$fullpath,$relpath);
12767:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12768:                             my $container = $dirorder{$referrer{$i}}->[-1];
12769:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12770:                                 if ($dirorder{$i}->[$j] eq $container) {
12771:                                     $itemidx = $j;
12772:                                 }
12773:                             }
12774:                         }
12775:                         if ($itemidx eq '') {
12776:                             $itemidx =  0;
12777:                         } 
12778:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12779:                             if ($mapinner{$referrer{$i}}) {
12780:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12781:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12782:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12783:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12784:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12785:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12786:                                             if (!-e $fullpath) {
12787:                                                 mkdir($fullpath,0755);
12788:                                             }
12789:                                         }
12790:                                     } else {
12791:                                         last;
12792:                                     }
12793:                                 }
12794:                             }
12795:                         } elsif ($newdest{$referrer{$i}}) {
12796:                             $fullpath = $newdest{$referrer{$i}};
12797:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12798:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12799:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12800:                                     last;
12801:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12802:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12803:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12804:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12805:                                         if (!-e $fullpath) {
12806:                                             mkdir($fullpath,0755);
12807:                                         }
12808:                                     }
12809:                                 } else {
12810:                                     last;
12811:                                 }
12812:                             }
12813:                         }
12814:                         if ($fullpath ne '') {
12815:                             if (-e "$prefix$path") {
12816:                                 system("mv $prefix$path $fullpath/$title");
12817:                             }
12818:                             if (-e "$fullpath/$title") {
12819:                                 my $showpath;
12820:                                 if ($relpath ne '') {
12821:                                     $showpath = "$relpath/$title";
12822:                                 } else {
12823:                                     $showpath = "/$title";
12824:                                 } 
12825:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12826:                             } 
12827:                             unless ($ishome) {
12828:                                 my $fetch = "$fullpath/$title";
12829:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
12830:                                 $prompttofetch{$fetch} = 1;
12831:                             }
12832:                         }
12833:                     }
12834:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12835:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12836:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12837:                 }
12838:             } else {
12839:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12840:             }
12841:         }
12842:         if (keys(%todelete)) {
12843:             foreach my $key (keys(%todelete)) {
12844:                 unlink($key);
12845:             }
12846:         }
12847:         if (keys(%todeletedir)) {
12848:             foreach my $key (keys(%todeletedir)) {
12849:                 rmdir($key);
12850:             }
12851:         }
12852:         foreach my $dir (sort(keys(%is_dir))) {
12853:             if (($pathtocheck ne '') && ($dir ne ''))  {
12854:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12855:             }
12856:         }
12857:         if ($result ne '') {
12858:             $output .= '<ul>'."\n".
12859:                        $result."\n".
12860:                        '</ul>';
12861:         }
12862:         unless ($ishome) {
12863:             my $replicationfail;
12864:             foreach my $item (keys(%prompttofetch)) {
12865:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12866:                 unless ($fetchresult eq 'ok') {
12867:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12868:                 }
12869:             }
12870:             if ($replicationfail) {
12871:                 $output .= '<p class="LC_error">'.
12872:                            &mt('Course home server failed to retrieve:').'<ul>'.
12873:                            $replicationfail.
12874:                            '</ul></p>';
12875:             }
12876:         }
12877:     } else {
12878:         $warning = &mt('No items found in archive.');
12879:     }
12880:     if ($error) {
12881:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12882:                    $error.'</p>'."\n";
12883:     }
12884:     if ($warning) {
12885:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12886:     }
12887:     return $output;
12888: }
12889: 
12890: sub cleanup_empty_dirs {
12891:     my ($path) = @_;
12892:     if (($path ne '') && (-d $path)) {
12893:         if (opendir(my $dirh,$path)) {
12894:             my @dircontents = grep(!/^\./,readdir($dirh));
12895:             my $numitems = 0;
12896:             foreach my $item (@dircontents) {
12897:                 if (-d "$path/$item") {
12898:                     &cleanup_empty_dirs("$path/$item");
12899:                     if (-e "$path/$item") {
12900:                         $numitems ++;
12901:                     }
12902:                 } else {
12903:                     $numitems ++;
12904:                 }
12905:             }
12906:             if ($numitems == 0) {
12907:                 rmdir($path);
12908:             }
12909:             closedir($dirh);
12910:         }
12911:     }
12912:     return;
12913: }
12914: 
12915: =pod
12916: 
12917: =item * &get_folder_hierarchy()
12918: 
12919: Provides hierarchy of names of folders/sub-folders containing the current
12920: item,
12921: 
12922: Inputs: 3
12923:      - $navmap - navmaps object
12924: 
12925:      - $map - url for map (either the trigger itself, or map containing
12926:                            the resource, which is the trigger).
12927: 
12928:      - $showitem - 1 => show title for map itself; 0 => do not show.
12929: 
12930: Outputs: 1 @pathitems - array of folder/subfolder names.
12931: 
12932: =cut
12933: 
12934: sub get_folder_hierarchy {
12935:     my ($navmap,$map,$showitem) = @_;
12936:     my @pathitems;
12937:     if (ref($navmap)) {
12938:         my $mapres = $navmap->getResourceByUrl($map);
12939:         if (ref($mapres)) {
12940:             my $pcslist = $mapres->map_hierarchy();
12941:             if ($pcslist ne '') {
12942:                 my @pcs = split(/,/,$pcslist);
12943:                 foreach my $pc (@pcs) {
12944:                     if ($pc == 1) {
12945:                         push(@pathitems,&mt('Main Content'));
12946:                     } else {
12947:                         my $res = $navmap->getByMapPc($pc);
12948:                         if (ref($res)) {
12949:                             my $title = $res->compTitle();
12950:                             $title =~ s/\W+/_/g;
12951:                             if ($title ne '') {
12952:                                 push(@pathitems,$title);
12953:                             }
12954:                         }
12955:                     }
12956:                 }
12957:             }
12958:             if ($showitem) {
12959:                 if ($mapres->{ID} eq '0.0') {
12960:                     push(@pathitems,&mt('Main Content'));
12961:                 } else {
12962:                     my $maptitle = $mapres->compTitle();
12963:                     $maptitle =~ s/\W+/_/g;
12964:                     if ($maptitle ne '') {
12965:                         push(@pathitems,$maptitle);
12966:                     }
12967:                 }
12968:             }
12969:         }
12970:     }
12971:     return @pathitems;
12972: }
12973: 
12974: =pod
12975: 
12976: =item * &get_turnedin_filepath()
12977: 
12978: Determines path in a user's portfolio file for storage of files uploaded
12979: to a specific essayresponse or dropbox item.
12980: 
12981: Inputs: 3 required + 1 optional.
12982: $symb is symb for resource, $uname and $udom are for current user (required).
12983: $caller is optional (can be "submission", if routine is called when storing
12984: an upoaded file when "Submit Answer" button was pressed).
12985: 
12986: Returns array containing $path and $multiresp. 
12987: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12988: than one file upload item.  Callers of routine should append partid as a 
12989: subdirectory to $path in cases where $multiresp is 1.
12990: 
12991: Called by: homework/essayresponse.pm and homework/structuretags.pm
12992: 
12993: =cut
12994: 
12995: sub get_turnedin_filepath {
12996:     my ($symb,$uname,$udom,$caller) = @_;
12997:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12998:     my $turnindir;
12999:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13000:     $turnindir = $userhash{'turnindir'};
13001:     my ($path,$multiresp);
13002:     if ($turnindir eq '') {
13003:         if ($caller eq 'submission') {
13004:             $turnindir = &mt('turned in');
13005:             $turnindir =~ s/\W+/_/g;
13006:             my %newhash = (
13007:                             'turnindir' => $turnindir,
13008:                           );
13009:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13010:         }
13011:     }
13012:     if ($turnindir ne '') {
13013:         $path = '/'.$turnindir.'/';
13014:         my ($multipart,$turnin,@pathitems);
13015:         my $navmap = Apache::lonnavmaps::navmap->new();
13016:         if (defined($navmap)) {
13017:             my $mapres = $navmap->getResourceByUrl($map);
13018:             if (ref($mapres)) {
13019:                 my $pcslist = $mapres->map_hierarchy();
13020:                 if ($pcslist ne '') {
13021:                     foreach my $pc (split(/,/,$pcslist)) {
13022:                         my $res = $navmap->getByMapPc($pc);
13023:                         if (ref($res)) {
13024:                             my $title = $res->compTitle();
13025:                             $title =~ s/\W+/_/g;
13026:                             if ($title ne '') {
13027:                                 if (($pc > 1) && (length($title) > 12)) {
13028:                                     $title = substr($title,0,12);
13029:                                 }
13030:                                 push(@pathitems,$title);
13031:                             }
13032:                         }
13033:                     }
13034:                 }
13035:                 my $maptitle = $mapres->compTitle();
13036:                 $maptitle =~ s/\W+/_/g;
13037:                 if ($maptitle ne '') {
13038:                     if (length($maptitle) > 12) {
13039:                         $maptitle = substr($maptitle,0,12);
13040:                     }
13041:                     push(@pathitems,$maptitle);
13042:                 }
13043:                 unless ($env{'request.state'} eq 'construct') {
13044:                     my $res = $navmap->getBySymb($symb);
13045:                     if (ref($res)) {
13046:                         my $partlist = $res->parts();
13047:                         my $totaluploads = 0;
13048:                         if (ref($partlist) eq 'ARRAY') {
13049:                             foreach my $part (@{$partlist}) {
13050:                                 my @types = $res->responseType($part);
13051:                                 my @ids = $res->responseIds($part);
13052:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13053:                                     if ($types[$i] eq 'essay') {
13054:                                         my $partid = $part.'_'.$ids[$i];
13055:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13056:                                             $totaluploads ++;
13057:                                         }
13058:                                     }
13059:                                 }
13060:                             }
13061:                             if ($totaluploads > 1) {
13062:                                 $multiresp = 1;
13063:                             }
13064:                         }
13065:                     }
13066:                 }
13067:             } else {
13068:                 return;
13069:             }
13070:         } else {
13071:             return;
13072:         }
13073:         my $restitle=&Apache::lonnet::gettitle($symb);
13074:         $restitle =~ s/\W+/_/g;
13075:         if ($restitle eq '') {
13076:             $restitle = ($resurl =~ m{/[^/]+$});
13077:             if ($restitle eq '') {
13078:                 $restitle = time;
13079:             }
13080:         }
13081:         if (length($restitle) > 12) {
13082:             $restitle = substr($restitle,0,12);
13083:         }
13084:         push(@pathitems,$restitle);
13085:         $path .= join('/',@pathitems);
13086:     }
13087:     return ($path,$multiresp);
13088: }
13089: 
13090: =pod
13091: 
13092: =back
13093: 
13094: =head1 CSV Upload/Handling functions
13095: 
13096: =over 4
13097: 
13098: =item * &upfile_store($r)
13099: 
13100: Store uploaded file, $r should be the HTTP Request object,
13101: needs $env{'form.upfile'}
13102: returns $datatoken to be put into hidden field
13103: 
13104: =cut
13105: 
13106: sub upfile_store {
13107:     my $r=shift;
13108:     $env{'form.upfile'}=~s/\r/\n/gs;
13109:     $env{'form.upfile'}=~s/\f/\n/gs;
13110:     $env{'form.upfile'}=~s/\n+/\n/gs;
13111:     $env{'form.upfile'}=~s/\n+$//gs;
13112: 
13113:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13114: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13115:     {
13116:         my $datafile = $r->dir_config('lonDaemons').
13117:                            '/tmp/'.$datatoken.'.tmp';
13118:         if ( open(my $fh,">$datafile") ) {
13119:             print $fh $env{'form.upfile'};
13120:             close($fh);
13121:         }
13122:     }
13123:     return $datatoken;
13124: }
13125: 
13126: =pod
13127: 
13128: =item * &load_tmp_file($r)
13129: 
13130: Load uploaded file from tmp, $r should be the HTTP Request object,
13131: needs $env{'form.datatoken'},
13132: sets $env{'form.upfile'} to the contents of the file
13133: 
13134: =cut
13135: 
13136: sub load_tmp_file {
13137:     my $r=shift;
13138:     my @studentdata=();
13139:     {
13140:         my $studentfile = $r->dir_config('lonDaemons').
13141:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13142:         if ( open(my $fh,"<$studentfile") ) {
13143:             @studentdata=<$fh>;
13144:             close($fh);
13145:         }
13146:     }
13147:     $env{'form.upfile'}=join('',@studentdata);
13148: }
13149: 
13150: =pod
13151: 
13152: =item * &upfile_record_sep()
13153: 
13154: Separate uploaded file into records
13155: returns array of records,
13156: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13157: 
13158: =cut
13159: 
13160: sub upfile_record_sep {
13161:     if ($env{'form.upfiletype'} eq 'xml') {
13162:     } else {
13163: 	my @records;
13164: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13165: 	    if ($line=~/^\s*$/) { next; }
13166: 	    push(@records,$line);
13167: 	}
13168: 	return @records;
13169:     }
13170: }
13171: 
13172: =pod
13173: 
13174: =item * &record_sep($record)
13175: 
13176: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13177: 
13178: =cut
13179: 
13180: sub takeleft {
13181:     my $index=shift;
13182:     return substr('0000'.$index,-4,4);
13183: }
13184: 
13185: sub record_sep {
13186:     my $record=shift;
13187:     my %components=();
13188:     if ($env{'form.upfiletype'} eq 'xml') {
13189:     } elsif ($env{'form.upfiletype'} eq 'space') {
13190:         my $i=0;
13191:         foreach my $field (split(/\s+/,$record)) {
13192:             $field=~s/^(\"|\')//;
13193:             $field=~s/(\"|\')$//;
13194:             $components{&takeleft($i)}=$field;
13195:             $i++;
13196:         }
13197:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13198:         my $i=0;
13199:         foreach my $field (split(/\t/,$record)) {
13200:             $field=~s/^(\"|\')//;
13201:             $field=~s/(\"|\')$//;
13202:             $components{&takeleft($i)}=$field;
13203:             $i++;
13204:         }
13205:     } else {
13206:         my $separator=',';
13207:         if ($env{'form.upfiletype'} eq 'semisv') {
13208:             $separator=';';
13209:         }
13210:         my $i=0;
13211: # the character we are looking for to indicate the end of a quote or a record 
13212:         my $looking_for=$separator;
13213: # do not add the characters to the fields
13214:         my $ignore=0;
13215: # we just encountered a separator (or the beginning of the record)
13216:         my $just_found_separator=1;
13217: # store the field we are working on here
13218:         my $field='';
13219: # work our way through all characters in record
13220:         foreach my $character ($record=~/(.)/g) {
13221:             if ($character eq $looking_for) {
13222:                if ($character ne $separator) {
13223: # Found the end of a quote, again looking for separator
13224:                   $looking_for=$separator;
13225:                   $ignore=1;
13226:                } else {
13227: # Found a separator, store away what we got
13228:                   $components{&takeleft($i)}=$field;
13229: 	          $i++;
13230:                   $just_found_separator=1;
13231:                   $ignore=0;
13232:                   $field='';
13233:                }
13234:                next;
13235:             }
13236: # single or double quotation marks after a separator indicate beginning of a quote
13237: # we are now looking for the end of the quote and need to ignore separators
13238:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13239:                $looking_for=$character;
13240:                next;
13241:             }
13242: # ignore would be true after we reached the end of a quote
13243:             if ($ignore) { next; }
13244:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13245:             $field.=$character;
13246:             $just_found_separator=0; 
13247:         }
13248: # catch the very last entry, since we never encountered the separator
13249:         $components{&takeleft($i)}=$field;
13250:     }
13251:     return %components;
13252: }
13253: 
13254: ######################################################
13255: ######################################################
13256: 
13257: =pod
13258: 
13259: =item * &upfile_select_html()
13260: 
13261: Return HTML code to select a file from the users machine and specify 
13262: the file type.
13263: 
13264: =cut
13265: 
13266: ######################################################
13267: ######################################################
13268: sub upfile_select_html {
13269:     my %Types = (
13270:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13271:                  semisv => &mt('Semicolon separated values'),
13272:                  space => &mt('Space separated'),
13273:                  tab   => &mt('Tabulator separated'),
13274: #                 xml   => &mt('HTML/XML'),
13275:                  );
13276:     my $Str = '<input type="file" name="upfile" size="50" />'.
13277:         '<br />'.&mt('Type').': <select name="upfiletype">';
13278:     foreach my $type (sort(keys(%Types))) {
13279:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13280:     }
13281:     $Str .= "</select>\n";
13282:     return $Str;
13283: }
13284: 
13285: sub get_samples {
13286:     my ($records,$toget) = @_;
13287:     my @samples=({});
13288:     my $got=0;
13289:     foreach my $rec (@$records) {
13290: 	my %temp = &record_sep($rec);
13291: 	if (! grep(/\S/, values(%temp))) { next; }
13292: 	if (%temp) {
13293: 	    $samples[$got]=\%temp;
13294: 	    $got++;
13295: 	    if ($got == $toget) { last; }
13296: 	}
13297:     }
13298:     return \@samples;
13299: }
13300: 
13301: ######################################################
13302: ######################################################
13303: 
13304: =pod
13305: 
13306: =item * &csv_print_samples($r,$records)
13307: 
13308: Prints a table of sample values from each column uploaded $r is an
13309: Apache Request ref, $records is an arrayref from
13310: &Apache::loncommon::upfile_record_sep
13311: 
13312: =cut
13313: 
13314: ######################################################
13315: ######################################################
13316: sub csv_print_samples {
13317:     my ($r,$records) = @_;
13318:     my $samples = &get_samples($records,5);
13319: 
13320:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13321:               &start_data_table_header_row());
13322:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13323:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13324:     $r->print(&end_data_table_header_row());
13325:     foreach my $hash (@$samples) {
13326: 	$r->print(&start_data_table_row());
13327: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13328: 	    $r->print('<td>');
13329: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13330: 	    $r->print('</td>');
13331: 	}
13332: 	$r->print(&end_data_table_row());
13333:     }
13334:     $r->print(&end_data_table().'<br />'."\n");
13335: }
13336: 
13337: ######################################################
13338: ######################################################
13339: 
13340: =pod
13341: 
13342: =item * &csv_print_select_table($r,$records,$d)
13343: 
13344: Prints a table to create associations between values and table columns.
13345: 
13346: $r is an Apache Request ref,
13347: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13348: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13349: 
13350: =cut
13351: 
13352: ######################################################
13353: ######################################################
13354: sub csv_print_select_table {
13355:     my ($r,$records,$d) = @_;
13356:     my $i=0;
13357:     my $samples = &get_samples($records,1);
13358:     $r->print(&mt('Associate columns with student attributes.')."\n".
13359: 	      &start_data_table().&start_data_table_header_row().
13360:               '<th>'.&mt('Attribute').'</th>'.
13361:               '<th>'.&mt('Column').'</th>'.
13362:               &end_data_table_header_row()."\n");
13363:     foreach my $array_ref (@$d) {
13364: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13365: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13366: 
13367: 	$r->print('<td><select name="f'.$i.'"'.
13368: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13369: 	$r->print('<option value="none"></option>');
13370: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13371: 	    $r->print('<option value="'.$sample.'"'.
13372:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13373:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13374: 	}
13375: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13376: 	$i++;
13377:     }
13378:     $r->print(&end_data_table());
13379:     $i--;
13380:     return $i;
13381: }
13382: 
13383: ######################################################
13384: ######################################################
13385: 
13386: =pod
13387: 
13388: =item * &csv_samples_select_table($r,$records,$d)
13389: 
13390: Prints a table of sample values from the upload and can make associate samples to internal names.
13391: 
13392: $r is an Apache Request ref,
13393: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13394: $d is an array of 2 element arrays (internal name, displayed name)
13395: 
13396: =cut
13397: 
13398: ######################################################
13399: ######################################################
13400: sub csv_samples_select_table {
13401:     my ($r,$records,$d) = @_;
13402:     my $i=0;
13403:     #
13404:     my $max_samples = 5;
13405:     my $samples = &get_samples($records,$max_samples);
13406:     $r->print(&start_data_table().
13407:               &start_data_table_header_row().'<th>'.
13408:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13409:               &end_data_table_header_row());
13410: 
13411:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13412: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13413: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13414: 	foreach my $option (@$d) {
13415: 	    my ($value,$display,$defaultcol)=@{ $option };
13416: 	    $r->print('<option value="'.$value.'"'.
13417:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13418:                       $display.'</option>');
13419: 	}
13420: 	$r->print('</select></td><td>');
13421: 	foreach my $line (0..($max_samples-1)) {
13422: 	    if (defined($samples->[$line]{$key})) { 
13423: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13424: 	    }
13425: 	}
13426: 	$r->print('</td>'.&end_data_table_row());
13427: 	$i++;
13428:     }
13429:     $r->print(&end_data_table());
13430:     $i--;
13431:     return($i);
13432: }
13433: 
13434: ######################################################
13435: ######################################################
13436: 
13437: =pod
13438: 
13439: =item * &clean_excel_name($name)
13440: 
13441: Returns a replacement for $name which does not contain any illegal characters.
13442: 
13443: =cut
13444: 
13445: ######################################################
13446: ######################################################
13447: sub clean_excel_name {
13448:     my ($name) = @_;
13449:     $name =~ s/[:\*\?\/\\]//g;
13450:     if (length($name) > 31) {
13451:         $name = substr($name,0,31);
13452:     }
13453:     return $name;
13454: }
13455: 
13456: =pod
13457: 
13458: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13459: 
13460: Returns either 1 or undef
13461: 
13462: 1 if the part is to be hidden, undef if it is to be shown
13463: 
13464: Arguments are:
13465: 
13466: $id the id of the part to be checked
13467: $symb, optional the symb of the resource to check
13468: $udom, optional the domain of the user to check for
13469: $uname, optional the username of the user to check for
13470: 
13471: =cut
13472: 
13473: sub check_if_partid_hidden {
13474:     my ($id,$symb,$udom,$uname) = @_;
13475:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13476: 					 $symb,$udom,$uname);
13477:     my $truth=1;
13478:     #if the string starts with !, then the list is the list to show not hide
13479:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13480:     my @hiddenlist=split(/,/,$hiddenparts);
13481:     foreach my $checkid (@hiddenlist) {
13482: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13483:     }
13484:     return !$truth;
13485: }
13486: 
13487: 
13488: ############################################################
13489: ############################################################
13490: 
13491: =pod
13492: 
13493: =back 
13494: 
13495: =head1 cgi-bin script and graphing routines
13496: 
13497: =over 4
13498: 
13499: =item * &get_cgi_id()
13500: 
13501: Inputs: none
13502: 
13503: Returns an id which can be used to pass environment variables
13504: to various cgi-bin scripts.  These environment variables will
13505: be removed from the users environment after a given time by
13506: the routine &Apache::lonnet::transfer_profile_to_env.
13507: 
13508: =cut
13509: 
13510: ############################################################
13511: ############################################################
13512: my $uniq=0;
13513: sub get_cgi_id {
13514:     $uniq=($uniq+1)%100000;
13515:     return (time.'_'.$$.'_'.$uniq);
13516: }
13517: 
13518: ############################################################
13519: ############################################################
13520: 
13521: =pod
13522: 
13523: =item * &DrawBarGraph()
13524: 
13525: Facilitates the plotting of data in a (stacked) bar graph.
13526: Puts plot definition data into the users environment in order for 
13527: graph.png to plot it.  Returns an <img> tag for the plot.
13528: The bars on the plot are labeled '1','2',...,'n'.
13529: 
13530: Inputs:
13531: 
13532: =over 4
13533: 
13534: =item $Title: string, the title of the plot
13535: 
13536: =item $xlabel: string, text describing the X-axis of the plot
13537: 
13538: =item $ylabel: string, text describing the Y-axis of the plot
13539: 
13540: =item $Max: scalar, the maximum Y value to use in the plot
13541: If $Max is < any data point, the graph will not be rendered.
13542: 
13543: =item $colors: array ref holding the colors to be used for the data sets when
13544: they are plotted.  If undefined, default values will be used.
13545: 
13546: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13547: 
13548: =item @Values: An array of array references.  Each array reference holds data
13549: to be plotted in a stacked bar chart.
13550: 
13551: =item If the final element of @Values is a hash reference the key/value
13552: pairs will be added to the graph definition.
13553: 
13554: =back
13555: 
13556: Returns:
13557: 
13558: An <img> tag which references graph.png and the appropriate identifying
13559: information for the plot.
13560: 
13561: =cut
13562: 
13563: ############################################################
13564: ############################################################
13565: sub DrawBarGraph {
13566:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13567:     #
13568:     if (! defined($colors)) {
13569:         $colors = ['#33ff00', 
13570:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13571:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13572:                   ]; 
13573:     }
13574:     my $extra_settings = {};
13575:     if (ref($Values[-1]) eq 'HASH') {
13576:         $extra_settings = pop(@Values);
13577:     }
13578:     #
13579:     my $identifier = &get_cgi_id();
13580:     my $id = 'cgi.'.$identifier;        
13581:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13582:         return '';
13583:     }
13584:     #
13585:     my @Labels;
13586:     if (defined($labels)) {
13587:         @Labels = @$labels;
13588:     } else {
13589:         for (my $i=0;$i<@{$Values[0]};$i++) {
13590:             push (@Labels,$i+1);
13591:         }
13592:     }
13593:     #
13594:     my $NumBars = scalar(@{$Values[0]});
13595:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13596:     my %ValuesHash;
13597:     my $NumSets=1;
13598:     foreach my $array (@Values) {
13599:         next if (! ref($array));
13600:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13601:             join(',',@$array);
13602:     }
13603:     #
13604:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13605:     if ($NumBars < 3) {
13606:         $width = 120+$NumBars*32;
13607:         $xskip = 1;
13608:         $bar_width = 30;
13609:     } elsif ($NumBars < 5) {
13610:         $width = 120+$NumBars*20;
13611:         $xskip = 1;
13612:         $bar_width = 20;
13613:     } elsif ($NumBars < 10) {
13614:         $width = 120+$NumBars*15;
13615:         $xskip = 1;
13616:         $bar_width = 15;
13617:     } elsif ($NumBars <= 25) {
13618:         $width = 120+$NumBars*11;
13619:         $xskip = 5;
13620:         $bar_width = 8;
13621:     } elsif ($NumBars <= 50) {
13622:         $width = 120+$NumBars*8;
13623:         $xskip = 5;
13624:         $bar_width = 4;
13625:     } else {
13626:         $width = 120+$NumBars*8;
13627:         $xskip = 5;
13628:         $bar_width = 4;
13629:     }
13630:     #
13631:     $Max = 1 if ($Max < 1);
13632:     if ( int($Max) < $Max ) {
13633:         $Max++;
13634:         $Max = int($Max);
13635:     }
13636:     $Title  = '' if (! defined($Title));
13637:     $xlabel = '' if (! defined($xlabel));
13638:     $ylabel = '' if (! defined($ylabel));
13639:     $ValuesHash{$id.'.title'}    = &escape($Title);
13640:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13641:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13642:     $ValuesHash{$id.'.y_max_value'} = $Max;
13643:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13644:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13645:     $ValuesHash{$id.'.PlotType'} = 'bar';
13646:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13647:     $ValuesHash{$id.'.height'}   = $height;
13648:     $ValuesHash{$id.'.width'}    = $width;
13649:     $ValuesHash{$id.'.xskip'}    = $xskip;
13650:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13651:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13652:     #
13653:     # Deal with other parameters
13654:     while (my ($key,$value) = each(%$extra_settings)) {
13655:         $ValuesHash{$id.'.'.$key} = $value;
13656:     }
13657:     #
13658:     &Apache::lonnet::appenv(\%ValuesHash);
13659:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13660: }
13661: 
13662: ############################################################
13663: ############################################################
13664: 
13665: =pod
13666: 
13667: =item * &DrawXYGraph()
13668: 
13669: Facilitates the plotting of data in an XY graph.
13670: Puts plot definition data into the users environment in order for 
13671: graph.png to plot it.  Returns an <img> tag for the plot.
13672: 
13673: Inputs:
13674: 
13675: =over 4
13676: 
13677: =item $Title: string, the title of the plot
13678: 
13679: =item $xlabel: string, text describing the X-axis of the plot
13680: 
13681: =item $ylabel: string, text describing the Y-axis of the plot
13682: 
13683: =item $Max: scalar, the maximum Y value to use in the plot
13684: If $Max is < any data point, the graph will not be rendered.
13685: 
13686: =item $colors: Array ref containing the hex color codes for the data to be 
13687: plotted in.  If undefined, default values will be used.
13688: 
13689: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13690: 
13691: =item $Ydata: Array ref containing Array refs.  
13692: Each of the contained arrays will be plotted as a separate curve.
13693: 
13694: =item %Values: hash indicating or overriding any default values which are 
13695: passed to graph.png.  
13696: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13697: 
13698: =back
13699: 
13700: Returns:
13701: 
13702: An <img> tag which references graph.png and the appropriate identifying
13703: information for the plot.
13704: 
13705: =cut
13706: 
13707: ############################################################
13708: ############################################################
13709: sub DrawXYGraph {
13710:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13711:     #
13712:     # Create the identifier for the graph
13713:     my $identifier = &get_cgi_id();
13714:     my $id = 'cgi.'.$identifier;
13715:     #
13716:     $Title  = '' if (! defined($Title));
13717:     $xlabel = '' if (! defined($xlabel));
13718:     $ylabel = '' if (! defined($ylabel));
13719:     my %ValuesHash = 
13720:         (
13721:          $id.'.title'  => &escape($Title),
13722:          $id.'.xlabel' => &escape($xlabel),
13723:          $id.'.ylabel' => &escape($ylabel),
13724:          $id.'.y_max_value'=> $Max,
13725:          $id.'.labels'     => join(',',@$Xlabels),
13726:          $id.'.PlotType'   => 'XY',
13727:          );
13728:     #
13729:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13730:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13731:     }
13732:     #
13733:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13734:         return '';
13735:     }
13736:     my $NumSets=1;
13737:     foreach my $array (@{$Ydata}){
13738:         next if (! ref($array));
13739:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13740:     }
13741:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13742:     #
13743:     # Deal with other parameters
13744:     while (my ($key,$value) = each(%Values)) {
13745:         $ValuesHash{$id.'.'.$key} = $value;
13746:     }
13747:     #
13748:     &Apache::lonnet::appenv(\%ValuesHash);
13749:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13750: }
13751: 
13752: ############################################################
13753: ############################################################
13754: 
13755: =pod
13756: 
13757: =item * &DrawXYYGraph()
13758: 
13759: Facilitates the plotting of data in an XY graph with two Y axes.
13760: Puts plot definition data into the users environment in order for 
13761: graph.png to plot it.  Returns an <img> tag for the plot.
13762: 
13763: Inputs:
13764: 
13765: =over 4
13766: 
13767: =item $Title: string, the title of the plot
13768: 
13769: =item $xlabel: string, text describing the X-axis of the plot
13770: 
13771: =item $ylabel: string, text describing the Y-axis of the plot
13772: 
13773: =item $colors: Array ref containing the hex color codes for the data to be 
13774: plotted in.  If undefined, default values will be used.
13775: 
13776: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13777: 
13778: =item $Ydata1: The first data set
13779: 
13780: =item $Min1: The minimum value of the left Y-axis
13781: 
13782: =item $Max1: The maximum value of the left Y-axis
13783: 
13784: =item $Ydata2: The second data set
13785: 
13786: =item $Min2: The minimum value of the right Y-axis
13787: 
13788: =item $Max2: The maximum value of the left Y-axis
13789: 
13790: =item %Values: hash indicating or overriding any default values which are 
13791: passed to graph.png.  
13792: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13793: 
13794: =back
13795: 
13796: Returns:
13797: 
13798: An <img> tag which references graph.png and the appropriate identifying
13799: information for the plot.
13800: 
13801: =cut
13802: 
13803: ############################################################
13804: ############################################################
13805: sub DrawXYYGraph {
13806:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13807:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13808:     #
13809:     # Create the identifier for the graph
13810:     my $identifier = &get_cgi_id();
13811:     my $id = 'cgi.'.$identifier;
13812:     #
13813:     $Title  = '' if (! defined($Title));
13814:     $xlabel = '' if (! defined($xlabel));
13815:     $ylabel = '' if (! defined($ylabel));
13816:     my %ValuesHash = 
13817:         (
13818:          $id.'.title'  => &escape($Title),
13819:          $id.'.xlabel' => &escape($xlabel),
13820:          $id.'.ylabel' => &escape($ylabel),
13821:          $id.'.labels' => join(',',@$Xlabels),
13822:          $id.'.PlotType' => 'XY',
13823:          $id.'.NumSets' => 2,
13824:          $id.'.two_axes' => 1,
13825:          $id.'.y1_max_value' => $Max1,
13826:          $id.'.y1_min_value' => $Min1,
13827:          $id.'.y2_max_value' => $Max2,
13828:          $id.'.y2_min_value' => $Min2,
13829:          );
13830:     #
13831:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13832:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13833:     }
13834:     #
13835:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13836:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13837:         return '';
13838:     }
13839:     my $NumSets=1;
13840:     foreach my $array ($Ydata1,$Ydata2){
13841:         next if (! ref($array));
13842:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13843:     }
13844:     #
13845:     # Deal with other parameters
13846:     while (my ($key,$value) = each(%Values)) {
13847:         $ValuesHash{$id.'.'.$key} = $value;
13848:     }
13849:     #
13850:     &Apache::lonnet::appenv(\%ValuesHash);
13851:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13852: }
13853: 
13854: ############################################################
13855: ############################################################
13856: 
13857: =pod
13858: 
13859: =back 
13860: 
13861: =head1 Statistics helper routines?  
13862: 
13863: Bad place for them but what the hell.
13864: 
13865: =over 4
13866: 
13867: =item * &chartlink()
13868: 
13869: Returns a link to the chart for a specific student.  
13870: 
13871: Inputs:
13872: 
13873: =over 4
13874: 
13875: =item $linktext: The text of the link
13876: 
13877: =item $sname: The students username
13878: 
13879: =item $sdomain: The students domain
13880: 
13881: =back
13882: 
13883: =back
13884: 
13885: =cut
13886: 
13887: ############################################################
13888: ############################################################
13889: sub chartlink {
13890:     my ($linktext, $sname, $sdomain) = @_;
13891:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13892:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13893:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13894:        '">'.$linktext.'</a>';
13895: }
13896: 
13897: #######################################################
13898: #######################################################
13899: 
13900: =pod
13901: 
13902: =head1 Course Environment Routines
13903: 
13904: =over 4
13905: 
13906: =item * &restore_course_settings()
13907: 
13908: =item * &store_course_settings()
13909: 
13910: Restores/Store indicated form parameters from the course environment.
13911: Will not overwrite existing values of the form parameters.
13912: 
13913: Inputs: 
13914: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13915: 
13916: a hash ref describing the data to be stored.  For example:
13917:    
13918: %Save_Parameters = ('Status' => 'scalar',
13919:     'chartoutputmode' => 'scalar',
13920:     'chartoutputdata' => 'scalar',
13921:     'Section' => 'array',
13922:     'Group' => 'array',
13923:     'StudentData' => 'array',
13924:     'Maps' => 'array');
13925: 
13926: Returns: both routines return nothing
13927: 
13928: =back
13929: 
13930: =cut
13931: 
13932: #######################################################
13933: #######################################################
13934: sub store_course_settings {
13935:     return &store_settings($env{'request.course.id'},@_);
13936: }
13937: 
13938: sub store_settings {
13939:     # save to the environment
13940:     # appenv the same items, just to be safe
13941:     my $udom  = $env{'user.domain'};
13942:     my $uname = $env{'user.name'};
13943:     my ($context,$prefix,$Settings) = @_;
13944:     my %SaveHash;
13945:     my %AppHash;
13946:     while (my ($setting,$type) = each(%$Settings)) {
13947:         my $basename = join('.','internal',$context,$prefix,$setting);
13948:         my $envname = 'environment.'.$basename;
13949:         if (exists($env{'form.'.$setting})) {
13950:             # Save this value away
13951:             if ($type eq 'scalar' &&
13952:                 (! exists($env{$envname}) || 
13953:                  $env{$envname} ne $env{'form.'.$setting})) {
13954:                 $SaveHash{$basename} = $env{'form.'.$setting};
13955:                 $AppHash{$envname}   = $env{'form.'.$setting};
13956:             } elsif ($type eq 'array') {
13957:                 my $stored_form;
13958:                 if (ref($env{'form.'.$setting})) {
13959:                     $stored_form = join(',',
13960:                                         map {
13961:                                             &escape($_);
13962:                                         } sort(@{$env{'form.'.$setting}}));
13963:                 } else {
13964:                     $stored_form = 
13965:                         &escape($env{'form.'.$setting});
13966:                 }
13967:                 # Determine if the array contents are the same.
13968:                 if ($stored_form ne $env{$envname}) {
13969:                     $SaveHash{$basename} = $stored_form;
13970:                     $AppHash{$envname}   = $stored_form;
13971:                 }
13972:             }
13973:         }
13974:     }
13975:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13976:                                           $udom,$uname);
13977:     if ($put_result !~ /^(ok|delayed)/) {
13978:         &Apache::lonnet::logthis('unable to save form parameters, '.
13979:                                  'got error:'.$put_result);
13980:     }
13981:     # Make sure these settings stick around in this session, too
13982:     &Apache::lonnet::appenv(\%AppHash);
13983:     return;
13984: }
13985: 
13986: sub restore_course_settings {
13987:     return &restore_settings($env{'request.course.id'},@_);
13988: }
13989: 
13990: sub restore_settings {
13991:     my ($context,$prefix,$Settings) = @_;
13992:     while (my ($setting,$type) = each(%$Settings)) {
13993:         next if (exists($env{'form.'.$setting}));
13994:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13995:             '.'.$setting;
13996:         if (exists($env{$envname})) {
13997:             if ($type eq 'scalar') {
13998:                 $env{'form.'.$setting} = $env{$envname};
13999:             } elsif ($type eq 'array') {
14000:                 $env{'form.'.$setting} = [ 
14001:                                            map { 
14002:                                                &unescape($_); 
14003:                                            } split(',',$env{$envname})
14004:                                            ];
14005:             }
14006:         }
14007:     }
14008: }
14009: 
14010: #######################################################
14011: #######################################################
14012: 
14013: =pod
14014: 
14015: =head1 Domain E-mail Routines  
14016: 
14017: =over 4
14018: 
14019: =item * &build_recipient_list()
14020: 
14021: Build recipient lists for following types of e-mail:
14022: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14023: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14024: module change checking, student/employee ID conflict checks, as
14025: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14026: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14027: 
14028: Inputs:
14029: defmail (scalar - email address of default recipient), 
14030: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14031: requestsmail, updatesmail, or idconflictsmail).
14032: 
14033: defdom (domain for which to retrieve configuration settings),
14034: 
14035: origmail (scalar - email address of recipient from loncapa.conf, 
14036: i.e., predates configuration by DC via domainprefs.pm 
14037: 
14038: Returns: comma separated list of addresses to which to send e-mail.
14039: 
14040: =back
14041: 
14042: =cut
14043: 
14044: ############################################################
14045: ############################################################
14046: sub build_recipient_list {
14047:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14048:     my @recipients;
14049:     my $otheremails;
14050:     my %domconfig =
14051:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14052:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14053:         if (exists($domconfig{'contacts'}{$mailing})) {
14054:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14055:                 my @contacts = ('adminemail','supportemail');
14056:                 foreach my $item (@contacts) {
14057:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14058:                         my $addr = $domconfig{'contacts'}{$item}; 
14059:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14060:                             push(@recipients,$addr);
14061:                         }
14062:                     }
14063:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14064:                 }
14065:             }
14066:         } elsif ($origmail ne '') {
14067:             push(@recipients,$origmail);
14068:         }
14069:     } elsif ($origmail ne '') {
14070:         push(@recipients,$origmail);
14071:     }
14072:     if (defined($defmail)) {
14073:         if ($defmail ne '') {
14074:             push(@recipients,$defmail);
14075:         }
14076:     }
14077:     if ($otheremails) {
14078:         my @others;
14079:         if ($otheremails =~ /,/) {
14080:             @others = split(/,/,$otheremails);
14081:         } else {
14082:             push(@others,$otheremails);
14083:         }
14084:         foreach my $addr (@others) {
14085:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14086:                 push(@recipients,$addr);
14087:             }
14088:         }
14089:     }
14090:     my $recipientlist = join(',',@recipients); 
14091:     return $recipientlist;
14092: }
14093: 
14094: ############################################################
14095: ############################################################
14096: 
14097: =pod
14098: 
14099: =over 4
14100: 
14101: =item * &mime_email()
14102: 
14103: Sends an email with a possible attachment
14104: 
14105: Inputs:
14106: 
14107: =over 4
14108: 
14109: from -              Sender's email address
14110: 
14111: to -                Email address of recipient
14112: 
14113: subject -           Subject of email
14114: 
14115: body -              Body of email
14116: 
14117: cc_string -         Carbon copy email address
14118: 
14119: bcc -               Blind carbon copy email address
14120: 
14121: type -              File type of attachment
14122: 
14123: attachment_path -   Path of file to be attached
14124: 
14125: file_name -         Name of file to be attached
14126: 
14127: attachment_text -   The body of an attachment of type "TEXT"
14128: 
14129: =back
14130: 
14131: =back
14132: 
14133: =cut
14134: 
14135: ############################################################
14136: ############################################################
14137: 
14138: sub mime_email {
14139:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14140:         $file_name, $attachment_text) = @_;
14141:     my $msg = MIME::Lite->new(
14142:              From    => $from,
14143:              To      => $to,
14144:              Subject => $subject,
14145:              Type    =>'TEXT',
14146:              Data    => $body,
14147:              );
14148:     if ($cc_string ne '') {
14149:         $msg->add("Cc" => $cc_string);
14150:     }
14151:     if ($bcc ne '') {
14152:         $msg->add("Bcc" => $bcc);
14153:     }
14154:     $msg->attr("content-type"         => "text/plain");
14155:     $msg->attr("content-type.charset" => "UTF-8");
14156:     # Attach file if given
14157:     if ($attachment_path) {
14158:         unless ($file_name) {
14159:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14160:         }
14161:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14162:         $msg->attach(Type     => $type,
14163:                      Path     => $attachment_path,
14164:                      Filename => $file_name
14165:                      );
14166:     # Otherwise attach text if given
14167:     } elsif ($attachment_text) {
14168:         $msg->attach(Type => 'TEXT',
14169:                      Data => $attachment_text);
14170:     }
14171:     # Send it
14172:     $msg->send('sendmail');
14173: }
14174: 
14175: ############################################################
14176: ############################################################
14177: 
14178: =pod
14179: 
14180: =head1 Course Catalog Routines
14181: 
14182: =over 4
14183: 
14184: =item * &gather_categories()
14185: 
14186: Converts category definitions - keys of categories hash stored in  
14187: coursecategories in configuration.db on the primary library server in a 
14188: domain - to an array.  Also generates javascript and idx hash used to 
14189: generate Domain Coordinator interface for editing Course Categories.
14190: 
14191: Inputs:
14192: 
14193: categories (reference to hash of category definitions).
14194: 
14195: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14196:       categories and subcategories).
14197: 
14198: idx (reference to hash of counters used in Domain Coordinator interface for 
14199:       editing Course Categories).
14200: 
14201: jsarray (reference to array of categories used to create Javascript arrays for
14202:          Domain Coordinator interface for editing Course Categories).
14203: 
14204: Returns: nothing
14205: 
14206: Side effects: populates cats, idx and jsarray. 
14207: 
14208: =cut
14209: 
14210: sub gather_categories {
14211:     my ($categories,$cats,$idx,$jsarray) = @_;
14212:     my %counters;
14213:     my $num = 0;
14214:     foreach my $item (keys(%{$categories})) {
14215:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14216:         if ($container eq '' && $depth == 0) {
14217:             $cats->[$depth][$categories->{$item}] = $cat;
14218:         } else {
14219:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14220:         }
14221:         my ($escitem,$tail) = split(/:/,$item,2);
14222:         if ($counters{$tail} eq '') {
14223:             $counters{$tail} = $num;
14224:             $num ++;
14225:         }
14226:         if (ref($idx) eq 'HASH') {
14227:             $idx->{$item} = $counters{$tail};
14228:         }
14229:         if (ref($jsarray) eq 'ARRAY') {
14230:             push(@{$jsarray->[$counters{$tail}]},$item);
14231:         }
14232:     }
14233:     return;
14234: }
14235: 
14236: =pod
14237: 
14238: =item * &extract_categories()
14239: 
14240: Used to generate breadcrumb trails for course categories.
14241: 
14242: Inputs:
14243: 
14244: categories (reference to hash of category definitions).
14245: 
14246: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14247:       categories and subcategories).
14248: 
14249: trails (reference to array of breacrumb trails for each category).
14250: 
14251: allitems (reference to hash - key is category key 
14252:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14253: 
14254: idx (reference to hash of counters used in Domain Coordinator interface for
14255:       editing Course Categories).
14256: 
14257: jsarray (reference to array of categories used to create Javascript arrays for
14258:          Domain Coordinator interface for editing Course Categories).
14259: 
14260: subcats (reference to hash of arrays containing all subcategories within each 
14261:          category, -recursive)
14262: 
14263: Returns: nothing
14264: 
14265: Side effects: populates trails and allitems hash references.
14266: 
14267: =cut
14268: 
14269: sub extract_categories {
14270:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14271:     if (ref($categories) eq 'HASH') {
14272:         &gather_categories($categories,$cats,$idx,$jsarray);
14273:         if (ref($cats->[0]) eq 'ARRAY') {
14274:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14275:                 my $name = $cats->[0][$i];
14276:                 my $item = &escape($name).'::0';
14277:                 my $trailstr;
14278:                 if ($name eq 'instcode') {
14279:                     $trailstr = &mt('Official courses (with institutional codes)');
14280:                 } elsif ($name eq 'communities') {
14281:                     $trailstr = &mt('Communities');
14282:                 } elsif ($name eq 'placement') {
14283:                     $trailstr = &mt('Placement Tests');
14284:                 } else {
14285:                     $trailstr = $name;
14286:                 }
14287:                 if ($allitems->{$item} eq '') {
14288:                     push(@{$trails},$trailstr);
14289:                     $allitems->{$item} = scalar(@{$trails})-1;
14290:                 }
14291:                 my @parents = ($name);
14292:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14293:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14294:                         my $category = $cats->[1]{$name}[$j];
14295:                         if (ref($subcats) eq 'HASH') {
14296:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14297:                         }
14298:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14299:                     }
14300:                 } else {
14301:                     if (ref($subcats) eq 'HASH') {
14302:                         $subcats->{$item} = [];
14303:                     }
14304:                 }
14305:             }
14306:         }
14307:     }
14308:     return;
14309: }
14310: 
14311: =pod
14312: 
14313: =item * &recurse_categories()
14314: 
14315: Recursively used to generate breadcrumb trails for course categories.
14316: 
14317: Inputs:
14318: 
14319: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14320:       categories and subcategories).
14321: 
14322: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14323: 
14324: category (current course category, for which breadcrumb trail is being generated).
14325: 
14326: trails (reference to array of breadcrumb trails for each category).
14327: 
14328: allitems (reference to hash - key is category key
14329:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14330: 
14331: parents (array containing containers directories for current category, 
14332:          back to top level). 
14333: 
14334: Returns: nothing
14335: 
14336: Side effects: populates trails and allitems hash references
14337: 
14338: =cut
14339: 
14340: sub recurse_categories {
14341:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14342:     my $shallower = $depth - 1;
14343:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14344:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14345:             my $name = $cats->[$depth]{$category}[$k];
14346:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14347:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14348:             if ($allitems->{$item} eq '') {
14349:                 push(@{$trails},$trailstr);
14350:                 $allitems->{$item} = scalar(@{$trails})-1;
14351:             }
14352:             my $deeper = $depth+1;
14353:             push(@{$parents},$category);
14354:             if (ref($subcats) eq 'HASH') {
14355:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14356:                 for (my $j=@{$parents}; $j>=0; $j--) {
14357:                     my $higher;
14358:                     if ($j > 0) {
14359:                         $higher = &escape($parents->[$j]).':'.
14360:                                   &escape($parents->[$j-1]).':'.$j;
14361:                     } else {
14362:                         $higher = &escape($parents->[$j]).'::'.$j;
14363:                     }
14364:                     push(@{$subcats->{$higher}},$subcat);
14365:                 }
14366:             }
14367:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14368:                                 $subcats);
14369:             pop(@{$parents});
14370:         }
14371:     } else {
14372:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14373:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14374:         if ($allitems->{$item} eq '') {
14375:             push(@{$trails},$trailstr);
14376:             $allitems->{$item} = scalar(@{$trails})-1;
14377:         }
14378:     }
14379:     return;
14380: }
14381: 
14382: =pod
14383: 
14384: =item * &assign_categories_table()
14385: 
14386: Create a datatable for display of hierarchical categories in a domain,
14387: with checkboxes to allow a course to be categorized. 
14388: 
14389: Inputs:
14390: 
14391: cathash - reference to hash of categories defined for the domain (from
14392:           configuration.db)
14393: 
14394: currcat - scalar with an & separated list of categories assigned to a course. 
14395: 
14396: type    - scalar contains course type (Course or Community).
14397: 
14398: Returns: $output (markup to be displayed) 
14399: 
14400: =cut
14401: 
14402: sub assign_categories_table {
14403:     my ($cathash,$currcat,$type) = @_;
14404:     my $output;
14405:     if (ref($cathash) eq 'HASH') {
14406:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14407:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14408:         $maxdepth = scalar(@cats);
14409:         if (@cats > 0) {
14410:             my $itemcount = 0;
14411:             if (ref($cats[0]) eq 'ARRAY') {
14412:                 my @currcategories;
14413:                 if ($currcat ne '') {
14414:                     @currcategories = split('&',$currcat);
14415:                 }
14416:                 my $table;
14417:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14418:                     my $parent = $cats[0][$i];
14419:                     next if ($parent eq 'instcode');
14420:                     if ($type eq 'Community') {
14421:                         next unless ($parent eq 'communities');
14422:                     } elsif ($type eq 'Placement') {
14423:                         next unless ($parent eq 'placement');
14424:                     } else {
14425:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
14426:                     }
14427:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14428:                     my $item = &escape($parent).'::0';
14429:                     my $checked = '';
14430:                     if (@currcategories > 0) {
14431:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14432:                             $checked = ' checked="checked"';
14433:                         }
14434:                     }
14435:                     my $parent_title = $parent;
14436:                     if ($parent eq 'communities') {
14437:                         $parent_title = &mt('Communities');
14438:                     } elsif ($parent eq 'placement') {
14439:                         $parent_title = &mt('Placement Tests');
14440:                     }
14441:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14442:                               '<input type="checkbox" name="usecategory" value="'.
14443:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
14444:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14445:                     my $depth = 1;
14446:                     push(@path,$parent);
14447:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14448:                     pop(@path);
14449:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14450:                     $itemcount ++;
14451:                 }
14452:                 if ($itemcount) {
14453:                     $output = &Apache::loncommon::start_data_table().
14454:                               $table.
14455:                               &Apache::loncommon::end_data_table();
14456:                 }
14457:             }
14458:         }
14459:     }
14460:     return $output;
14461: }
14462: 
14463: =pod
14464: 
14465: =item * &assign_category_rows()
14466: 
14467: Create a datatable row for display of nested categories in a domain,
14468: with checkboxes to allow a course to be categorized,called recursively.
14469: 
14470: Inputs:
14471: 
14472: itemcount - track row number for alternating colors
14473: 
14474: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14475:       categories and subcategories.
14476: 
14477: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14478: 
14479: parent - parent of current category item
14480: 
14481: path - Array containing all categories back up through the hierarchy from the
14482:        current category to the top level.
14483: 
14484: currcategories - reference to array of current categories assigned to the course
14485: 
14486: Returns: $output (markup to be displayed).
14487: 
14488: =cut
14489: 
14490: sub assign_category_rows {
14491:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14492:     my ($text,$name,$item,$chgstr);
14493:     if (ref($cats) eq 'ARRAY') {
14494:         my $maxdepth = scalar(@{$cats});
14495:         if (ref($cats->[$depth]) eq 'HASH') {
14496:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14497:                 my $numchildren = @{$cats->[$depth]{$parent}};
14498:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14499:                 $text .= '<td><table class="LC_data_table">';
14500:                 for (my $j=0; $j<$numchildren; $j++) {
14501:                     $name = $cats->[$depth]{$parent}[$j];
14502:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14503:                     my $deeper = $depth+1;
14504:                     my $checked = '';
14505:                     if (ref($currcategories) eq 'ARRAY') {
14506:                         if (@{$currcategories} > 0) {
14507:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14508:                                 $checked = ' checked="checked"';
14509:                             }
14510:                         }
14511:                     }
14512:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14513:                              '<input type="checkbox" name="usecategory" value="'.
14514:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
14515:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14516:                              '</td><td>';
14517:                     if (ref($path) eq 'ARRAY') {
14518:                         push(@{$path},$name);
14519:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14520:                         pop(@{$path});
14521:                     }
14522:                     $text .= '</td></tr>';
14523:                 }
14524:                 $text .= '</table></td>';
14525:             }
14526:         }
14527:     }
14528:     return $text;
14529: }
14530: 
14531: =pod
14532: 
14533: =back
14534: 
14535: =cut
14536: 
14537: ############################################################
14538: ############################################################
14539: 
14540: 
14541: sub commit_customrole {
14542:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14543:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14544:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14545:                          ($end?', ending '.localtime($end):'').': <b>'.
14546:               &Apache::lonnet::assigncustomrole(
14547:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14548:                  '</b><br />';
14549:     return $output;
14550: }
14551: 
14552: sub commit_standardrole {
14553:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14554:     my ($output,$logmsg,$linefeed);
14555:     if ($context eq 'auto') {
14556:         $linefeed = "\n";
14557:     } else {
14558:         $linefeed = "<br />\n";
14559:     }  
14560:     if ($three eq 'st') {
14561:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14562:                                          $one,$two,$sec,$context,$credits);
14563:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14564:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14565:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14566:         } else {
14567:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14568:                ($start?', '.&mt('starting').' '.localtime($start):'').
14569:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14570:             if ($context eq 'auto') {
14571:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14572:             } else {
14573:                $output .= '<b>'.$result.'</b>'.$linefeed.
14574:                &mt('Add to classlist').': <b>ok</b>';
14575:             }
14576:             $output .= $linefeed;
14577:         }
14578:     } else {
14579:         $output = &mt('Assigning').' '.$three.' in '.$url.
14580:                ($start?', '.&mt('starting').' '.localtime($start):'').
14581:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14582:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14583:         if ($context eq 'auto') {
14584:             $output .= $result.$linefeed;
14585:         } else {
14586:             $output .= '<b>'.$result.'</b>'.$linefeed;
14587:         }
14588:     }
14589:     return $output;
14590: }
14591: 
14592: sub commit_studentrole {
14593:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14594:         $credits) = @_;
14595:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14596:     if ($context eq 'auto') {
14597:         $linefeed = "\n";
14598:     } else {
14599:         $linefeed = '<br />'."\n";
14600:     }
14601:     if (defined($one) && defined($two)) {
14602:         my $cid=$one.'_'.$two;
14603:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14604:         my $secchange = 0;
14605:         my $expire_role_result;
14606:         my $modify_section_result;
14607:         if ($oldsec ne '-1') { 
14608:             if ($oldsec ne $sec) {
14609:                 $secchange = 1;
14610:                 my $now = time;
14611:                 my $uurl='/'.$cid;
14612:                 $uurl=~s/\_/\//g;
14613:                 if ($oldsec) {
14614:                     $uurl.='/'.$oldsec;
14615:                 }
14616:                 $oldsecurl = $uurl;
14617:                 $expire_role_result = 
14618:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14619:                 if ($env{'request.course.sec'} ne '') { 
14620:                     if ($expire_role_result eq 'refused') {
14621:                         my @roles = ('st');
14622:                         my @statuses = ('previous');
14623:                         my @roledoms = ($one);
14624:                         my $withsec = 1;
14625:                         my %roleshash = 
14626:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14627:                                               \@statuses,\@roles,\@roledoms,$withsec);
14628:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14629:                             my ($oldstart,$oldend) = 
14630:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14631:                             if ($oldend > 0 && $oldend <= $now) {
14632:                                 $expire_role_result = 'ok';
14633:                             }
14634:                         }
14635:                     }
14636:                 }
14637:                 $result = $expire_role_result;
14638:             }
14639:         }
14640:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14641:             $modify_section_result = 
14642:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14643:                                                            undef,undef,undef,$sec,
14644:                                                            $end,$start,'','',$cid,
14645:                                                            '',$context,$credits);
14646:             if ($modify_section_result =~ /^ok/) {
14647:                 if ($secchange == 1) {
14648:                     if ($sec eq '') {
14649:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14650:                     } else {
14651:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14652:                     }
14653:                 } elsif ($oldsec eq '-1') {
14654:                     if ($sec eq '') {
14655:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14656:                     } else {
14657:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14658:                     }
14659:                 } else {
14660:                     if ($sec eq '') {
14661:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14662:                     } else {
14663:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14664:                     }
14665:                 }
14666:             } else {
14667:                 if ($secchange) { 
14668:                     $$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;
14669:                 } else {
14670:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14671:                 }
14672:             }
14673:             $result = $modify_section_result;
14674:         } elsif ($secchange == 1) {
14675:             if ($oldsec eq '') {
14676:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14677:             } else {
14678:                 $$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;
14679:             }
14680:             if ($expire_role_result eq 'refused') {
14681:                 my $newsecurl = '/'.$cid;
14682:                 $newsecurl =~ s/\_/\//g;
14683:                 if ($sec ne '') {
14684:                     $newsecurl.='/'.$sec;
14685:                 }
14686:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14687:                     if ($sec eq '') {
14688:                         $$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;
14689:                     } else {
14690:                         $$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;
14691:                     }
14692:                 }
14693:             }
14694:         }
14695:     } else {
14696:         $$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;
14697:         $result = "error: incomplete course id\n";
14698:     }
14699:     return $result;
14700: }
14701: 
14702: sub show_role_extent {
14703:     my ($scope,$context,$role) = @_;
14704:     $scope =~ s{^/}{};
14705:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14706:     push(@courseroles,'co');
14707:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14708:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14709:         $scope =~ s{/}{_};
14710:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14711:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14712:         my ($audom,$auname) = split(/\//,$scope);
14713:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14714:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14715:     } else {
14716:         $scope =~ s{/$}{};
14717:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14718:                    &Apache::lonnet::domain($scope,'description').'</span>');
14719:     }
14720: }
14721: 
14722: ############################################################
14723: ############################################################
14724: 
14725: sub check_clone {
14726:     my ($args,$linefeed) = @_;
14727:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14728:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14729:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14730:     my $clonemsg;
14731:     my $can_clone = 0;
14732:     my $lctype = lc($args->{'crstype'});
14733:     if ($lctype ne 'community') {
14734:         $lctype = 'course';
14735:     }
14736:     if ($clonehome eq 'no_host') {
14737:         if ($args->{'crstype'} eq 'Community') {
14738:             $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'});
14739:         } else {
14740:             $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'});
14741:         }     
14742:     } else {
14743: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14744:         if ($args->{'crstype'} eq 'Community') {
14745:             if ($clonedesc{'type'} ne 'Community') {
14746:                  $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'});
14747:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14748:             }
14749:         }
14750: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14751:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14752: 	    $can_clone = 1;
14753: 	} else {
14754: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14755: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14756:             if ($clonehash{'cloners'} eq '') {
14757:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14758:                 if ($domdefs{'canclone'}) {
14759:                     unless ($domdefs{'canclone'} eq 'none') {
14760:                         if ($domdefs{'canclone'} eq 'domain') {
14761:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14762:                                 $can_clone = 1;
14763:                             }
14764:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
14765:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14766:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14767:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14768:                                 $can_clone = 1;
14769:                             }
14770:                         }
14771:                     }
14772:                 }
14773:             } else {
14774: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14775:                 if (grep(/^\*$/,@cloners)) {
14776:                     $can_clone = 1;
14777:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14778:                     $can_clone = 1;
14779:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14780:                     $can_clone = 1;
14781:                 }
14782:                 unless ($can_clone) {
14783:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
14784:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14785:                         my (%gotdomdefaults,%gotcodedefaults);
14786:                         foreach my $cloner (@cloners) {
14787:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14788:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14789:                                 my (%codedefaults,@code_order);
14790:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14791:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14792:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14793:                                     }
14794:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14795:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14796:                                     }
14797:                                 } else {
14798:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14799:                                                                             \%codedefaults,
14800:                                                                             \@code_order);
14801:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14802:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14803:                                 }
14804:                                 if (@code_order > 0) {
14805:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14806:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14807:                                                                                 $args->{'crscode'})) {
14808:                                         $can_clone = 1;
14809:                                         last;
14810:                                     }
14811:                                 }
14812:                             }
14813:                         }
14814:                     }
14815:                 }
14816:             }
14817:             unless ($can_clone) {
14818:                 my $ccrole = 'cc';
14819:                 if ($args->{'crstype'} eq 'Community') {
14820:                     $ccrole = 'co';
14821:                 }
14822: 	        my %roleshash =
14823: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
14824: 					          $args->{'ccdomain'},
14825:                                                   'userroles',['active'],[$ccrole],
14826: 					          [$args->{'clonedomain'}]);
14827: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14828:                     $can_clone = 1;
14829:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14830:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14831:                     $can_clone = 1;
14832:                 }
14833:             }
14834:             unless ($can_clone) {
14835:                 if ($args->{'crstype'} eq 'Community') {
14836:                     $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'});
14837:                 } else {
14838:                     $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'});
14839:                 }
14840: 	    }
14841:         }
14842:     }
14843:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14844: }
14845: 
14846: sub construct_course {
14847:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14848:     my $outcome;
14849:     my $linefeed =  '<br />'."\n";
14850:     if ($context eq 'auto') {
14851:         $linefeed = "\n";
14852:     }
14853: 
14854: #
14855: # Are we cloning?
14856: #
14857:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14858:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14859: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14860: 	if ($context ne 'auto') {
14861:             if ($clonemsg ne '') {
14862: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14863:             }
14864: 	}
14865: 	$outcome .= $clonemsg.$linefeed;
14866: 
14867:         if (!$can_clone) {
14868: 	    return (0,$outcome);
14869: 	}
14870:     }
14871: 
14872: #
14873: # Open course
14874: #
14875:     my $showncrstype;
14876:     if ($args->{'crstype'} eq 'Placement') {
14877:         $showncrstype = 'placement test'; 
14878:     } else {  
14879:         $showncrstype = lc($args->{'crstype'});
14880:     }
14881:     my %cenv=();
14882:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14883:                                              $args->{'cdescr'},
14884:                                              $args->{'curl'},
14885:                                              $args->{'course_home'},
14886:                                              $args->{'nonstandard'},
14887:                                              $args->{'crscode'},
14888:                                              $args->{'ccuname'}.':'.
14889:                                              $args->{'ccdomain'},
14890:                                              $args->{'crstype'},
14891:                                              $cnum,$context,$category);
14892: 
14893:     # Note: The testing routines depend on this being output; see 
14894:     # Utils::Course. This needs to at least be output as a comment
14895:     # if anyone ever decides to not show this, and Utils::Course::new
14896:     # will need to be suitably modified.
14897:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
14898:     if ($$courseid =~ /^error:/) {
14899:         return (0,$outcome);
14900:     }
14901: 
14902: #
14903: # Check if created correctly
14904: #
14905:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14906:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14907:     if ($crsuhome eq 'no_host') {
14908:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14909:         return (0,$outcome);
14910:     }
14911:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14912: 
14913: #
14914: # Do the cloning
14915: #   
14916:     if ($can_clone && $cloneid) {
14917: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
14918: 	if ($context ne 'auto') {
14919: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14920: 	}
14921: 	$outcome .= $clonemsg.$linefeed;
14922: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14923: # Copy all files
14924: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14925: # Restore URL
14926: 	$cenv{'url'}=$oldcenv{'url'};
14927: # Restore title
14928: 	$cenv{'description'}=$oldcenv{'description'};
14929: # Restore creation date, creator and creation context.
14930:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14931:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14932:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14933: # Mark as cloned
14934: 	$cenv{'clonedfrom'}=$cloneid;
14935: # Need to clone grading mode
14936:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14937:         $cenv{'grading'}=$newenv{'grading'};
14938: # Do not clone these environment entries
14939:         &Apache::lonnet::del('environment',
14940:                   ['default_enrollment_start_date',
14941:                    'default_enrollment_end_date',
14942:                    'question.email',
14943:                    'policy.email',
14944:                    'comment.email',
14945:                    'pch.users.denied',
14946:                    'plc.users.denied',
14947:                    'hidefromcat',
14948:                    'checkforpriv',
14949:                    'categories',
14950:                    'internal.uniquecode'],
14951:                    $$crsudom,$$crsunum);
14952:         if ($args->{'textbook'}) {
14953:             $cenv{'internal.textbook'} = $args->{'textbook'};
14954:         }
14955:     }
14956: 
14957: #
14958: # Set environment (will override cloned, if existing)
14959: #
14960:     my @sections = ();
14961:     my @xlists = ();
14962:     if ($args->{'crstype'}) {
14963:         $cenv{'type'}=$args->{'crstype'};
14964:     }
14965:     if ($args->{'crsid'}) {
14966:         $cenv{'courseid'}=$args->{'crsid'};
14967:     }
14968:     if ($args->{'crscode'}) {
14969:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14970:     }
14971:     if ($args->{'crsquota'} ne '') {
14972:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14973:     } else {
14974:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14975:     }
14976:     if ($args->{'ccuname'}) {
14977:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14978:                                         ':'.$args->{'ccdomain'};
14979:     } else {
14980:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14981:     }
14982:     if ($args->{'defaultcredits'}) {
14983:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14984:     }
14985:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14986:     if ($args->{'crssections'}) {
14987:         $cenv{'internal.sectionnums'} = '';
14988:         if ($args->{'crssections'} =~ m/,/) {
14989:             @sections = split/,/,$args->{'crssections'};
14990:         } else {
14991:             $sections[0] = $args->{'crssections'};
14992:         }
14993:         if (@sections > 0) {
14994:             foreach my $item (@sections) {
14995:                 my ($sec,$gp) = split/:/,$item;
14996:                 my $class = $args->{'crscode'}.$sec;
14997:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14998:                 $cenv{'internal.sectionnums'} .= $item.',';
14999:                 unless ($addcheck eq 'ok') {
15000:                     push @badclasses, $class;
15001:                 }
15002:             }
15003:             $cenv{'internal.sectionnums'} =~ s/,$//;
15004:         }
15005:     }
15006: # do not hide course coordinator from staff listing, 
15007: # even if privileged
15008:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15009: # add course coordinator's domain to domains to check for privileged users
15010: # if different to course domain
15011:     if ($$crsudom ne $args->{'ccdomain'}) {
15012:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15013:     }
15014: # add crosslistings
15015:     if ($args->{'crsxlist'}) {
15016:         $cenv{'internal.crosslistings'}='';
15017:         if ($args->{'crsxlist'} =~ m/,/) {
15018:             @xlists = split/,/,$args->{'crsxlist'};
15019:         } else {
15020:             $xlists[0] = $args->{'crsxlist'};
15021:         }
15022:         if (@xlists > 0) {
15023:             foreach my $item (@xlists) {
15024:                 my ($xl,$gp) = split/:/,$item;
15025:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15026:                 $cenv{'internal.crosslistings'} .= $item.',';
15027:                 unless ($addcheck eq 'ok') {
15028:                     push @badclasses, $xl;
15029:                 }
15030:             }
15031:             $cenv{'internal.crosslistings'} =~ s/,$//;
15032:         }
15033:     }
15034:     if ($args->{'autoadds'}) {
15035:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15036:     }
15037:     if ($args->{'autodrops'}) {
15038:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15039:     }
15040: # check for notification of enrollment changes
15041:     my @notified = ();
15042:     if ($args->{'notify_owner'}) {
15043:         if ($args->{'ccuname'} ne '') {
15044:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15045:         }
15046:     }
15047:     if ($args->{'notify_dc'}) {
15048:         if ($uname ne '') { 
15049:             push(@notified,$uname.':'.$udom);
15050:         }
15051:     }
15052:     if (@notified > 0) {
15053:         my $notifylist;
15054:         if (@notified > 1) {
15055:             $notifylist = join(',',@notified);
15056:         } else {
15057:             $notifylist = $notified[0];
15058:         }
15059:         $cenv{'internal.notifylist'} = $notifylist;
15060:     }
15061:     if (@badclasses > 0) {
15062:         my %lt=&Apache::lonlocal::texthash(
15063:                 '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',
15064:                 'dnhr' => 'does not have rights to access enrollment in these classes',
15065:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
15066:         );
15067:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
15068:                            ' ('.$lt{'adby'}.')';
15069:         if ($context eq 'auto') {
15070:             $outcome .= $badclass_msg.$linefeed;
15071:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15072:             foreach my $item (@badclasses) {
15073:                 if ($context eq 'auto') {
15074:                     $outcome .= " - $item\n";
15075:                 } else {
15076:                     $outcome .= "<li>$item</li>\n";
15077:                 }
15078:             }
15079:             if ($context eq 'auto') {
15080:                 $outcome .= $linefeed;
15081:             } else {
15082:                 $outcome .= "</ul><br /><br /></div>\n";
15083:             }
15084:         } 
15085:     }
15086:     if ($args->{'no_end_date'}) {
15087:         $args->{'endaccess'} = 0;
15088:     }
15089:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15090:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15091:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15092:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15093:     if ($args->{'showphotos'}) {
15094:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15095:     }
15096:     $cenv{'internal.authtype'} = $args->{'authtype'};
15097:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15098:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15099:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15100:             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'); 
15101:             if ($context eq 'auto') {
15102:                 $outcome .= $krb_msg;
15103:             } else {
15104:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15105:             }
15106:             $outcome .= $linefeed;
15107:         }
15108:     }
15109:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15110:        if ($args->{'setpolicy'}) {
15111:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15112:        }
15113:        if ($args->{'setcontent'}) {
15114:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15115:        }
15116:     }
15117:     if ($args->{'reshome'}) {
15118: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15119: 	$cenv{'reshome'}=~s/\/+$/\//;
15120:     }
15121: #
15122: # course has keyed access
15123: #
15124:     if ($args->{'setkeys'}) {
15125:        $cenv{'keyaccess'}='yes';
15126:     }
15127: # if specified, key authority is not course, but user
15128: # only active if keyaccess is yes
15129:     if ($args->{'keyauth'}) {
15130: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15131: 	$user = &LONCAPA::clean_username($user);
15132: 	$domain = &LONCAPA::clean_username($domain);
15133: 	if ($user ne '' && $domain ne '') {
15134: 	    $cenv{'keyauth'}=$user.':'.$domain;
15135: 	}
15136:     }
15137: 
15138: #
15139: #  generate and store uniquecode (available to course requester), if course should have one.
15140: #
15141:     if ($args->{'uniquecode'}) {
15142:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15143:         if ($code) {
15144:             $cenv{'internal.uniquecode'} = $code;
15145:             my %crsinfo =
15146:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15147:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15148:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15149:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15150:             } 
15151:             if (ref($coderef)) {
15152:                 $$coderef = $code;
15153:             }
15154:         }
15155:     }
15156: 
15157:     if ($args->{'disresdis'}) {
15158:         $cenv{'pch.roles.denied'}='st';
15159:     }
15160:     if ($args->{'disablechat'}) {
15161:         $cenv{'plc.roles.denied'}='st';
15162:     }
15163: 
15164:     # Record we've not yet viewed the Course Initialization Helper for this 
15165:     # course
15166:     $cenv{'course.helper.not.run'} = 1;
15167:     #
15168:     # Use new Randomseed
15169:     #
15170:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15171:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15172:     #
15173:     # The encryption code and receipt prefix for this course
15174:     #
15175:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15176:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15177:     #
15178:     # By default, use standard grading
15179:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15180: 
15181:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15182:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15183: #
15184: # Open all assignments
15185: #
15186:     if ($args->{'openall'}) {
15187:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15188:        my %storecontent = ($storeunder         => time,
15189:                            $storeunder.'.type' => 'date_start');
15190:        
15191:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15192:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15193:    }
15194: #
15195: # Set first page
15196: #
15197:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15198: 	    || ($cloneid)) {
15199: 	use LONCAPA::map;
15200: 	$outcome .= &mt('Setting first resource').': ';
15201: 
15202: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15203:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15204: 
15205:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15206:         my $title; my $url;
15207:         if ($args->{'firstres'} eq 'syl') {
15208: 	    $title=&mt('Syllabus');
15209:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15210:         } else {
15211:             $title=&mt('Table of Contents');
15212:             $url='/adm/navmaps';
15213:         }
15214: 
15215:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15216: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15217: 
15218: 	if ($errtext) { $fatal=2; }
15219:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15220:     }
15221: 
15222: # 
15223: # Set params for Placement Tests
15224: #
15225:     if ($args->{'crstype'} eq 'Placement') {
15226:        my %storecontent; 
15227:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
15228:        my %defaults = (
15229:                         buttonshide   => { value => 'yes',
15230:                                            type => 'string_yesno',},
15231:                         type          => { value => 'randomizetry',
15232:                                            type  => 'string_questiontype',},
15233:                         maxtries      => { value => 1,
15234:                                            type => 'int_pos',},
15235:                         problemstatus => { value => 'no',
15236:                                            type  => 'string_problemstatus',},
15237:                       );
15238:        foreach my $key (keys(%defaults)) {
15239:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
15240:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
15241:        }
15242:        &Apache::lonnet::cput
15243:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
15244:     }
15245: 
15246:     return (1,$outcome);
15247: }
15248: 
15249: sub make_unique_code {
15250:     my ($cdom,$cnum) = @_;
15251:     # get lock on uniquecodes db
15252:     my $lockhash = {
15253:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15254:                                                   ':'.$env{'user.domain'},
15255:                    };
15256:     my $tries = 0;
15257:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15258:     my ($code,$error);
15259:   
15260:     while (($gotlock ne 'ok') && ($tries<3)) {
15261:         $tries ++;
15262:         sleep 1;
15263:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15264:     }
15265:     if ($gotlock eq 'ok') {
15266:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15267:         my $gotcode;
15268:         my $attempts = 0;
15269:         while ((!$gotcode) && ($attempts < 100)) {
15270:             $code = &generate_code();
15271:             if (!exists($currcodes{$code})) {
15272:                 $gotcode = 1;
15273:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15274:                     $error = 'nostore';
15275:                 }
15276:             }
15277:             $attempts ++;
15278:         }
15279:         my @del_lock = ($cnum."\0".'uniquecodes');
15280:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15281:     } else {
15282:         $error = 'nolock';
15283:     }
15284:     return ($code,$error);
15285: }
15286: 
15287: sub generate_code {
15288:     my $code;
15289:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15290:     for (my $i=0; $i<6; $i++) {
15291:         my $lettnum = int (rand 2);
15292:         my $item = '';
15293:         if ($lettnum) {
15294:             $item = $letts[int( rand(18) )];
15295:         } else {
15296:             $item = 1+int( rand(8) );
15297:         }
15298:         $code .= $item;
15299:     }
15300:     return $code;
15301: }
15302: 
15303: ############################################################
15304: ############################################################
15305: 
15306: # Community, Course and Placement Test
15307: sub course_type {
15308:     my ($cid) = @_;
15309:     if (!defined($cid)) {
15310:         $cid = $env{'request.course.id'};
15311:     }
15312:     if (defined($env{'course.'.$cid.'.type'})) {
15313:         return $env{'course.'.$cid.'.type'};
15314:     } else {
15315:         return 'Course';
15316:     }
15317: }
15318: 
15319: sub group_term {
15320:     my $crstype = &course_type();
15321:     my %names = (
15322:                   'Course' => 'group',
15323:                   'Community' => 'group',
15324:                   'Placement' => 'group',
15325:                 );
15326:     return $names{$crstype};
15327: }
15328: 
15329: sub course_types {
15330:     my @types = ('official','unofficial','community','textbook','placement');
15331:     my %typename = (
15332:                          official   => 'Official course',
15333:                          unofficial => 'Unofficial course',
15334:                          community  => 'Community',
15335:                          textbook   => 'Textbook course',
15336:                          placement  => 'Placement test',
15337:                    );
15338:     return (\@types,\%typename);
15339: }
15340: 
15341: sub icon {
15342:     my ($file)=@_;
15343:     my $curfext = lc((split(/\./,$file))[-1]);
15344:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15345:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15346:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15347: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15348: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15349: 	            $curfext.".gif") {
15350: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15351: 		$curfext.".gif";
15352: 	}
15353:     }
15354:     return &lonhttpdurl($iconname);
15355: } 
15356: 
15357: sub lonhttpdurl {
15358: #
15359: # Had been used for "small fry" static images on separate port 8080.
15360: # Modify here if lightweight http functionality desired again.
15361: # Currently eliminated due to increasing firewall issues.
15362: #
15363:     my ($url)=@_;
15364:     return $url;
15365: }
15366: 
15367: sub connection_aborted {
15368:     my ($r)=@_;
15369:     $r->print(" ");$r->rflush();
15370:     my $c = $r->connection;
15371:     return $c->aborted();
15372: }
15373: 
15374: #    Escapes strings that may have embedded 's that will be put into
15375: #    strings as 'strings'.
15376: sub escape_single {
15377:     my ($input) = @_;
15378:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15379:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15380:     return $input;
15381: }
15382: 
15383: #  Same as escape_single, but escape's "'s  This 
15384: #  can be used for  "strings"
15385: sub escape_double {
15386:     my ($input) = @_;
15387:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15388:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15389:     return $input;
15390: }
15391:  
15392: #   Escapes the last element of a full URL.
15393: sub escape_url {
15394:     my ($url)   = @_;
15395:     my @urlslices = split(/\//, $url,-1);
15396:     my $lastitem = &escape(pop(@urlslices));
15397:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15398: }
15399: 
15400: sub compare_arrays {
15401:     my ($arrayref1,$arrayref2) = @_;
15402:     my (@difference,%count);
15403:     @difference = ();
15404:     %count = ();
15405:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15406:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15407:         foreach my $element (keys(%count)) {
15408:             if ($count{$element} == 1) {
15409:                 push(@difference,$element);
15410:             }
15411:         }
15412:     }
15413:     return @difference;
15414: }
15415: 
15416: # -------------------------------------------------------- Initialize user login
15417: sub init_user_environment {
15418:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15419:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15420: 
15421:     my $public=($username eq 'public' && $domain eq 'public');
15422: 
15423: # See if old ID present, if so, remove
15424: 
15425:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15426:     my $now=time;
15427: 
15428:     if ($public) {
15429: 	my $max_public=100;
15430: 	my $oldest;
15431: 	my $oldest_time=0;
15432: 	for(my $next=1;$next<=$max_public;$next++) {
15433: 	    if (-e $lonids."/publicuser_$next.id") {
15434: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15435: 		if ($mtime<$oldest_time || !$oldest_time) {
15436: 		    $oldest_time=$mtime;
15437: 		    $oldest=$next;
15438: 		}
15439: 	    } else {
15440: 		$cookie="publicuser_$next";
15441: 		last;
15442: 	    }
15443: 	}
15444: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15445:     } else {
15446: 	# if this isn't a robot, kill any existing non-robot sessions
15447: 	if (!$args->{'robot'}) {
15448: 	    opendir(DIR,$lonids);
15449: 	    while ($filename=readdir(DIR)) {
15450: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15451: 		    unlink($lonids.'/'.$filename);
15452: 		}
15453: 	    }
15454: 	    closedir(DIR);
15455: # If there is a undeleted lockfile for the user's paste buffer remove it.
15456:             my $namespace = 'nohist_courseeditor';
15457:             my $lockingkey = 'paste'."\0".'locked_num';
15458:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15459:                                                 $domain,$username);
15460:             if (exists($lockhash{$lockingkey})) {
15461:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15462:                 unless ($delresult eq 'ok') {
15463:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15464:                 }
15465:             }
15466: 	}
15467: # Give them a new cookie
15468: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15469: 		                   : $now.$$.int(rand(10000)));
15470: 	$cookie="$username\_$id\_$domain\_$authhost";
15471:     
15472: # Initialize roles
15473: 
15474: 	($userroles,$firstaccenv,$timerintenv) = 
15475:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15476:     }
15477: # ------------------------------------ Check browser type and MathML capability
15478: 
15479:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15480:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15481: 
15482: # ------------------------------------------------------------- Get environment
15483: 
15484:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15485:     my ($tmp) = keys(%userenv);
15486:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15487:     } else {
15488: 	undef(%userenv);
15489:     }
15490:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15491: 	$form->{'interface'}=$userenv{'interface'};
15492:     }
15493:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15494: 
15495: # --------------- Do not trust query string to be put directly into environment
15496:     foreach my $option ('interface','localpath','localres') {
15497:         $form->{$option}=~s/[\n\r\=]//gs;
15498:     }
15499: # --------------------------------------------------------- Write first profile
15500: 
15501:     {
15502: 	my %initial_env = 
15503: 	    ("user.name"          => $username,
15504: 	     "user.domain"        => $domain,
15505: 	     "user.home"          => $authhost,
15506: 	     "browser.type"       => $clientbrowser,
15507: 	     "browser.version"    => $clientversion,
15508: 	     "browser.mathml"     => $clientmathml,
15509: 	     "browser.unicode"    => $clientunicode,
15510: 	     "browser.os"         => $clientos,
15511:              "browser.mobile"     => $clientmobile,
15512:              "browser.info"       => $clientinfo,
15513:              "browser.osversion"  => $clientosversion,
15514: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15515: 	     "request.course.fn"  => '',
15516: 	     "request.course.uri" => '',
15517: 	     "request.course.sec" => '',
15518: 	     "request.role"       => 'cm',
15519: 	     "request.role.adv"   => $env{'user.adv'},
15520: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15521: 
15522:         if ($form->{'localpath'}) {
15523: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15524: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15525:         }
15526: 	
15527: 	if ($form->{'interface'}) {
15528: 	    $form->{'interface'}=~s/\W//gs;
15529: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15530: 	    $env{'browser.interface'}=$form->{'interface'};
15531: 	}
15532: 
15533:         if ($form->{'iptoken'}) {
15534:             my $lonhost = $r->dir_config('lonHostID');
15535:             $initial_env{"user.noloadbalance"} = $lonhost;
15536:             $env{'user.noloadbalance'} = $lonhost;
15537:         }
15538: 
15539:         my %is_adv = ( is_adv => $env{'user.adv'} );
15540:         my %domdef;
15541:         unless ($domain eq 'public') {
15542:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
15543:         }
15544: 
15545:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
15546:             $userenv{'availabletools.'.$tool} = 
15547:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15548:                                                   undef,\%userenv,\%domdef,\%is_adv);
15549:         }
15550: 
15551:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
15552:             $userenv{'canrequest.'.$crstype} =
15553:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
15554:                                                   'reload','requestcourses',
15555:                                                   \%userenv,\%domdef,\%is_adv);
15556:         }
15557: 
15558:         $userenv{'canrequest.author'} =
15559:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15560:                                         'reload','requestauthor',
15561:                                         \%userenv,\%domdef,\%is_adv);
15562:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15563:                                              $domain,$username);
15564:         my $reqstatus = $reqauthor{'author_status'};
15565:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
15566:             if (ref($reqauthor{'author'}) eq 'HASH') {
15567:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15568:                                                   $reqauthor{'author'}{'timestamp'};
15569:             }
15570:         }
15571: 
15572: 	$env{'user.environment'} = "$lonids/$cookie.id";
15573: 
15574: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15575: 		 &GDBM_WRCREAT(),0640)) {
15576: 	    &_add_to_env(\%disk_env,\%initial_env);
15577: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15578: 	    &_add_to_env(\%disk_env,$userroles);
15579:             if (ref($firstaccenv) eq 'HASH') {
15580:                 &_add_to_env(\%disk_env,$firstaccenv);
15581:             }
15582:             if (ref($timerintenv) eq 'HASH') {
15583:                 &_add_to_env(\%disk_env,$timerintenv);
15584:             }
15585: 	    if (ref($args->{'extra_env'})) {
15586: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15587: 	    }
15588: 	    untie(%disk_env);
15589: 	} else {
15590: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15591: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15592: 	    return 'error: '.$!;
15593: 	}
15594:     }
15595:     $env{'request.role'}='cm';
15596:     $env{'request.role.adv'}=$env{'user.adv'};
15597:     $env{'browser.type'}=$clientbrowser;
15598: 
15599:     return $cookie;
15600: 
15601: }
15602: 
15603: sub _add_to_env {
15604:     my ($idf,$env_data,$prefix) = @_;
15605:     if (ref($env_data) eq 'HASH') {
15606:         while (my ($key,$value) = each(%$env_data)) {
15607: 	    $idf->{$prefix.$key} = $value;
15608: 	    $env{$prefix.$key}   = $value;
15609:         }
15610:     }
15611: }
15612: 
15613: # --- Get the symbolic name of a problem and the url
15614: sub get_symb {
15615:     my ($request,$silent) = @_;
15616:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15617:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15618:     if ($symb eq '') {
15619:         if (!$silent) {
15620:             if (ref($request)) { 
15621:                 $request->print("Unable to handle ambiguous references:$url:.");
15622:             }
15623:             return ();
15624:         }
15625:     }
15626:     &Apache::lonenc::check_decrypt(\$symb);
15627:     return ($symb);
15628: }
15629: 
15630: # --------------------------------------------------------------Get annotation
15631: 
15632: sub get_annotation {
15633:     my ($symb,$enc) = @_;
15634: 
15635:     my $key = $symb;
15636:     if (!$enc) {
15637:         $key =
15638:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15639:     }
15640:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15641:     return $annotation{$key};
15642: }
15643: 
15644: sub clean_symb {
15645:     my ($symb,$delete_enc) = @_;
15646: 
15647:     &Apache::lonenc::check_decrypt(\$symb);
15648:     my $enc = $env{'request.enc'};
15649:     if ($delete_enc) {
15650:         delete($env{'request.enc'});
15651:     }
15652: 
15653:     return ($symb,$enc);
15654: }
15655: 
15656: ############################################################
15657: ############################################################
15658: 
15659: =pod
15660: 
15661: =head1 Routines for building display used to search for courses
15662: 
15663: 
15664: =over 4
15665: 
15666: =item * &build_filters()
15667: 
15668: Create markup for a table used to set filters to use when selecting
15669: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15670: and quotacheck.pl
15671: 
15672: 
15673: Inputs:
15674: 
15675: filterlist - anonymous array of fields to include as potential filters 
15676: 
15677: crstype - course type
15678: 
15679: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15680:               to pop-open a course selector (will contain "extra element"). 
15681: 
15682: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15683: 
15684: filter - anonymous hash of criteria and their values
15685: 
15686: action - form action
15687: 
15688: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15689: 
15690: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15691: 
15692: cloneruname - username of owner of new course who wants to clone
15693: 
15694: clonerudom - domain of owner of new course who wants to clone
15695: 
15696: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
15697: 
15698: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15699: 
15700: codedom - domain
15701: 
15702: formname - value of form element named "form". 
15703: 
15704: fixeddom - domain, if fixed.
15705: 
15706: prevphase - value to assign to form element named "phase" when going back to the previous screen  
15707: 
15708: cnameelement - name of form element in form on opener page which will receive title of selected course 
15709: 
15710: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15711: 
15712: cdomelement - name of form element in form on opener page which will receive domain of selected course
15713: 
15714: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15715: 
15716: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15717: 
15718: clonewarning - warning message about missing information for intended course owner when DC creates a course
15719: 
15720: 
15721: Returns: $output - HTML for display of search criteria, and hidden form elements.
15722: 
15723: 
15724: Side Effects: None
15725: 
15726: =cut
15727: 
15728: # ---------------------------------------------- search for courses based on last activity etc.
15729: 
15730: sub build_filters {
15731:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15732:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15733:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15734:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15735:         $clonetext,$clonewarning) = @_;
15736:     my ($list,$jscript);
15737:     my $onchange = 'javascript:updateFilters(this)';
15738:     my ($domainselectform,$sincefilterform,$createdfilterform,
15739:         $ownerdomselectform,$persondomselectform,$instcodeform,
15740:         $typeselectform,$instcodetitle);
15741:     if ($formname eq '') {
15742:         $formname = $caller;
15743:     }
15744:     foreach my $item (@{$filterlist}) {
15745:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15746:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15747:             if ($item eq 'domainfilter') {
15748:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15749:             } elsif ($item eq 'coursefilter') {
15750:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15751:             } elsif ($item eq 'ownerfilter') {
15752:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15753:             } elsif ($item eq 'ownerdomfilter') {
15754:                 $filter->{'ownerdomfilter'} =
15755:                     &LONCAPA::clean_domain($filter->{$item});
15756:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15757:                                                        'ownerdomfilter',1);
15758:             } elsif ($item eq 'personfilter') {
15759:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15760:             } elsif ($item eq 'persondomfilter') {
15761:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15762:                                                         'persondomfilter',1);
15763:             } else {
15764:                 $filter->{$item} =~ s/\W//g;
15765:             }
15766:             if (!$filter->{$item}) {
15767:                 $filter->{$item} = '';
15768:             }
15769:         }
15770:         if ($item eq 'domainfilter') {
15771:             my $allow_blank = 1;
15772:             if ($formname eq 'portform') {
15773:                 $allow_blank=0;
15774:             } elsif ($formname eq 'studentform') {
15775:                 $allow_blank=0;
15776:             }
15777:             if ($fixeddom) {
15778:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15779:                                     ' value="'.$codedom.'" />'.
15780:                                     &Apache::lonnet::domain($codedom,'description');
15781:             } else {
15782:                 $domainselectform = &select_dom_form($filter->{$item},
15783:                                                      'domainfilter',
15784:                                                       $allow_blank,'',$onchange);
15785:             }
15786:         } else {
15787:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15788:         }
15789:     }
15790: 
15791:     # last course activity filter and selection
15792:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15793: 
15794:     # course created filter and selection
15795:     if (exists($filter->{'createdfilter'})) {
15796:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15797:     }
15798: 
15799:     my $prefix = $crstype;
15800:     if ($crstype eq 'Placement') {
15801:         $prefix = 'Placement Test'
15802:     }
15803:     my %lt = &Apache::lonlocal::texthash(
15804:                 'cac' => "$prefix Activity",
15805:                 'ccr' => "$prefix Created",
15806:                 'cde' => "$prefix Title",
15807:                 'cdo' => "$prefix Domain",
15808:                 'ins' => 'Institutional Code',
15809:                 'inc' => 'Institutional Categorization',
15810:                 'cow' => "$prefix Owner/Co-owner",
15811:                 'cop' => "$prefix Personnel Includes",
15812:                 'cog' => 'Type',
15813:              );
15814: 
15815:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15816:         my $typeval = 'Course';
15817:         if ($crstype eq 'Community') {
15818:             $typeval = 'Community';
15819:         } elsif ($crstype eq 'Placement') {
15820:             $typeval = 'Placement';
15821:         }
15822:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15823:     } else {
15824:         $typeselectform =  '<select name="type" size="1"';
15825:         if ($onchange) {
15826:             $typeselectform .= ' onchange="'.$onchange.'"';
15827:         }
15828:         $typeselectform .= '>'."\n";
15829:         foreach my $posstype ('Course','Community','Placement') {
15830:             my $shown;
15831:             if ($posstype eq 'Placement') {
15832:                 $shown = &mt('Placement Test');
15833:             } else {
15834:                 $shown = &mt($posstype);
15835:             }
15836:             $typeselectform.='<option value="'.$posstype.'"'.
15837:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
15838:         }
15839:         $typeselectform.="</select>";
15840:     }
15841: 
15842:     my ($cloneableonlyform,$cloneabletitle);
15843:     if (exists($filter->{'cloneableonly'})) {
15844:         my $cloneableon = '';
15845:         my $cloneableoff = ' checked="checked"';
15846:         if ($filter->{'cloneableonly'}) {
15847:             $cloneableon = $cloneableoff;
15848:             $cloneableoff = '';
15849:         }
15850:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
15851:         if ($formname eq 'ccrs') {
15852:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15853:         } else {
15854:             $cloneabletitle = &mt('Cloneable by you');
15855:         }
15856:     }
15857:     my $officialjs;
15858:     if ($crstype eq 'Course') {
15859:         if (exists($filter->{'instcodefilter'})) {
15860: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15861: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15862:             if ($codedom) { 
15863:                 $officialjs = 1;
15864:                 ($instcodeform,$jscript,$$numtitlesref) =
15865:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15866:                                                                   $officialjs,$codetitlesref);
15867:                 if ($jscript) {
15868:                     $jscript = '<script type="text/javascript">'."\n".
15869:                                '// <![CDATA['."\n".
15870:                                $jscript."\n".
15871:                                '// ]]>'."\n".
15872:                                '</script>'."\n";
15873:                 }
15874:             }
15875:             if ($instcodeform eq '') {
15876:                 $instcodeform =
15877:                     '<input type="text" name="instcodefilter" size="10" value="'.
15878:                     $list->{'instcodefilter'}.'" />';
15879:                 $instcodetitle = $lt{'ins'};
15880:             } else {
15881:                 $instcodetitle = $lt{'inc'};
15882:             }
15883:             if ($fixeddom) {
15884:                 $instcodetitle .= '<br />('.$codedom.')';
15885:             }
15886:         }
15887:     }
15888:     my $output = qq|
15889: <form method="post" name="filterpicker" action="$action">
15890: <input type="hidden" name="form" value="$formname" />
15891: |;
15892:     if ($formname eq 'modifycourse') {
15893:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15894:                    '<input type="hidden" name="prevphase" value="'.
15895:                    $prevphase.'" />'."\n";
15896:     } elsif ($formname eq 'quotacheck') {
15897:         $output .= qq|
15898: <input type="hidden" name="sortby" value="" />
15899: <input type="hidden" name="sortorder" value="" />
15900: |;
15901:     } else {
15902:         my $name_input;
15903:         if ($cnameelement ne '') {
15904:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15905:                           $cnameelement.'" />';
15906:         }
15907:         $output .= qq|
15908: <input type="hidden" name="cnumelement" value="$cnumelement" />
15909: <input type="hidden" name="cdomelement" value="$cdomelement" />
15910: $name_input
15911: $roleelement
15912: $multelement
15913: $typeelement
15914: |;
15915:         if ($formname eq 'portform') {
15916:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15917:         }
15918:     }
15919:     if ($fixeddom) {
15920:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15921:     }
15922:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15923:     if ($sincefilterform) {
15924:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15925:                   .$sincefilterform
15926:                   .&Apache::lonhtmlcommon::row_closure();
15927:     }
15928:     if ($createdfilterform) {
15929:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15930:                   .$createdfilterform
15931:                   .&Apache::lonhtmlcommon::row_closure();
15932:     }
15933:     if ($domainselectform) {
15934:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15935:                   .$domainselectform
15936:                   .&Apache::lonhtmlcommon::row_closure();
15937:     }
15938:     if ($typeselectform) {
15939:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15940:             $output .= $typeselectform;
15941:         } else {
15942:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15943:                       .$typeselectform
15944:                       .&Apache::lonhtmlcommon::row_closure();
15945:         }
15946:     }
15947:     if ($instcodeform) {
15948:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15949:                   .$instcodeform
15950:                   .&Apache::lonhtmlcommon::row_closure();
15951:     }
15952:     if (exists($filter->{'ownerfilter'})) {
15953:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15954:                    '<table><tr><td>'.&mt('Username').'<br />'.
15955:                    '<input type="text" name="ownerfilter" size="20" value="'.
15956:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15957:                    $ownerdomselectform.'</td></tr></table>'.
15958:                    &Apache::lonhtmlcommon::row_closure();
15959:     }
15960:     if (exists($filter->{'personfilter'})) {
15961:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15962:                    '<table><tr><td>'.&mt('Username').'<br />'.
15963:                    '<input type="text" name="personfilter" size="20" value="'.
15964:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15965:                    $persondomselectform.'</td></tr></table>'.
15966:                    &Apache::lonhtmlcommon::row_closure();
15967:     }
15968:     if (exists($filter->{'coursefilter'})) {
15969:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15970:                   .'<input type="text" name="coursefilter" size="25" value="'
15971:                   .$list->{'coursefilter'}.'" />'
15972:                   .&Apache::lonhtmlcommon::row_closure();
15973:     }
15974:     if ($cloneableonlyform) {
15975:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15976:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15977:     }
15978:     if (exists($filter->{'descriptfilter'})) {
15979:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15980:                   .'<input type="text" name="descriptfilter" size="40" value="'
15981:                   .$list->{'descriptfilter'}.'" />'
15982:                   .&Apache::lonhtmlcommon::row_closure(1);
15983:     }
15984:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15985:                '<input type="hidden" name="updater" value="" />'."\n".
15986:                '<input type="submit" name="gosearch" value="'.
15987:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15988:     return $jscript.$clonewarning.$output;
15989: }
15990: 
15991: =pod 
15992: 
15993: =item * &timebased_select_form()
15994: 
15995: Create markup for a dropdown list used to select a time-based
15996: filter e.g., Course Activity, Course Created, when searching for courses
15997: or communities
15998: 
15999: Inputs:
16000: 
16001: item - name of form element (sincefilter or createdfilter)
16002: 
16003: filter - anonymous hash of criteria and their values
16004: 
16005: Returns: HTML for a select box contained a blank, then six time selections,
16006:          with value set in incoming form variables currently selected. 
16007: 
16008: Side Effects: None
16009: 
16010: =cut
16011: 
16012: sub timebased_select_form {
16013:     my ($item,$filter) = @_;
16014:     if (ref($filter) eq 'HASH') {
16015:         $filter->{$item} =~ s/[^\d-]//g;
16016:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16017:         return &select_form(
16018:                             $filter->{$item},
16019:                             $item,
16020:                             {      '-1' => '',
16021:                                 '86400' => &mt('today'),
16022:                                '604800' => &mt('last week'),
16023:                               '2592000' => &mt('last month'),
16024:                               '7776000' => &mt('last three months'),
16025:                              '15552000' => &mt('last six months'),
16026:                              '31104000' => &mt('last year'),
16027:                     'select_form_order' =>
16028:                            ['-1','86400','604800','2592000','7776000',
16029:                             '15552000','31104000']});
16030:     }
16031: }
16032: 
16033: =pod
16034: 
16035: =item * &js_changer()
16036: 
16037: Create script tag containing Javascript used to submit course search form
16038: when course type or domain is changed, and also to hide 'Searching ...' on
16039: page load completion for page showing search result.
16040: 
16041: Inputs: None
16042: 
16043: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
16044: 
16045: Side Effects: None
16046: 
16047: =cut
16048: 
16049: sub js_changer {
16050:     return <<ENDJS;
16051: <script type="text/javascript">
16052: // <![CDATA[
16053: function updateFilters(caller) {
16054:     if (typeof(caller) != "undefined") {
16055:         document.filterpicker.updater.value = caller.name;
16056:     }
16057:     document.filterpicker.submit();
16058: }
16059: 
16060: function hideSearching() {
16061:     if (document.getElementById('searching')) {
16062:         document.getElementById('searching').style.display = 'none';
16063:     }
16064:     return;
16065: }
16066: 
16067: // ]]>
16068: </script>
16069: 
16070: ENDJS
16071: }
16072: 
16073: =pod
16074: 
16075: =item * &search_courses()
16076: 
16077: Process selected filters form course search form and pass to lonnet::courseiddump
16078: to retrieve a hash for which keys are courseIDs which match the selected filters.
16079: 
16080: Inputs:
16081: 
16082: dom - domain being searched 
16083: 
16084: type - course type ('Course' or 'Community' or '.' if any).
16085: 
16086: filter - anonymous hash of criteria and their values
16087: 
16088: numtitles - for institutional codes - number of categories
16089: 
16090: cloneruname - optional username of new course owner
16091: 
16092: clonerudom - optional domain of new course owner
16093: 
16094: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16095:             (used when DC is using course creation form)
16096: 
16097: codetitles - reference to array of titles of components in institutional codes (official courses).
16098: 
16099: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16100:            (and so can clone automatically)
16101: 
16102: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16103: 
16104: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16105:               courses to clone 
16106: 
16107: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16108: 
16109: 
16110: Side Effects: None
16111: 
16112: =cut
16113: 
16114: 
16115: sub search_courses {
16116:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16117:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16118:     my (%courses,%showcourses,$cloner);
16119:     if (($filter->{'ownerfilter'} ne '') ||
16120:         ($filter->{'ownerdomfilter'} ne '')) {
16121:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16122:                                        $filter->{'ownerdomfilter'};
16123:     }
16124:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16125:         if (!$filter->{$item}) {
16126:             $filter->{$item}='.';
16127:         }
16128:     }
16129:     my $now = time;
16130:     my $timefilter =
16131:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16132:     my ($createdbefore,$createdafter);
16133:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16134:         $createdbefore = $now;
16135:         $createdafter = $now-$filter->{'createdfilter'};
16136:     }
16137:     my ($instcodefilter,$regexpok);
16138:     if ($numtitles) {
16139:         if ($env{'form.official'} eq 'on') {
16140:             $instcodefilter =
16141:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16142:             $regexpok = 1;
16143:         } elsif ($env{'form.official'} eq 'off') {
16144:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16145:             unless ($instcodefilter eq '') {
16146:                 $regexpok = -1;
16147:             }
16148:         }
16149:     } else {
16150:         $instcodefilter = $filter->{'instcodefilter'};
16151:     }
16152:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16153:     if ($type eq '') { $type = '.'; }
16154: 
16155:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16156:         $cloner = $cloneruname.':'.$clonerudom;
16157:     }
16158:     %courses = &Apache::lonnet::courseiddump($dom,
16159:                                              $filter->{'descriptfilter'},
16160:                                              $timefilter,
16161:                                              $instcodefilter,
16162:                                              $filter->{'combownerfilter'},
16163:                                              $filter->{'coursefilter'},
16164:                                              undef,undef,$type,$regexpok,undef,undef,
16165:                                              undef,undef,$cloner,$cc_clone,
16166:                                              $filter->{'cloneableonly'},
16167:                                              $createdbefore,$createdafter,undef,
16168:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16169:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16170:         my $ccrole;
16171:         if ($type eq 'Community') {
16172:             $ccrole = 'co';
16173:         } else {
16174:             $ccrole = 'cc';
16175:         }
16176:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16177:                                                      $filter->{'persondomfilter'},
16178:                                                      'userroles',undef,
16179:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16180:                                                      $dom);
16181:         foreach my $role (keys(%rolehash)) {
16182:             my ($cnum,$cdom,$courserole) = split(':',$role);
16183:             my $cid = $cdom.'_'.$cnum;
16184:             if (exists($courses{$cid})) {
16185:                 if (ref($courses{$cid}) eq 'HASH') {
16186:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16187:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16188:                             push (@{$courses{$cid}{roles}},$courserole);
16189:                         }
16190:                     } else {
16191:                         $courses{$cid}{roles} = [$courserole];
16192:                     }
16193:                     $showcourses{$cid} = $courses{$cid};
16194:                 }
16195:             }
16196:         }
16197:         %courses = %showcourses;
16198:     }
16199:     return %courses;
16200: }
16201: 
16202: =pod
16203: 
16204: =back
16205: 
16206: =head1 Routines for version requirements for current course.
16207: 
16208: =over 4
16209: 
16210: =item * &check_release_required()
16211: 
16212: Compares required LON-CAPA version with version on server, and
16213: if required version is newer looks for a server with the required version.
16214: 
16215: Looks first at servers in user's owen domain; if none suitable, looks at
16216: servers in course's domain are permitted to host sessions for user's domain.
16217: 
16218: Inputs:
16219: 
16220: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16221: 
16222: $courseid - Course ID of current course
16223: 
16224: $rolecode - User's current role in course (for switchserver query string).
16225: 
16226: $required - LON-CAPA version needed by course (format: Major.Minor).
16227: 
16228: 
16229: Returns:
16230: 
16231: $switchserver - query string tp append to /adm/switchserver call (if 
16232:                 current server's LON-CAPA version is too old. 
16233: 
16234: $warning - Message is displayed if no suitable server could be found.
16235: 
16236: =cut
16237: 
16238: sub check_release_required {
16239:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16240:     my ($switchserver,$warning);
16241:     if ($required ne '') {
16242:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16243:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16244:         if ($reqdmajor ne '' && $reqdminor ne '') {
16245:             my $otherserver;
16246:             if (($major eq '' && $minor eq '') ||
16247:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16248:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16249:                 my $switchlcrev =
16250:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16251:                                                            $userdomserver);
16252:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16253:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16254:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16255:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16256:                     if ($cdom ne $env{'user.domain'}) {
16257:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16258:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16259:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16260:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16261:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16262:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16263:                         my $canhost =
16264:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16265:                                                               $coursedomserver,
16266:                                                               $remoterev,
16267:                                                               $udomdefaults{'remotesessions'},
16268:                                                               $defdomdefaults{'hostedsessions'});
16269: 
16270:                         if ($canhost) {
16271:                             $otherserver = $coursedomserver;
16272:                         } else {
16273:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
16274:                         }
16275:                     } else {
16276:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
16277:                     }
16278:                 } else {
16279:                     $otherserver = $userdomserver;
16280:                 }
16281:             }
16282:             if ($otherserver ne '') {
16283:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16284:             }
16285:         }
16286:     }
16287:     return ($switchserver,$warning);
16288: }
16289: 
16290: =pod
16291: 
16292: =item * &check_release_result()
16293: 
16294: Inputs:
16295: 
16296: $switchwarning - Warning message if no suitable server found to host session.
16297: 
16298: $switchserver - query string to append to /adm/switchserver containing lonHostID
16299:                 and current role.
16300: 
16301: Returns: HTML to display with information about requirement to switch server.
16302:          Either displaying warning with link to Roles/Courses screen or
16303:          display link to switchserver.
16304: 
16305: =cut
16306: 
16307: sub check_release_result {
16308:     my ($switchwarning,$switchserver) = @_;
16309:     my $output = &start_page('Selected course unavailable on this server').
16310:                  '<p class="LC_warning">';
16311:     if ($switchwarning) {
16312:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16313:         if (&show_course()) {
16314:             $output .= &mt('Display courses');
16315:         } else {
16316:             $output .= &mt('Display roles');
16317:         }
16318:         $output .= '</a>';
16319:     } elsif ($switchserver) {
16320:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16321:                    '<br />'.
16322:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16323:                    &mt('Switch Server').
16324:                    '</a>';
16325:     }
16326:     $output .= '</p>'.&end_page();
16327:     return $output;
16328: }
16329: 
16330: =pod
16331: 
16332: =item * &needs_coursereinit()
16333: 
16334: Determine if course contents stored for user's session needs to be
16335: refreshed, because content has changed since "Big Hash" last tied.
16336: 
16337: Check for change is made if time last checked is more than 10 minutes ago
16338: (by default).
16339: 
16340: Inputs:
16341: 
16342: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16343: 
16344: $interval (optional) - Time which may elapse (in s) between last check for content
16345:                        change in current course. (default: 600 s).  
16346: 
16347: Returns: an array; first element is:
16348: 
16349: =over 4
16350: 
16351: 'switch' - if content updates mean user's session
16352:            needs to be switched to a server running a newer LON-CAPA version
16353:  
16354: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16355:            on current server hosting user's session                
16356: 
16357: ''       - if no action required.
16358: 
16359: =back
16360: 
16361: If first item element is 'switch':
16362: 
16363: second item is $switchwarning - Warning message if no suitable server found to host session. 
16364: 
16365: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16366:                               and current role. 
16367: 
16368: otherwise: no other elements returned.
16369: 
16370: =back
16371: 
16372: =cut
16373: 
16374: sub needs_coursereinit {
16375:     my ($loncaparev,$interval) = @_;
16376:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16377:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16378:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16379:     my $now = time;
16380:     if ($interval eq '') {
16381:         $interval = 600;
16382:     }
16383:     if (($now-$env{'request.course.timechecked'})>$interval) {
16384:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16385:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16386:         if ($lastchange > $env{'request.course.tied'}) {
16387:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16388:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16389:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16390:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16391:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16392:                                              $curr_reqd_hash{'internal.releaserequired'}});
16393:                     my ($switchserver,$switchwarning) =
16394:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16395:                                                 $curr_reqd_hash{'internal.releaserequired'});
16396:                     if ($switchwarning ne '' || $switchserver ne '') {
16397:                         return ('switch',$switchwarning,$switchserver);
16398:                     }
16399:                 }
16400:             }
16401:             return ('update');
16402:         }
16403:     }
16404:     return ();
16405: }
16406: 
16407: sub update_content_constraints {
16408:     my ($cdom,$cnum,$chome,$cid) = @_;
16409:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16410:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16411:     my %checkresponsetypes;
16412:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16413:         my ($item,$name,$value) = split(/:/,$key);
16414:         if ($item eq 'resourcetag') {
16415:             if ($name eq 'responsetype') {
16416:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16417:             }
16418:         }
16419:     }
16420:     my $navmap = Apache::lonnavmaps::navmap->new();
16421:     if (defined($navmap)) {
16422:         my %allresponses;
16423:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16424:             my %responses = $res->responseTypes();
16425:             foreach my $key (keys(%responses)) {
16426:                 next unless(exists($checkresponsetypes{$key}));
16427:                 $allresponses{$key} += $responses{$key};
16428:             }
16429:         }
16430:         foreach my $key (keys(%allresponses)) {
16431:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16432:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16433:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16434:             }
16435:         }
16436:         undef($navmap);
16437:     }
16438:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16439:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16440:     }
16441:     return;
16442: }
16443: 
16444: sub allmaps_incourse {
16445:     my ($cdom,$cnum,$chome,$cid) = @_;
16446:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16447:         $cid = $env{'request.course.id'};
16448:         $cdom = $env{'course.'.$cid.'.domain'};
16449:         $cnum = $env{'course.'.$cid.'.num'};
16450:         $chome = $env{'course.'.$cid.'.home'};
16451:     }
16452:     my %allmaps = ();
16453:     my $lastchange =
16454:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16455:     if ($lastchange > $env{'request.course.tied'}) {
16456:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16457:         unless ($ferr) {
16458:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16459:         }
16460:     }
16461:     my $navmap = Apache::lonnavmaps::navmap->new();
16462:     if (defined($navmap)) {
16463:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16464:             $allmaps{$res->src()} = 1;
16465:         }
16466:     }
16467:     return \%allmaps;
16468: }
16469: 
16470: sub parse_supplemental_title {
16471:     my ($title) = @_;
16472: 
16473:     my ($foldertitle,$renametitle);
16474:     if ($title =~ /&amp;&amp;&amp;/) {
16475:         $title = &HTML::Entites::decode($title);
16476:     }
16477:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16478:         $renametitle=$4;
16479:         my ($time,$uname,$udom) = ($1,$2,$3);
16480:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16481:         my $name =  &plainname($uname,$udom);
16482:         $name = &HTML::Entities::encode($name,'"<>&\'');
16483:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16484:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16485:             $name.': <br />'.$foldertitle;
16486:     }
16487:     if (wantarray) {
16488:         return ($title,$foldertitle,$renametitle);
16489:     }
16490:     return $title;
16491: }
16492: 
16493: sub recurse_supplemental {
16494:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16495:     if ($suppmap) {
16496:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16497:         if ($fatal) {
16498:             $errors ++;
16499:         } else {
16500:             if ($#LONCAPA::map::resources > 0) {
16501:                 foreach my $res (@LONCAPA::map::resources) {
16502:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16503:                     if (($src ne '') && ($status eq 'res')) {
16504:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16505:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16506:                         } else {
16507:                             $numfiles ++;
16508:                         }
16509:                     }
16510:                 }
16511:             }
16512:         }
16513:     }
16514:     return ($numfiles,$errors);
16515: }
16516: 
16517: sub symb_to_docspath {
16518:     my ($symb) = @_;
16519:     return unless ($symb);
16520:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16521:     if ($resurl=~/\.(sequence|page)$/) {
16522:         $mapurl=$resurl;
16523:     } elsif ($resurl eq 'adm/navmaps') {
16524:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16525:     }
16526:     my $mapresobj;
16527:     my $navmap = Apache::lonnavmaps::navmap->new();
16528:     if (ref($navmap)) {
16529:         $mapresobj = $navmap->getResourceByUrl($mapurl);
16530:     }
16531:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16532:     my $type=$2;
16533:     my $path;
16534:     if (ref($mapresobj)) {
16535:         my $pcslist = $mapresobj->map_hierarchy();
16536:         if ($pcslist ne '') {
16537:             foreach my $pc (split(/,/,$pcslist)) {
16538:                 next if ($pc <= 1);
16539:                 my $res = $navmap->getByMapPc($pc);
16540:                 if (ref($res)) {
16541:                     my $thisurl = $res->src();
16542:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16543:                     my $thistitle = $res->title();
16544:                     $path .= '&'.
16545:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16546:                              &escape($thistitle).
16547:                              ':'.$res->randompick().
16548:                              ':'.$res->randomout().
16549:                              ':'.$res->encrypted().
16550:                              ':'.$res->randomorder().
16551:                              ':'.$res->is_page();
16552:                 }
16553:             }
16554:         }
16555:         $path =~ s/^\&//;
16556:         my $maptitle = $mapresobj->title();
16557:         if ($mapurl eq 'default') {
16558:             $maptitle = 'Main Content';
16559:         }
16560:         $path .= (($path ne '')? '&' : '').
16561:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16562:                  &escape($maptitle).
16563:                  ':'.$mapresobj->randompick().
16564:                  ':'.$mapresobj->randomout().
16565:                  ':'.$mapresobj->encrypted().
16566:                  ':'.$mapresobj->randomorder().
16567:                  ':'.$mapresobj->is_page();
16568:     } else {
16569:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16570:         my $ispage = (($type eq 'page')? 1 : '');
16571:         if ($mapurl eq 'default') {
16572:             $maptitle = 'Main Content';
16573:         }
16574:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16575:                 &escape($maptitle).':::::'.$ispage;
16576:     }
16577:     unless ($mapurl eq 'default') {
16578:         $path = 'default&'.
16579:                 &escape('Main Content').
16580:                 ':::::&'.$path;
16581:     }
16582:     return $path;
16583: }
16584: 
16585: sub captcha_display {
16586:     my ($context,$lonhost) = @_;
16587:     my ($output,$error);
16588:     my ($captcha,$pubkey,$privkey,$version) = 
16589:         &get_captcha_config($context,$lonhost);
16590:     if ($captcha eq 'original') {
16591:         $output = &create_captcha();
16592:         unless ($output) {
16593:             $error = 'captcha';
16594:         }
16595:     } elsif ($captcha eq 'recaptcha') {
16596:         $output = &create_recaptcha($pubkey,$version);
16597:         unless ($output) {
16598:             $error = 'recaptcha';
16599:         }
16600:     }
16601:     return ($output,$error,$captcha,$version);
16602: }
16603: 
16604: sub captcha_response {
16605:     my ($context,$lonhost) = @_;
16606:     my ($captcha_chk,$captcha_error);
16607:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16608:     if ($captcha eq 'original') {
16609:         ($captcha_chk,$captcha_error) = &check_captcha();
16610:     } elsif ($captcha eq 'recaptcha') {
16611:         $captcha_chk = &check_recaptcha($privkey,$version);
16612:     } else {
16613:         $captcha_chk = 1;
16614:     }
16615:     return ($captcha_chk,$captcha_error);
16616: }
16617: 
16618: sub get_captcha_config {
16619:     my ($context,$lonhost) = @_;
16620:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16621:     my $hostname = &Apache::lonnet::hostname($lonhost);
16622:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16623:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16624:     if ($context eq 'usercreation') {
16625:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16626:         if (ref($domconfig{$context}) eq 'HASH') {
16627:             $hashtocheck = $domconfig{$context}{'cancreate'};
16628:             if (ref($hashtocheck) eq 'HASH') {
16629:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16630:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16631:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16632:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16633:                     }
16634:                     if ($privkey && $pubkey) {
16635:                         $captcha = 'recaptcha';
16636:                         $version = $hashtocheck->{'recaptchaversion'};
16637:                         if ($version ne '2') {
16638:                             $version = 1;
16639:                         }
16640:                     } else {
16641:                         $captcha = 'original';
16642:                     }
16643:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16644:                     $captcha = 'original';
16645:                 }
16646:             }
16647:         } else {
16648:             $captcha = 'captcha';
16649:         }
16650:     } elsif ($context eq 'login') {
16651:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16652:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16653:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16654:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16655:             if ($privkey && $pubkey) {
16656:                 $captcha = 'recaptcha';
16657:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16658:                 if ($version ne '2') {
16659:                     $version = 1; 
16660:                 }
16661:             } else {
16662:                 $captcha = 'original';
16663:             }
16664:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16665:             $captcha = 'original';
16666:         }
16667:     }
16668:     return ($captcha,$pubkey,$privkey,$version);
16669: }
16670: 
16671: sub create_captcha {
16672:     my %captcha_params = &captcha_settings();
16673:     my ($output,$maxtries,$tries) = ('',10,0);
16674:     while ($tries < $maxtries) {
16675:         $tries ++;
16676:         my $captcha = Authen::Captcha->new (
16677:                                            output_folder => $captcha_params{'output_dir'},
16678:                                            data_folder   => $captcha_params{'db_dir'},
16679:                                           );
16680:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16681: 
16682:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16683:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16684:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16685:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16686:                       '<br />'.
16687:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16688:             last;
16689:         }
16690:     }
16691:     return $output;
16692: }
16693: 
16694: sub captcha_settings {
16695:     my %captcha_params = (
16696:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16697:                            www_output_dir => "/captchaspool",
16698:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16699:                            numchars       => '5',
16700:                          );
16701:     return %captcha_params;
16702: }
16703: 
16704: sub check_captcha {
16705:     my ($captcha_chk,$captcha_error);
16706:     my $code = $env{'form.code'};
16707:     my $md5sum = $env{'form.crypt'};
16708:     my %captcha_params = &captcha_settings();
16709:     my $captcha = Authen::Captcha->new(
16710:                       output_folder => $captcha_params{'output_dir'},
16711:                       data_folder   => $captcha_params{'db_dir'},
16712:                   );
16713:     $captcha_chk = $captcha->check_code($code,$md5sum);
16714:     my %captcha_hash = (
16715:                         0       => 'Code not checked (file error)',
16716:                        -1      => 'Failed: code expired',
16717:                        -2      => 'Failed: invalid code (not in database)',
16718:                        -3      => 'Failed: invalid code (code does not match crypt)',
16719:     );
16720:     if ($captcha_chk != 1) {
16721:         $captcha_error = $captcha_hash{$captcha_chk}
16722:     }
16723:     return ($captcha_chk,$captcha_error);
16724: }
16725: 
16726: sub create_recaptcha {
16727:     my ($pubkey,$version) = @_;
16728:     if ($version >= 2) {
16729:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16730:     } else {
16731:         my $use_ssl;
16732:         if ($ENV{'SERVER_PORT'} == 443) {
16733:             $use_ssl = 1;
16734:         }
16735:         my $captcha = Captcha::reCAPTCHA->new;
16736:         return $captcha->get_options_setter({theme => 'white'})."\n".
16737:                $captcha->get_html($pubkey,undef,$use_ssl).
16738:                &mt('If the text is hard to read, [_1] will replace them.',
16739:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16740:                '<br /><br />';
16741:     }
16742: }
16743: 
16744: sub check_recaptcha {
16745:     my ($privkey,$version) = @_;
16746:     my $captcha_chk;
16747:     if ($version >= 2) {
16748:         my $ua = LWP::UserAgent->new;
16749:         $ua->timeout(10);
16750:         my %info = (
16751:                      secret   => $privkey, 
16752:                      response => $env{'form.g-recaptcha-response'},
16753:                      remoteip => $ENV{'REMOTE_ADDR'},
16754:                    );
16755:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16756:         if ($response->is_success)  {
16757:             my $data = JSON::DWIW->from_json($response->decoded_content);
16758:             if (ref($data) eq 'HASH') {
16759:                 if ($data->{'success'}) {
16760:                     $captcha_chk = 1;
16761:                 }
16762:             }
16763:         }
16764:     } else {
16765:         my $captcha = Captcha::reCAPTCHA->new;
16766:         my $captcha_result =
16767:             $captcha->check_answer(
16768:                                     $privkey,
16769:                                     $ENV{'REMOTE_ADDR'},
16770:                                     $env{'form.recaptcha_challenge_field'},
16771:                                     $env{'form.recaptcha_response_field'},
16772:                                   );
16773:         if ($captcha_result->{is_valid}) {
16774:             $captcha_chk = 1;
16775:         }
16776:     }
16777:     return $captcha_chk;
16778: }
16779: 
16780: sub emailusername_info {
16781:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
16782:     my %titles = &Apache::lonlocal::texthash (
16783:                      lastname      => 'Last Name',
16784:                      firstname     => 'First Name',
16785:                      institution   => 'School/college/university',
16786:                      location      => "School's city, state/province, country",
16787:                      web           => "School's web address",
16788:                      officialemail => 'E-mail address at institution (if different)',
16789:                  );
16790:     return (\@fields,\%titles);
16791: }
16792: 
16793: sub cleanup_html {
16794:     my ($incoming) = @_;
16795:     my $outgoing;
16796:     if ($incoming ne '') {
16797:         $outgoing = $incoming;
16798:         $outgoing =~ s/;/&#059;/g;
16799:         $outgoing =~ s/\#/&#035;/g;
16800:         $outgoing =~ s/\&/&#038;/g;
16801:         $outgoing =~ s/</&#060;/g;
16802:         $outgoing =~ s/>/&#062;/g;
16803:         $outgoing =~ s/\(/&#040/g;
16804:         $outgoing =~ s/\)/&#041;/g;
16805:         $outgoing =~ s/"/&#034;/g;
16806:         $outgoing =~ s/'/&#039;/g;
16807:         $outgoing =~ s/\$/&#036;/g;
16808:         $outgoing =~ s{/}{&#047;}g;
16809:         $outgoing =~ s/=/&#061;/g;
16810:         $outgoing =~ s/\\/&#092;/g
16811:     }
16812:     return $outgoing;
16813: }
16814: 
16815: # Checks for critical messages and returns a redirect url if one exists.
16816: # $interval indicates how often to check for messages.
16817: sub critical_redirect {
16818:     my ($interval) = @_;
16819:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16820:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
16821:                                         $env{'user.name'});
16822:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16823:         my $redirecturl;
16824:         if ($what[0]) {
16825: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16826: 	        $redirecturl='/adm/email?critical=display';
16827: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
16828:                 return (1, $url);
16829:             }
16830:         }
16831:     } 
16832:     return ();
16833: }
16834: 
16835: # Use:
16836: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16837: #
16838: ##################################################
16839: #          password associated functions         #
16840: ##################################################
16841: sub des_keys {
16842:     # Make a new key for DES encryption.
16843:     # Each key has two parts which are returned separately.
16844:     # Please note:  Each key must be passed through the &hex function
16845:     # before it is output to the web browser.  The hex versions cannot
16846:     # be used to decrypt.
16847:     my @hexstr=('0','1','2','3','4','5','6','7',
16848:                 '8','9','a','b','c','d','e','f');
16849:     my $lkey='';
16850:     for (0..7) {
16851:         $lkey.=$hexstr[rand(15)];
16852:     }
16853:     my $ukey='';
16854:     for (0..7) {
16855:         $ukey.=$hexstr[rand(15)];
16856:     }
16857:     return ($lkey,$ukey);
16858: }
16859: 
16860: sub des_decrypt {
16861:     my ($key,$cyphertext) = @_;
16862:     my $keybin=pack("H16",$key);
16863:     my $cypher;
16864:     if ($Crypt::DES::VERSION>=2.03) {
16865:         $cypher=new Crypt::DES $keybin;
16866:     } else {
16867:         $cypher=new DES $keybin;
16868:     }
16869:     my $plaintext='';
16870:     my $cypherlength = length($cyphertext);
16871:     my $numchunks = int($cypherlength/32);
16872:     for (my $j=0; $j<$numchunks; $j++) {
16873:         my $start = $j*32;
16874:         my $cypherblock = substr($cyphertext,$start,32);
16875:         my $chunk =
16876:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16877:         $chunk .=
16878:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16879:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16880:         $plaintext .= $chunk;
16881:     }
16882:     return $plaintext;
16883: }
16884: 
16885: 1;
16886: __END__;
16887: 

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