File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1234: download - view: text, annotated - select for diffs
Fri Feb 19 02:39:07 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support version 2 of Google reCAPTCHA.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1234 2016/02/19 02:39:07 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+'&crscode='+document.forms[formid].crscode.value;
  594:         }
  595:         if (formname == 'requestcrs') {
  596:             url += '&crsdom=$domainfilter&crscode=$instcode';
  597:         }
  598:         if (multflag !=null && multflag != '') {
  599:             url += '&multiple='+multflag;
  600:         }
  601:         var title = '$wintitle';
  602:         var options = 'scrollbars=1,resizable=1,menubar=0';
  603:         options += ',width=700,height=600';
  604:         stdeditbrowser = open(url,title,options,'1');
  605:         stdeditbrowser.focus();
  606:     }
  607: $id_functions
  608: ENDSTDBRW
  609:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  610:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  611:                                       $credits_element);
  612:     }
  613:     $output .= '
  614: // ]]>
  615: </script>';
  616:     return $output;
  617: }
  618: 
  619: sub javascript_index_functions {
  620:     return <<"ENDJS";
  621: 
  622: function getFormIdByName(formname) {
  623:     for (var i=0;i<document.forms.length;i++) {
  624:         if (document.forms[i].name == formname) {
  625:             return i;
  626:         }
  627:     }
  628:     return -1;
  629: }
  630: 
  631: function getIndexByName(formid,item) {
  632:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  633:         if (document.forms[formid].elements[i].name == item) {
  634:             return i;
  635:         }
  636:     }
  637:     return -1;
  638: }
  639: 
  640: function getDomainFromSelectbox(formname,udom) {
  641:     var userdom;
  642:     var formid = getFormIdByName(formname);
  643:     if (formid > -1) {
  644:         var domid = getIndexByName(formid,udom);
  645:         if (domid > -1) {
  646:             if (document.forms[formid].elements[domid].type == 'select-one') {
  647:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  648:             }
  649:             if (document.forms[formid].elements[domid].type == 'hidden') {
  650:                 userdom=document.forms[formid].elements[domid].value;
  651:             }
  652:         }
  653:     }
  654:     return userdom;
  655: }
  656: 
  657: ENDJS
  658: 
  659: }
  660: 
  661: sub javascript_array_indexof {
  662:     return <<ENDJS;
  663: <script type="text/javascript" language="JavaScript">
  664: // <![CDATA[
  665: 
  666: if (!Array.prototype.indexOf) {
  667:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  668:         "use strict";
  669:         if (this === void 0 || this === null) {
  670:             throw new TypeError();
  671:         }
  672:         var t = Object(this);
  673:         var len = t.length >>> 0;
  674:         if (len === 0) {
  675:             return -1;
  676:         }
  677:         var n = 0;
  678:         if (arguments.length > 0) {
  679:             n = Number(arguments[1]);
  680:             if (n !== n) { // shortcut for verifying if it is NaN
  681:                 n = 0;
  682:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  683:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  684:             }
  685:         }
  686:         if (n >= len) {
  687:             return -1;
  688:         }
  689:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  690:         for (; k < len; k++) {
  691:             if (k in t && t[k] === searchElement) {
  692:                 return k;
  693:             }
  694:         }
  695:         return -1;
  696:     }
  697: }
  698: 
  699: // ]]>
  700: </script>
  701: 
  702: ENDJS
  703: 
  704: }
  705: 
  706: sub userbrowser_javascript {
  707:     my $id_functions = &javascript_index_functions();
  708:     return <<"ENDUSERBRW";
  709: 
  710: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  711:     var url = '/adm/pickuser?';
  712:     var userdom = getDomainFromSelectbox(formname,udom);
  713:     if (userdom != null) {
  714:        if (userdom != '') {
  715:            url += 'srchdom='+userdom+'&';
  716:        }
  717:     }
  718:     url += 'form=' + formname + '&unameelement='+uname+
  719:                                 '&udomelement='+udom+
  720:                                 '&ulastelement='+ulast+
  721:                                 '&ufirstelement='+ufirst+
  722:                                 '&uemailelement='+uemail+
  723:                                 '&hideudomelement='+hideudom+
  724:                                 '&coursedom='+crsdom;
  725:     if ((caller != null) && (caller != undefined)) {
  726:         url += '&caller='+caller;
  727:     }
  728:     var title = 'User_Browser';
  729:     var options = 'scrollbars=1,resizable=1,menubar=0';
  730:     options += ',width=700,height=600';
  731:     var stdeditbrowser = open(url,title,options,'1');
  732:     stdeditbrowser.focus();
  733: }
  734: 
  735: function fix_domain (formname,udom,origdom,uname) {
  736:     var formid = getFormIdByName(formname);
  737:     if (formid > -1) {
  738:         var unameid = getIndexByName(formid,uname);
  739:         var domid = getIndexByName(formid,udom);
  740:         var hidedomid = getIndexByName(formid,origdom);
  741:         if (hidedomid > -1) {
  742:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  743:             var unameval = document.forms[formid].elements[unameid].value;
  744:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  745:                 if (domid > -1) {
  746:                     var slct = document.forms[formid].elements[domid];
  747:                     if (slct.type == 'select-one') {
  748:                         var i;
  749:                         for (i=0;i<slct.length;i++) {
  750:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  751:                         }
  752:                     }
  753:                     if (slct.type == 'hidden') {
  754:                         slct.value = fixeddom;
  755:                     }
  756:                 }
  757:             }
  758:         }
  759:     }
  760:     return;
  761: }
  762: 
  763: $id_functions
  764: ENDUSERBRW
  765: }
  766: 
  767: sub setsec_javascript {
  768:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  769:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  770:         $communityrolestr);
  771:     if ($role_element ne '') {
  772:         my @allroles = ('st','ta','ep','in','ad');
  773:         foreach my $crstype ('Course','Community') {
  774:             if ($crstype eq 'Community') {
  775:                 foreach my $role (@allroles) {
  776:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  777:                 }
  778:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  779:             } else {
  780:                 foreach my $role (@allroles) {
  781:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  782:                 }
  783:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  784:             }
  785:         }
  786:         $rolestr = '"'.join('","',@allroles).'"';
  787:         $courserolestr = '"'.join('","',@courserolenames).'"';
  788:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  789:     }
  790:     my $setsections = qq|
  791: function setSect(sectionlist) {
  792:     var sectionsArray = new Array();
  793:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  794:         sectionsArray = sectionlist.split(",");
  795:     }
  796:     var numSections = sectionsArray.length;
  797:     document.$formname.$sec_element.length = 0;
  798:     if (numSections == 0) {
  799:         document.$formname.$sec_element.multiple=false;
  800:         document.$formname.$sec_element.size=1;
  801:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  802:     } else {
  803:         if (numSections == 1) {
  804:             document.$formname.$sec_element.multiple=false;
  805:             document.$formname.$sec_element.size=1;
  806:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  807:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  808:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  809:         } else {
  810:             for (var i=0; i<numSections; i++) {
  811:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  812:             }
  813:             document.$formname.$sec_element.multiple=true
  814:             if (numSections < 3) {
  815:                 document.$formname.$sec_element.size=numSections;
  816:             } else {
  817:                 document.$formname.$sec_element.size=3;
  818:             }
  819:             document.$formname.$sec_element.options[0].selected = false
  820:         }
  821:     }
  822: }
  823: 
  824: function setRole(crstype) {
  825: |;
  826:     if ($role_element eq '') {
  827:         $setsections .= '    return;
  828: }
  829: ';
  830:     } else {
  831:         $setsections .= qq|
  832:     var elementLength = document.$formname.$role_element.length;
  833:     var allroles = Array($rolestr);
  834:     var courserolenames = Array($courserolestr);
  835:     var communityrolenames = Array($communityrolestr);
  836:     if (elementLength != undefined) {
  837:         if (document.$formname.$role_element.options[5].value == 'cc') {
  838:             if (crstype == 'Course') {
  839:                 return;
  840:             } else {
  841:                 allroles[5] = 'co';
  842:                 for (var i=0; i<6; i++) {
  843:                     document.$formname.$role_element.options[i].value = allroles[i];
  844:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  845:                 }
  846:             }
  847:         } else {
  848:             if (crstype == 'Community') {
  849:                 return;
  850:             } else {
  851:                 allroles[5] = 'cc';
  852:                 for (var i=0; i<6; i++) {
  853:                     document.$formname.$role_element.options[i].value = allroles[i];
  854:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  855:                 }
  856:             }
  857:         }
  858:     }
  859:     return;
  860: }
  861: |;
  862:     }
  863:     if ($credits_element) {
  864:         $setsections .= qq|
  865: function setCredits(defaultcredits) {
  866:     document.$formname.$credits_element.value = defaultcredits;
  867:     return;
  868: }
  869: |;
  870:     }
  871:     return $setsections;
  872: }
  873: 
  874: sub selectcourse_link {
  875:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  876:        $typeelement) = @_;
  877:    my $type = $selecttype;
  878:    my $linktext = &mt('Select Course');
  879:    if ($selecttype eq 'Community') {
  880:        $linktext = &mt('Select Community');
  881:    } elsif ($selecttype eq 'Course/Community') {
  882:        $linktext = &mt('Select Course/Community');
  883:        $type = '';
  884:    } elsif ($selecttype eq 'Select') {
  885:        $linktext = &mt('Select');
  886:        $type = '';
  887:    }
  888:    return '<span class="LC_nobreak">'
  889:          ."<a href='"
  890:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  891:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  892:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  893:          ."'>".$linktext.'</a>'
  894:          .'</span>';
  895: }
  896: 
  897: sub selectauthor_link {
  898:    my ($form,$udom)=@_;
  899:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  900:           &mt('Select Author').'</a>';
  901: }
  902: 
  903: sub selectuser_link {
  904:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  905:         $coursedom,$linktext,$caller) = @_;
  906:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  907:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  908:            ');">'.$linktext.'</a>';
  909: }
  910: 
  911: sub check_uncheck_jscript {
  912:     my $jscript = <<"ENDSCRT";
  913: function checkAll(field) {
  914:     if (field.length > 0) {
  915:         for (i = 0; i < field.length; i++) {
  916:             if (!field[i].disabled) { 
  917:                 field[i].checked = true;
  918:             }
  919:         }
  920:     } else {
  921:         if (!field.disabled) { 
  922:             field.checked = true;
  923:         }
  924:     }
  925: }
  926:  
  927: function uncheckAll(field) {
  928:     if (field.length > 0) {
  929:         for (i = 0; i < field.length; i++) {
  930:             field[i].checked = false ;
  931:         }
  932:     } else {
  933:         field.checked = false ;
  934:     }
  935: }
  936: ENDSCRT
  937:     return $jscript;
  938: }
  939: 
  940: sub select_timezone {
  941:    my ($name,$selected,$onchange,$includeempty)=@_;
  942:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  943:    if ($includeempty) {
  944:        $output .= '<option value=""';
  945:        if (($selected eq '') || ($selected eq 'local')) {
  946:            $output .= ' selected="selected" ';
  947:        }
  948:        $output .= '> </option>';
  949:    }
  950:    my @timezones = DateTime::TimeZone->all_names;
  951:    foreach my $tzone (@timezones) {
  952:        $output.= '<option value="'.$tzone.'"';
  953:        if ($tzone eq $selected) {
  954:            $output.=' selected="selected"';
  955:        }
  956:        $output.=">$tzone</option>\n";
  957:    }
  958:    $output.="</select>";
  959:    return $output;
  960: }
  961: 
  962: sub select_datelocale {
  963:     my ($name,$selected,$onchange,$includeempty)=@_;
  964:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  965:     if ($includeempty) {
  966:         $output .= '<option value=""';
  967:         if ($selected eq '') {
  968:             $output .= ' selected="selected" ';
  969:         }
  970:         $output .= '> </option>';
  971:     }
  972:     my (@possibles,%locale_names);
  973:     my @locales = DateTime::Locale::Catalog::Locales;
  974:     foreach my $locale (@locales) {
  975:         if (ref($locale) eq 'HASH') {
  976:             my $id = $locale->{'id'};
  977:             if ($id ne '') {
  978:                 my $en_terr = $locale->{'en_territory'};
  979:                 my $native_terr = $locale->{'native_territory'};
  980:                 my @languages = &Apache::lonlocal::preferred_languages();
  981:                 if (grep(/^en$/,@languages) || !@languages) {
  982:                     if ($en_terr ne '') {
  983:                         $locale_names{$id} = '('.$en_terr.')';
  984:                     } elsif ($native_terr ne '') {
  985:                         $locale_names{$id} = $native_terr;
  986:                     }
  987:                 } else {
  988:                     if ($native_terr ne '') {
  989:                         $locale_names{$id} = $native_terr.' ';
  990:                     } elsif ($en_terr ne '') {
  991:                         $locale_names{$id} = '('.$en_terr.')';
  992:                     }
  993:                 }
  994:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  995:                 push (@possibles,$id);
  996:             }
  997:         }
  998:     }
  999:     foreach my $item (sort(@possibles)) {
 1000:         $output.= '<option value="'.$item.'"';
 1001:         if ($item eq $selected) {
 1002:             $output.=' selected="selected"';
 1003:         }
 1004:         $output.=">$item";
 1005:         if ($locale_names{$item} ne '') {
 1006:             $output.='  '.$locale_names{$item};
 1007:         }
 1008:         $output.="</option>\n";
 1009:     }
 1010:     $output.="</select>";
 1011:     return $output;
 1012: }
 1013: 
 1014: sub select_language {
 1015:     my ($name,$selected,$includeempty) = @_;
 1016:     my %langchoices;
 1017:     if ($includeempty) {
 1018:         %langchoices = ('' => 'No language preference');
 1019:     }
 1020:     foreach my $id (&languageids()) {
 1021:         my $code = &supportedlanguagecode($id);
 1022:         if ($code) {
 1023:             $langchoices{$code} = &plainlanguagedescription($id);
 1024:         }
 1025:     }
 1026:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1027:     return &select_form($selected,$name,\%langchoices);
 1028: }
 1029: 
 1030: =pod
 1031: 
 1032: 
 1033: =item * &list_languages()
 1034: 
 1035: Returns an array reference that is suitable for use in language prompters.
 1036: Each array element is itself a two element array.  The first element
 1037: is the language code.  The second element a descsriptiuon of the 
 1038: language itself.  This is suitable for use in e.g.
 1039: &Apache::edit::select_arg (once dereferenced that is).
 1040: 
 1041: =cut 
 1042: 
 1043: sub list_languages {
 1044:     my @lang_choices;
 1045: 
 1046:     foreach my $id (&languageids()) {
 1047: 	my $code = &supportedlanguagecode($id);
 1048: 	if ($code) {
 1049: 	    my $selector    = $supported_codes{$id};
 1050: 	    my $description = &plainlanguagedescription($id);
 1051: 	    push (@lang_choices, [$selector, $description]);
 1052: 	}
 1053:     }
 1054:     return \@lang_choices;
 1055: }
 1056: 
 1057: =pod
 1058: 
 1059: =item * &linked_select_forms(...)
 1060: 
 1061: linked_select_forms returns a string containing a <script></script> block
 1062: and html for two <select> menus.  The select menus will be linked in that
 1063: changing the value of the first menu will result in new values being placed
 1064: in the second menu.  The values in the select menu will appear in alphabetical
 1065: order unless a defined order is provided.
 1066: 
 1067: linked_select_forms takes the following ordered inputs:
 1068: 
 1069: =over 4
 1070: 
 1071: =item * $formname, the name of the <form> tag
 1072: 
 1073: =item * $middletext, the text which appears between the <select> tags
 1074: 
 1075: =item * $firstdefault, the default value for the first menu
 1076: 
 1077: =item * $firstselectname, the name of the first <select> tag
 1078: 
 1079: =item * $secondselectname, the name of the second <select> tag
 1080: 
 1081: =item * $hashref, a reference to a hash containing the data for the menus.
 1082: 
 1083: =item * $menuorder, the order of values in the first menu
 1084: 
 1085: =item * $onchangefirst, additional javascript call to execute for an onchange
 1086:         event for the first <select> tag
 1087: 
 1088: =item * $onchangesecond, additional javascript call to execute for an onchange
 1089:         event for the second <select> tag
 1090: 
 1091: =back 
 1092: 
 1093: Below is an example of such a hash.  Only the 'text', 'default', and 
 1094: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1095: values for the first select menu.  The text that coincides with the 
 1096: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1097: and text for the second menu are given in the hash pointed to by 
 1098: $menu{$choice1}->{'select2'}.  
 1099: 
 1100:  my %menu = ( A1 => { text =>"Choice A1" ,
 1101:                        default => "B3",
 1102:                        select2 => { 
 1103:                            B1 => "Choice B1",
 1104:                            B2 => "Choice B2",
 1105:                            B3 => "Choice B3",
 1106:                            B4 => "Choice B4"
 1107:                            },
 1108:                        order => ['B4','B3','B1','B2'],
 1109:                    },
 1110:                A2 => { text =>"Choice A2" ,
 1111:                        default => "C2",
 1112:                        select2 => { 
 1113:                            C1 => "Choice C1",
 1114:                            C2 => "Choice C2",
 1115:                            C3 => "Choice C3"
 1116:                            },
 1117:                        order => ['C2','C1','C3'],
 1118:                    },
 1119:                A3 => { text =>"Choice A3" ,
 1120:                        default => "D6",
 1121:                        select2 => { 
 1122:                            D1 => "Choice D1",
 1123:                            D2 => "Choice D2",
 1124:                            D3 => "Choice D3",
 1125:                            D4 => "Choice D4",
 1126:                            D5 => "Choice D5",
 1127:                            D6 => "Choice D6",
 1128:                            D7 => "Choice D7"
 1129:                            },
 1130:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1131:                    }
 1132:                );
 1133: 
 1134: =cut
 1135: 
 1136: sub linked_select_forms {
 1137:     my ($formname,
 1138:         $middletext,
 1139:         $firstdefault,
 1140:         $firstselectname,
 1141:         $secondselectname, 
 1142:         $hashref,
 1143:         $menuorder,
 1144:         $onchangefirst,
 1145:         $onchangesecond
 1146:         ) = @_;
 1147:     my $second = "document.$formname.$secondselectname";
 1148:     my $first = "document.$formname.$firstselectname";
 1149:     # output the javascript to do the changing
 1150:     my $result = '';
 1151:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1152:     $result.="// <![CDATA[\n";
 1153:     $result.="var select2data = new Object();\n";
 1154:     $" = '","';
 1155:     my $debug = '';
 1156:     foreach my $s1 (sort(keys(%$hashref))) {
 1157:         $result.="select2data.d_$s1 = new Object();\n";        
 1158:         $result.="select2data.d_$s1.def = new String('".
 1159:             $hashref->{$s1}->{'default'}."');\n";
 1160:         $result.="select2data.d_$s1.values = new Array(";
 1161:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1162:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1163:             @s2values = @{$hashref->{$s1}->{'order'}};
 1164:         }
 1165:         $result.="\"@s2values\");\n";
 1166:         $result.="select2data.d_$s1.texts = new Array(";        
 1167:         my @s2texts;
 1168:         foreach my $value (@s2values) {
 1169:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1170:         }
 1171:         $result.="\"@s2texts\");\n";
 1172:     }
 1173:     $"=' ';
 1174:     $result.= <<"END";
 1175: 
 1176: function select1_changed() {
 1177:     // Determine new choice
 1178:     var newvalue = "d_" + $first.value;
 1179:     // update select2
 1180:     var values     = select2data[newvalue].values;
 1181:     var texts      = select2data[newvalue].texts;
 1182:     var select2def = select2data[newvalue].def;
 1183:     var i;
 1184:     // out with the old
 1185:     for (i = 0; i < $second.options.length; i++) {
 1186:         $second.options[i] = null;
 1187:     }
 1188:     // in with the nuclear
 1189:     for (i=0;i<values.length; i++) {
 1190:         $second.options[i] = new Option(values[i]);
 1191:         $second.options[i].value = values[i];
 1192:         $second.options[i].text = texts[i];
 1193:         if (values[i] == select2def) {
 1194:             $second.options[i].selected = true;
 1195:         }
 1196:     }
 1197: }
 1198: // ]]>
 1199: </script>
 1200: END
 1201:     # output the initial values for the selection lists
 1202:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1203:     my @order = sort(keys(%{$hashref}));
 1204:     if (ref($menuorder) eq 'ARRAY') {
 1205:         @order = @{$menuorder};
 1206:     }
 1207:     foreach my $value (@order) {
 1208:         $result.="    <option value=\"$value\" ";
 1209:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1210:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1211:     }
 1212:     $result .= "</select>\n";
 1213:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1214:     $result .= $middletext;
 1215:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1216:     if ($onchangesecond) {
 1217:         $result .= ' onchange="'.$onchangesecond.'"';
 1218:     }
 1219:     $result .= ">\n";
 1220:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1221:     
 1222:     my @secondorder = sort(keys(%select2));
 1223:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1224:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1225:     }
 1226:     foreach my $value (@secondorder) {
 1227:         $result.="    <option value=\"$value\" ";        
 1228:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1229:         $result.=">".&mt($select2{$value})."</option>\n";
 1230:     }
 1231:     $result .= "</select>\n";
 1232:     #    return $debug;
 1233:     return $result;
 1234: }   #  end of sub linked_select_forms {
 1235: 
 1236: =pod
 1237: 
 1238: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1239: 
 1240: Returns a string corresponding to an HTML link to the given help
 1241: $topic, where $topic corresponds to the name of a .tex file in
 1242: /home/httpd/html/adm/help/tex, with underscores replaced by
 1243: spaces. 
 1244: 
 1245: $text will optionally be linked to the same topic, allowing you to
 1246: link text in addition to the graphic. If you do not want to link
 1247: text, but wish to specify one of the later parameters, pass an
 1248: empty string. 
 1249: 
 1250: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1251: the link will not open a new window. If false, the link will open
 1252: a new window using Javascript. (Default is false.) 
 1253: 
 1254: $width and $height are optional numerical parameters that will
 1255: override the width and height of the popped up window, which may
 1256: be useful for certain help topics with big pictures included.
 1257: 
 1258: $imgid is the id of the img tag used for the help icon. This may be
 1259: used in a javascript call to switch the image src.  See 
 1260: lonhtmlcommon::htmlareaselectactive() for an example.
 1261: 
 1262: =cut
 1263: 
 1264: sub help_open_topic {
 1265:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1266:     $text = "" if (not defined $text);
 1267:     $stayOnPage = 0 if (not defined $stayOnPage);
 1268:     $width = 500 if (not defined $width);
 1269:     $height = 400 if (not defined $height);
 1270:     my $filename = $topic;
 1271:     $filename =~ s/ /_/g;
 1272: 
 1273:     my $template = "";
 1274:     my $link;
 1275:     
 1276:     $topic=~s/\W/\_/g;
 1277: 
 1278:     if (!$stayOnPage) {
 1279: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1280:     } elsif ($stayOnPage eq 'popup') {
 1281:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1282:     } else {
 1283: 	$link = "/adm/help/${filename}.hlp";
 1284:     }
 1285: 
 1286:     # Add the text
 1287:     if ($text ne "") {	
 1288: 	$template.='<span class="LC_help_open_topic">'
 1289:                   .'<a target="_top" href="'.$link.'">'
 1290:                   .$text.'</a>';
 1291:     }
 1292: 
 1293:     # (Always) Add the graphic
 1294:     my $title = &mt('Online Help');
 1295:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1296:     if ($imgid ne '') {
 1297:         $imgid = ' id="'.$imgid.'"';
 1298:     }
 1299:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1300:               .'<img src="'.$helpicon.'" border="0"'
 1301:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1302:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1303:               .' /></a>';
 1304:     if ($text ne "") {	
 1305:         $template.='</span>';
 1306:     }
 1307:     return $template;
 1308: 
 1309: }
 1310: 
 1311: # This is a quicky function for Latex cheatsheet editing, since it 
 1312: # appears in at least four places
 1313: sub helpLatexCheatsheet {
 1314:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1315:     my $out;
 1316:     my $addOther = '';
 1317:     if ($topic) {
 1318: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1319:     }
 1320:     $out = '<span>' # Start cheatsheet
 1321: 	  .$addOther
 1322:           .'<span>'
 1323: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1324: 	  .'</span> <span>'
 1325: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1326: 	  .'</span>';
 1327:     unless ($not_author) {
 1328:         $out .= '<span>'
 1329:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1330:                .'</span> <span>'
 1331:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1332: 	       .'</span>';
 1333:     }
 1334:     $out .= '</span>'; # End cheatsheet
 1335:     return $out;
 1336: }
 1337: 
 1338: sub general_help {
 1339:     my $helptopic='Student_Intro';
 1340:     if ($env{'request.role'}=~/^(ca|au)/) {
 1341: 	$helptopic='Authoring_Intro';
 1342:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1343: 	$helptopic='Course_Coordination_Intro';
 1344:     } elsif ($env{'request.role'}=~/^dc/) {
 1345:         $helptopic='Domain_Coordination_Intro';
 1346:     }
 1347:     return $helptopic;
 1348: }
 1349: 
 1350: sub update_help_link {
 1351:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1352:     my $origurl = $ENV{'REQUEST_URI'};
 1353:     $origurl=~s|^/~|/priv/|;
 1354:     my $timestamp = time;
 1355:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1356:         $$datum = &escape($$datum);
 1357:     }
 1358: 
 1359:     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";
 1360:     my $output .= <<"ENDOUTPUT";
 1361: <script type="text/javascript">
 1362: // <![CDATA[
 1363: banner_link = '$banner_link';
 1364: // ]]>
 1365: </script>
 1366: ENDOUTPUT
 1367:     return $output;
 1368: }
 1369: 
 1370: # now just updates the help link and generates a blue icon
 1371: sub help_open_menu {
 1372:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1373: 	= @_;    
 1374:     $stayOnPage = 1;
 1375:     my $output;
 1376:     if ($component_help) {
 1377: 	if (!$text) {
 1378: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1379: 				       $width,$height);
 1380: 	} else {
 1381: 	    my $help_text;
 1382: 	    $help_text=&unescape($topic);
 1383: 	    $output='<table><tr><td>'.
 1384: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1385: 				 $width,$height).'</td></tr></table>';
 1386: 	}
 1387:     }
 1388:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1389:     return $output.$banner_link;
 1390: }
 1391: 
 1392: sub top_nav_help {
 1393:     my ($text) = @_;
 1394:     $text = &mt($text);
 1395:     my $stay_on_page = 1;
 1396: 
 1397:     my ($link,$banner_link);
 1398:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1399:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1400: 	                         : "javascript:helpMenu('open')";
 1401:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1402:     }
 1403:     my $title = &mt('Get help');
 1404:     if ($link) {
 1405:         return <<"END";
 1406: $banner_link
 1407: <a href="$link" title="$title">$text</a>
 1408: END
 1409:     } else {
 1410:         return '&nbsp;'.$text.'&nbsp;';
 1411:     }
 1412: }
 1413: 
 1414: sub help_menu_js {
 1415:     my ($httphost) = @_;
 1416:     my $stayOnPage = 1;
 1417:     my $width = 620;
 1418:     my $height = 600;
 1419:     my $helptopic=&general_help();
 1420:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1421:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1422:     my $start_page =
 1423:         &Apache::loncommon::start_page('Help Menu', undef,
 1424: 				       {'frameset'    => 1,
 1425: 					'js_ready'    => 1,
 1426:                                         'use_absolute' => $httphost,
 1427: 					'add_entries' => {
 1428: 					    'border' => '0', 
 1429: 					    'rows'   => "110,*",},});
 1430:     my $end_page =
 1431:         &Apache::loncommon::end_page({'frameset' => 1,
 1432: 				      'js_ready' => 1,});
 1433: 
 1434:     my $template .= <<"ENDTEMPLATE";
 1435: <script type="text/javascript">
 1436: // <![CDATA[
 1437: // <!-- BEGIN LON-CAPA Internal
 1438: var banner_link = '';
 1439: function helpMenu(target) {
 1440:     var caller = this;
 1441:     if (target == 'open') {
 1442:         var newWindow = null;
 1443:         try {
 1444:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1445:         }
 1446:         catch(error) {
 1447:             writeHelp(caller);
 1448:             return;
 1449:         }
 1450:         if (newWindow) {
 1451:             caller = newWindow;
 1452:         }
 1453:     }
 1454:     writeHelp(caller);
 1455:     return;
 1456: }
 1457: function writeHelp(caller) {
 1458:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1459:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1460:     caller.document.close();
 1461:     caller.focus();
 1462: }
 1463: // END LON-CAPA Internal -->
 1464: // ]]>
 1465: </script>
 1466: ENDTEMPLATE
 1467:     return $template;
 1468: }
 1469: 
 1470: sub help_open_bug {
 1471:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1472:     unless ($env{'user.adv'}) { return ''; }
 1473:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1474:     $text = "" if (not defined $text);
 1475: 	$stayOnPage=1;
 1476:     $width = 600 if (not defined $width);
 1477:     $height = 600 if (not defined $height);
 1478: 
 1479:     $topic=~s/\W+/\+/g;
 1480:     my $link='';
 1481:     my $template='';
 1482:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1483: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1484:     if (!$stayOnPage)
 1485:     {
 1486: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1487:     }
 1488:     else
 1489:     {
 1490: 	$link = $url;
 1491:     }
 1492:     # Add the text
 1493:     if ($text ne "")
 1494:     {
 1495: 	$template .= 
 1496:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1497:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1498:     }
 1499: 
 1500:     # Add the graphic
 1501:     my $title = &mt('Report a Bug');
 1502:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1503:     $template .= <<"ENDTEMPLATE";
 1504:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1505: ENDTEMPLATE
 1506:     if ($text ne '') { $template.='</td></tr></table>' };
 1507:     return $template;
 1508: 
 1509: }
 1510: 
 1511: sub help_open_faq {
 1512:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1513:     unless ($env{'user.adv'}) { return ''; }
 1514:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1515:     $text = "" if (not defined $text);
 1516: 	$stayOnPage=1;
 1517:     $width = 350 if (not defined $width);
 1518:     $height = 400 if (not defined $height);
 1519: 
 1520:     $topic=~s/\W+/\+/g;
 1521:     my $link='';
 1522:     my $template='';
 1523:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1524:     if (!$stayOnPage)
 1525:     {
 1526: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1527:     }
 1528:     else
 1529:     {
 1530: 	$link = $url;
 1531:     }
 1532: 
 1533:     # Add the text
 1534:     if ($text ne "")
 1535:     {
 1536: 	$template .= 
 1537:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1538:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1539:     }
 1540: 
 1541:     # Add the graphic
 1542:     my $title = &mt('View the FAQ');
 1543:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1544:     $template .= <<"ENDTEMPLATE";
 1545:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1546: ENDTEMPLATE
 1547:     if ($text ne '') { $template.='</td></tr></table>' };
 1548:     return $template;
 1549: 
 1550: }
 1551: 
 1552: ###############################################################
 1553: ###############################################################
 1554: 
 1555: =pod
 1556: 
 1557: =item * &change_content_javascript():
 1558: 
 1559: This and the next function allow you to create small sections of an
 1560: otherwise static HTML page that you can update on the fly with
 1561: Javascript, even in Netscape 4.
 1562: 
 1563: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1564: must be written to the HTML page once. It will prove the Javascript
 1565: function "change(name, content)". Calling the change function with the
 1566: name of the section 
 1567: you want to update, matching the name passed to C<changable_area>, and
 1568: the new content you want to put in there, will put the content into
 1569: that area.
 1570: 
 1571: B<Note>: Netscape 4 only reserves enough space for the changable area
 1572: to contain room for the original contents. You need to "make space"
 1573: for whatever changes you wish to make, and be B<sure> to check your
 1574: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1575: it's adequate for updating a one-line status display, but little more.
 1576: This script will set the space to 100% width, so you only need to
 1577: worry about height in Netscape 4.
 1578: 
 1579: Modern browsers are much less limiting, and if you can commit to the
 1580: user not using Netscape 4, this feature may be used freely with
 1581: pretty much any HTML.
 1582: 
 1583: =cut
 1584: 
 1585: sub change_content_javascript {
 1586:     # If we're on Netscape 4, we need to use Layer-based code
 1587:     if ($env{'browser.type'} eq 'netscape' &&
 1588: 	$env{'browser.version'} =~ /^4\./) {
 1589: 	return (<<NETSCAPE4);
 1590: 	function change(name, content) {
 1591: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1592: 	    doc.open();
 1593: 	    doc.write(content);
 1594: 	    doc.close();
 1595: 	}
 1596: NETSCAPE4
 1597:     } else {
 1598: 	# Otherwise, we need to use semi-standards-compliant code
 1599: 	# (technically, "innerHTML" isn't standard but the equivalent
 1600: 	# is really scary, and every useful browser supports it
 1601: 	return (<<DOMBASED);
 1602: 	function change(name, content) {
 1603: 	    element = document.getElementById(name);
 1604: 	    element.innerHTML = content;
 1605: 	}
 1606: DOMBASED
 1607:     }
 1608: }
 1609: 
 1610: =pod
 1611: 
 1612: =item * &changable_area($name,$origContent):
 1613: 
 1614: This provides a "changable area" that can be modified on the fly via
 1615: the Javascript code provided in C<change_content_javascript>. $name is
 1616: the name you will use to reference the area later; do not repeat the
 1617: same name on a given HTML page more then once. $origContent is what
 1618: the area will originally contain, which can be left blank.
 1619: 
 1620: =cut
 1621: 
 1622: sub changable_area {
 1623:     my ($name, $origContent) = @_;
 1624: 
 1625:     if ($env{'browser.type'} eq 'netscape' &&
 1626: 	$env{'browser.version'} =~ /^4\./) {
 1627: 	# If this is netscape 4, we need to use the Layer tag
 1628: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1629:     } else {
 1630: 	return "<span id='$name'>$origContent</span>";
 1631:     }
 1632: }
 1633: 
 1634: =pod
 1635: 
 1636: =item * &viewport_geometry_js 
 1637: 
 1638: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1639: 
 1640: =cut
 1641: 
 1642: 
 1643: sub viewport_geometry_js { 
 1644:     return <<"GEOMETRY";
 1645: var Geometry = {};
 1646: function init_geometry() {
 1647:     if (Geometry.init) { return };
 1648:     Geometry.init=1;
 1649:     if (window.innerHeight) {
 1650:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1651:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1652:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1653:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1654:     }
 1655:     else if (document.documentElement && document.documentElement.clientHeight) {
 1656:         Geometry.getViewportHeight =
 1657:             function() { return document.documentElement.clientHeight; };
 1658:         Geometry.getViewportWidth =
 1659:             function() { return document.documentElement.clientWidth; };
 1660: 
 1661:         Geometry.getHorizontalScroll =
 1662:             function() { return document.documentElement.scrollLeft; };
 1663:         Geometry.getVerticalScroll =
 1664:             function() { return document.documentElement.scrollTop; };
 1665:     }
 1666:     else if (document.body.clientHeight) {
 1667:         Geometry.getViewportHeight =
 1668:             function() { return document.body.clientHeight; };
 1669:         Geometry.getViewportWidth =
 1670:             function() { return document.body.clientWidth; };
 1671:         Geometry.getHorizontalScroll =
 1672:             function() { return document.body.scrollLeft; };
 1673:         Geometry.getVerticalScroll =
 1674:             function() { return document.body.scrollTop; };
 1675:     }
 1676: }
 1677: 
 1678: GEOMETRY
 1679: }
 1680: 
 1681: =pod
 1682: 
 1683: =item * &viewport_size_js()
 1684: 
 1685: 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. 
 1686: 
 1687: =cut
 1688: 
 1689: sub viewport_size_js {
 1690:     my $geometry = &viewport_geometry_js();
 1691:     return <<"DIMS";
 1692: 
 1693: $geometry
 1694: 
 1695: function getViewportDims(width,height) {
 1696:     init_geometry();
 1697:     width.value = Geometry.getViewportWidth();
 1698:     height.value = Geometry.getViewportHeight();
 1699:     return;
 1700: }
 1701: 
 1702: DIMS
 1703: }
 1704: 
 1705: =pod
 1706: 
 1707: =item * &resize_textarea_js()
 1708: 
 1709: emits the needed javascript to resize a textarea to be as big as possible
 1710: 
 1711: creates a function resize_textrea that takes two IDs first should be
 1712: the id of the element to resize, second should be the id of a div that
 1713: surrounds everything that comes after the textarea, this routine needs
 1714: to be attached to the <body> for the onload and onresize events.
 1715: 
 1716: =back
 1717: 
 1718: =cut
 1719: 
 1720: sub resize_textarea_js {
 1721:     my $geometry = &viewport_geometry_js();
 1722:     return <<"RESIZE";
 1723:     <script type="text/javascript">
 1724: // <![CDATA[
 1725: $geometry
 1726: 
 1727: function getX(element) {
 1728:     var x = 0;
 1729:     while (element) {
 1730: 	x += element.offsetLeft;
 1731: 	element = element.offsetParent;
 1732:     }
 1733:     return x;
 1734: }
 1735: function getY(element) {
 1736:     var y = 0;
 1737:     while (element) {
 1738: 	y += element.offsetTop;
 1739: 	element = element.offsetParent;
 1740:     }
 1741:     return y;
 1742: }
 1743: 
 1744: 
 1745: function resize_textarea(textarea_id,bottom_id) {
 1746:     init_geometry();
 1747:     var textarea        = document.getElementById(textarea_id);
 1748:     //alert(textarea);
 1749: 
 1750:     var textarea_top    = getY(textarea);
 1751:     var textarea_height = textarea.offsetHeight;
 1752:     var bottom          = document.getElementById(bottom_id);
 1753:     var bottom_top      = getY(bottom);
 1754:     var bottom_height   = bottom.offsetHeight;
 1755:     var window_height   = Geometry.getViewportHeight();
 1756:     var fudge           = 23;
 1757:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1758:     if (new_height < 300) {
 1759: 	new_height = 300;
 1760:     }
 1761:     textarea.style.height=new_height+'px';
 1762: }
 1763: // ]]>
 1764: </script>
 1765: RESIZE
 1766: 
 1767: }
 1768: 
 1769: sub colorfuleditor_js {
 1770:     return <<"COLORFULEDIT"
 1771: <script type="text/javascript">
 1772: // <![CDATA[>
 1773:     function fold_box(curDepth, lastresource){
 1774: 
 1775:     // we need a list because there can be several blocks you need to fold in one tag
 1776:         var block = document.getElementsByName('foldblock_'+curDepth);
 1777:     // but there is only one folding button per tag
 1778:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1779: 
 1780:         if(block.item(0).style.display == 'none'){
 1781: 
 1782:             foldbutton.value = '@{[&mt("Hide")]}';
 1783:             for (i = 0; i < block.length; i++){
 1784:                 block.item(i).style.display = '';
 1785:             }
 1786:         }else{
 1787: 
 1788:             foldbutton.value = '@{[&mt("Show")]}';
 1789:             for (i = 0; i < block.length; i++){
 1790:                 // block.item(i).style.visibility = 'collapse';
 1791:                 block.item(i).style.display = 'none';
 1792:             }
 1793:         };
 1794:         saveState(lastresource);
 1795:     }
 1796: 
 1797:     function saveState (lastresource) {
 1798: 
 1799:         var tag_list = getTagList();
 1800:         if(tag_list != null){
 1801:             var timestamp = new Date().getTime();
 1802:             var key = lastresource;
 1803: 
 1804:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1805:             // starting with timestamp
 1806:             var value = timestamp+';';
 1807: 
 1808:             // building the list of key-value pairs
 1809:             for(var i = 0; i < tag_list.length; i++){
 1810:                 value += tag_list[i]+',';
 1811:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1812:             }
 1813: 
 1814:             // only iterate whole storage if nothing to override
 1815:             if(localStorage.getItem(key) == null){        
 1816: 
 1817:                 // prevent storage from growing large
 1818:                 if(localStorage.length > 50){
 1819:                     var regex_getTimestamp = /^(?:\d)+;/;
 1820:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1821:                     var oldest_key;
 1822:                     
 1823:                     for(var i = 1; i < localStorage.length; i++){
 1824:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1825:                             oldest_key = localStorage.key(i);
 1826:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1827:                         }
 1828:                     }
 1829:                     localStorage.removeItem(oldest_key);
 1830:                 }
 1831:             }
 1832:             localStorage.setItem(key,value);
 1833:         }
 1834:     }
 1835: 
 1836:     // restore folding status of blocks (on page load)
 1837:     function restoreState (lastresource) {
 1838:         if(localStorage.getItem(lastresource) != null){
 1839:             var key = lastresource;
 1840:             var value = localStorage.getItem(key);
 1841:             var regex_delTimestamp = /^\d+;/;
 1842: 
 1843:             value.replace(regex_delTimestamp, '');
 1844: 
 1845:             var valueArr = value.split(';');
 1846:             var pairs;
 1847:             var elements;
 1848:             for (var i = 0; i < valueArr.length; i++){
 1849:                 pairs = valueArr[i].split(',');
 1850:                 elements = document.getElementsByName(pairs[0]);
 1851: 
 1852:                 for (var j = 0; j < elements.length; j++){  
 1853:                     elements[j].style.display = pairs[1];
 1854:                     if (pairs[1] == "none"){
 1855:                         var regex_id = /([_\\d]+)\$/;
 1856:                         regex_id.exec(pairs[0]);
 1857:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1858:                     }
 1859:                 }
 1860:             }
 1861:         }
 1862:     }
 1863: 
 1864:     function getTagList () {
 1865:         
 1866:         var stringToSearch = document.lonhomework.innerHTML;
 1867: 
 1868:         var ret = new Array();
 1869:         var regex_findBlock = /(foldblock_.*?)"/g;
 1870:         var tag_list = stringToSearch.match(regex_findBlock);
 1871: 
 1872:         if(tag_list != null){
 1873:             for(var i = 0; i < tag_list.length; i++){            
 1874:                 ret.push(tag_list[i].replace(/"/, ''));
 1875:             }
 1876:         }
 1877:         return ret;
 1878:     }
 1879: 
 1880:     function saveScrollPosition (resource) {
 1881:         var tag_list = getTagList();
 1882: 
 1883:         // we dont always want to jump to the first block
 1884:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1885:         if(\$(window).scrollTop() > 170){
 1886:             if(tag_list != null){
 1887:                 var result;
 1888:                 for(var i = 0; i < tag_list.length; i++){
 1889:                     if(isElementInViewport(tag_list[i])){
 1890:                         result += tag_list[i]+';';
 1891:                     }
 1892:                 }
 1893:                 sessionStorage.setItem('anchor_'+resource, result);
 1894:             }
 1895:         } else {
 1896:             // we dont need to save zero, just delete the item to leave everything tidy
 1897:             sessionStorage.removeItem('anchor_'+resource);
 1898:         }
 1899:     }
 1900: 
 1901:     function restoreScrollPosition(resource){
 1902: 
 1903:         var elem = sessionStorage.getItem('anchor_'+resource);
 1904:         if(elem != null){
 1905:             var tag_list = elem.split(';');
 1906:             var elem_list;
 1907: 
 1908:             for(var i = 0; i < tag_list.length; i++){
 1909:                 elem_list = document.getElementsByName(tag_list[i]);
 1910:                 
 1911:                 if(elem_list.length > 0){
 1912:                     elem = elem_list[0];
 1913:                     break;
 1914:                 }
 1915:             }
 1916:             elem.scrollIntoView();
 1917:         }
 1918:     }
 1919: 
 1920:     function isElementInViewport(el) {
 1921: 
 1922:         // change to last element instead of first
 1923:         var elem = document.getElementsByName(el);
 1924:         var rect = elem[0].getBoundingClientRect();
 1925: 
 1926:         return (
 1927:             rect.top >= 0 &&
 1928:             rect.left >= 0 &&
 1929:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1930:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1931:         );
 1932:     }
 1933:     
 1934:     function autosize(depth){
 1935:         var cmInst = window['cm'+depth];
 1936:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1937: 
 1938:         // is fixed size, switching to dynamic
 1939:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1940:             cmInst.setSize("","auto");
 1941:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1942:             sessionStorage.setItem("autosized_"+depth, "yes");
 1943: 
 1944:         // is dynamic size, switching to fixed
 1945:         } else {
 1946:             cmInst.setSize("","300px");
 1947:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1948:             sessionStorage.removeItem("autosized_"+depth);
 1949:         }
 1950:     }
 1951: 
 1952: 
 1953: 
 1954: // ]]>
 1955: </script>
 1956: COLORFULEDIT
 1957: }
 1958: 
 1959: sub xmleditor_js {
 1960:     return <<XMLEDIT
 1961: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1962: <script type="text/javascript">
 1963: // <![CDATA[>
 1964: 
 1965:     function saveScrollPosition (resource) {
 1966: 
 1967:         var scrollPos = \$(window).scrollTop();
 1968:         sessionStorage.setItem(resource,scrollPos);
 1969:     }
 1970: 
 1971:     function restoreScrollPosition(resource){
 1972: 
 1973:         var scrollPos = sessionStorage.getItem(resource);
 1974:         \$(window).scrollTop(scrollPos);
 1975:     }
 1976: 
 1977:     // unless internet explorer
 1978:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1979: 
 1980:         \$(document).ready(function() {
 1981:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1982:         });
 1983:     }
 1984: 
 1985:     // inserts text at cursor position into codemirror (xml editor only)
 1986:     function insertText(text){
 1987:         cm.focus();
 1988:         var curPos = cm.getCursor();
 1989:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1990:     }
 1991: // ]]>
 1992: </script>
 1993: XMLEDIT
 1994: }
 1995: 
 1996: sub insert_folding_button {
 1997:     my $curDepth = $Apache::lonxml::curdepth;
 1998:     my $lastresource = $env{'request.ambiguous'};
 1999: 
 2000:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2001:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2002: }
 2003: 
 2004: =pod
 2005: 
 2006: =head1 Excel and CSV file utility routines
 2007: 
 2008: =cut
 2009: 
 2010: ###############################################################
 2011: ###############################################################
 2012: 
 2013: =pod
 2014: 
 2015: =over 4
 2016: 
 2017: =item * &csv_translate($text) 
 2018: 
 2019: Translate $text to allow it to be output as a 'comma separated values' 
 2020: format.
 2021: 
 2022: =cut
 2023: 
 2024: ###############################################################
 2025: ###############################################################
 2026: sub csv_translate {
 2027:     my $text = shift;
 2028:     $text =~ s/\"/\"\"/g;
 2029:     $text =~ s/\n/ /g;
 2030:     return $text;
 2031: }
 2032: 
 2033: ###############################################################
 2034: ###############################################################
 2035: 
 2036: =pod
 2037: 
 2038: =item * &define_excel_formats()
 2039: 
 2040: Define some commonly used Excel cell formats.
 2041: 
 2042: Currently supported formats:
 2043: 
 2044: =over 4
 2045: 
 2046: =item header
 2047: 
 2048: =item bold
 2049: 
 2050: =item h1
 2051: 
 2052: =item h2
 2053: 
 2054: =item h3
 2055: 
 2056: =item h4
 2057: 
 2058: =item i
 2059: 
 2060: =item date
 2061: 
 2062: =back
 2063: 
 2064: Inputs: $workbook
 2065: 
 2066: Returns: $format, a hash reference.
 2067: 
 2068: 
 2069: =cut
 2070: 
 2071: ###############################################################
 2072: ###############################################################
 2073: sub define_excel_formats {
 2074:     my ($workbook) = @_;
 2075:     my $format;
 2076:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2077:                                                 bottom    => 1,
 2078:                                                 align     => 'center');
 2079:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2080:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2081:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2082:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2083:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2084:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2085:     $format->{'date'} = $workbook->add_format(num_format=>
 2086:                                             'mm/dd/yyyy hh:mm:ss');
 2087:     return $format;
 2088: }
 2089: 
 2090: ###############################################################
 2091: ###############################################################
 2092: 
 2093: =pod
 2094: 
 2095: =item * &create_workbook()
 2096: 
 2097: Create an Excel worksheet.  If it fails, output message on the
 2098: request object and return undefs.
 2099: 
 2100: Inputs: Apache request object
 2101: 
 2102: Returns (undef) on failure, 
 2103:     Excel worksheet object, scalar with filename, and formats 
 2104:     from &Apache::loncommon::define_excel_formats on success
 2105: 
 2106: =cut
 2107: 
 2108: ###############################################################
 2109: ###############################################################
 2110: sub create_workbook {
 2111:     my ($r) = @_;
 2112:         #
 2113:     # Create the excel spreadsheet
 2114:     my $filename = '/prtspool/'.
 2115:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2116:         time.'_'.rand(1000000000).'.xls';
 2117:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2118:     if (! defined($workbook)) {
 2119:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2120:         $r->print(
 2121:             '<p class="LC_error">'
 2122:            .&mt('Problems occurred in creating the new Excel file.')
 2123:            .' '.&mt('This error has been logged.')
 2124:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2125:            .'</p>'
 2126:         );
 2127:         return (undef);
 2128:     }
 2129:     #
 2130:     $workbook->set_tempdir(LONCAPA::tempdir());
 2131:     #
 2132:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2133:     return ($workbook,$filename,$format);
 2134: }
 2135: 
 2136: ###############################################################
 2137: ###############################################################
 2138: 
 2139: =pod
 2140: 
 2141: =item * &create_text_file()
 2142: 
 2143: Create a file to write to and eventually make available to the user.
 2144: If file creation fails, outputs an error message on the request object and 
 2145: return undefs.
 2146: 
 2147: Inputs: Apache request object, and file suffix
 2148: 
 2149: Returns (undef) on failure, 
 2150:     Filehandle and filename on success.
 2151: 
 2152: =cut
 2153: 
 2154: ###############################################################
 2155: ###############################################################
 2156: sub create_text_file {
 2157:     my ($r,$suffix) = @_;
 2158:     if (! defined($suffix)) { $suffix = 'txt'; };
 2159:     my $fh;
 2160:     my $filename = '/prtspool/'.
 2161:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2162:         time.'_'.rand(1000000000).'.'.$suffix;
 2163:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2164:     if (! defined($fh)) {
 2165:         $r->log_error("Couldn't open $filename for output $!");
 2166:         $r->print(
 2167:             '<p class="LC_error">'
 2168:            .&mt('Problems occurred in creating the output file.')
 2169:            .' '.&mt('This error has been logged.')
 2170:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2171:            .'</p>'
 2172:         );
 2173:     }
 2174:     return ($fh,$filename)
 2175: }
 2176: 
 2177: 
 2178: =pod 
 2179: 
 2180: =back
 2181: 
 2182: =cut
 2183: 
 2184: ###############################################################
 2185: ##        Home server <option> list generating code          ##
 2186: ###############################################################
 2187: 
 2188: # ------------------------------------------
 2189: 
 2190: sub domain_select {
 2191:     my ($name,$value,$multiple)=@_;
 2192:     my %domains=map { 
 2193: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2194:     } &Apache::lonnet::all_domains();
 2195:     if ($multiple) {
 2196: 	$domains{''}=&mt('Any domain');
 2197: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2198: 	return &multiple_select_form($name,$value,4,\%domains);
 2199:     } else {
 2200: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2201: 	return &select_form($name,$value,\%domains);
 2202:     }
 2203: }
 2204: 
 2205: #-------------------------------------------
 2206: 
 2207: =pod
 2208: 
 2209: =head1 Routines for form select boxes
 2210: 
 2211: =over 4
 2212: 
 2213: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2214: 
 2215: Returns a string containing a <select> element int multiple mode
 2216: 
 2217: 
 2218: Args:
 2219:   $name - name of the <select> element
 2220:   $value - scalar or array ref of values that should already be selected
 2221:   $size - number of rows long the select element is
 2222:   $hash - the elements should be 'option' => 'shown text'
 2223:           (shown text should already have been &mt())
 2224:   $order - (optional) array ref of the order to show the elements in
 2225: 
 2226: =cut
 2227: 
 2228: #-------------------------------------------
 2229: sub multiple_select_form {
 2230:     my ($name,$value,$size,$hash,$order)=@_;
 2231:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2232:     my $output='';
 2233:     if (! defined($size)) {
 2234:         $size = 4;
 2235:         if (scalar(keys(%$hash))<4) {
 2236:             $size = scalar(keys(%$hash));
 2237:         }
 2238:     }
 2239:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2240:     my @order;
 2241:     if (ref($order) eq 'ARRAY')  {
 2242:         @order = @{$order};
 2243:     } else {
 2244:         @order = sort(keys(%$hash));
 2245:     }
 2246:     if (exists($$hash{'select_form_order'})) {
 2247:         @order = @{$$hash{'select_form_order'}};
 2248:     }
 2249:         
 2250:     foreach my $key (@order) {
 2251:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2252:         $output.='selected="selected" ' if ($selected{$key});
 2253:         $output.='>'.$hash->{$key}."</option>\n";
 2254:     }
 2255:     $output.="</select>\n";
 2256:     return $output;
 2257: }
 2258: 
 2259: #-------------------------------------------
 2260: 
 2261: =pod
 2262: 
 2263: =item * &select_form($defdom,$name,$hashref,$onchange)
 2264: 
 2265: Returns a string containing a <select name='$name' size='1'> form to 
 2266: allow a user to select options from a ref to a hash containing:
 2267: option_name => displayed text. An optional $onchange can include
 2268: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2269: 
 2270: See lonrights.pm for an example invocation and use.
 2271: 
 2272: =cut
 2273: 
 2274: #-------------------------------------------
 2275: sub select_form {
 2276:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2277:     return unless (ref($hashref) eq 'HASH');
 2278:     if ($onchange) {
 2279:         $onchange = ' onchange="'.$onchange.'"';
 2280:     }
 2281:     my $disabled;
 2282:     if ($readonly) {
 2283:         $disabled = ' disabled="disabled"';
 2284:     }
 2285:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2286:     my @keys;
 2287:     if (exists($hashref->{'select_form_order'})) {
 2288: 	@keys=@{$hashref->{'select_form_order'}};
 2289:     } else {
 2290: 	@keys=sort(keys(%{$hashref}));
 2291:     }
 2292:     foreach my $key (@keys) {
 2293:         $selectform.=
 2294: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2295:             ($key eq $def ? 'selected="selected" ' : '').
 2296:                 ">".$hashref->{$key}."</option>\n";
 2297:     }
 2298:     $selectform.="</select>";
 2299:     return $selectform;
 2300: }
 2301: 
 2302: # For display filters
 2303: 
 2304: sub display_filter {
 2305:     my ($context) = @_;
 2306:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2307:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2308:     my $phraseinput = 'hidden';
 2309:     my $includeinput = 'hidden';
 2310:     my ($checked,$includetypestext);
 2311:     if ($env{'form.displayfilter'} eq 'containing') {
 2312:         $phraseinput = 'text'; 
 2313:         if ($context eq 'parmslog') {
 2314:             $includeinput = 'checkbox';
 2315:             if ($env{'form.includetypes'}) {
 2316:                 $checked = ' checked="checked"';
 2317:             }
 2318:             $includetypestext = &mt('Include parameter types');
 2319:         }
 2320:     } else {
 2321:         $includetypestext = '&nbsp;';
 2322:     }
 2323:     my ($additional,$secondid,$thirdid);
 2324:     if ($context eq 'parmslog') {
 2325:         $additional = 
 2326:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2327:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2328:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2329:             '</label>';
 2330:         $secondid = 'includetypes';
 2331:         $thirdid = 'includetypestext';
 2332:     }
 2333:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2334:                                                     '$secondid','$thirdid')";
 2335:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2336: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2337: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2338: 	   '</label></span> <span class="LC_nobreak">'.
 2339:            &mt('Filter: [_1]',
 2340: 	   &select_form($env{'form.displayfilter'},
 2341: 			'displayfilter',
 2342: 			{'currentfolder' => 'Current folder/page',
 2343: 			 'containing' => 'Containing phrase',
 2344: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2345: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2346:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2347:                          '" />'.$additional;
 2348: }
 2349: 
 2350: sub display_filter_js {
 2351:     my $includetext = &mt('Include parameter types');
 2352:     return <<"ENDJS";
 2353:   
 2354: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2355:     var firstType = 'hidden';
 2356:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2357:         firstType = 'text';
 2358:     }
 2359:     firstObject = document.getElementById(firstid);
 2360:     if (typeof(firstObject) == 'object') {
 2361:         if (firstObject.type != firstType) {
 2362:             changeInputType(firstObject,firstType);
 2363:         }
 2364:     }
 2365:     if (context == 'parmslog') {
 2366:         var secondType = 'hidden';
 2367:         if (firstType == 'text') {
 2368:             secondType = 'checkbox';
 2369:         }
 2370:         secondObject = document.getElementById(secondid);  
 2371:         if (typeof(secondObject) == 'object') {
 2372:             if (secondObject.type != secondType) {
 2373:                 changeInputType(secondObject,secondType);
 2374:             }
 2375:         }
 2376:         var textItem = document.getElementById(thirdid);
 2377:         var currtext = textItem.innerHTML;
 2378:         var newtext;
 2379:         if (firstType == 'text') {
 2380:             newtext = '$includetext';
 2381:         } else {
 2382:             newtext = '&nbsp;';
 2383:         }
 2384:         if (currtext != newtext) {
 2385:             textItem.innerHTML = newtext;
 2386:         }
 2387:     }
 2388:     return;
 2389: }
 2390: 
 2391: function changeInputType(oldObject,newType) {
 2392:     var newObject = document.createElement('input');
 2393:     newObject.type = newType;
 2394:     if (oldObject.size) {
 2395:         newObject.size = oldObject.size;
 2396:     }
 2397:     if (oldObject.value) {
 2398:         newObject.value = oldObject.value;
 2399:     }
 2400:     if (oldObject.name) {
 2401:         newObject.name = oldObject.name;
 2402:     }
 2403:     if (oldObject.id) {
 2404:         newObject.id = oldObject.id;
 2405:     }
 2406:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2407:     return;
 2408: }
 2409: 
 2410: ENDJS
 2411: }
 2412: 
 2413: sub gradeleveldescription {
 2414:     my $gradelevel=shift;
 2415:     my %gradelevels=(0 => 'Not specified',
 2416: 		     1 => 'Grade 1',
 2417: 		     2 => 'Grade 2',
 2418: 		     3 => 'Grade 3',
 2419: 		     4 => 'Grade 4',
 2420: 		     5 => 'Grade 5',
 2421: 		     6 => 'Grade 6',
 2422: 		     7 => 'Grade 7',
 2423: 		     8 => 'Grade 8',
 2424: 		     9 => 'Grade 9',
 2425: 		     10 => 'Grade 10',
 2426: 		     11 => 'Grade 11',
 2427: 		     12 => 'Grade 12',
 2428: 		     13 => 'Grade 13',
 2429: 		     14 => '100 Level',
 2430: 		     15 => '200 Level',
 2431: 		     16 => '300 Level',
 2432: 		     17 => '400 Level',
 2433: 		     18 => 'Graduate Level');
 2434:     return &mt($gradelevels{$gradelevel});
 2435: }
 2436: 
 2437: sub select_level_form {
 2438:     my ($deflevel,$name)=@_;
 2439:     unless ($deflevel) { $deflevel=0; }
 2440:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2441:     for (my $i=0; $i<=18; $i++) {
 2442:         $selectform.="<option value=\"$i\" ".
 2443:             ($i==$deflevel ? 'selected="selected" ' : '').
 2444:                 ">".&gradeleveldescription($i)."</option>\n";
 2445:     }
 2446:     $selectform.="</select>";
 2447:     return $selectform;
 2448: }
 2449: 
 2450: #-------------------------------------------
 2451: 
 2452: =pod
 2453: 
 2454: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2455: 
 2456: Returns a string containing a <select name='$name' size='1'> form to 
 2457: allow a user to select the domain to preform an operation in.  
 2458: See loncreateuser.pm for an example invocation and use.
 2459: 
 2460: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2461: selected");
 2462: 
 2463: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2464: 
 2465: 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.
 2466: 
 2467: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2468: 
 2469: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2470: 
 2471: =cut
 2472: 
 2473: #-------------------------------------------
 2474: sub select_dom_form {
 2475:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2476:     if ($onchange) {
 2477:         $onchange = ' onchange="'.$onchange.'"';
 2478:     }
 2479:     my (@domains,%exclude);
 2480:     if (ref($incdoms) eq 'ARRAY') {
 2481:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2482:     } else {
 2483:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2484:     }
 2485:     if ($includeempty) { @domains=('',@domains); }
 2486:     if (ref($excdoms) eq 'ARRAY') {
 2487:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2488:     }
 2489:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2490:     foreach my $dom (@domains) {
 2491:         next if ($exclude{$dom});
 2492:         $selectdomain.="<option value=\"$dom\" ".
 2493:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2494:         if ($showdomdesc) {
 2495:             if ($dom ne '') {
 2496:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2497:                 if ($domdesc ne '') {
 2498:                     $selectdomain .= ' ('.$domdesc.')';
 2499:                 }
 2500:             } 
 2501:         }
 2502:         $selectdomain .= "</option>\n";
 2503:     }
 2504:     $selectdomain.="</select>";
 2505:     return $selectdomain;
 2506: }
 2507: 
 2508: #-------------------------------------------
 2509: 
 2510: =pod
 2511: 
 2512: =item * &home_server_form_item($domain,$name,$defaultflag)
 2513: 
 2514: input: 4 arguments (two required, two optional) - 
 2515:     $domain - domain of new user
 2516:     $name - name of form element
 2517:     $default - Value of 'default' causes a default item to be first 
 2518:                             option, and selected by default. 
 2519:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2520:                             if 1 server found, or default, if 0 found.
 2521: output: returns 2 items: 
 2522: (a) form element which contains either:
 2523:    (i) <select name="$name">
 2524:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2525:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2526:        </select>
 2527:        form item if there are multiple library servers in $domain, or
 2528:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2529:        if there is only one library server in $domain.
 2530: 
 2531: (b) number of library servers found.
 2532: 
 2533: See loncreateuser.pm for example of use.
 2534: 
 2535: =cut
 2536: 
 2537: #-------------------------------------------
 2538: sub home_server_form_item {
 2539:     my ($domain,$name,$default,$hide) = @_;
 2540:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2541:     my $result;
 2542:     my $numlib = keys(%servers);
 2543:     if ($numlib > 1) {
 2544:         $result .= '<select name="'.$name.'" />'."\n";
 2545:         if ($default) {
 2546:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2547:                        '</option>'."\n";
 2548:         }
 2549:         foreach my $hostid (sort(keys(%servers))) {
 2550:             $result.= '<option value="'.$hostid.'">'.
 2551: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2552:         }
 2553:         $result .= '</select>'."\n";
 2554:     } elsif ($numlib == 1) {
 2555:         my $hostid;
 2556:         foreach my $item (keys(%servers)) {
 2557:             $hostid = $item;
 2558:         }
 2559:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2560:                    $hostid.'" />';
 2561:                    if (!$hide) {
 2562:                        $result .= $hostid.' '.$servers{$hostid};
 2563:                    }
 2564:                    $result .= "\n";
 2565:     } elsif ($default) {
 2566:         $result .= '<input type="hidden" name="'.$name.
 2567:                    '" value="default" />';
 2568:                    if (!$hide) {
 2569:                        $result .= &mt('default');
 2570:                    }
 2571:                    $result .= "\n";
 2572:     }
 2573:     return ($result,$numlib);
 2574: }
 2575: 
 2576: =pod
 2577: 
 2578: =back 
 2579: 
 2580: =cut
 2581: 
 2582: ###############################################################
 2583: ##                  Decoding User Agent                      ##
 2584: ###############################################################
 2585: 
 2586: =pod
 2587: 
 2588: =head1 Decoding the User Agent
 2589: 
 2590: =over 4
 2591: 
 2592: =item * &decode_user_agent()
 2593: 
 2594: Inputs: $r
 2595: 
 2596: Outputs:
 2597: 
 2598: =over 4
 2599: 
 2600: =item * $httpbrowser
 2601: 
 2602: =item * $clientbrowser
 2603: 
 2604: =item * $clientversion
 2605: 
 2606: =item * $clientmathml
 2607: 
 2608: =item * $clientunicode
 2609: 
 2610: =item * $clientos
 2611: 
 2612: =item * $clientmobile
 2613: 
 2614: =item * $clientinfo
 2615: 
 2616: =item * $clientosversion
 2617: 
 2618: =back
 2619: 
 2620: =back 
 2621: 
 2622: =cut
 2623: 
 2624: ###############################################################
 2625: ###############################################################
 2626: sub decode_user_agent {
 2627:     my ($r)=@_;
 2628:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2629:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2630:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2631:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2632:     my $clientbrowser='unknown';
 2633:     my $clientversion='0';
 2634:     my $clientmathml='';
 2635:     my $clientunicode='0';
 2636:     my $clientmobile=0;
 2637:     my $clientosversion='';
 2638:     for (my $i=0;$i<=$#browsertype;$i++) {
 2639:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2640: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2641: 	    $clientbrowser=$bname;
 2642:             $httpbrowser=~/$vreg/i;
 2643: 	    $clientversion=$1;
 2644:             $clientmathml=($clientversion>=$minv);
 2645:             $clientunicode=($clientversion>=$univ);
 2646: 	}
 2647:     }
 2648:     my $clientos='unknown';
 2649:     my $clientinfo;
 2650:     if (($httpbrowser=~/linux/i) ||
 2651:         ($httpbrowser=~/unix/i) ||
 2652:         ($httpbrowser=~/ux/i) ||
 2653:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2654:     if (($httpbrowser=~/vax/i) ||
 2655:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2656:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2657:     if (($httpbrowser=~/mac/i) ||
 2658:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2659:     if ($httpbrowser=~/win/i) {
 2660:         $clientos='win';
 2661:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2662:             $clientosversion = $1;
 2663:         }
 2664:     }
 2665:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2666:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2667:         $clientmobile=lc($1);
 2668:     }
 2669:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2670:         $clientinfo = 'firefox-'.$1;
 2671:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2672:         $clientinfo = 'chromeframe-'.$1;
 2673:     }
 2674:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2675:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2676:             $clientosversion);
 2677: }
 2678: 
 2679: ###############################################################
 2680: ##    Authentication changing form generation subroutines    ##
 2681: ###############################################################
 2682: ##
 2683: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2684: ## hash, and have reasonable default values.
 2685: ##
 2686: ##    formname = the name given in the <form> tag.
 2687: #-------------------------------------------
 2688: 
 2689: =pod
 2690: 
 2691: =head1 Authentication Routines
 2692: 
 2693: =over 4
 2694: 
 2695: =item * &authform_xxxxxx()
 2696: 
 2697: The authform_xxxxxx subroutines provide javascript and html forms which 
 2698: handle some of the conveniences required for authentication forms.  
 2699: This is not an optimal method, but it works.  
 2700: 
 2701: =over 4
 2702: 
 2703: =item * authform_header
 2704: 
 2705: =item * authform_authorwarning
 2706: 
 2707: =item * authform_nochange
 2708: 
 2709: =item * authform_kerberos
 2710: 
 2711: =item * authform_internal
 2712: 
 2713: =item * authform_filesystem
 2714: 
 2715: =back
 2716: 
 2717: See loncreateuser.pm for invocation and use examples.
 2718: 
 2719: =cut
 2720: 
 2721: #-------------------------------------------
 2722: sub authform_header{  
 2723:     my %in = (
 2724:         formname => 'cu',
 2725:         kerb_def_dom => '',
 2726:         @_,
 2727:     );
 2728:     $in{'formname'} = 'document.' . $in{'formname'};
 2729:     my $result='';
 2730: 
 2731: #---------------------------------------------- Code for upper case translation
 2732:     my $Javascript_toUpperCase;
 2733:     unless ($in{kerb_def_dom}) {
 2734:         $Javascript_toUpperCase =<<"END";
 2735:         switch (choice) {
 2736:            case 'krb': currentform.elements[choicearg].value =
 2737:                currentform.elements[choicearg].value.toUpperCase();
 2738:                break;
 2739:            default:
 2740:         }
 2741: END
 2742:     } else {
 2743:         $Javascript_toUpperCase = "";
 2744:     }
 2745: 
 2746:     my $radioval = "'nochange'";
 2747:     if (defined($in{'curr_authtype'})) {
 2748:         if ($in{'curr_authtype'} ne '') {
 2749:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2750:         }
 2751:     }
 2752:     my $argfield = 'null';
 2753:     if (defined($in{'mode'})) {
 2754:         if ($in{'mode'} eq 'modifycourse')  {
 2755:             if (defined($in{'curr_autharg'})) {
 2756:                 if ($in{'curr_autharg'} ne '') {
 2757:                     $argfield = "'$in{'curr_autharg'}'";
 2758:                 }
 2759:             }
 2760:         }
 2761:     }
 2762: 
 2763:     $result.=<<"END";
 2764: var current = new Object();
 2765: current.radiovalue = $radioval;
 2766: current.argfield = $argfield;
 2767: 
 2768: function changed_radio(choice,currentform) {
 2769:     var choicearg = choice + 'arg';
 2770:     // If a radio button in changed, we need to change the argfield
 2771:     if (current.radiovalue != choice) {
 2772:         current.radiovalue = choice;
 2773:         if (current.argfield != null) {
 2774:             currentform.elements[current.argfield].value = '';
 2775:         }
 2776:         if (choice == 'nochange') {
 2777:             current.argfield = null;
 2778:         } else {
 2779:             current.argfield = choicearg;
 2780:             switch(choice) {
 2781:                 case 'krb': 
 2782:                     currentform.elements[current.argfield].value = 
 2783:                         "$in{'kerb_def_dom'}";
 2784:                 break;
 2785:               default:
 2786:                 break;
 2787:             }
 2788:         }
 2789:     }
 2790:     return;
 2791: }
 2792: 
 2793: function changed_text(choice,currentform) {
 2794:     var choicearg = choice + 'arg';
 2795:     if (currentform.elements[choicearg].value !='') {
 2796:         $Javascript_toUpperCase
 2797:         // clear old field
 2798:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2799:             currentform.elements[current.argfield].value = '';
 2800:         }
 2801:         current.argfield = choicearg;
 2802:     }
 2803:     set_auth_radio_buttons(choice,currentform);
 2804:     return;
 2805: }
 2806: 
 2807: function set_auth_radio_buttons(newvalue,currentform) {
 2808:     var numauthchoices = currentform.login.length;
 2809:     if (typeof numauthchoices  == "undefined") {
 2810:         return;
 2811:     } 
 2812:     var i=0;
 2813:     while (i < numauthchoices) {
 2814:         if (currentform.login[i].value == newvalue) { break; }
 2815:         i++;
 2816:     }
 2817:     if (i == numauthchoices) {
 2818:         return;
 2819:     }
 2820:     current.radiovalue = newvalue;
 2821:     currentform.login[i].checked = true;
 2822:     return;
 2823: }
 2824: END
 2825:     return $result;
 2826: }
 2827: 
 2828: sub authform_authorwarning {
 2829:     my $result='';
 2830:     $result='<i>'.
 2831:         &mt('As a general rule, only authors or co-authors should be '.
 2832:             'filesystem authenticated '.
 2833:             '(which allows access to the server filesystem).')."</i>\n";
 2834:     return $result;
 2835: }
 2836: 
 2837: sub authform_nochange {
 2838:     my %in = (
 2839:               formname => 'document.cu',
 2840:               kerb_def_dom => 'MSU.EDU',
 2841:               @_,
 2842:           );
 2843:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2844:     my $result;
 2845:     if (!$authnum) {
 2846:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2847:     } else {
 2848:         $result = '<label>'.&mt('[_1] Do not change login data',
 2849:                   '<input type="radio" name="login" value="nochange" '.
 2850:                   'checked="checked" onclick="'.
 2851:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2852: 	    '</label>';
 2853:     }
 2854:     return $result;
 2855: }
 2856: 
 2857: sub authform_kerberos {
 2858:     my %in = (
 2859:               formname => 'document.cu',
 2860:               kerb_def_dom => 'MSU.EDU',
 2861:               kerb_def_auth => 'krb4',
 2862:               @_,
 2863:               );
 2864:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2865:         $autharg,$jscall);
 2866:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2867:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2868:        $check5 = ' checked="checked"';
 2869:     } else {
 2870:        $check4 = ' checked="checked"';
 2871:     }
 2872:     $krbarg = $in{'kerb_def_dom'};
 2873:     if (defined($in{'curr_authtype'})) {
 2874:         if ($in{'curr_authtype'} eq 'krb') {
 2875:             $krbcheck = ' checked="checked"';
 2876:             if (defined($in{'mode'})) {
 2877:                 if ($in{'mode'} eq 'modifyuser') {
 2878:                     $krbcheck = '';
 2879:                 }
 2880:             }
 2881:             if (defined($in{'curr_kerb_ver'})) {
 2882:                 if ($in{'curr_krb_ver'} eq '5') {
 2883:                     $check5 = ' checked="checked"';
 2884:                     $check4 = '';
 2885:                 } else {
 2886:                     $check4 = ' checked="checked"';
 2887:                     $check5 = '';
 2888:                 }
 2889:             }
 2890:             if (defined($in{'curr_autharg'})) {
 2891:                 $krbarg = $in{'curr_autharg'};
 2892:             }
 2893:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2894:                 if (defined($in{'curr_autharg'})) {
 2895:                     $result = 
 2896:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2897:         $in{'curr_autharg'},$krbver);
 2898:                 } else {
 2899:                     $result =
 2900:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2901:                 }
 2902:                 return $result; 
 2903:             }
 2904:         }
 2905:     } else {
 2906:         if ($authnum == 1) {
 2907:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2908:         }
 2909:     }
 2910:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2911:         return;
 2912:     } elsif ($authtype eq '') {
 2913:         if (defined($in{'mode'})) {
 2914:             if ($in{'mode'} eq 'modifycourse') {
 2915:                 if ($authnum == 1) {
 2916:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2917:                 }
 2918:             }
 2919:         }
 2920:     }
 2921:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2922:     if ($authtype eq '') {
 2923:         $authtype = '<input type="radio" name="login" value="krb" '.
 2924:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2925:                     $krbcheck.' />';
 2926:     }
 2927:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2928:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2929:          $in{'curr_authtype'} eq 'krb5') ||
 2930:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2931:          $in{'curr_authtype'} eq 'krb4')) {
 2932:         $result .= &mt
 2933:         ('[_1] Kerberos authenticated with domain [_2] '.
 2934:          '[_3] Version 4 [_4] Version 5 [_5]',
 2935:          '<label>'.$authtype,
 2936:          '</label><input type="text" size="10" name="krbarg" '.
 2937:              'value="'.$krbarg.'" '.
 2938:              'onchange="'.$jscall.'" />',
 2939:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2940:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2941: 	 '</label>');
 2942:     } elsif ($can_assign{'krb4'}) {
 2943:         $result .= &mt
 2944:         ('[_1] Kerberos authenticated with domain [_2] '.
 2945:          '[_3] Version 4 [_4]',
 2946:          '<label>'.$authtype,
 2947:          '</label><input type="text" size="10" name="krbarg" '.
 2948:              'value="'.$krbarg.'" '.
 2949:              'onchange="'.$jscall.'" />',
 2950:          '<label><input type="hidden" name="krbver" value="4" />',
 2951:          '</label>');
 2952:     } elsif ($can_assign{'krb5'}) {
 2953:         $result .= &mt
 2954:         ('[_1] Kerberos authenticated with domain [_2] '.
 2955:          '[_3] Version 5 [_4]',
 2956:          '<label>'.$authtype,
 2957:          '</label><input type="text" size="10" name="krbarg" '.
 2958:              'value="'.$krbarg.'" '.
 2959:              'onchange="'.$jscall.'" />',
 2960:          '<label><input type="hidden" name="krbver" value="5" />',
 2961:          '</label>');
 2962:     }
 2963:     return $result;
 2964: }
 2965: 
 2966: sub authform_internal {
 2967:     my %in = (
 2968:                 formname => 'document.cu',
 2969:                 kerb_def_dom => 'MSU.EDU',
 2970:                 @_,
 2971:                 );
 2972:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2973:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2974:     if (defined($in{'curr_authtype'})) {
 2975:         if ($in{'curr_authtype'} eq 'int') {
 2976:             if ($can_assign{'int'}) {
 2977:                 $intcheck = 'checked="checked" ';
 2978:                 if (defined($in{'mode'})) {
 2979:                     if ($in{'mode'} eq 'modifyuser') {
 2980:                         $intcheck = '';
 2981:                     }
 2982:                 }
 2983:                 if (defined($in{'curr_autharg'})) {
 2984:                     $intarg = $in{'curr_autharg'};
 2985:                 }
 2986:             } else {
 2987:                 $result = &mt('Currently internally authenticated.');
 2988:                 return $result;
 2989:             }
 2990:         }
 2991:     } else {
 2992:         if ($authnum == 1) {
 2993:             $authtype = '<input type="hidden" name="login" value="int" />';
 2994:         }
 2995:     }
 2996:     if (!$can_assign{'int'}) {
 2997:         return;
 2998:     } elsif ($authtype eq '') {
 2999:         if (defined($in{'mode'})) {
 3000:             if ($in{'mode'} eq 'modifycourse') {
 3001:                 if ($authnum == 1) {
 3002:                     $authtype = '<input type="radio" name="login" value="int" />';
 3003:                 }
 3004:             }
 3005:         }
 3006:     }
 3007:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3008:     if ($authtype eq '') {
 3009:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3010:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 3011:     }
 3012:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3013:                $intarg.'" onchange="'.$jscall.'" />';
 3014:     $result = &mt
 3015:         ('[_1] Internally authenticated (with initial password [_2])',
 3016:          '<label>'.$authtype,'</label>'.$autharg);
 3017:     $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>';
 3018:     return $result;
 3019: }
 3020: 
 3021: sub authform_local {
 3022:     my %in = (
 3023:               formname => 'document.cu',
 3024:               kerb_def_dom => 'MSU.EDU',
 3025:               @_,
 3026:               );
 3027:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 3028:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3029:     if (defined($in{'curr_authtype'})) {
 3030:         if ($in{'curr_authtype'} eq 'loc') {
 3031:             if ($can_assign{'loc'}) {
 3032:                 $loccheck = 'checked="checked" ';
 3033:                 if (defined($in{'mode'})) {
 3034:                     if ($in{'mode'} eq 'modifyuser') {
 3035:                         $loccheck = '';
 3036:                     }
 3037:                 }
 3038:                 if (defined($in{'curr_autharg'})) {
 3039:                     $locarg = $in{'curr_autharg'};
 3040:                 }
 3041:             } else {
 3042:                 $result = &mt('Currently using local (institutional) authentication.');
 3043:                 return $result;
 3044:             }
 3045:         }
 3046:     } else {
 3047:         if ($authnum == 1) {
 3048:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3049:         }
 3050:     }
 3051:     if (!$can_assign{'loc'}) {
 3052:         return;
 3053:     } elsif ($authtype eq '') {
 3054:         if (defined($in{'mode'})) {
 3055:             if ($in{'mode'} eq 'modifycourse') {
 3056:                 if ($authnum == 1) {
 3057:                     $authtype = '<input type="radio" name="login" value="loc" />';
 3058:                 }
 3059:             }
 3060:         }
 3061:     }
 3062:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3063:     if ($authtype eq '') {
 3064:         $authtype = '<input type="radio" name="login" value="loc" '.
 3065:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3066:                     $jscall.'" />';
 3067:     }
 3068:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3069:                $locarg.'" onchange="'.$jscall.'" />';
 3070:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3071:                   '<label>'.$authtype,'</label>'.$autharg);
 3072:     return $result;
 3073: }
 3074: 
 3075: sub authform_filesystem {
 3076:     my %in = (
 3077:               formname => 'document.cu',
 3078:               kerb_def_dom => 'MSU.EDU',
 3079:               @_,
 3080:               );
 3081:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 3082:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3083:     if (defined($in{'curr_authtype'})) {
 3084:         if ($in{'curr_authtype'} eq 'fsys') {
 3085:             if ($can_assign{'fsys'}) {
 3086:                 $fsyscheck = 'checked="checked" ';
 3087:                 if (defined($in{'mode'})) {
 3088:                     if ($in{'mode'} eq 'modifyuser') {
 3089:                         $fsyscheck = '';
 3090:                     }
 3091:                 }
 3092:             } else {
 3093:                 $result = &mt('Currently Filesystem Authenticated.');
 3094:                 return $result;
 3095:             }           
 3096:         }
 3097:     } else {
 3098:         if ($authnum == 1) {
 3099:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3100:         }
 3101:     }
 3102:     if (!$can_assign{'fsys'}) {
 3103:         return;
 3104:     } elsif ($authtype eq '') {
 3105:         if (defined($in{'mode'})) {
 3106:             if ($in{'mode'} eq 'modifycourse') {
 3107:                 if ($authnum == 1) {
 3108:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 3109:                 }
 3110:             }
 3111:         }
 3112:     }
 3113:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3114:     if ($authtype eq '') {
 3115:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3116:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3117:                     $jscall.'" />';
 3118:     }
 3119:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3120:                ' onchange="'.$jscall.'" />';
 3121:     $result = &mt
 3122:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3123:          '<label><input type="radio" name="login" value="fsys" '.
 3124:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 3125:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3126:                   'onchange="'.$jscall.'" />');
 3127:     return $result;
 3128: }
 3129: 
 3130: sub get_assignable_auth {
 3131:     my ($dom) = @_;
 3132:     if ($dom eq '') {
 3133:         $dom = $env{'request.role.domain'};
 3134:     }
 3135:     my %can_assign = (
 3136:                           krb4 => 1,
 3137:                           krb5 => 1,
 3138:                           int  => 1,
 3139:                           loc  => 1,
 3140:                      );
 3141:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3142:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3143:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3144:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3145:             my $context;
 3146:             if ($env{'request.role'} =~ /^au/) {
 3147:                 $context = 'author';
 3148:             } elsif ($env{'request.role'} =~ /^dc/) {
 3149:                 $context = 'domain';
 3150:             } elsif ($env{'request.course.id'}) {
 3151:                 $context = 'course';
 3152:             }
 3153:             if ($context) {
 3154:                 if (ref($authhash->{$context}) eq 'HASH') {
 3155:                    %can_assign = %{$authhash->{$context}}; 
 3156:                 }
 3157:             }
 3158:         }
 3159:     }
 3160:     my $authnum = 0;
 3161:     foreach my $key (keys(%can_assign)) {
 3162:         if ($can_assign{$key}) {
 3163:             $authnum ++;
 3164:         }
 3165:     }
 3166:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3167:         $authnum --;
 3168:     }
 3169:     return ($authnum,%can_assign);
 3170: }
 3171: 
 3172: ###############################################################
 3173: ##    Get Kerberos Defaults for Domain                 ##
 3174: ###############################################################
 3175: ##
 3176: ## Returns default kerberos version and an associated argument
 3177: ## as listed in file domain.tab. If not listed, provides
 3178: ## appropriate default domain and kerberos version.
 3179: ##
 3180: #-------------------------------------------
 3181: 
 3182: =pod
 3183: 
 3184: =item * &get_kerberos_defaults()
 3185: 
 3186: get_kerberos_defaults($target_domain) returns the default kerberos
 3187: version and domain. If not found, it defaults to version 4 and the 
 3188: domain of the server.
 3189: 
 3190: =over 4
 3191: 
 3192: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3193: 
 3194: =back
 3195: 
 3196: =back
 3197: 
 3198: =cut
 3199: 
 3200: #-------------------------------------------
 3201: sub get_kerberos_defaults {
 3202:     my $domain=shift;
 3203:     my ($krbdef,$krbdefdom);
 3204:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3205:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3206:         $krbdef = $domdefaults{'auth_def'};
 3207:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3208:     } else {
 3209:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3210:         my $krbdefdom=$1;
 3211:         $krbdefdom=~tr/a-z/A-Z/;
 3212:         $krbdef = "krb4";
 3213:     }
 3214:     return ($krbdef,$krbdefdom);
 3215: }
 3216: 
 3217: 
 3218: ###############################################################
 3219: ##                Thesaurus Functions                        ##
 3220: ###############################################################
 3221: 
 3222: =pod
 3223: 
 3224: =head1 Thesaurus Functions
 3225: 
 3226: =over 4
 3227: 
 3228: =item * &initialize_keywords()
 3229: 
 3230: Initializes the package variable %Keywords if it is empty.  Uses the
 3231: package variable $thesaurus_db_file.
 3232: 
 3233: =cut
 3234: 
 3235: ###################################################
 3236: 
 3237: sub initialize_keywords {
 3238:     return 1 if (scalar keys(%Keywords));
 3239:     # If we are here, %Keywords is empty, so fill it up
 3240:     #   Make sure the file we need exists...
 3241:     if (! -e $thesaurus_db_file) {
 3242:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3243:                                  " failed because it does not exist");
 3244:         return 0;
 3245:     }
 3246:     #   Set up the hash as a database
 3247:     my %thesaurus_db;
 3248:     if (! tie(%thesaurus_db,'GDBM_File',
 3249:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3250:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3251:                                  $thesaurus_db_file);
 3252:         return 0;
 3253:     } 
 3254:     #  Get the average number of appearances of a word.
 3255:     my $avecount = $thesaurus_db{'average.count'};
 3256:     #  Put keywords (those that appear > average) into %Keywords
 3257:     while (my ($word,$data)=each (%thesaurus_db)) {
 3258:         my ($count,undef) = split /:/,$data;
 3259:         $Keywords{$word}++ if ($count > $avecount);
 3260:     }
 3261:     untie %thesaurus_db;
 3262:     # Remove special values from %Keywords.
 3263:     foreach my $value ('total.count','average.count') {
 3264:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3265:   }
 3266:     return 1;
 3267: }
 3268: 
 3269: ###################################################
 3270: 
 3271: =pod
 3272: 
 3273: =item * &keyword($word)
 3274: 
 3275: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3276: than the average number of times in the thesaurus database.  Calls 
 3277: &initialize_keywords
 3278: 
 3279: =cut
 3280: 
 3281: ###################################################
 3282: 
 3283: sub keyword {
 3284:     return if (!&initialize_keywords());
 3285:     my $word=lc(shift());
 3286:     $word=~s/\W//g;
 3287:     return exists($Keywords{$word});
 3288: }
 3289: 
 3290: ###############################################################
 3291: 
 3292: =pod 
 3293: 
 3294: =item * &get_related_words()
 3295: 
 3296: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3297: an array of words.  If the keyword is not in the thesaurus, an empty array
 3298: will be returned.  The order of the words returned is determined by the
 3299: database which holds them.
 3300: 
 3301: Uses global $thesaurus_db_file.
 3302: 
 3303: 
 3304: =cut
 3305: 
 3306: ###############################################################
 3307: sub get_related_words {
 3308:     my $keyword = shift;
 3309:     my %thesaurus_db;
 3310:     if (! -e $thesaurus_db_file) {
 3311:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3312:                                  "failed because the file does not exist");
 3313:         return ();
 3314:     }
 3315:     if (! tie(%thesaurus_db,'GDBM_File',
 3316:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3317:         return ();
 3318:     } 
 3319:     my @Words=();
 3320:     my $count=0;
 3321:     if (exists($thesaurus_db{$keyword})) {
 3322: 	# The first element is the number of times
 3323: 	# the word appears.  We do not need it now.
 3324: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3325: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3326: 	my $threshold=$mostfrequentcount/10;
 3327:         foreach my $possibleword (@RelatedWords) {
 3328:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3329:             if ($wordcount>$threshold) {
 3330: 		push(@Words,$word);
 3331:                 $count++;
 3332:                 if ($count>10) { last; }
 3333: 	    }
 3334:         }
 3335:     }
 3336:     untie %thesaurus_db;
 3337:     return @Words;
 3338: }
 3339: ###############################################################
 3340: #
 3341: #  Spell checking
 3342: #
 3343: 
 3344: =pod
 3345: 
 3346: =back
 3347: 
 3348: =head1 Spell checking
 3349: 
 3350: =over 4
 3351: 
 3352: =item * &check_spelling($wordlist $language)
 3353: 
 3354: Takes a string containing words and feeds it to an external
 3355: spellcheck program via a pipeline. Returns a string containing
 3356: them mis-spelled words.
 3357: 
 3358: Parameters:
 3359: 
 3360: =over 4
 3361: 
 3362: =item - $wordlist
 3363: 
 3364: String that will be fed into the spellcheck program.
 3365: 
 3366: =item - $language
 3367: 
 3368: Language string that specifies the language for which the spell
 3369: check will be performed.
 3370: 
 3371: =back
 3372: 
 3373: =back
 3374: 
 3375: Note: This sub assumes that aspell is installed.
 3376: 
 3377: 
 3378: =cut
 3379: 
 3380: 
 3381: sub check_spelling {
 3382:     my ($wordlist, $language) = @_;
 3383:     my @misspellings;
 3384:     
 3385:     # Generate the speller and set the langauge.
 3386:     # if explicitly selected:
 3387: 
 3388:     my $speller = Text::Aspell->new;
 3389:     if ($language) {
 3390: 	$speller->set_option('lang', $language);
 3391:     }
 3392: 
 3393:     # Turn the word list into an array of words by splittingon whitespace
 3394: 
 3395:     my @words = split(/\s+/, $wordlist);
 3396: 
 3397:     foreach my $word (@words) {
 3398: 	if(! $speller->check($word)) {
 3399: 	    push(@misspellings, $word);
 3400: 	}
 3401:     }
 3402:     return join(' ', @misspellings);
 3403:     
 3404: }
 3405: 
 3406: # -------------------------------------------------------------- Plaintext name
 3407: =pod
 3408: 
 3409: =head1 User Name Functions
 3410: 
 3411: =over 4
 3412: 
 3413: =item * &plainname($uname,$udom,$first)
 3414: 
 3415: Takes a users logon name and returns it as a string in
 3416: "first middle last generation" form 
 3417: if $first is set to 'lastname' then it returns it as
 3418: 'lastname generation, firstname middlename' if their is a lastname
 3419: 
 3420: =cut
 3421: 
 3422: 
 3423: ###############################################################
 3424: sub plainname {
 3425:     my ($uname,$udom,$first)=@_;
 3426:     return if (!defined($uname) || !defined($udom));
 3427:     my %names=&getnames($uname,$udom);
 3428:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3429: 					  $names{'middlename'},
 3430: 					  $names{'lastname'},
 3431: 					  $names{'generation'},$first);
 3432:     $name=~s/^\s+//;
 3433:     $name=~s/\s+$//;
 3434:     $name=~s/\s+/ /g;
 3435:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3436:     return $name;
 3437: }
 3438: 
 3439: # -------------------------------------------------------------------- Nickname
 3440: =pod
 3441: 
 3442: =item * &nickname($uname,$udom)
 3443: 
 3444: Gets a users name and returns it as a string as
 3445: 
 3446: "&quot;nickname&quot;"
 3447: 
 3448: if the user has a nickname or
 3449: 
 3450: "first middle last generation"
 3451: 
 3452: if the user does not
 3453: 
 3454: =cut
 3455: 
 3456: sub nickname {
 3457:     my ($uname,$udom)=@_;
 3458:     return if (!defined($uname) || !defined($udom));
 3459:     my %names=&getnames($uname,$udom);
 3460:     my $name=$names{'nickname'};
 3461:     if ($name) {
 3462:        $name='&quot;'.$name.'&quot;'; 
 3463:     } else {
 3464:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3465: 	     $names{'lastname'}.' '.$names{'generation'};
 3466:        $name=~s/\s+$//;
 3467:        $name=~s/\s+/ /g;
 3468:     }
 3469:     return $name;
 3470: }
 3471: 
 3472: sub getnames {
 3473:     my ($uname,$udom)=@_;
 3474:     return if (!defined($uname) || !defined($udom));
 3475:     if ($udom eq 'public' && $uname eq 'public') {
 3476: 	return ('lastname' => &mt('Public'));
 3477:     }
 3478:     my $id=$uname.':'.$udom;
 3479:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3480:     if ($cached) {
 3481: 	return %{$names};
 3482:     } else {
 3483: 	my %loadnames=&Apache::lonnet::get('environment',
 3484:                     ['firstname','middlename','lastname','generation','nickname'],
 3485: 					 $udom,$uname);
 3486: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3487: 	return %loadnames;
 3488:     }
 3489: }
 3490: 
 3491: # -------------------------------------------------------------------- getemails
 3492: 
 3493: =pod
 3494: 
 3495: =item * &getemails($uname,$udom)
 3496: 
 3497: Gets a user's email information and returns it as a hash with keys:
 3498: notification, critnotification, permanentemail
 3499: 
 3500: For notification and critnotification, values are comma-separated lists 
 3501: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3502:  
 3503: 
 3504: =cut
 3505: 
 3506: 
 3507: sub getemails {
 3508:     my ($uname,$udom)=@_;
 3509:     if ($udom eq 'public' && $uname eq 'public') {
 3510: 	return;
 3511:     }
 3512:     if (!$udom) { $udom=$env{'user.domain'}; }
 3513:     if (!$uname) { $uname=$env{'user.name'}; }
 3514:     my $id=$uname.':'.$udom;
 3515:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3516:     if ($cached) {
 3517: 	return %{$names};
 3518:     } else {
 3519: 	my %loadnames=&Apache::lonnet::get('environment',
 3520:                     			   ['notification','critnotification',
 3521: 					    'permanentemail'],
 3522: 					   $udom,$uname);
 3523: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3524: 	return %loadnames;
 3525:     }
 3526: }
 3527: 
 3528: sub flush_email_cache {
 3529:     my ($uname,$udom)=@_;
 3530:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3531:     if (!$uname) { $uname=$env{'user.name'};   }
 3532:     return if ($udom eq 'public' && $uname eq 'public');
 3533:     my $id=$uname.':'.$udom;
 3534:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3535: }
 3536: 
 3537: # -------------------------------------------------------------------- getlangs
 3538: 
 3539: =pod
 3540: 
 3541: =item * &getlangs($uname,$udom)
 3542: 
 3543: Gets a user's language preference and returns it as a hash with key:
 3544: language.
 3545: 
 3546: =cut
 3547: 
 3548: 
 3549: sub getlangs {
 3550:     my ($uname,$udom) = @_;
 3551:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3552:     if (!$uname) { $uname=$env{'user.name'};   }
 3553:     my $id=$uname.':'.$udom;
 3554:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3555:     if ($cached) {
 3556:         return %{$langs};
 3557:     } else {
 3558:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3559:                                            $udom,$uname);
 3560:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3561:         return %loadlangs;
 3562:     }
 3563: }
 3564: 
 3565: sub flush_langs_cache {
 3566:     my ($uname,$udom)=@_;
 3567:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3568:     if (!$uname) { $uname=$env{'user.name'};   }
 3569:     return if ($udom eq 'public' && $uname eq 'public');
 3570:     my $id=$uname.':'.$udom;
 3571:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3572: }
 3573: 
 3574: # ------------------------------------------------------------------ Screenname
 3575: 
 3576: =pod
 3577: 
 3578: =item * &screenname($uname,$udom)
 3579: 
 3580: Gets a users screenname and returns it as a string
 3581: 
 3582: =cut
 3583: 
 3584: sub screenname {
 3585:     my ($uname,$udom)=@_;
 3586:     if ($uname eq $env{'user.name'} &&
 3587: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3588:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3589:     return $names{'screenname'};
 3590: }
 3591: 
 3592: 
 3593: # ------------------------------------------------------------- Confirm Wrapper
 3594: =pod
 3595: 
 3596: =item * &confirmwrapper($message)
 3597: 
 3598: Wrap messages about completion of operation in box
 3599: 
 3600: =cut
 3601: 
 3602: sub confirmwrapper {
 3603:     my ($message)=@_;
 3604:     if ($message) {
 3605:         return "\n".'<div class="LC_confirm_box">'."\n"
 3606:                .$message."\n"
 3607:                .'</div>'."\n";
 3608:     } else {
 3609:         return $message;
 3610:     }
 3611: }
 3612: 
 3613: # ------------------------------------------------------------- Message Wrapper
 3614: 
 3615: sub messagewrapper {
 3616:     my ($link,$username,$domain,$subject,$text)=@_;
 3617:     return 
 3618:         '<a href="/adm/email?compose=individual&amp;'.
 3619:         'recname='.$username.'&amp;recdom='.$domain.
 3620: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3621:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3622: }
 3623: 
 3624: # --------------------------------------------------------------- Notes Wrapper
 3625: 
 3626: sub noteswrapper {
 3627:     my ($link,$un,$do)=@_;
 3628:     return 
 3629: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3630: }
 3631: 
 3632: # ------------------------------------------------------------- Aboutme Wrapper
 3633: 
 3634: sub aboutmewrapper {
 3635:     my ($link,$username,$domain,$target,$class)=@_;
 3636:     if (!defined($username)  && !defined($domain)) {
 3637:         return;
 3638:     }
 3639:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3640: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3641: }
 3642: 
 3643: # ------------------------------------------------------------ Syllabus Wrapper
 3644: 
 3645: sub syllabuswrapper {
 3646:     my ($linktext,$coursedir,$domain)=@_;
 3647:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3648: }
 3649: 
 3650: # -----------------------------------------------------------------------------
 3651: 
 3652: sub track_student_link {
 3653:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3654:     my $link ="/adm/trackstudent?";
 3655:     my $title = 'View recent activity';
 3656:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3657:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3658:         $link .= "selected_student=$sname:$sdom";
 3659:         $title .= ' of this student';
 3660:     } 
 3661:     if (defined($target) && $target !~ /^\s*$/) {
 3662:         $target = qq{target="$target"};
 3663:     } else {
 3664:         $target = '';
 3665:     }
 3666:     if ($start) { $link.='&amp;start='.$start; }
 3667:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3668:     $title = &mt($title);
 3669:     $linktext = &mt($linktext);
 3670:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3671: 	&help_open_topic('View_recent_activity');
 3672: }
 3673: 
 3674: sub slot_reservations_link {
 3675:     my ($linktext,$sname,$sdom,$target) = @_;
 3676:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3677:     my $title = 'View slot reservation history';
 3678:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3679:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3680:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3681:         $title .= ' of this student';
 3682:     }
 3683:     if (defined($target) && $target !~ /^\s*$/) {
 3684:         $target = qq{target="$target"};
 3685:     } else {
 3686:         $target = '';
 3687:     }
 3688:     $title = &mt($title);
 3689:     $linktext = &mt($linktext);
 3690:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3691: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3692: 
 3693: }
 3694: 
 3695: # ===================================================== Display a student photo
 3696: 
 3697: 
 3698: sub student_image_tag {
 3699:     my ($domain,$user)=@_;
 3700:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3701:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3702: 	return '<img src="'.$imgsrc.'" align="right" />';
 3703:     } else {
 3704: 	return '';
 3705:     }
 3706: }
 3707: 
 3708: =pod
 3709: 
 3710: =back
 3711: 
 3712: =head1 Access .tab File Data
 3713: 
 3714: =over 4
 3715: 
 3716: =item * &languageids() 
 3717: 
 3718: returns list of all language ids
 3719: 
 3720: =cut
 3721: 
 3722: sub languageids {
 3723:     return sort(keys(%language));
 3724: }
 3725: 
 3726: =pod
 3727: 
 3728: =item * &languagedescription() 
 3729: 
 3730: returns description of a specified language id
 3731: 
 3732: =cut
 3733: 
 3734: sub languagedescription {
 3735:     my $code=shift;
 3736:     return  ($supported_language{$code}?'* ':'').
 3737:             $language{$code}.
 3738: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3739: }
 3740: 
 3741: =pod
 3742: 
 3743: =item * &plainlanguagedescription
 3744: 
 3745: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3746: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3747: 
 3748: =cut
 3749: 
 3750: sub plainlanguagedescription {
 3751:     my $code=shift;
 3752:     return $language{$code};
 3753: }
 3754: 
 3755: =pod
 3756: 
 3757: =item * &supportedlanguagecode
 3758: 
 3759: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3760: code.
 3761: 
 3762: =cut
 3763: 
 3764: sub supportedlanguagecode {
 3765:     my $code=shift;
 3766:     return $supported_language{$code};
 3767: }
 3768: 
 3769: =pod
 3770: 
 3771: =item * &latexlanguage()
 3772: 
 3773: Given a language key code returns the correspondnig language to use
 3774: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3775: is no supported hyphenation for the language code.
 3776: 
 3777: =cut
 3778: 
 3779: sub latexlanguage {
 3780:     my $code = shift;
 3781:     return $latex_language{$code};
 3782: }
 3783: 
 3784: =pod
 3785: 
 3786: =item * &latexhyphenation()
 3787: 
 3788: Same as above but what's supplied is the language as it might be stored
 3789: in the metadata.
 3790: 
 3791: =cut
 3792: 
 3793: sub latexhyphenation {
 3794:     my $key = shift;
 3795:     return $latex_language_bykey{$key};
 3796: }
 3797: 
 3798: =pod
 3799: 
 3800: =item * &copyrightids() 
 3801: 
 3802: returns list of all copyrights
 3803: 
 3804: =cut
 3805: 
 3806: sub copyrightids {
 3807:     return sort(keys(%cprtag));
 3808: }
 3809: 
 3810: =pod
 3811: 
 3812: =item * &copyrightdescription() 
 3813: 
 3814: returns description of a specified copyright id
 3815: 
 3816: =cut
 3817: 
 3818: sub copyrightdescription {
 3819:     return &mt($cprtag{shift(@_)});
 3820: }
 3821: 
 3822: =pod
 3823: 
 3824: =item * &source_copyrightids() 
 3825: 
 3826: returns list of all source copyrights
 3827: 
 3828: =cut
 3829: 
 3830: sub source_copyrightids {
 3831:     return sort(keys(%scprtag));
 3832: }
 3833: 
 3834: =pod
 3835: 
 3836: =item * &source_copyrightdescription() 
 3837: 
 3838: returns description of a specified source copyright id
 3839: 
 3840: =cut
 3841: 
 3842: sub source_copyrightdescription {
 3843:     return &mt($scprtag{shift(@_)});
 3844: }
 3845: 
 3846: =pod
 3847: 
 3848: =item * &filecategories() 
 3849: 
 3850: returns list of all file categories
 3851: 
 3852: =cut
 3853: 
 3854: sub filecategories {
 3855:     return sort(keys(%category_extensions));
 3856: }
 3857: 
 3858: =pod
 3859: 
 3860: =item * &filecategorytypes() 
 3861: 
 3862: returns list of file types belonging to a given file
 3863: category
 3864: 
 3865: =cut
 3866: 
 3867: sub filecategorytypes {
 3868:     my ($cat) = @_;
 3869:     return @{$category_extensions{lc($cat)}};
 3870: }
 3871: 
 3872: =pod
 3873: 
 3874: =item * &fileembstyle() 
 3875: 
 3876: returns embedding style for a specified file type
 3877: 
 3878: =cut
 3879: 
 3880: sub fileembstyle {
 3881:     return $fe{lc(shift(@_))};
 3882: }
 3883: 
 3884: sub filemimetype {
 3885:     return $fm{lc(shift(@_))};
 3886: }
 3887: 
 3888: 
 3889: sub filecategoryselect {
 3890:     my ($name,$value)=@_;
 3891:     return &select_form($value,$name,
 3892:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3893: }
 3894: 
 3895: =pod
 3896: 
 3897: =item * &filedescription() 
 3898: 
 3899: returns description for a specified file type
 3900: 
 3901: =cut
 3902: 
 3903: sub filedescription {
 3904:     my $file_description = $fd{lc(shift())};
 3905:     $file_description =~ s:([\[\]]):~$1:g;
 3906:     return &mt($file_description);
 3907: }
 3908: 
 3909: =pod
 3910: 
 3911: =item * &filedescriptionex() 
 3912: 
 3913: returns description for a specified file type with
 3914: extra formatting
 3915: 
 3916: =cut
 3917: 
 3918: sub filedescriptionex {
 3919:     my $ex=shift;
 3920:     my $file_description = $fd{lc($ex)};
 3921:     $file_description =~ s:([\[\]]):~$1:g;
 3922:     return '.'.$ex.' '.&mt($file_description);
 3923: }
 3924: 
 3925: # End of .tab access
 3926: =pod
 3927: 
 3928: =back
 3929: 
 3930: =cut
 3931: 
 3932: # ------------------------------------------------------------------ File Types
 3933: sub fileextensions {
 3934:     return sort(keys(%fe));
 3935: }
 3936: 
 3937: # ----------------------------------------------------------- Display Languages
 3938: # returns a hash with all desired display languages
 3939: #
 3940: 
 3941: sub display_languages {
 3942:     my %languages=();
 3943:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3944: 	$languages{$lang}=1;
 3945:     }
 3946:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3947:     if ($env{'form.displaylanguage'}) {
 3948: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3949: 	    $languages{$lang}=1;
 3950:         }
 3951:     }
 3952:     return %languages;
 3953: }
 3954: 
 3955: sub languages {
 3956:     my ($possible_langs) = @_;
 3957:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3958:     if (!ref($possible_langs)) {
 3959: 	if( wantarray ) {
 3960: 	    return @preferred_langs;
 3961: 	} else {
 3962: 	    return $preferred_langs[0];
 3963: 	}
 3964:     }
 3965:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3966:     my @preferred_possibilities;
 3967:     foreach my $preferred_lang (@preferred_langs) {
 3968: 	if (exists($possibilities{$preferred_lang})) {
 3969: 	    push(@preferred_possibilities, $preferred_lang);
 3970: 	}
 3971:     }
 3972:     if( wantarray ) {
 3973: 	return @preferred_possibilities;
 3974:     }
 3975:     return $preferred_possibilities[0];
 3976: }
 3977: 
 3978: sub user_lang {
 3979:     my ($touname,$toudom,$fromcid) = @_;
 3980:     my @userlangs;
 3981:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3982:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3983:                     $env{'course.'.$fromcid.'.languages'}));
 3984:     } else {
 3985:         my %langhash = &getlangs($touname,$toudom);
 3986:         if ($langhash{'languages'} ne '') {
 3987:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3988:         } else {
 3989:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3990:             if ($domdefs{'lang_def'} ne '') {
 3991:                 @userlangs = ($domdefs{'lang_def'});
 3992:             }
 3993:         }
 3994:     }
 3995:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3996:     my $user_lh = Apache::localize->get_handle(@languages);
 3997:     return $user_lh;
 3998: }
 3999: 
 4000: 
 4001: ###############################################################
 4002: ##               Student Answer Attempts                     ##
 4003: ###############################################################
 4004: 
 4005: =pod
 4006: 
 4007: =head1 Alternate Problem Views
 4008: 
 4009: =over 4
 4010: 
 4011: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4012:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4013: 
 4014: Return string with previous attempt on problem. Arguments:
 4015: 
 4016: =over 4
 4017: 
 4018: =item * $symb: Problem, including path
 4019: 
 4020: =item * $username: username of the desired student
 4021: 
 4022: =item * $domain: domain of the desired student
 4023: 
 4024: =item * $course: Course ID
 4025: 
 4026: =item * $getattempt: Leave blank for all attempts, otherwise put
 4027:     something
 4028: 
 4029: =item * $regexp: if string matches this regexp, the string will be
 4030:     sent to $gradesub
 4031: 
 4032: =item * $gradesub: routine that processes the string if it matches $regexp
 4033: 
 4034: =item * $usec: section of the desired student
 4035: 
 4036: =item * $identifier: counter for student (multiple students one problem) or 
 4037:     problem (one student; whole sequence).
 4038: 
 4039: =back
 4040: 
 4041: The output string is a table containing all desired attempts, if any.
 4042: 
 4043: =cut
 4044: 
 4045: sub get_previous_attempt {
 4046:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4047:   my $prevattempts='';
 4048:   no strict 'refs';
 4049:   if ($symb) {
 4050:     my (%returnhash)=
 4051:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4052:     if ($returnhash{'version'}) {
 4053:       my %lasthash=();
 4054:       my $version;
 4055:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4056:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4057:             if ($key =~ /\.rawrndseed$/) {
 4058:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4059:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4060:             } else {
 4061:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4062:             }
 4063:         }
 4064:       }
 4065:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4066:       $prevattempts.='<th>'.&mt('History').'</th>';
 4067:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4068:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4069:       foreach my $key (sort(keys(%lasthash))) {
 4070: 	my ($ign,@parts) = split(/\./,$key);
 4071: 	if ($#parts > 0) {
 4072: 	  my $data=$parts[-1];
 4073:           next if ($data eq 'foilorder');
 4074: 	  pop(@parts);
 4075:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4076:           if ($data eq 'type') {
 4077:               unless ($showsurv) {
 4078:                   my $id = join(',',@parts);
 4079:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4080:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4081:                       $lasthidden{$ign.'.'.$id} = 1;
 4082:                   }
 4083:               }
 4084:               if ($identifier ne '') {
 4085:                   my $id = join(',',@parts);
 4086:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4087:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4088:                       $hidestatus{$ign.'.'.$id} = 1;
 4089:                   }
 4090:               }
 4091:           } elsif ($data eq 'regrader') {
 4092:               if (($identifier ne '') && (@parts)) {
 4093:                   my $id = join(',',@parts);
 4094:                   $regraded{$ign.'.'.$id} = 1;
 4095:               }
 4096:           } 
 4097: 	} else {
 4098: 	  if ($#parts == 0) {
 4099: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4100: 	  } else {
 4101: 	    $prevattempts.='<th>'.$ign.'</th>';
 4102: 	  }
 4103: 	}
 4104:       }
 4105:       $prevattempts.=&end_data_table_header_row();
 4106:       if ($getattempt eq '') {
 4107:         my (%solved,%resets,%probstatus);
 4108:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4109:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4110:                 foreach my $id (keys(%regraded)) {
 4111:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4112:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4113:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4114:                         push(@{$resets{$id}},$version);
 4115:                     }
 4116:                 }
 4117:             }
 4118:         }
 4119: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4120:             my (@hidden,@unsolved);
 4121:             if (%typeparts) {
 4122:                 foreach my $id (keys(%typeparts)) {
 4123:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4124:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4125:                         push(@hidden,$id);
 4126:                     } elsif ($identifier ne '') {
 4127:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4128:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4129:                                 ($hidestatus{$id})) {
 4130:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4131:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4132:                                 push(@{$solved{$id}},$version);
 4133:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4134:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4135:                                 my $skip;
 4136:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4137:                                     foreach my $reset (@{$resets{$id}}) {
 4138:                                         if ($reset > $solved{$id}[-1]) {
 4139:                                             $skip=1;
 4140:                                             last;
 4141:                                         }
 4142:                                     }
 4143:                                 }
 4144:                                 unless ($skip) {
 4145:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4146:                                     push(@unsolved,$partslist);
 4147:                                 }
 4148:                             }
 4149:                         }
 4150:                     }
 4151:                 }
 4152:             }
 4153:             $prevattempts.=&start_data_table_row().
 4154:                            '<td>'.&mt('Transaction [_1]',$version);
 4155:             if (@unsolved) {
 4156:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4157:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4158:                                  &mt('Hide').'</label></span>';
 4159:             }
 4160:             $prevattempts .= '</td>';
 4161:             if (@hidden) {
 4162:                 foreach my $key (sort(keys(%lasthash))) {
 4163:                     next if ($key =~ /\.foilorder$/);
 4164:                     my $hide;
 4165:                     foreach my $id (@hidden) {
 4166:                         if ($key =~ /^\Q$id\E/) {
 4167:                             $hide = 1;
 4168:                             last;
 4169:                         }
 4170:                     }
 4171:                     if ($hide) {
 4172:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4173:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4174:                             my $value = &format_previous_attempt_value($key,
 4175:                                              $returnhash{$version.':'.$key});
 4176:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4177:                         } else {
 4178:                             $prevattempts.='<td>&nbsp;</td>';
 4179:                         }
 4180:                     } else {
 4181:                         if ($key =~ /\./) {
 4182:                             my $value = $returnhash{$version.':'.$key};
 4183:                             if ($key =~ /\.rndseed$/) {
 4184:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4185:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4186:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4187:                                 }
 4188:                             }
 4189:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4190:                                            '&nbsp;</td>';
 4191:                         } else {
 4192:                             $prevattempts.='<td>&nbsp;</td>';
 4193:                         }
 4194:                     }
 4195:                 }
 4196:             } else {
 4197: 	        foreach my $key (sort(keys(%lasthash))) {
 4198:                     next if ($key =~ /\.foilorder$/);
 4199:                     my $value = $returnhash{$version.':'.$key};
 4200:                     if ($key =~ /\.rndseed$/) {
 4201:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4202:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4203:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4204:                         }
 4205:                     }
 4206:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4207:                                    '&nbsp;</td>';
 4208: 	        }
 4209:             }
 4210: 	    $prevattempts.=&end_data_table_row();
 4211: 	 }
 4212:       }
 4213:       my @currhidden = keys(%lasthidden);
 4214:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4215:       foreach my $key (sort(keys(%lasthash))) {
 4216:           next if ($key =~ /\.foilorder$/);
 4217:           if (%typeparts) {
 4218:               my $hidden;
 4219:               foreach my $id (@currhidden) {
 4220:                   if ($key =~ /^\Q$id\E/) {
 4221:                       $hidden = 1;
 4222:                       last;
 4223:                   }
 4224:               }
 4225:               if ($hidden) {
 4226:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4227:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4228:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4229:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4230:                           $value = &$gradesub($value);
 4231:                       }
 4232:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4233:                   } else {
 4234:                       $prevattempts.='<td>&nbsp;</td>';
 4235:                   }
 4236:               } else {
 4237:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4238:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4239:                       $value = &$gradesub($value);
 4240:                   }
 4241:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4242:               }
 4243:           } else {
 4244: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4245: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4246:                   $value = &$gradesub($value);
 4247:               }
 4248: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4249:           }
 4250:       }
 4251:       $prevattempts.= &end_data_table_row().&end_data_table();
 4252:     } else {
 4253:       $prevattempts=
 4254: 	  &start_data_table().&start_data_table_row().
 4255: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4256: 	  &end_data_table_row().&end_data_table();
 4257:     }
 4258:   } else {
 4259:     $prevattempts=
 4260: 	  &start_data_table().&start_data_table_row().
 4261: 	  '<td>'.&mt('No data.').'</td>'.
 4262: 	  &end_data_table_row().&end_data_table();
 4263:   }
 4264: }
 4265: 
 4266: sub format_previous_attempt_value {
 4267:     my ($key,$value) = @_;
 4268:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4269:         $value = &Apache::lonlocal::locallocaltime($value);
 4270:     } elsif (ref($value) eq 'ARRAY') {
 4271:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4272:     } elsif ($key =~ /answerstring$/) {
 4273:         my %answers = &Apache::lonnet::str2hash($value);
 4274:         my @answer = %answers;
 4275:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4276:         my @anskeys = sort(keys(%answers));
 4277:         if (@anskeys == 1) {
 4278:             my $answer = $answers{$anskeys[0]};
 4279:             if ($answer =~ m{\0}) {
 4280:                 $answer =~ s{\0}{,}g;
 4281:             }
 4282:             my $tag_internal_answer_name = 'INTERNAL';
 4283:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4284:                 $value = $answer; 
 4285:             } else {
 4286:                 $value = $anskeys[0].'='.$answer;
 4287:             }
 4288:         } else {
 4289:             foreach my $ans (@anskeys) {
 4290:                 my $answer = $answers{$ans};
 4291:                 if ($answer =~ m{\0}) {
 4292:                     $answer =~ s{\0}{,}g;
 4293:                 }
 4294:                 $value .=  $ans.'='.$answer.'<br />';;
 4295:             } 
 4296:         }
 4297:     } else {
 4298:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4299:     }
 4300:     return $value;
 4301: }
 4302: 
 4303: 
 4304: sub relative_to_absolute {
 4305:     my ($url,$output)=@_;
 4306:     my $parser=HTML::TokeParser->new(\$output);
 4307:     my $token;
 4308:     my $thisdir=$url;
 4309:     my @rlinks=();
 4310:     while ($token=$parser->get_token) {
 4311: 	if ($token->[0] eq 'S') {
 4312: 	    if ($token->[1] eq 'a') {
 4313: 		if ($token->[2]->{'href'}) {
 4314: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4315: 		}
 4316: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4317: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4318: 	    } elsif ($token->[1] eq 'base') {
 4319: 		$thisdir=$token->[2]->{'href'};
 4320: 	    }
 4321: 	}
 4322:     }
 4323:     $thisdir=~s-/[^/]*$--;
 4324:     foreach my $link (@rlinks) {
 4325: 	unless (($link=~/^https?\:\/\//i) ||
 4326: 		($link=~/^\//) ||
 4327: 		($link=~/^javascript:/i) ||
 4328: 		($link=~/^mailto:/i) ||
 4329: 		($link=~/^\#/)) {
 4330: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4331: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4332: 	}
 4333:     }
 4334: # -------------------------------------------------- Deal with Applet codebases
 4335:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4336:     return $output;
 4337: }
 4338: 
 4339: =pod
 4340: 
 4341: =item * &get_student_view()
 4342: 
 4343: show a snapshot of what student was looking at
 4344: 
 4345: =cut
 4346: 
 4347: sub get_student_view {
 4348:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4349:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4350:   my (%form);
 4351:   my @elements=('symb','courseid','domain','username');
 4352:   foreach my $element (@elements) {
 4353:       $form{'grade_'.$element}=eval '$'.$element #'
 4354:   }
 4355:   if (defined($moreenv)) {
 4356:       %form=(%form,%{$moreenv});
 4357:   }
 4358:   if (defined($target)) { $form{'grade_target'} = $target; }
 4359:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4360:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4361:   $userview=~s/\<body[^\>]*\>//gi;
 4362:   $userview=~s/\<\/body\>//gi;
 4363:   $userview=~s/\<html\>//gi;
 4364:   $userview=~s/\<\/html\>//gi;
 4365:   $userview=~s/\<head\>//gi;
 4366:   $userview=~s/\<\/head\>//gi;
 4367:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4368:   $userview=&relative_to_absolute($feedurl,$userview);
 4369:   if (wantarray) {
 4370:      return ($userview,$response);
 4371:   } else {
 4372:      return $userview;
 4373:   }
 4374: }
 4375: 
 4376: sub get_student_view_with_retries {
 4377:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4378: 
 4379:     my $ok = 0;                 # True if we got a good response.
 4380:     my $content;
 4381:     my $response;
 4382: 
 4383:     # Try to get the student_view done. within the retries count:
 4384:     
 4385:     do {
 4386:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4387:          $ok      = $response->is_success;
 4388:          if (!$ok) {
 4389:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4390:          }
 4391:          $retries--;
 4392:     } while (!$ok && ($retries > 0));
 4393:     
 4394:     if (!$ok) {
 4395:        $content = '';          # On error return an empty content.
 4396:     }
 4397:     if (wantarray) {
 4398:        return ($content, $response);
 4399:     } else {
 4400:        return $content;
 4401:     }
 4402: }
 4403: 
 4404: =pod
 4405: 
 4406: =item * &get_student_answers() 
 4407: 
 4408: show a snapshot of how student was answering problem
 4409: 
 4410: =cut
 4411: 
 4412: sub get_student_answers {
 4413:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4414:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4415:   my (%moreenv);
 4416:   my @elements=('symb','courseid','domain','username');
 4417:   foreach my $element (@elements) {
 4418:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4419:   }
 4420:   $moreenv{'grade_target'}='answer';
 4421:   %moreenv=(%form,%moreenv);
 4422:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4423:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4424:   return $userview;
 4425: }
 4426: 
 4427: =pod
 4428: 
 4429: =item * &submlink()
 4430: 
 4431: Inputs: $text $uname $udom $symb $target
 4432: 
 4433: Returns: A link to grades.pm such as to see the SUBM view of a student
 4434: 
 4435: =cut
 4436: 
 4437: ###############################################
 4438: sub submlink {
 4439:     my ($text,$uname,$udom,$symb,$target)=@_;
 4440:     if (!($uname && $udom)) {
 4441: 	(my $cursymb, my $courseid,$udom,$uname)=
 4442: 	    &Apache::lonnet::whichuser($symb);
 4443: 	if (!$symb) { $symb=$cursymb; }
 4444:     }
 4445:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4446:     $symb=&escape($symb);
 4447:     if ($target) { $target=" target=\"$target\""; }
 4448:     return
 4449:         '<a href="/adm/grades?command=submission'.
 4450:         '&amp;symb='.$symb.
 4451:         '&amp;student='.$uname.
 4452:         '&amp;userdom='.$udom.'"'.
 4453:         $target.'>'.$text.'</a>';
 4454: }
 4455: ##############################################
 4456: 
 4457: =pod
 4458: 
 4459: =item * &pgrdlink()
 4460: 
 4461: Inputs: $text $uname $udom $symb $target
 4462: 
 4463: Returns: A link to grades.pm such as to see the PGRD view of a student
 4464: 
 4465: =cut
 4466: 
 4467: ###############################################
 4468: sub pgrdlink {
 4469:     my $link=&submlink(@_);
 4470:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4471:     return $link;
 4472: }
 4473: ##############################################
 4474: 
 4475: =pod
 4476: 
 4477: =item * &pprmlink()
 4478: 
 4479: Inputs: $text $uname $udom $symb $target
 4480: 
 4481: Returns: A link to parmset.pm such as to see the PPRM view of a
 4482: student and a specific resource
 4483: 
 4484: =cut
 4485: 
 4486: ###############################################
 4487: sub pprmlink {
 4488:     my ($text,$uname,$udom,$symb,$target)=@_;
 4489:     if (!($uname && $udom)) {
 4490: 	(my $cursymb, my $courseid,$udom,$uname)=
 4491: 	    &Apache::lonnet::whichuser($symb);
 4492: 	if (!$symb) { $symb=$cursymb; }
 4493:     }
 4494:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4495:     $symb=&escape($symb);
 4496:     if ($target) { $target="target=\"$target\""; }
 4497:     return '<a href="/adm/parmset?command=set&amp;'.
 4498: 	'symb='.$symb.'&amp;uname='.$uname.
 4499: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4500: }
 4501: ##############################################
 4502: 
 4503: =pod
 4504: 
 4505: =back
 4506: 
 4507: =cut
 4508: 
 4509: ###############################################
 4510: 
 4511: 
 4512: sub timehash {
 4513:     my ($thistime) = @_;
 4514:     my $timezone = &Apache::lonlocal::gettimezone();
 4515:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4516:                      ->set_time_zone($timezone);
 4517:     my $wday = $dt->day_of_week();
 4518:     if ($wday == 7) { $wday = 0; }
 4519:     return ( 'second' => $dt->second(),
 4520:              'minute' => $dt->minute(),
 4521:              'hour'   => $dt->hour(),
 4522:              'day'     => $dt->day_of_month(),
 4523:              'month'   => $dt->month(),
 4524:              'year'    => $dt->year(),
 4525:              'weekday' => $wday,
 4526:              'dayyear' => $dt->day_of_year(),
 4527:              'dlsav'   => $dt->is_dst() );
 4528: }
 4529: 
 4530: sub utc_string {
 4531:     my ($date)=@_;
 4532:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4533: }
 4534: 
 4535: sub maketime {
 4536:     my %th=@_;
 4537:     my ($epoch_time,$timezone,$dt);
 4538:     $timezone = &Apache::lonlocal::gettimezone();
 4539:     eval {
 4540:         $dt = DateTime->new( year   => $th{'year'},
 4541:                              month  => $th{'month'},
 4542:                              day    => $th{'day'},
 4543:                              hour   => $th{'hour'},
 4544:                              minute => $th{'minute'},
 4545:                              second => $th{'second'},
 4546:                              time_zone => $timezone,
 4547:                          );
 4548:     };
 4549:     if (!$@) {
 4550:         $epoch_time = $dt->epoch;
 4551:         if ($epoch_time) {
 4552:             return $epoch_time;
 4553:         }
 4554:     }
 4555:     return POSIX::mktime(
 4556:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4557:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4558: }
 4559: 
 4560: #########################################
 4561: 
 4562: sub findallcourses {
 4563:     my ($roles,$uname,$udom) = @_;
 4564:     my %roles;
 4565:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4566:     my %courses;
 4567:     my $now=time;
 4568:     if (!defined($uname)) {
 4569:         $uname = $env{'user.name'};
 4570:     }
 4571:     if (!defined($udom)) {
 4572:         $udom = $env{'user.domain'};
 4573:     }
 4574:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4575:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4576:         if (!%roles) {
 4577:             %roles = (
 4578:                        cc => 1,
 4579:                        co => 1,
 4580:                        in => 1,
 4581:                        ep => 1,
 4582:                        ta => 1,
 4583:                        cr => 1,
 4584:                        st => 1,
 4585:              );
 4586:         }
 4587:         foreach my $entry (keys(%roleshash)) {
 4588:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4589:             if ($trole =~ /^cr/) { 
 4590:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4591:             } else {
 4592:                 next if (!exists($roles{$trole}));
 4593:             }
 4594:             if ($tend) {
 4595:                 next if ($tend < $now);
 4596:             }
 4597:             if ($tstart) {
 4598:                 next if ($tstart > $now);
 4599:             }
 4600:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4601:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4602:             my $value = $trole.'/'.$cdom.'/';
 4603:             if ($secpart eq '') {
 4604:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4605:                 $sec = 'none';
 4606:                 $value .= $cnum.'/';
 4607:             } else {
 4608:                 $cnum = $cnumpart;
 4609:                 ($sec,$role) = split(/_/,$secpart);
 4610:                 $value .= $cnum.'/'.$sec;
 4611:             }
 4612:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4613:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4614:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4615:                 }
 4616:             } else {
 4617:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4618:             }
 4619:         }
 4620:     } else {
 4621:         foreach my $key (keys(%env)) {
 4622: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4623:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4624: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4625: 	        next if ($role eq 'ca' || $role eq 'aa');
 4626: 	        next if (%roles && !exists($roles{$role}));
 4627: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4628:                 my $active=1;
 4629:                 if ($starttime) {
 4630: 		    if ($now<$starttime) { $active=0; }
 4631:                 }
 4632:                 if ($endtime) {
 4633:                     if ($now>$endtime) { $active=0; }
 4634:                 }
 4635:                 if ($active) {
 4636:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4637:                     if ($sec eq '') {
 4638:                         $sec = 'none';
 4639:                     } else {
 4640:                         $value .= $sec;
 4641:                     }
 4642:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4643:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4644:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4645:                         }
 4646:                     } else {
 4647:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4648:                     }
 4649:                 }
 4650:             }
 4651:         }
 4652:     }
 4653:     return %courses;
 4654: }
 4655: 
 4656: ###############################################
 4657: 
 4658: sub blockcheck {
 4659:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4660: 
 4661:     if (defined($udom) && defined($uname)) {
 4662:         # If uname and udom are for a course, check for blocks in the course.
 4663:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4664:             my ($startblock,$endblock,$triggerblock) =
 4665:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4666:             return ($startblock,$endblock,$triggerblock);
 4667:         }
 4668:     } else {
 4669:         $udom = $env{'user.domain'};
 4670:         $uname = $env{'user.name'};
 4671:     }
 4672: 
 4673:     my $startblock = 0;
 4674:     my $endblock = 0;
 4675:     my $triggerblock = '';
 4676:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4677: 
 4678:     # If uname is for a user, and activity is course-specific, i.e.,
 4679:     # boards, chat or groups, check for blocking in current course only.
 4680: 
 4681:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4682:          $activity eq 'groups' || $activity eq 'printout') &&
 4683:         ($env{'request.course.id'})) {
 4684:         foreach my $key (keys(%live_courses)) {
 4685:             if ($key ne $env{'request.course.id'}) {
 4686:                 delete($live_courses{$key});
 4687:             }
 4688:         }
 4689:     }
 4690: 
 4691:     my $otheruser = 0;
 4692:     my %own_courses;
 4693:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4694:         # Resource belongs to user other than current user.
 4695:         $otheruser = 1;
 4696:         # Gather courses for current user
 4697:         %own_courses = 
 4698:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4699:     }
 4700: 
 4701:     # Gather active course roles - course coordinator, instructor, 
 4702:     # exam proctor, ta, student, or custom role.
 4703: 
 4704:     foreach my $course (keys(%live_courses)) {
 4705:         my ($cdom,$cnum);
 4706:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4707:             $cdom = $env{'course.'.$course.'.domain'};
 4708:             $cnum = $env{'course.'.$course.'.num'};
 4709:         } else {
 4710:             ($cdom,$cnum) = split(/_/,$course); 
 4711:         }
 4712:         my $no_ownblock = 0;
 4713:         my $no_userblock = 0;
 4714:         if ($otheruser && $activity ne 'com') {
 4715:             # Check if current user has 'evb' priv for this
 4716:             if (defined($own_courses{$course})) {
 4717:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4718:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4719:                     if ($sec ne 'none') {
 4720:                         $checkrole .= '/'.$sec;
 4721:                     }
 4722:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4723:                         $no_ownblock = 1;
 4724:                         last;
 4725:                     }
 4726:                 }
 4727:             }
 4728:             # if they have 'evb' priv and are currently not playing student
 4729:             next if (($no_ownblock) &&
 4730:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4731:         }
 4732:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4733:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4734:             if ($sec ne 'none') {
 4735:                 $checkrole .= '/'.$sec;
 4736:             }
 4737:             if ($otheruser) {
 4738:                 # Resource belongs to user other than current user.
 4739:                 # Assemble privs for that user, and check for 'evb' priv.
 4740:                 my (%allroles,%userroles);
 4741:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4742:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4743:                         my ($trole,$tdom,$tnum,$tsec);
 4744:                         if ($entry =~ /^cr/) {
 4745:                             ($trole,$tdom,$tnum,$tsec) = 
 4746:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4747:                         } else {
 4748:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4749:                         }
 4750:                         my ($spec,$area,$trest);
 4751:                         $area = '/'.$tdom.'/'.$tnum;
 4752:                         $trest = $tnum;
 4753:                         if ($tsec ne '') {
 4754:                             $area .= '/'.$tsec;
 4755:                             $trest .= '/'.$tsec;
 4756:                         }
 4757:                         $spec = $trole.'.'.$area;
 4758:                         if ($trole =~ /^cr/) {
 4759:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4760:                                                               $tdom,$spec,$trest,$area);
 4761:                         } else {
 4762:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4763:                                                                 $tdom,$spec,$trest,$area);
 4764:                         }
 4765:                     }
 4766:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4767:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4768:                         if ($1) {
 4769:                             $no_userblock = 1;
 4770:                             last;
 4771:                         }
 4772:                     }
 4773:                 }
 4774:             } else {
 4775:                 # Resource belongs to current user
 4776:                 # Check for 'evb' priv via lonnet::allowed().
 4777:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4778:                     $no_ownblock = 1;
 4779:                     last;
 4780:                 }
 4781:             }
 4782:         }
 4783:         # if they have the evb priv and are currently not playing student
 4784:         next if (($no_ownblock) &&
 4785:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4786:         next if ($no_userblock);
 4787: 
 4788:         # Retrieve blocking times and identity of locker for course
 4789:         # of specified user, unless user has 'evb' privilege.
 4790:         
 4791:         my ($start,$end,$trigger) = 
 4792:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4793:         if (($start != 0) && 
 4794:             (($startblock == 0) || ($startblock > $start))) {
 4795:             $startblock = $start;
 4796:             if ($trigger ne '') {
 4797:                 $triggerblock = $trigger;
 4798:             }
 4799:         }
 4800:         if (($end != 0)  &&
 4801:             (($endblock == 0) || ($endblock < $end))) {
 4802:             $endblock = $end;
 4803:             if ($trigger ne '') {
 4804:                 $triggerblock = $trigger;
 4805:             }
 4806:         }
 4807:     }
 4808:     return ($startblock,$endblock,$triggerblock);
 4809: }
 4810: 
 4811: sub get_blocks {
 4812:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4813:     my $startblock = 0;
 4814:     my $endblock = 0;
 4815:     my $triggerblock = '';
 4816:     my $course = $cdom.'_'.$cnum;
 4817:     $setters->{$course} = {};
 4818:     $setters->{$course}{'staff'} = [];
 4819:     $setters->{$course}{'times'} = [];
 4820:     $setters->{$course}{'triggers'} = [];
 4821:     my (@blockers,%triggered);
 4822:     my $now = time;
 4823:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4824:     if ($activity eq 'docs') {
 4825:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4826:         foreach my $block (@blockers) {
 4827:             if ($block =~ /^firstaccess____(.+)$/) {
 4828:                 my $item = $1;
 4829:                 my $type = 'map';
 4830:                 my $timersymb = $item;
 4831:                 if ($item eq 'course') {
 4832:                     $type = 'course';
 4833:                 } elsif ($item =~ /___\d+___/) {
 4834:                     $type = 'resource';
 4835:                 } else {
 4836:                     $timersymb = &Apache::lonnet::symbread($item);
 4837:                 }
 4838:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4839:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4840:                 $triggered{$block} = {
 4841:                                        start => $start,
 4842:                                        end   => $end,
 4843:                                        type  => $type,
 4844:                                      };
 4845:             }
 4846:         }
 4847:     } else {
 4848:         foreach my $block (keys(%commblocks)) {
 4849:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4850:                 my ($start,$end) = ($1,$2);
 4851:                 if ($start <= time && $end >= time) {
 4852:                     if (ref($commblocks{$block}) eq 'HASH') {
 4853:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4854:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4855:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4856:                                     push(@blockers,$block);
 4857:                                 }
 4858:                             }
 4859:                         }
 4860:                     }
 4861:                 }
 4862:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4863:                 my $item = $1;
 4864:                 my $timersymb = $item; 
 4865:                 my $type = 'map';
 4866:                 if ($item eq 'course') {
 4867:                     $type = 'course';
 4868:                 } elsif ($item =~ /___\d+___/) {
 4869:                     $type = 'resource';
 4870:                 } else {
 4871:                     $timersymb = &Apache::lonnet::symbread($item);
 4872:                 }
 4873:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4874:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4875:                 if ($start && $end) {
 4876:                     if (($start <= time) && ($end >= time)) {
 4877:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4878:                             push(@blockers,$block);
 4879:                             $triggered{$block} = {
 4880:                                                    start => $start,
 4881:                                                    end   => $end,
 4882:                                                    type  => $type,
 4883:                                                  };
 4884:                         }
 4885:                     }
 4886:                 }
 4887:             }
 4888:         }
 4889:     }
 4890:     foreach my $blocker (@blockers) {
 4891:         my ($staff_name,$staff_dom,$title,$blocks) =
 4892:             &parse_block_record($commblocks{$blocker});
 4893:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4894:         my ($start,$end,$triggertype);
 4895:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4896:             ($start,$end) = ($1,$2);
 4897:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4898:             $start = $triggered{$blocker}{'start'};
 4899:             $end = $triggered{$blocker}{'end'};
 4900:             $triggertype = $triggered{$blocker}{'type'};
 4901:         }
 4902:         if ($start) {
 4903:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4904:             if ($triggertype) {
 4905:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4906:             } else {
 4907:                 push(@{$$setters{$course}{'triggers'}},0);
 4908:             }
 4909:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4910:                 $startblock = $start;
 4911:                 if ($triggertype) {
 4912:                     $triggerblock = $blocker;
 4913:                 }
 4914:             }
 4915:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4916:                $endblock = $end;
 4917:                if ($triggertype) {
 4918:                    $triggerblock = $blocker;
 4919:                }
 4920:             }
 4921:         }
 4922:     }
 4923:     return ($startblock,$endblock,$triggerblock);
 4924: }
 4925: 
 4926: sub parse_block_record {
 4927:     my ($record) = @_;
 4928:     my ($setuname,$setudom,$title,$blocks);
 4929:     if (ref($record) eq 'HASH') {
 4930:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4931:         $title = &unescape($record->{'event'});
 4932:         $blocks = $record->{'blocks'};
 4933:     } else {
 4934:         my @data = split(/:/,$record,3);
 4935:         if (scalar(@data) eq 2) {
 4936:             $title = $data[1];
 4937:             ($setuname,$setudom) = split(/@/,$data[0]);
 4938:         } else {
 4939:             ($setuname,$setudom,$title) = @data;
 4940:         }
 4941:         $blocks = { 'com' => 'on' };
 4942:     }
 4943:     return ($setuname,$setudom,$title,$blocks);
 4944: }
 4945: 
 4946: sub blocking_status {
 4947:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4948:     my %setters;
 4949: 
 4950: # check for active blocking
 4951:     my ($startblock,$endblock,$triggerblock) = 
 4952:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4953:     my $blocked = 0;
 4954:     if ($startblock && $endblock) {
 4955:         $blocked = 1;
 4956:     }
 4957: 
 4958: # caller just wants to know whether a block is active
 4959:     if (!wantarray) { return $blocked; }
 4960: 
 4961: # build a link to a popup window containing the details
 4962:     my $querystring  = "?activity=$activity";
 4963: # $uname and $udom decide whose portfolio the user is trying to look at
 4964:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4965:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 4966:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4967:     } elsif ($activity eq 'docs') {
 4968:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4969:     }
 4970: 
 4971:     my $output .= <<'END_MYBLOCK';
 4972: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4973:     var options = "width=" + w + ",height=" + h + ",";
 4974:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4975:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4976:     var newWin = window.open(url, wdwName, options);
 4977:     newWin.focus();
 4978: }
 4979: END_MYBLOCK
 4980: 
 4981:     $output = Apache::lonhtmlcommon::scripttag($output);
 4982:   
 4983:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4984:     my $text = &mt('Communication Blocked');
 4985:     my $class = 'LC_comblock';
 4986:     if ($activity eq 'docs') {
 4987:         $text = &mt('Content Access Blocked');
 4988:         $class = '';
 4989:     } elsif ($activity eq 'printout') {
 4990:         $text = &mt('Printing Blocked');
 4991:     } elsif ($activity eq 'passwd') {
 4992:         $text = &mt('Password Changing Blocked');
 4993:     }
 4994:     $output .= <<"END_BLOCK";
 4995: <div class='$class'>
 4996:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4997:   title='$text'>
 4998:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4999:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5000:   title='$text'>$text</a>
 5001: </div>
 5002: 
 5003: END_BLOCK
 5004: 
 5005:     return ($blocked, $output);
 5006: }
 5007: 
 5008: ###############################################
 5009: 
 5010: sub check_ip_acc {
 5011:     my ($acc,$clientip)=@_;
 5012:     &Apache::lonxml::debug("acc is $acc");
 5013:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5014:         return 1;
 5015:     }
 5016:     my $allowed;
 5017:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5018: 
 5019:     my $name;
 5020:     my %access = (
 5021:                      allowfrom => 1,
 5022:                      denyfrom  => 0,
 5023:                  );
 5024:     my @allows;
 5025:     my @denies;
 5026:     foreach my $item (split(',',$acc)) {
 5027:         $item =~ s/^\s*//;
 5028:         $item =~ s/\s*$//;
 5029:         my $pattern;
 5030:         if ($item =~ /^\!(.+)$/) {
 5031:             push(@denies,$1);
 5032:         } else {
 5033:             push(@allows,$item);
 5034:         }
 5035:    }
 5036:    my $numdenies = scalar(@denies);
 5037:    my $numallows = scalar(@allows);
 5038:    my $count = 0;
 5039:    foreach my $pattern (@denies,@allows) {
 5040:         $count ++; 
 5041:         my $acctype = 'allowfrom';
 5042:         if ($count <= $numdenies) {
 5043:             $acctype = 'denyfrom';
 5044:         }
 5045:         if ($pattern =~ /\*$/) {
 5046:             #35.8.*
 5047:             $pattern=~s/\*//;
 5048:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5049:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5050:             #35.8.3.[34-56]
 5051:             my $low=$2;
 5052:             my $high=$3;
 5053:             $pattern=$1;
 5054:             if ($ip =~ /^\Q$pattern\E/) {
 5055:                 my $last=(split(/\./,$ip))[3];
 5056:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5057:             }
 5058:         } elsif ($pattern =~ /^\*/) {
 5059:             #*.msu.edu
 5060:             $pattern=~s/\*//;
 5061:             if (!defined($name)) {
 5062:                 use Socket;
 5063:                 my $netaddr=inet_aton($ip);
 5064:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5065:             }
 5066:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5067:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5068:             #127.0.0.1
 5069:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5070:         } else {
 5071:             #some.name.com
 5072:             if (!defined($name)) {
 5073:                 use Socket;
 5074:                 my $netaddr=inet_aton($ip);
 5075:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5076:             }
 5077:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5078:         }
 5079:         if ($allowed =~ /^(0|1)$/) { last; }
 5080:     }
 5081:     if ($allowed eq '') {
 5082:         if ($numdenies && !$numallows) {
 5083:             $allowed = 1;
 5084:         } else {
 5085:             $allowed = 0;
 5086:         }
 5087:     }
 5088:     return $allowed;
 5089: }
 5090: 
 5091: ###############################################
 5092: 
 5093: =pod
 5094: 
 5095: =head1 Domain Template Functions
 5096: 
 5097: =over 4
 5098: 
 5099: =item * &determinedomain()
 5100: 
 5101: Inputs: $domain (usually will be undef)
 5102: 
 5103: Returns: Determines which domain should be used for designs
 5104: 
 5105: =cut
 5106: 
 5107: ###############################################
 5108: sub determinedomain {
 5109:     my $domain=shift;
 5110:     if (! $domain) {
 5111:         # Determine domain if we have not been given one
 5112:         $domain = &Apache::lonnet::default_login_domain();
 5113:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5114:         if ($env{'request.role.domain'}) { 
 5115:             $domain=$env{'request.role.domain'}; 
 5116:         }
 5117:     }
 5118:     return $domain;
 5119: }
 5120: ###############################################
 5121: 
 5122: sub devalidate_domconfig_cache {
 5123:     my ($udom)=@_;
 5124:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5125: }
 5126: 
 5127: # ---------------------- Get domain configuration for a domain
 5128: sub get_domainconf {
 5129:     my ($udom) = @_;
 5130:     my $cachetime=1800;
 5131:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5132:     if (defined($cached)) { return %{$result}; }
 5133: 
 5134:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5135: 					     ['login','rolecolors','autoenroll'],$udom);
 5136:     my (%designhash,%legacy);
 5137:     if (keys(%domconfig) > 0) {
 5138:         if (ref($domconfig{'login'}) eq 'HASH') {
 5139:             if (keys(%{$domconfig{'login'}})) {
 5140:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5141:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5142:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5143:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5144:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5145:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5146:                                         if ($key eq 'loginvia') {
 5147:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5148:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5149:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5150:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5151: 
 5152:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5153:                                                 } else {
 5154:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5155:                                                 }
 5156:                                             }
 5157:                                         } elsif ($key eq 'headtag') {
 5158:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5159:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5160:                                             }
 5161:                                         }
 5162:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5163:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5164:                                         }
 5165:                                     }
 5166:                                 }
 5167:                             }
 5168:                         } else {
 5169:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5170:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5171:                                     $domconfig{'login'}{$key}{$img};
 5172:                             }
 5173:                         }
 5174:                     } else {
 5175:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5176:                     }
 5177:                 }
 5178:             } else {
 5179:                 $legacy{'login'} = 1;
 5180:             }
 5181:         } else {
 5182:             $legacy{'login'} = 1;
 5183:         }
 5184:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5185:             if (keys(%{$domconfig{'rolecolors'}})) {
 5186:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5187:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5188:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5189:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5190:                         }
 5191:                     }
 5192:                 }
 5193:             } else {
 5194:                 $legacy{'rolecolors'} = 1;
 5195:             }
 5196:         } else {
 5197:             $legacy{'rolecolors'} = 1;
 5198:         }
 5199:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5200:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5201:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5202:             }
 5203:         }
 5204:         if (keys(%legacy) > 0) {
 5205:             my %legacyhash = &get_legacy_domconf($udom);
 5206:             foreach my $item (keys(%legacyhash)) {
 5207:                 if ($item =~ /^\Q$udom\E\.login/) {
 5208:                     if ($legacy{'login'}) { 
 5209:                         $designhash{$item} = $legacyhash{$item};
 5210:                     }
 5211:                 } else {
 5212:                     if ($legacy{'rolecolors'}) {
 5213:                         $designhash{$item} = $legacyhash{$item};
 5214:                     }
 5215:                 }
 5216:             }
 5217:         }
 5218:     } else {
 5219:         %designhash = &get_legacy_domconf($udom); 
 5220:     }
 5221:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5222: 				  $cachetime);
 5223:     return %designhash;
 5224: }
 5225: 
 5226: sub get_legacy_domconf {
 5227:     my ($udom) = @_;
 5228:     my %legacyhash;
 5229:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5230:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5231:     if (-e $designfile) {
 5232:         if ( open (my $fh,"<$designfile") ) {
 5233:             while (my $line = <$fh>) {
 5234:                 next if ($line =~ /^\#/);
 5235:                 chomp($line);
 5236:                 my ($key,$val)=(split(/\=/,$line));
 5237:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5238:             }
 5239:             close($fh);
 5240:         }
 5241:     }
 5242:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5243:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5244:     }
 5245:     return %legacyhash;
 5246: }
 5247: 
 5248: =pod
 5249: 
 5250: =item * &domainlogo()
 5251: 
 5252: Inputs: $domain (usually will be undef)
 5253: 
 5254: Returns: A link to a domain logo, if the domain logo exists.
 5255: If the domain logo does not exist, a description of the domain.
 5256: 
 5257: =cut
 5258: 
 5259: ###############################################
 5260: sub domainlogo {
 5261:     my $domain = &determinedomain(shift);
 5262:     my %designhash = &get_domainconf($domain);    
 5263:     # See if there is a logo
 5264:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5265:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5266:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5267: 	    if ($imgsrc =~ m{^/res/}) {
 5268: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5269: 		&Apache::lonnet::repcopy($local_name);
 5270: 	    }
 5271: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5272:         } 
 5273:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5274:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5275:         return &Apache::lonnet::domain($domain,'description');
 5276:     } else {
 5277:         return '';
 5278:     }
 5279: }
 5280: ##############################################
 5281: 
 5282: =pod
 5283: 
 5284: =item * &designparm()
 5285: 
 5286: Inputs: $which parameter; $domain (usually will be undef)
 5287: 
 5288: Returns: value of designparamter $which
 5289: 
 5290: =cut
 5291: 
 5292: 
 5293: ##############################################
 5294: sub designparm {
 5295:     my ($which,$domain)=@_;
 5296:     if (exists($env{'environment.color.'.$which})) {
 5297:         return $env{'environment.color.'.$which};
 5298:     }
 5299:     $domain=&determinedomain($domain);
 5300:     my %domdesign;
 5301:     unless ($domain eq 'public') {
 5302:         %domdesign = &get_domainconf($domain);
 5303:     }
 5304:     my $output;
 5305:     if ($domdesign{$domain.'.'.$which} ne '') {
 5306:         $output = $domdesign{$domain.'.'.$which};
 5307:     } else {
 5308:         $output = $defaultdesign{$which};
 5309:     }
 5310:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5311:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5312:         if ($output =~ m{^/(adm|res)/}) {
 5313:             if ($output =~ m{^/res/}) {
 5314:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5315:                 &Apache::lonnet::repcopy($local_name);
 5316:             }
 5317:             $output = &lonhttpdurl($output);
 5318:         }
 5319:     }
 5320:     return $output;
 5321: }
 5322: 
 5323: ##############################################
 5324: =pod
 5325: 
 5326: =item * &authorspace()
 5327: 
 5328: Inputs: $url (usually will be undef).
 5329: 
 5330: Returns: Path to Authoring Space containing the resource or 
 5331:          directory being viewed (or for which action is being taken). 
 5332:          If $url is provided, and begins /priv/<domain>/<uname>
 5333:          the path will be that portion of the $context argument.
 5334:          Otherwise the path will be for the author space of the current
 5335:          user when the current role is author, or for that of the 
 5336:          co-author/assistant co-author space when the current role 
 5337:          is co-author or assistant co-author.
 5338: 
 5339: =cut
 5340: 
 5341: sub authorspace {
 5342:     my ($url) = @_;
 5343:     if ($url ne '') {
 5344:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5345:            return $1;
 5346:         }
 5347:     }
 5348:     my $caname = '';
 5349:     my $cadom = '';
 5350:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5351:         ($cadom,$caname) =
 5352:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5353:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5354:         $caname = $env{'user.name'};
 5355:         $cadom = $env{'user.domain'};
 5356:     }
 5357:     if (($caname ne '') && ($cadom ne '')) {
 5358:         return "/priv/$cadom/$caname/";
 5359:     }
 5360:     return;
 5361: }
 5362: 
 5363: ##############################################
 5364: =pod
 5365: 
 5366: =item * &head_subbox()
 5367: 
 5368: Inputs: $content (contains HTML code with page functions, etc.)
 5369: 
 5370: Returns: HTML div with $content
 5371:          To be included in page header
 5372: 
 5373: =cut
 5374: 
 5375: sub head_subbox {
 5376:     my ($content)=@_;
 5377:     my $output =
 5378:         '<div class="LC_head_subbox">'
 5379:        .$content
 5380:        .'</div>'
 5381: }
 5382: 
 5383: ##############################################
 5384: =pod
 5385: 
 5386: =item * &CSTR_pageheader()
 5387: 
 5388: Input: (optional) filename from which breadcrumb trail is built.
 5389:        In most cases no input as needed, as $env{'request.filename'}
 5390:        is appropriate for use in building the breadcrumb trail.
 5391: 
 5392: Returns: HTML div with CSTR path and recent box
 5393:          To be included on Authoring Space pages
 5394: 
 5395: =cut
 5396: 
 5397: sub CSTR_pageheader {
 5398:     my ($trailfile) = @_;
 5399:     if ($trailfile eq '') {
 5400:         $trailfile = $env{'request.filename'};
 5401:     }
 5402: 
 5403: # this is for resources; directories have customtitle, and crumbs
 5404: # and select recent are created in lonpubdir.pm
 5405: 
 5406:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5407:     my ($udom,$uname,$thisdisfn)=
 5408:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5409:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5410:     $formaction =~ s{/+}{/}g;
 5411: 
 5412:     my $parentpath = '';
 5413:     my $lastitem = '';
 5414:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5415:         $parentpath = $1;
 5416:         $lastitem = $2;
 5417:     } else {
 5418:         $lastitem = $thisdisfn;
 5419:     }
 5420: 
 5421:     my $output =
 5422:          '<div>'
 5423:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5424:         .'<b>'.&mt('Authoring Space:').'</b> '
 5425:         .'<form name="dirs" method="post" action="'.$formaction
 5426:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5427:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5428: 
 5429:     if ($lastitem) {
 5430:         $output .=
 5431:              '<span class="LC_filename">'
 5432:             .$lastitem
 5433:             .'</span>';
 5434:     }
 5435:     $output .=
 5436:          '<br />'
 5437:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5438:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5439:         .'</form>'
 5440:         .&Apache::lonmenu::constspaceform()
 5441:         .'</div>';
 5442: 
 5443:     return $output;
 5444: }
 5445: 
 5446: ###############################################
 5447: ###############################################
 5448: 
 5449: =pod
 5450: 
 5451: =back
 5452: 
 5453: =head1 HTML Helpers
 5454: 
 5455: =over 4
 5456: 
 5457: =item * &bodytag()
 5458: 
 5459: Returns a uniform header for LON-CAPA web pages.
 5460: 
 5461: Inputs: 
 5462: 
 5463: =over 4
 5464: 
 5465: =item * $title, A title to be displayed on the page.
 5466: 
 5467: =item * $function, the current role (can be undef).
 5468: 
 5469: =item * $addentries, extra parameters for the <body> tag.
 5470: 
 5471: =item * $bodyonly, if defined, only return the <body> tag.
 5472: 
 5473: =item * $domain, if defined, force a given domain.
 5474: 
 5475: =item * $forcereg, if page should register as content page (relevant for 
 5476:             text interface only)
 5477: 
 5478: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5479:                      navigational links
 5480: 
 5481: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5482: 
 5483: =item * $args, optional argument valid values are
 5484:             no_auto_mt_title -> prevents &mt()ing the title arg
 5485:             inherit_jsmath -> when creating popup window in a page,
 5486:                               should it have jsmath forced on by the
 5487:                               current page
 5488: 
 5489: =item * $advtoolsref, optional argument, ref to an array containing
 5490:             inlineremote items to be added in "Functions" menu below
 5491:             breadcrumbs.
 5492: 
 5493: =back
 5494: 
 5495: Returns: A uniform header for LON-CAPA web pages.  
 5496: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5497: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5498: other decorations will be returned.
 5499: 
 5500: =cut
 5501: 
 5502: sub bodytag {
 5503:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5504:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5505: 
 5506:     my $public;
 5507:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5508:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5509:         $public = 1;
 5510:     }
 5511:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5512:     my $httphost = $args->{'use_absolute'};
 5513: 
 5514:     $function = &get_users_function() if (!$function);
 5515:     my $img =    &designparm($function.'.img',$domain);
 5516:     my $font =   &designparm($function.'.font',$domain);
 5517:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5518: 
 5519:     my %design = ( 'style'   => 'margin-top: 0',
 5520: 		   'bgcolor' => $pgbg,
 5521: 		   'text'    => $font,
 5522:                    'alink'   => &designparm($function.'.alink',$domain),
 5523: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5524: 		   'link'    => &designparm($function.'.link',$domain),);
 5525:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5526: 
 5527:  # role and realm
 5528:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5529:     if ($realm) {
 5530:         $realm = '/'.$realm;
 5531:     }
 5532:     if ($role  eq 'ca') {
 5533:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5534:         $realm = &plainname($rname,$rdom);
 5535:     } 
 5536: # realm
 5537:     if ($env{'request.course.id'}) {
 5538:         if ($env{'request.role'} !~ /^cr/) {
 5539:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5540:         }
 5541:         if ($env{'request.course.sec'}) {
 5542:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5543:         }   
 5544: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5545:     } else {
 5546:         $role = &Apache::lonnet::plaintext($role);
 5547:     }
 5548: 
 5549:     if (!$realm) { $realm='&nbsp;'; }
 5550: 
 5551:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5552: 
 5553: # construct main body tag
 5554:     my $bodytag = "<body $extra_body_attr>".
 5555: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5556: 
 5557:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5558: 
 5559:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5560:         return $bodytag;
 5561:     }
 5562: 
 5563:     if ($public) {
 5564: 	undef($role);
 5565:     }
 5566:     
 5567:     my $titleinfo = '<h1>'.$title.'</h1>';
 5568:     #
 5569:     # Extra info if you are the DC
 5570:     my $dc_info = '';
 5571:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5572:                         $env{'course.'.$env{'request.course.id'}.
 5573:                                  '.domain'}.'/'})) {
 5574:         my $cid = $env{'request.course.id'};
 5575:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5576:         $dc_info =~ s/\s+$//;
 5577:     }
 5578: 
 5579:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5580: 
 5581:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5582: 
 5583:         #    if ($env{'request.state'} eq 'construct') {
 5584:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5585:         #    }
 5586: 
 5587:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5588:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5589: 
 5590:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5591: 
 5592:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5593:              if ($dc_info) {
 5594:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5595:              }
 5596:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5597:                 <em>$realm</em> $dc_info</div>|;
 5598:             return $bodytag;
 5599:         }
 5600: 
 5601:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5602:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5603:         }
 5604: 
 5605:         $bodytag .= $right;
 5606: 
 5607:         if ($dc_info) {
 5608:             $dc_info = &dc_courseid_toggle($dc_info);
 5609:         }
 5610:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5611: 
 5612:         #if directed to not display the secondary menu, don't.  
 5613:         if ($args->{'no_secondary_menu'}) {
 5614:             return $bodytag;
 5615:         }
 5616:         #don't show menus for public users
 5617:         if (!$public){
 5618:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5619:             $bodytag .= Apache::lonmenu::serverform();
 5620:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5621:             if ($env{'request.state'} eq 'construct') {
 5622:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5623:                                 $args->{'bread_crumbs'});
 5624:             } elsif ($forcereg) {
 5625:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5626:                                                             $args->{'group'});
 5627:             } else {
 5628:                 $bodytag .= 
 5629:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5630:                                                         $forcereg,$args->{'group'},
 5631:                                                         $args->{'bread_crumbs'},
 5632:                                                         $advtoolsref);
 5633:             }
 5634:         }else{
 5635:             # this is to seperate menu from content when there's no secondary
 5636:             # menu. Especially needed for public accessible ressources.
 5637:             $bodytag .= '<hr style="clear:both" />';
 5638:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5639:         }
 5640: 
 5641:         return $bodytag;
 5642: }
 5643: 
 5644: sub dc_courseid_toggle {
 5645:     my ($dc_info) = @_;
 5646:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5647:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5648:            &mt('(More ...)').'</a></span>'.
 5649:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5650: }
 5651: 
 5652: sub make_attr_string {
 5653:     my ($register,$attr_ref) = @_;
 5654: 
 5655:     if ($attr_ref && !ref($attr_ref)) {
 5656: 	die("addentries Must be a hash ref ".
 5657: 	    join(':',caller(1))." ".
 5658: 	    join(':',caller(0))." ");
 5659:     }
 5660: 
 5661:     if ($register) {
 5662: 	my ($on_load,$on_unload);
 5663: 	foreach my $key (keys(%{$attr_ref})) {
 5664: 	    if      (lc($key) eq 'onload') {
 5665: 		$on_load.=$attr_ref->{$key}.';';
 5666: 		delete($attr_ref->{$key});
 5667: 
 5668: 	    } elsif (lc($key) eq 'onunload') {
 5669: 		$on_unload.=$attr_ref->{$key}.';';
 5670: 		delete($attr_ref->{$key});
 5671: 	    }
 5672: 	}
 5673: 	$attr_ref->{'onload'}  = $on_load;
 5674: 	$attr_ref->{'onunload'}= $on_unload;
 5675:     }
 5676: 
 5677:     my $attr_string;
 5678:     foreach my $attr (sort(keys(%$attr_ref))) {
 5679: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5680:     }
 5681:     return $attr_string;
 5682: }
 5683: 
 5684: 
 5685: ###############################################
 5686: ###############################################
 5687: 
 5688: =pod
 5689: 
 5690: =item * &endbodytag()
 5691: 
 5692: Returns a uniform footer for LON-CAPA web pages.
 5693: 
 5694: Inputs: 1 - optional reference to an args hash
 5695: If in the hash, key for noredirectlink has a value which evaluates to true,
 5696: a 'Continue' link is not displayed if the page contains an
 5697: internal redirect in the <head></head> section,
 5698: i.e., $env{'internal.head.redirect'} exists   
 5699: 
 5700: =cut
 5701: 
 5702: sub endbodytag {
 5703:     my ($args) = @_;
 5704:     my $endbodytag;
 5705:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5706:         $endbodytag='</body>';
 5707:     }
 5708:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5709:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5710:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5711: 	    $endbodytag=
 5712: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5713: 	        &mt('Continue').'</a>'.
 5714: 	        $endbodytag;
 5715:         }
 5716:     }
 5717:     return $endbodytag;
 5718: }
 5719: 
 5720: =pod
 5721: 
 5722: =item * &standard_css()
 5723: 
 5724: Returns a style sheet
 5725: 
 5726: Inputs: (all optional)
 5727:             domain         -> force to color decorate a page for a specific
 5728:                                domain
 5729:             function       -> force usage of a specific rolish color scheme
 5730:             bgcolor        -> override the default page bgcolor
 5731: 
 5732: =cut
 5733: 
 5734: sub standard_css {
 5735:     my ($function,$domain,$bgcolor) = @_;
 5736:     $function  = &get_users_function() if (!$function);
 5737:     my $img    = &designparm($function.'.img',   $domain);
 5738:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5739:     my $font   = &designparm($function.'.font',  $domain);
 5740:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5741: #second colour for later usage
 5742:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5743:     my $pgbg_or_bgcolor =
 5744: 	         $bgcolor ||
 5745: 	         &designparm($function.'.pgbg',  $domain);
 5746:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5747:     my $alink  = &designparm($function.'.alink', $domain);
 5748:     my $vlink  = &designparm($function.'.vlink', $domain);
 5749:     my $link   = &designparm($function.'.link',  $domain);
 5750: 
 5751:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5752:     my $mono                 = 'monospace';
 5753:     my $data_table_head      = $sidebg;
 5754:     my $data_table_light     = '#FAFAFA';
 5755:     my $data_table_dark      = '#E0E0E0';
 5756:     my $data_table_darker    = '#CCCCCC';
 5757:     my $data_table_highlight = '#FFFF00';
 5758:     my $mail_new             = '#FFBB77';
 5759:     my $mail_new_hover       = '#DD9955';
 5760:     my $mail_read            = '#BBBB77';
 5761:     my $mail_read_hover      = '#999944';
 5762:     my $mail_replied         = '#AAAA88';
 5763:     my $mail_replied_hover   = '#888855';
 5764:     my $mail_other           = '#99BBBB';
 5765:     my $mail_other_hover     = '#669999';
 5766:     my $table_header         = '#DDDDDD';
 5767:     my $feedback_link_bg     = '#BBBBBB';
 5768:     my $lg_border_color      = '#C8C8C8';
 5769:     my $button_hover         = '#BF2317';
 5770: 
 5771:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5772:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5773:                                              : '0 3px 0 4px';
 5774: 
 5775: 
 5776:     return <<END;
 5777: 
 5778: /* needed for iframe to allow 100% height in FF */
 5779: body, html { 
 5780:     margin: 0;
 5781:     padding: 0 0.5%;
 5782:     height: 99%; /* to avoid scrollbars */
 5783: }
 5784: 
 5785: body {
 5786:   font-family: $sans;
 5787:   line-height:130%;
 5788:   font-size:0.83em;
 5789:   color:$font;
 5790: }
 5791: 
 5792: a:focus,
 5793: a:focus img {
 5794:   color: red;
 5795: }
 5796: 
 5797: form, .inline {
 5798:   display: inline;
 5799: }
 5800: 
 5801: .LC_right {
 5802:   text-align:right;
 5803: }
 5804: 
 5805: .LC_middle {
 5806:   vertical-align:middle;
 5807: }
 5808: 
 5809: .LC_floatleft {
 5810:   float: left;
 5811: }
 5812: 
 5813: .LC_floatright {
 5814:   float: right;
 5815: }
 5816: 
 5817: .LC_400Box {
 5818:   width:400px;
 5819: }
 5820: 
 5821: .LC_iframecontainer {
 5822:     width: 98%;
 5823:     margin: 0;
 5824:     position: fixed;
 5825:     top: 8.5em;
 5826:     bottom: 0;
 5827: }
 5828: 
 5829: .LC_iframecontainer iframe{
 5830:     border: none;
 5831:     width: 100%;
 5832:     height: 100%;
 5833: }
 5834: 
 5835: .LC_filename {
 5836:   font-family: $mono;
 5837:   white-space:pre;
 5838:   font-size: 120%;
 5839: }
 5840: 
 5841: .LC_fileicon {
 5842:   border: none;
 5843:   height: 1.3em;
 5844:   vertical-align: text-bottom;
 5845:   margin-right: 0.3em;
 5846:   text-decoration:none;
 5847: }
 5848: 
 5849: .LC_setting {
 5850:   text-decoration:underline;
 5851: }
 5852: 
 5853: .LC_error {
 5854:   color: red;
 5855: }
 5856: 
 5857: .LC_warning {
 5858:   color: darkorange;
 5859: }
 5860: 
 5861: .LC_diff_removed {
 5862:   color: red;
 5863: }
 5864: 
 5865: .LC_info,
 5866: .LC_success,
 5867: .LC_diff_added {
 5868:   color: green;
 5869: }
 5870: 
 5871: div.LC_confirm_box {
 5872:   background-color: #FAFAFA;
 5873:   border: 1px solid $lg_border_color;
 5874:   margin-right: 0;
 5875:   padding: 5px;
 5876: }
 5877: 
 5878: div.LC_confirm_box .LC_error img,
 5879: div.LC_confirm_box .LC_success img {
 5880:   vertical-align: middle;
 5881: }
 5882: 
 5883: .LC_icon {
 5884:   border: none;
 5885:   vertical-align: middle;
 5886: }
 5887: 
 5888: .LC_docs_spacer {
 5889:   width: 25px;
 5890:   height: 1px;
 5891:   border: none;
 5892: }
 5893: 
 5894: .LC_internal_info {
 5895:   color: #999999;
 5896: }
 5897: 
 5898: .LC_discussion {
 5899:   background: $data_table_dark;
 5900:   border: 1px solid black;
 5901:   margin: 2px;
 5902: }
 5903: 
 5904: .LC_disc_action_left {
 5905:   background: $sidebg;
 5906:   text-align: left;
 5907:   padding: 4px;
 5908:   margin: 2px;
 5909: }
 5910: 
 5911: .LC_disc_action_right {
 5912:   background: $sidebg;
 5913:   text-align: right;
 5914:   padding: 4px;
 5915:   margin: 2px;
 5916: }
 5917: 
 5918: .LC_disc_new_item {
 5919:   background: white;
 5920:   border: 2px solid red;
 5921:   margin: 4px;
 5922:   padding: 4px;
 5923: }
 5924: 
 5925: .LC_disc_old_item {
 5926:   background: white;
 5927:   margin: 4px;
 5928:   padding: 4px;
 5929: }
 5930: 
 5931: table.LC_pastsubmission {
 5932:   border: 1px solid black;
 5933:   margin: 2px;
 5934: }
 5935: 
 5936: table#LC_menubuttons {
 5937:   width: 100%;
 5938:   background: $pgbg;
 5939:   border: 2px;
 5940:   border-collapse: separate;
 5941:   padding: 0;
 5942: }
 5943: 
 5944: table#LC_title_bar a {
 5945:   color: $fontmenu;
 5946: }
 5947: 
 5948: table#LC_title_bar {
 5949:   clear: both;
 5950:   display: none;
 5951: }
 5952: 
 5953: table#LC_title_bar,
 5954: table.LC_breadcrumbs, /* obsolete? */
 5955: table#LC_title_bar.LC_with_remote {
 5956:   width: 100%;
 5957:   border-color: $pgbg;
 5958:   border-style: solid;
 5959:   border-width: $border;
 5960:   background: $pgbg;
 5961:   color: $fontmenu;
 5962:   border-collapse: collapse;
 5963:   padding: 0;
 5964:   margin: 0;
 5965: }
 5966: 
 5967: ul.LC_breadcrumb_tools_outerlist {
 5968:     margin: 0;
 5969:     padding: 0;
 5970:     position: relative;
 5971:     list-style: none;
 5972: }
 5973: ul.LC_breadcrumb_tools_outerlist li {
 5974:     display: inline;
 5975: }
 5976: 
 5977: .LC_breadcrumb_tools_navigation {
 5978:     padding: 0;
 5979:     margin: 0;
 5980:     float: left;
 5981: }
 5982: .LC_breadcrumb_tools_tools {
 5983:     padding: 0;
 5984:     margin: 0;
 5985:     float: right;
 5986: }
 5987: 
 5988: table#LC_title_bar td {
 5989:   background: $tabbg;
 5990: }
 5991: 
 5992: table#LC_menubuttons img {
 5993:   border: none;
 5994: }
 5995: 
 5996: .LC_breadcrumbs_component {
 5997:   float: right;
 5998:   margin: 0 1em;
 5999: }
 6000: .LC_breadcrumbs_component img {
 6001:   vertical-align: middle;
 6002: }
 6003: 
 6004: td.LC_table_cell_checkbox {
 6005:   text-align: center;
 6006: }
 6007: 
 6008: .LC_fontsize_small {
 6009:   font-size: 70%;
 6010: }
 6011: 
 6012: #LC_breadcrumbs {
 6013:   clear:both;
 6014:   background: $sidebg;
 6015:   border-bottom: 1px solid $lg_border_color;
 6016:   line-height: 2.5em;
 6017:   overflow: hidden;
 6018:   margin: 0;
 6019:   padding: 0;
 6020:   text-align: left;
 6021: }
 6022: 
 6023: .LC_head_subbox, .LC_actionbox {
 6024:   clear:both;
 6025:   background: #F8F8F8; /* $sidebg; */
 6026:   border: 1px solid $sidebg;
 6027:   margin: 0 0 10px 0;
 6028:   padding: 3px;
 6029:   text-align: left;
 6030: }
 6031: 
 6032: .LC_fontsize_medium {
 6033:   font-size: 85%;
 6034: }
 6035: 
 6036: .LC_fontsize_large {
 6037:   font-size: 120%;
 6038: }
 6039: 
 6040: .LC_menubuttons_inline_text {
 6041:   color: $font;
 6042:   font-size: 90%;
 6043:   padding-left:3px;
 6044: }
 6045: 
 6046: .LC_menubuttons_inline_text img{
 6047:   vertical-align: middle;
 6048: }
 6049: 
 6050: li.LC_menubuttons_inline_text img {
 6051:   cursor:pointer;
 6052:   text-decoration: none;
 6053: }
 6054: 
 6055: .LC_menubuttons_link {
 6056:   text-decoration: none;
 6057: }
 6058: 
 6059: .LC_menubuttons_category {
 6060:   color: $font;
 6061:   background: $pgbg;
 6062:   font-size: larger;
 6063:   font-weight: bold;
 6064: }
 6065: 
 6066: td.LC_menubuttons_text {
 6067:   color: $font;
 6068: }
 6069: 
 6070: .LC_current_location {
 6071:   background: $tabbg;
 6072: }
 6073: 
 6074: table.LC_data_table {
 6075:   border: 1px solid #000000;
 6076:   border-collapse: separate;
 6077:   border-spacing: 1px;
 6078:   background: $pgbg;
 6079: }
 6080: 
 6081: .LC_data_table_dense {
 6082:   font-size: small;
 6083: }
 6084: 
 6085: table.LC_nested_outer {
 6086:   border: 1px solid #000000;
 6087:   border-collapse: collapse;
 6088:   border-spacing: 0;
 6089:   width: 100%;
 6090: }
 6091: 
 6092: table.LC_innerpickbox,
 6093: table.LC_nested {
 6094:   border: none;
 6095:   border-collapse: collapse;
 6096:   border-spacing: 0;
 6097:   width: 100%;
 6098: }
 6099: 
 6100: table.LC_data_table tr th,
 6101: table.LC_calendar tr th,
 6102: table.LC_prior_tries tr th,
 6103: table.LC_innerpickbox tr th {
 6104:   font-weight: bold;
 6105:   background-color: $data_table_head;
 6106:   color:$fontmenu;
 6107:   font-size:90%;
 6108: }
 6109: 
 6110: table.LC_innerpickbox tr th,
 6111: table.LC_innerpickbox tr td {
 6112:   vertical-align: top;
 6113: }
 6114: 
 6115: table.LC_data_table tr.LC_info_row > td {
 6116:   background-color: #CCCCCC;
 6117:   font-weight: bold;
 6118:   text-align: left;
 6119: }
 6120: 
 6121: table.LC_data_table tr.LC_odd_row > td {
 6122:   background-color: $data_table_light;
 6123:   padding: 2px;
 6124:   vertical-align: top;
 6125: }
 6126: 
 6127: table.LC_pick_box tr > td.LC_odd_row {
 6128:   background-color: $data_table_light;
 6129:   vertical-align: top;
 6130: }
 6131: 
 6132: table.LC_data_table tr.LC_even_row > td {
 6133:   background-color: $data_table_dark;
 6134:   padding: 2px;
 6135:   vertical-align: top;
 6136: }
 6137: 
 6138: table.LC_pick_box tr > td.LC_even_row {
 6139:   background-color: $data_table_dark;
 6140:   vertical-align: top;
 6141: }
 6142: 
 6143: table.LC_data_table tr.LC_data_table_highlight td {
 6144:   background-color: $data_table_darker;
 6145: }
 6146: 
 6147: table.LC_data_table tr td.LC_leftcol_header {
 6148:   background-color: $data_table_head;
 6149:   font-weight: bold;
 6150: }
 6151: 
 6152: table.LC_data_table tr.LC_empty_row td,
 6153: table.LC_nested tr.LC_empty_row td {
 6154:   font-weight: bold;
 6155:   font-style: italic;
 6156:   text-align: center;
 6157:   padding: 8px;
 6158: }
 6159: 
 6160: table.LC_data_table tr.LC_empty_row td,
 6161: table.LC_data_table tr.LC_footer_row td {
 6162:   background-color: $sidebg;
 6163: }
 6164: 
 6165: table.LC_nested tr.LC_empty_row td {
 6166:   background-color: #FFFFFF;
 6167: }
 6168: 
 6169: table.LC_caption {
 6170: }
 6171: 
 6172: table.LC_nested tr.LC_empty_row td {
 6173:   padding: 4ex
 6174: }
 6175: 
 6176: table.LC_nested_outer tr th {
 6177:   font-weight: bold;
 6178:   color:$fontmenu;
 6179:   background-color: $data_table_head;
 6180:   font-size: small;
 6181:   border-bottom: 1px solid #000000;
 6182: }
 6183: 
 6184: table.LC_nested_outer tr td.LC_subheader {
 6185:   background-color: $data_table_head;
 6186:   font-weight: bold;
 6187:   font-size: small;
 6188:   border-bottom: 1px solid #000000;
 6189:   text-align: right;
 6190: }
 6191: 
 6192: table.LC_nested tr.LC_info_row td {
 6193:   background-color: #CCCCCC;
 6194:   font-weight: bold;
 6195:   font-size: small;
 6196:   text-align: center;
 6197: }
 6198: 
 6199: table.LC_nested tr.LC_info_row td.LC_left_item,
 6200: table.LC_nested_outer tr th.LC_left_item {
 6201:   text-align: left;
 6202: }
 6203: 
 6204: table.LC_nested td {
 6205:   background-color: #FFFFFF;
 6206:   font-size: small;
 6207: }
 6208: 
 6209: table.LC_nested_outer tr th.LC_right_item,
 6210: table.LC_nested tr.LC_info_row td.LC_right_item,
 6211: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6212: table.LC_nested tr td.LC_right_item {
 6213:   text-align: right;
 6214: }
 6215: 
 6216: table.LC_nested tr.LC_odd_row td {
 6217:   background-color: #EEEEEE;
 6218: }
 6219: 
 6220: table.LC_createuser {
 6221: }
 6222: 
 6223: table.LC_createuser tr.LC_section_row td {
 6224:   font-size: small;
 6225: }
 6226: 
 6227: table.LC_createuser tr.LC_info_row td  {
 6228:   background-color: #CCCCCC;
 6229:   font-weight: bold;
 6230:   text-align: center;
 6231: }
 6232: 
 6233: table.LC_calendar {
 6234:   border: 1px solid #000000;
 6235:   border-collapse: collapse;
 6236:   width: 98%;
 6237: }
 6238: 
 6239: table.LC_calendar_pickdate {
 6240:   font-size: xx-small;
 6241: }
 6242: 
 6243: table.LC_calendar tr td {
 6244:   border: 1px solid #000000;
 6245:   vertical-align: top;
 6246:   width: 14%;
 6247: }
 6248: 
 6249: table.LC_calendar tr td.LC_calendar_day_empty {
 6250:   background-color: $data_table_dark;
 6251: }
 6252: 
 6253: table.LC_calendar tr td.LC_calendar_day_current {
 6254:   background-color: $data_table_highlight;
 6255: }
 6256: 
 6257: table.LC_data_table tr td.LC_mail_new {
 6258:   background-color: $mail_new;
 6259: }
 6260: 
 6261: table.LC_data_table tr.LC_mail_new:hover {
 6262:   background-color: $mail_new_hover;
 6263: }
 6264: 
 6265: table.LC_data_table tr td.LC_mail_read {
 6266:   background-color: $mail_read;
 6267: }
 6268: 
 6269: /*
 6270: table.LC_data_table tr.LC_mail_read:hover {
 6271:   background-color: $mail_read_hover;
 6272: }
 6273: */
 6274: 
 6275: table.LC_data_table tr td.LC_mail_replied {
 6276:   background-color: $mail_replied;
 6277: }
 6278: 
 6279: /*
 6280: table.LC_data_table tr.LC_mail_replied:hover {
 6281:   background-color: $mail_replied_hover;
 6282: }
 6283: */
 6284: 
 6285: table.LC_data_table tr td.LC_mail_other {
 6286:   background-color: $mail_other;
 6287: }
 6288: 
 6289: /*
 6290: table.LC_data_table tr.LC_mail_other:hover {
 6291:   background-color: $mail_other_hover;
 6292: }
 6293: */
 6294: 
 6295: table.LC_data_table tr > td.LC_browser_file,
 6296: table.LC_data_table tr > td.LC_browser_file_published {
 6297:   background: #AAEE77;
 6298: }
 6299: 
 6300: table.LC_data_table tr > td.LC_browser_file_locked,
 6301: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6302:   background: #FFAA99;
 6303: }
 6304: 
 6305: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6306:   background: #888888;
 6307: }
 6308: 
 6309: table.LC_data_table tr > td.LC_browser_file_modified,
 6310: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6311:   background: #F8F866;
 6312: }
 6313: 
 6314: table.LC_data_table tr.LC_browser_folder > td {
 6315:   background: #E0E8FF;
 6316: }
 6317: 
 6318: table.LC_data_table tr > td.LC_roles_is {
 6319:   /* background: #77FF77; */
 6320: }
 6321: 
 6322: table.LC_data_table tr > td.LC_roles_future {
 6323:   border-right: 8px solid #FFFF77;
 6324: }
 6325: 
 6326: table.LC_data_table tr > td.LC_roles_will {
 6327:   border-right: 8px solid #FFAA77;
 6328: }
 6329: 
 6330: table.LC_data_table tr > td.LC_roles_expired {
 6331:   border-right: 8px solid #FF7777;
 6332: }
 6333: 
 6334: table.LC_data_table tr > td.LC_roles_will_not {
 6335:   border-right: 8px solid #AAFF77;
 6336: }
 6337: 
 6338: table.LC_data_table tr > td.LC_roles_selected {
 6339:   border-right: 8px solid #11CC55;
 6340: }
 6341: 
 6342: span.LC_current_location {
 6343:   font-size:larger;
 6344:   background: $pgbg;
 6345: }
 6346: 
 6347: span.LC_current_nav_location {
 6348:   font-weight:bold;
 6349:   background: $sidebg;
 6350: }
 6351: 
 6352: span.LC_parm_menu_item {
 6353:   font-size: larger;
 6354: }
 6355: 
 6356: span.LC_parm_scope_all {
 6357:   color: red;
 6358: }
 6359: 
 6360: span.LC_parm_scope_folder {
 6361:   color: green;
 6362: }
 6363: 
 6364: span.LC_parm_scope_resource {
 6365:   color: orange;
 6366: }
 6367: 
 6368: span.LC_parm_part {
 6369:   color: blue;
 6370: }
 6371: 
 6372: span.LC_parm_folder,
 6373: span.LC_parm_symb {
 6374:   font-size: x-small;
 6375:   font-family: $mono;
 6376:   color: #AAAAAA;
 6377: }
 6378: 
 6379: ul.LC_parm_parmlist li {
 6380:   display: inline-block;
 6381:   padding: 0.3em 0.8em;
 6382:   vertical-align: top;
 6383:   width: 150px;
 6384:   border-top:1px solid $lg_border_color;
 6385: }
 6386: 
 6387: td.LC_parm_overview_level_menu,
 6388: td.LC_parm_overview_map_menu,
 6389: td.LC_parm_overview_parm_selectors,
 6390: td.LC_parm_overview_restrictions  {
 6391:   border: 1px solid black;
 6392:   border-collapse: collapse;
 6393: }
 6394: 
 6395: table.LC_parm_overview_restrictions td {
 6396:   border-width: 1px 4px 1px 4px;
 6397:   border-style: solid;
 6398:   border-color: $pgbg;
 6399:   text-align: center;
 6400: }
 6401: 
 6402: table.LC_parm_overview_restrictions th {
 6403:   background: $tabbg;
 6404:   border-width: 1px 4px 1px 4px;
 6405:   border-style: solid;
 6406:   border-color: $pgbg;
 6407: }
 6408: 
 6409: table#LC_helpmenu {
 6410:   border: none;
 6411:   height: 55px;
 6412:   border-spacing: 0;
 6413: }
 6414: 
 6415: table#LC_helpmenu fieldset legend {
 6416:   font-size: larger;
 6417: }
 6418: 
 6419: table#LC_helpmenu_links {
 6420:   width: 100%;
 6421:   border: 1px solid black;
 6422:   background: $pgbg;
 6423:   padding: 0;
 6424:   border-spacing: 1px;
 6425: }
 6426: 
 6427: table#LC_helpmenu_links tr td {
 6428:   padding: 1px;
 6429:   background: $tabbg;
 6430:   text-align: center;
 6431:   font-weight: bold;
 6432: }
 6433: 
 6434: table#LC_helpmenu_links a:link,
 6435: table#LC_helpmenu_links a:visited,
 6436: table#LC_helpmenu_links a:active {
 6437:   text-decoration: none;
 6438:   color: $font;
 6439: }
 6440: 
 6441: table#LC_helpmenu_links a:hover {
 6442:   text-decoration: underline;
 6443:   color: $vlink;
 6444: }
 6445: 
 6446: .LC_chrt_popup_exists {
 6447:   border: 1px solid #339933;
 6448:   margin: -1px;
 6449: }
 6450: 
 6451: .LC_chrt_popup_up {
 6452:   border: 1px solid yellow;
 6453:   margin: -1px;
 6454: }
 6455: 
 6456: .LC_chrt_popup {
 6457:   border: 1px solid #8888FF;
 6458:   background: #CCCCFF;
 6459: }
 6460: 
 6461: table.LC_pick_box {
 6462:   border-collapse: separate;
 6463:   background: white;
 6464:   border: 1px solid black;
 6465:   border-spacing: 1px;
 6466: }
 6467: 
 6468: table.LC_pick_box td.LC_pick_box_title {
 6469:   background: $sidebg;
 6470:   font-weight: bold;
 6471:   text-align: left;
 6472:   vertical-align: top;
 6473:   width: 184px;
 6474:   padding: 8px;
 6475: }
 6476: 
 6477: table.LC_pick_box td.LC_pick_box_value {
 6478:   text-align: left;
 6479:   padding: 8px;
 6480: }
 6481: 
 6482: table.LC_pick_box td.LC_pick_box_select {
 6483:   text-align: left;
 6484:   padding: 8px;
 6485: }
 6486: 
 6487: table.LC_pick_box td.LC_pick_box_separator {
 6488:   padding: 0;
 6489:   height: 1px;
 6490:   background: black;
 6491: }
 6492: 
 6493: table.LC_pick_box td.LC_pick_box_submit {
 6494:   text-align: right;
 6495: }
 6496: 
 6497: table.LC_pick_box td.LC_evenrow_value {
 6498:   text-align: left;
 6499:   padding: 8px;
 6500:   background-color: $data_table_light;
 6501: }
 6502: 
 6503: table.LC_pick_box td.LC_oddrow_value {
 6504:   text-align: left;
 6505:   padding: 8px;
 6506:   background-color: $data_table_light;
 6507: }
 6508: 
 6509: span.LC_helpform_receipt_cat {
 6510:   font-weight: bold;
 6511: }
 6512: 
 6513: table.LC_group_priv_box {
 6514:   background: white;
 6515:   border: 1px solid black;
 6516:   border-spacing: 1px;
 6517: }
 6518: 
 6519: table.LC_group_priv_box td.LC_pick_box_title {
 6520:   background: $tabbg;
 6521:   font-weight: bold;
 6522:   text-align: right;
 6523:   width: 184px;
 6524: }
 6525: 
 6526: table.LC_group_priv_box td.LC_groups_fixed {
 6527:   background: $data_table_light;
 6528:   text-align: center;
 6529: }
 6530: 
 6531: table.LC_group_priv_box td.LC_groups_optional {
 6532:   background: $data_table_dark;
 6533:   text-align: center;
 6534: }
 6535: 
 6536: table.LC_group_priv_box td.LC_groups_functionality {
 6537:   background: $data_table_darker;
 6538:   text-align: center;
 6539:   font-weight: bold;
 6540: }
 6541: 
 6542: table.LC_group_priv td {
 6543:   text-align: left;
 6544:   padding: 0;
 6545: }
 6546: 
 6547: .LC_navbuttons {
 6548:   margin: 2ex 0ex 2ex 0ex;
 6549: }
 6550: 
 6551: .LC_topic_bar {
 6552:   font-weight: bold;
 6553:   background: $tabbg;
 6554:   margin: 1em 0em 1em 2em;
 6555:   padding: 3px;
 6556:   font-size: 1.2em;
 6557: }
 6558: 
 6559: .LC_topic_bar span {
 6560:   left: 0.5em;
 6561:   position: absolute;
 6562:   vertical-align: middle;
 6563:   font-size: 1.2em;
 6564: }
 6565: 
 6566: table.LC_course_group_status {
 6567:   margin: 20px;
 6568: }
 6569: 
 6570: table.LC_status_selector td {
 6571:   vertical-align: top;
 6572:   text-align: center;
 6573:   padding: 4px;
 6574: }
 6575: 
 6576: div.LC_feedback_link {
 6577:   clear: both;
 6578:   background: $sidebg;
 6579:   width: 100%;
 6580:   padding-bottom: 10px;
 6581:   border: 1px $tabbg solid;
 6582:   height: 22px;
 6583:   line-height: 22px;
 6584:   padding-top: 5px;
 6585: }
 6586: 
 6587: div.LC_feedback_link img {
 6588:   height: 22px;
 6589:   vertical-align:middle;
 6590: }
 6591: 
 6592: div.LC_feedback_link a {
 6593:   text-decoration: none;
 6594: }
 6595: 
 6596: div.LC_comblock {
 6597:   display:inline;
 6598:   color:$font;
 6599:   font-size:90%;
 6600: }
 6601: 
 6602: div.LC_feedback_link div.LC_comblock {
 6603:   padding-left:5px;
 6604: }
 6605: 
 6606: div.LC_feedback_link div.LC_comblock a {
 6607:   color:$font;
 6608: }
 6609: 
 6610: span.LC_feedback_link {
 6611:   /* background: $feedback_link_bg; */
 6612:   font-size: larger;
 6613: }
 6614: 
 6615: span.LC_message_link {
 6616:   /* background: $feedback_link_bg; */
 6617:   font-size: larger;
 6618:   position: absolute;
 6619:   right: 1em;
 6620: }
 6621: 
 6622: table.LC_prior_tries {
 6623:   border: 1px solid #000000;
 6624:   border-collapse: separate;
 6625:   border-spacing: 1px;
 6626: }
 6627: 
 6628: table.LC_prior_tries td {
 6629:   padding: 2px;
 6630: }
 6631: 
 6632: .LC_answer_correct {
 6633:   background: lightgreen;
 6634:   color: darkgreen;
 6635:   padding: 6px;
 6636: }
 6637: 
 6638: .LC_answer_charged_try {
 6639:   background: #FFAAAA;
 6640:   color: darkred;
 6641:   padding: 6px;
 6642: }
 6643: 
 6644: .LC_answer_not_charged_try,
 6645: .LC_answer_no_grade,
 6646: .LC_answer_late {
 6647:   background: lightyellow;
 6648:   color: black;
 6649:   padding: 6px;
 6650: }
 6651: 
 6652: .LC_answer_previous {
 6653:   background: lightblue;
 6654:   color: darkblue;
 6655:   padding: 6px;
 6656: }
 6657: 
 6658: .LC_answer_no_message {
 6659:   background: #FFFFFF;
 6660:   color: black;
 6661:   padding: 6px;
 6662: }
 6663: 
 6664: .LC_answer_unknown {
 6665:   background: orange;
 6666:   color: black;
 6667:   padding: 6px;
 6668: }
 6669: 
 6670: span.LC_prior_numerical,
 6671: span.LC_prior_string,
 6672: span.LC_prior_custom,
 6673: span.LC_prior_reaction,
 6674: span.LC_prior_math {
 6675:   font-family: $mono;
 6676:   white-space: pre;
 6677: }
 6678: 
 6679: span.LC_prior_string {
 6680:   font-family: $mono;
 6681:   white-space: pre;
 6682: }
 6683: 
 6684: table.LC_prior_option {
 6685:   width: 100%;
 6686:   border-collapse: collapse;
 6687: }
 6688: 
 6689: table.LC_prior_rank,
 6690: table.LC_prior_match {
 6691:   border-collapse: collapse;
 6692: }
 6693: 
 6694: table.LC_prior_option tr td,
 6695: table.LC_prior_rank tr td,
 6696: table.LC_prior_match tr td {
 6697:   border: 1px solid #000000;
 6698: }
 6699: 
 6700: .LC_nobreak {
 6701:   white-space: nowrap;
 6702: }
 6703: 
 6704: span.LC_cusr_emph {
 6705:   font-style: italic;
 6706: }
 6707: 
 6708: span.LC_cusr_subheading {
 6709:   font-weight: normal;
 6710:   font-size: 85%;
 6711: }
 6712: 
 6713: div.LC_docs_entry_move {
 6714:   border: 1px solid #BBBBBB;
 6715:   background: #DDDDDD;
 6716:   width: 22px;
 6717:   padding: 1px;
 6718:   margin: 0;
 6719: }
 6720: 
 6721: table.LC_data_table tr > td.LC_docs_entry_commands,
 6722: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6723:   font-size: x-small;
 6724: }
 6725: 
 6726: .LC_docs_entry_parameter {
 6727:   white-space: nowrap;
 6728: }
 6729: 
 6730: .LC_docs_copy {
 6731:   color: #000099;
 6732: }
 6733: 
 6734: .LC_docs_cut {
 6735:   color: #550044;
 6736: }
 6737: 
 6738: .LC_docs_rename {
 6739:   color: #009900;
 6740: }
 6741: 
 6742: .LC_docs_remove {
 6743:   color: #990000;
 6744: }
 6745: 
 6746: .LC_docs_reinit_warn,
 6747: .LC_docs_ext_edit {
 6748:   font-size: x-small;
 6749: }
 6750: 
 6751: table.LC_docs_adddocs td,
 6752: table.LC_docs_adddocs th {
 6753:   border: 1px solid #BBBBBB;
 6754:   padding: 4px;
 6755:   background: #DDDDDD;
 6756: }
 6757: 
 6758: table.LC_sty_begin {
 6759:   background: #BBFFBB;
 6760: }
 6761: 
 6762: table.LC_sty_end {
 6763:   background: #FFBBBB;
 6764: }
 6765: 
 6766: table.LC_double_column {
 6767:   border-width: 0;
 6768:   border-collapse: collapse;
 6769:   width: 100%;
 6770:   padding: 2px;
 6771: }
 6772: 
 6773: table.LC_double_column tr td.LC_left_col {
 6774:   top: 2px;
 6775:   left: 2px;
 6776:   width: 47%;
 6777:   vertical-align: top;
 6778: }
 6779: 
 6780: table.LC_double_column tr td.LC_right_col {
 6781:   top: 2px;
 6782:   right: 2px;
 6783:   width: 47%;
 6784:   vertical-align: top;
 6785: }
 6786: 
 6787: div.LC_left_float {
 6788:   float: left;
 6789:   padding-right: 5%;
 6790:   padding-bottom: 4px;
 6791: }
 6792: 
 6793: div.LC_clear_float_header {
 6794:   padding-bottom: 2px;
 6795: }
 6796: 
 6797: div.LC_clear_float_footer {
 6798:   padding-top: 10px;
 6799:   clear: both;
 6800: }
 6801: 
 6802: div.LC_grade_show_user {
 6803: /*  border-left: 5px solid $sidebg; */
 6804:   border-top: 5px solid #000000;
 6805:   margin: 50px 0 0 0;
 6806:   padding: 15px 0 5px 10px;
 6807: }
 6808: 
 6809: div.LC_grade_show_user_odd_row {
 6810: /*  border-left: 5px solid #000000; */
 6811: }
 6812: 
 6813: div.LC_grade_show_user div.LC_Box {
 6814:   margin-right: 50px;
 6815: }
 6816: 
 6817: div.LC_grade_submissions,
 6818: div.LC_grade_message_center,
 6819: div.LC_grade_info_links {
 6820:   margin: 5px;
 6821:   width: 99%;
 6822:   background: #FFFFFF;
 6823: }
 6824: 
 6825: div.LC_grade_submissions_header,
 6826: div.LC_grade_message_center_header {
 6827:   font-weight: bold;
 6828:   font-size: large;
 6829: }
 6830: 
 6831: div.LC_grade_submissions_body,
 6832: div.LC_grade_message_center_body {
 6833:   border: 1px solid black;
 6834:   width: 99%;
 6835:   background: #FFFFFF;
 6836: }
 6837: 
 6838: table.LC_scantron_action {
 6839:   width: 100%;
 6840: }
 6841: 
 6842: table.LC_scantron_action tr th {
 6843:   font-weight:bold;
 6844:   font-style:normal;
 6845: }
 6846: 
 6847: .LC_edit_problem_header,
 6848: div.LC_edit_problem_footer {
 6849:   font-weight: normal;
 6850:   font-size:  medium;
 6851:   margin: 2px;
 6852:   background-color: $sidebg;
 6853: }
 6854: 
 6855: div.LC_edit_problem_header,
 6856: div.LC_edit_problem_header div,
 6857: div.LC_edit_problem_footer,
 6858: div.LC_edit_problem_footer div,
 6859: div.LC_edit_problem_editxml_header,
 6860: div.LC_edit_problem_editxml_header div {
 6861:   z-index: 100;
 6862: }
 6863: 
 6864: div.LC_edit_problem_header_title {
 6865:   font-weight: bold;
 6866:   font-size: larger;
 6867:   background: $tabbg;
 6868:   padding: 3px;
 6869:   margin: 0 0 5px 0;
 6870: }
 6871: 
 6872: table.LC_edit_problem_header_title {
 6873:   width: 100%;
 6874:   background: $tabbg;
 6875: }
 6876: 
 6877: div.LC_edit_actionbar {
 6878:     background-color: $sidebg;
 6879:     margin: 0;
 6880:     padding: 0;
 6881:     line-height: 200%;
 6882: }
 6883: 
 6884: div.LC_edit_actionbar div{
 6885:     padding: 0;
 6886:     margin: 0;
 6887:     display: inline-block;
 6888: }
 6889: 
 6890: .LC_edit_opt {
 6891:   padding-left: 1em;
 6892:   white-space: nowrap;
 6893: }
 6894: 
 6895: .LC_edit_problem_latexhelper{
 6896:     text-align: right;
 6897: }
 6898: 
 6899: #LC_edit_problem_colorful div{
 6900:     margin-left: 40px;
 6901: }
 6902: 
 6903: #LC_edit_problem_codemirror div{
 6904:     margin-left: 0px;
 6905: }
 6906: 
 6907: img.stift {
 6908:   border-width: 0;
 6909:   vertical-align: middle;
 6910: }
 6911: 
 6912: table td.LC_mainmenu_col_fieldset {
 6913:   vertical-align: top;
 6914: }
 6915: 
 6916: div.LC_createcourse {
 6917:   margin: 10px 10px 10px 10px;
 6918: }
 6919: 
 6920: .LC_dccid {
 6921:   float: right;
 6922:   margin: 0.2em 0 0 0;
 6923:   padding: 0;
 6924:   font-size: 90%;
 6925:   display:none;
 6926: }
 6927: 
 6928: ol.LC_primary_menu a:hover,
 6929: ol#LC_MenuBreadcrumbs a:hover,
 6930: ol#LC_PathBreadcrumbs a:hover,
 6931: ul#LC_secondary_menu a:hover,
 6932: .LC_FormSectionClearButton input:hover
 6933: ul.LC_TabContent   li:hover a {
 6934:   color:$button_hover;
 6935:   text-decoration:none;
 6936: }
 6937: 
 6938: h1 {
 6939:   padding: 0;
 6940:   line-height:130%;
 6941: }
 6942: 
 6943: h2,
 6944: h3,
 6945: h4,
 6946: h5,
 6947: h6 {
 6948:   margin: 5px 0 5px 0;
 6949:   padding: 0;
 6950:   line-height:130%;
 6951: }
 6952: 
 6953: .LC_hcell {
 6954:   padding:3px 15px 3px 15px;
 6955:   margin: 0;
 6956:   background-color:$tabbg;
 6957:   color:$fontmenu;
 6958:   border-bottom:solid 1px $lg_border_color;
 6959: }
 6960: 
 6961: .LC_Box > .LC_hcell {
 6962:   margin: 0 -10px 10px -10px;
 6963: }
 6964: 
 6965: .LC_noBorder {
 6966:   border: 0;
 6967: }
 6968: 
 6969: .LC_FormSectionClearButton input {
 6970:   background-color:transparent;
 6971:   border: none;
 6972:   cursor:pointer;
 6973:   text-decoration:underline;
 6974: }
 6975: 
 6976: .LC_help_open_topic {
 6977:   color: #FFFFFF;
 6978:   background-color: #EEEEFF;
 6979:   margin: 1px;
 6980:   padding: 4px;
 6981:   border: 1px solid #000033;
 6982:   white-space: nowrap;
 6983:   /* vertical-align: middle; */
 6984: }
 6985: 
 6986: dl,
 6987: ul,
 6988: div,
 6989: fieldset {
 6990:   margin: 10px 10px 10px 0;
 6991:   /* overflow: hidden; */
 6992: }
 6993: 
 6994: article.geogebraweb div {
 6995:     margin: 0;
 6996: }
 6997: 
 6998: fieldset > legend {
 6999:   font-weight: bold;
 7000:   padding: 0 5px 0 5px;
 7001: }
 7002: 
 7003: #LC_nav_bar {
 7004:   float: left;
 7005:   background-color: $pgbg_or_bgcolor;
 7006:   margin: 0 0 2px 0;
 7007: }
 7008: 
 7009: #LC_realm {
 7010:   margin: 0.2em 0 0 0;
 7011:   padding: 0;
 7012:   font-weight: bold;
 7013:   text-align: center;
 7014:   background-color: $pgbg_or_bgcolor;
 7015: }
 7016: 
 7017: #LC_nav_bar em {
 7018:   font-weight: bold;
 7019:   font-style: normal;
 7020: }
 7021: 
 7022: ol.LC_primary_menu {
 7023:   margin: 0;
 7024:   padding: 0;
 7025: }
 7026: 
 7027: ol#LC_PathBreadcrumbs {
 7028:   margin: 0;
 7029: }
 7030: 
 7031: ol.LC_primary_menu li {
 7032:   color: RGB(80, 80, 80);
 7033:   vertical-align: middle;
 7034:   text-align: left;
 7035:   list-style: none;
 7036:   position: relative;
 7037:   float: left;
 7038:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7039:   line-height: 1.5em;
 7040: }
 7041: 
 7042: ol.LC_primary_menu li a,
 7043: ol.LC_primary_menu li p {
 7044:   display: block;
 7045:   margin: 0;
 7046:   padding: 0 5px 0 10px;
 7047:   text-decoration: none;
 7048: }
 7049: 
 7050: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7051:   display: inline-block;
 7052:   width: 95%;
 7053:   text-align: left;
 7054: }
 7055: 
 7056: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7057:   display: inline-block;	
 7058:   width: 5%;
 7059:   float: right;
 7060:   text-align: right;
 7061:   font-size: 70%;
 7062: }
 7063: 
 7064: ol.LC_primary_menu ul {
 7065:   display: none;
 7066:   width: 15em;
 7067:   background-color: $data_table_light;
 7068:   position: absolute;
 7069:   top: 100%;
 7070: }
 7071: 
 7072: ol.LC_primary_menu ul ul {
 7073:   left: 100%;
 7074:   top: 0;
 7075: }
 7076: 
 7077: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7078:   display: block;
 7079:   position: absolute;
 7080:   margin: 0;
 7081:   padding: 0;
 7082:   z-index: 2;
 7083: }
 7084: 
 7085: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7086: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7087:   font-size: 90%;
 7088:   vertical-align: top;
 7089:   float: none;
 7090:   border-left: 1px solid black;
 7091:   border-right: 1px solid black;
 7092: /* A dark bottom border to visualize different menu options; 
 7093: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7094:   border-bottom: 1px solid $data_table_dark; 
 7095: }
 7096: 
 7097: ol.LC_primary_menu li li p:hover {
 7098:   color:$button_hover;
 7099:   text-decoration:none;
 7100:   background-color:$data_table_dark;
 7101: }
 7102: 
 7103: ol.LC_primary_menu li li a:hover {
 7104:    color:$button_hover;
 7105:    background-color:$data_table_dark;
 7106: }
 7107: 
 7108: /* Font-size equal to the size of the predecessors*/
 7109: ol.LC_primary_menu li:hover li li {
 7110:   font-size: 100%;
 7111: }
 7112: 
 7113: ol.LC_primary_menu li img {
 7114:   vertical-align: bottom;
 7115:   height: 1.1em;
 7116:   margin: 0.2em 0 0 0;
 7117: }
 7118: 
 7119: ol.LC_primary_menu a {
 7120:   color: RGB(80, 80, 80);
 7121:   text-decoration: none;
 7122: }
 7123: 
 7124: ol.LC_primary_menu a.LC_new_message {
 7125:   font-weight:bold;
 7126:   color: darkred;
 7127: }
 7128: 
 7129: ol.LC_docs_parameters {
 7130:   margin-left: 0;
 7131:   padding: 0;
 7132:   list-style: none;
 7133: }
 7134: 
 7135: ol.LC_docs_parameters li {
 7136:   margin: 0;
 7137:   padding-right: 20px;
 7138:   display: inline;
 7139: }
 7140: 
 7141: ol.LC_docs_parameters li:before {
 7142:   content: "\\002022 \\0020";
 7143: }
 7144: 
 7145: li.LC_docs_parameters_title {
 7146:   font-weight: bold;
 7147: }
 7148: 
 7149: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7150:   content: "";
 7151: }
 7152: 
 7153: ul#LC_secondary_menu {
 7154:   clear: right;
 7155:   color: $fontmenu;
 7156:   background: $tabbg;
 7157:   list-style: none;
 7158:   padding: 0;
 7159:   margin: 0;
 7160:   width: 100%;
 7161:   text-align: left;
 7162:   float: left;
 7163: }
 7164: 
 7165: ul#LC_secondary_menu li {
 7166:   font-weight: bold;
 7167:   line-height: 1.8em;
 7168:   border-right: 1px solid black;
 7169:   float: left;
 7170: }
 7171: 
 7172: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7173:   background-color: $data_table_light;
 7174: }
 7175: 
 7176: ul#LC_secondary_menu li a {
 7177:   padding: 0 0.8em;
 7178: }
 7179: 
 7180: ul#LC_secondary_menu li ul {
 7181:   display: none;
 7182: }
 7183: 
 7184: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7185:   display: block;
 7186:   position: absolute;
 7187:   margin: 0;
 7188:   padding: 0;
 7189:   list-style:none;
 7190:   float: none;
 7191:   background-color: $data_table_light;
 7192:   z-index: 2;
 7193:   margin-left: -1px;
 7194: }
 7195: 
 7196: ul#LC_secondary_menu li ul li {
 7197:   font-size: 90%;
 7198:   vertical-align: top;
 7199:   border-left: 1px solid black;
 7200:   border-right: 1px solid black;
 7201:   background-color: $data_table_light;
 7202:   list-style:none;
 7203:   float: none;
 7204: }
 7205: 
 7206: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7207:   background-color: $data_table_dark;
 7208: }
 7209: 
 7210: ul.LC_TabContent {
 7211:   display:block;
 7212:   background: $sidebg;
 7213:   border-bottom: solid 1px $lg_border_color;
 7214:   list-style:none;
 7215:   margin: -1px -10px 0 -10px;
 7216:   padding: 0;
 7217: }
 7218: 
 7219: ul.LC_TabContent li,
 7220: ul.LC_TabContentBigger li {
 7221:   float:left;
 7222: }
 7223: 
 7224: ul#LC_secondary_menu li a {
 7225:   color: $fontmenu;
 7226:   text-decoration: none;
 7227: }
 7228: 
 7229: ul.LC_TabContent {
 7230:   min-height:20px;
 7231: }
 7232: 
 7233: ul.LC_TabContent li {
 7234:   vertical-align:middle;
 7235:   padding: 0 16px 0 10px;
 7236:   background-color:$tabbg;
 7237:   border-bottom:solid 1px $lg_border_color;
 7238:   border-left: solid 1px $font;
 7239: }
 7240: 
 7241: ul.LC_TabContent .right {
 7242:   float:right;
 7243: }
 7244: 
 7245: ul.LC_TabContent li a,
 7246: ul.LC_TabContent li {
 7247:   color:rgb(47,47,47);
 7248:   text-decoration:none;
 7249:   font-size:95%;
 7250:   font-weight:bold;
 7251:   min-height:20px;
 7252: }
 7253: 
 7254: ul.LC_TabContent li a:hover,
 7255: ul.LC_TabContent li a:focus {
 7256:   color: $button_hover;
 7257:   background:none;
 7258:   outline:none;
 7259: }
 7260: 
 7261: ul.LC_TabContent li:hover {
 7262:   color: $button_hover;
 7263:   cursor:pointer;
 7264: }
 7265: 
 7266: ul.LC_TabContent li.active {
 7267:   color: $font;
 7268:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7269:   border-bottom:solid 1px #FFFFFF;
 7270:   cursor: default;
 7271: }
 7272: 
 7273: ul.LC_TabContent li.active a {
 7274:   color:$font;
 7275:   background:#FFFFFF;
 7276:   outline: none;
 7277: }
 7278: 
 7279: ul.LC_TabContent li.goback {
 7280:   float: left;
 7281:   border-left: none;
 7282: }
 7283: 
 7284: #maincoursedoc {
 7285:   clear:both;
 7286: }
 7287: 
 7288: ul.LC_TabContentBigger {
 7289:   display:block;
 7290:   list-style:none;
 7291:   padding: 0;
 7292: }
 7293: 
 7294: ul.LC_TabContentBigger li {
 7295:   vertical-align:bottom;
 7296:   height: 30px;
 7297:   font-size:110%;
 7298:   font-weight:bold;
 7299:   color: #737373;
 7300: }
 7301: 
 7302: ul.LC_TabContentBigger li.active {
 7303:   position: relative;
 7304:   top: 1px;
 7305: }
 7306: 
 7307: ul.LC_TabContentBigger li a {
 7308:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7309:   height: 30px;
 7310:   line-height: 30px;
 7311:   text-align: center;
 7312:   display: block;
 7313:   text-decoration: none;
 7314:   outline: none;  
 7315: }
 7316: 
 7317: ul.LC_TabContentBigger li.active a {
 7318:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7319:   color:$font;
 7320: }
 7321: 
 7322: ul.LC_TabContentBigger li b {
 7323:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7324:   display: block;
 7325:   float: left;
 7326:   padding: 0 30px;
 7327:   border-bottom: 1px solid $lg_border_color;
 7328: }
 7329: 
 7330: ul.LC_TabContentBigger li:hover b {
 7331:   color:$button_hover;
 7332: }
 7333: 
 7334: ul.LC_TabContentBigger li.active b {
 7335:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7336:   color:$font;
 7337:   border: 0;
 7338: }
 7339: 
 7340: 
 7341: ul.LC_CourseBreadcrumbs {
 7342:   background: $sidebg;
 7343:   height: 2em;
 7344:   padding-left: 10px;
 7345:   margin: 0;
 7346:   list-style-position: inside;
 7347: }
 7348: 
 7349: ol#LC_MenuBreadcrumbs,
 7350: ol#LC_PathBreadcrumbs {
 7351:   padding-left: 10px;
 7352:   margin: 0;
 7353:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7354: }
 7355: 
 7356: ol#LC_MenuBreadcrumbs li,
 7357: ol#LC_PathBreadcrumbs li,
 7358: ul.LC_CourseBreadcrumbs li {
 7359:   display: inline;
 7360:   white-space: normal;  
 7361: }
 7362: 
 7363: ol#LC_MenuBreadcrumbs li a,
 7364: ul.LC_CourseBreadcrumbs li a {
 7365:   text-decoration: none;
 7366:   font-size:90%;
 7367: }
 7368: 
 7369: ol#LC_MenuBreadcrumbs h1 {
 7370:   display: inline;
 7371:   font-size: 90%;
 7372:   line-height: 2.5em;
 7373:   margin: 0;
 7374:   padding: 0;
 7375: }
 7376: 
 7377: ol#LC_PathBreadcrumbs li a {
 7378:   text-decoration:none;
 7379:   font-size:100%;
 7380:   font-weight:bold;
 7381: }
 7382: 
 7383: .LC_Box {
 7384:   border: solid 1px $lg_border_color;
 7385:   padding: 0 10px 10px 10px;
 7386: }
 7387: 
 7388: .LC_DocsBox {
 7389:   border: solid 1px $lg_border_color;
 7390:   padding: 0 0 10px 10px;
 7391: }
 7392: 
 7393: .LC_AboutMe_Image {
 7394:   float:left;
 7395:   margin-right:10px;
 7396: }
 7397: 
 7398: .LC_Clear_AboutMe_Image {
 7399:   clear:left;
 7400: }
 7401: 
 7402: dl.LC_ListStyleClean dt {
 7403:   padding-right: 5px;
 7404:   display: table-header-group;
 7405: }
 7406: 
 7407: dl.LC_ListStyleClean dd {
 7408:   display: table-row;
 7409: }
 7410: 
 7411: .LC_ListStyleClean,
 7412: .LC_ListStyleSimple,
 7413: .LC_ListStyleNormal,
 7414: .LC_ListStyleSpecial {
 7415:   /* display:block; */
 7416:   list-style-position: inside;
 7417:   list-style-type: none;
 7418:   overflow: hidden;
 7419:   padding: 0;
 7420: }
 7421: 
 7422: .LC_ListStyleSimple li,
 7423: .LC_ListStyleSimple dd,
 7424: .LC_ListStyleNormal li,
 7425: .LC_ListStyleNormal dd,
 7426: .LC_ListStyleSpecial li,
 7427: .LC_ListStyleSpecial dd {
 7428:   margin: 0;
 7429:   padding: 5px 5px 5px 10px;
 7430:   clear: both;
 7431: }
 7432: 
 7433: .LC_ListStyleClean li,
 7434: .LC_ListStyleClean dd {
 7435:   padding-top: 0;
 7436:   padding-bottom: 0;
 7437: }
 7438: 
 7439: .LC_ListStyleSimple dd,
 7440: .LC_ListStyleSimple li {
 7441:   border-bottom: solid 1px $lg_border_color;
 7442: }
 7443: 
 7444: .LC_ListStyleSpecial li,
 7445: .LC_ListStyleSpecial dd {
 7446:   list-style-type: none;
 7447:   background-color: RGB(220, 220, 220);
 7448:   margin-bottom: 4px;
 7449: }
 7450: 
 7451: table.LC_SimpleTable {
 7452:   margin:5px;
 7453:   border:solid 1px $lg_border_color;
 7454: }
 7455: 
 7456: table.LC_SimpleTable tr {
 7457:   padding: 0;
 7458:   border:solid 1px $lg_border_color;
 7459: }
 7460: 
 7461: table.LC_SimpleTable thead {
 7462:   background:rgb(220,220,220);
 7463: }
 7464: 
 7465: div.LC_columnSection {
 7466:   display: block;
 7467:   clear: both;
 7468:   overflow: hidden;
 7469:   margin: 0;
 7470: }
 7471: 
 7472: div.LC_columnSection>* {
 7473:   float: left;
 7474:   margin: 10px 20px 10px 0;
 7475:   overflow:hidden;
 7476: }
 7477: 
 7478: table em {
 7479:   font-weight: bold;
 7480:   font-style: normal;
 7481: }
 7482: 
 7483: table.LC_tableBrowseRes,
 7484: table.LC_tableOfContent {
 7485:   border:none;
 7486:   border-spacing: 1px;
 7487:   padding: 3px;
 7488:   background-color: #FFFFFF;
 7489:   font-size: 90%;
 7490: }
 7491: 
 7492: table.LC_tableOfContent {
 7493:   border-collapse: collapse;
 7494: }
 7495: 
 7496: table.LC_tableBrowseRes a,
 7497: table.LC_tableOfContent a {
 7498:   background-color: transparent;
 7499:   text-decoration: none;
 7500: }
 7501: 
 7502: table.LC_tableOfContent img {
 7503:   border: none;
 7504:   height: 1.3em;
 7505:   vertical-align: text-bottom;
 7506:   margin-right: 0.3em;
 7507: }
 7508: 
 7509: a#LC_content_toolbar_firsthomework {
 7510:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7511: }
 7512: 
 7513: a#LC_content_toolbar_everything {
 7514:   background-image:url(/res/adm/pages/show-all.gif);
 7515: }
 7516: 
 7517: a#LC_content_toolbar_uncompleted {
 7518:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7519: }
 7520: 
 7521: #LC_content_toolbar_clearbubbles {
 7522:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7523: }
 7524: 
 7525: a#LC_content_toolbar_changefolder {
 7526:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7527: }
 7528: 
 7529: a#LC_content_toolbar_changefolder_toggled {
 7530:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7531: }
 7532: 
 7533: a#LC_content_toolbar_edittoplevel {
 7534:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7535: }
 7536: 
 7537: ul#LC_toolbar li a:hover {
 7538:   background-position: bottom center;
 7539: }
 7540: 
 7541: ul#LC_toolbar {
 7542:   padding: 0;
 7543:   margin: 2px;
 7544:   list-style:none;
 7545:   position:relative;
 7546:   background-color:white;
 7547:   overflow: auto;
 7548: }
 7549: 
 7550: ul#LC_toolbar li {
 7551:   border:1px solid white;
 7552:   padding: 0;
 7553:   margin: 0;
 7554:   float: left;
 7555:   display:inline;
 7556:   vertical-align:middle;
 7557:   white-space: nowrap;
 7558: }
 7559: 
 7560: 
 7561: a.LC_toolbarItem {
 7562:   display:block;
 7563:   padding: 0;
 7564:   margin: 0;
 7565:   height: 32px;
 7566:   width: 32px;
 7567:   color:white;
 7568:   border: none;
 7569:   background-repeat:no-repeat;
 7570:   background-color:transparent;
 7571: }
 7572: 
 7573: ul.LC_funclist {
 7574:     margin: 0;
 7575:     padding: 0.5em 1em 0.5em 0;
 7576: }
 7577: 
 7578: ul.LC_funclist > li:first-child {
 7579:     font-weight:bold; 
 7580:     margin-left:0.8em;
 7581: }
 7582: 
 7583: ul.LC_funclist + ul.LC_funclist {
 7584:     /* 
 7585:        left border as a seperator if we have more than
 7586:        one list 
 7587:     */
 7588:     border-left: 1px solid $sidebg;
 7589:     /* 
 7590:        this hides the left border behind the border of the 
 7591:        outer box if element is wrapped to the next 'line' 
 7592:     */
 7593:     margin-left: -1px;
 7594: }
 7595: 
 7596: ul.LC_funclist li {
 7597:   display: inline;
 7598:   white-space: nowrap;
 7599:   margin: 0 0 0 25px;
 7600:   line-height: 150%;
 7601: }
 7602: 
 7603: .LC_hidden {
 7604:   display: none;
 7605: }
 7606: 
 7607: .LCmodal-overlay {
 7608: 		position:fixed;
 7609: 		top:0;
 7610: 		right:0;
 7611: 		bottom:0;
 7612: 		left:0;
 7613: 		height:100%;
 7614: 		width:100%;
 7615: 		margin:0;
 7616: 		padding:0;
 7617: 		background:#999;
 7618: 		opacity:.75;
 7619: 		filter: alpha(opacity=75);
 7620: 		-moz-opacity: 0.75;
 7621: 		z-index:101;
 7622: }
 7623: 
 7624: * html .LCmodal-overlay {   
 7625: 		position: absolute;
 7626: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7627: }
 7628: 
 7629: .LCmodal-window {
 7630: 		position:fixed;
 7631: 		top:50%;
 7632: 		left:50%;
 7633: 		margin:0;
 7634: 		padding:0;
 7635: 		z-index:102;
 7636: 	}
 7637: 
 7638: * html .LCmodal-window {
 7639: 		position:absolute;
 7640: }
 7641: 
 7642: .LCclose-window {
 7643: 		position:absolute;
 7644: 		width:32px;
 7645: 		height:32px;
 7646: 		right:8px;
 7647: 		top:8px;
 7648: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7649: 		text-indent:-99999px;
 7650: 		overflow:hidden;
 7651: 		cursor:pointer;
 7652: }
 7653: 
 7654: /*
 7655:   styles used for response display
 7656: */
 7657: div.LC_radiofoil, div.LC_rankfoil {
 7658:   margin: .5em 0em .5em 0em;
 7659: }
 7660: table.LC_itemgroup {
 7661:   margin-top: 1em;
 7662: }
 7663: 
 7664: /*
 7665:   styles used by TTH when "Default set of options to pass to tth/m
 7666:   when converting TeX" in course settings has been set
 7667: 
 7668:   option passed: -t
 7669: 
 7670: */
 7671: 
 7672: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7673: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7674: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7675: td div.norm {line-height:normal;}
 7676: 
 7677: /*
 7678:   option passed -y3
 7679: */
 7680: 
 7681: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7682: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7683: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7684: 
 7685: /*
 7686:   sections with roles, for content only
 7687: */
 7688: section[class^="role-"] {
 7689:   padding-left: 10px;
 7690:   padding-right: 5px;
 7691:   margin-top: 8px;
 7692:   margin-bottom: 8px;
 7693:   border: 1px solid #2A4;
 7694:   border-radius: 5px;
 7695:   box-shadow: 0px 1px 1px #BBB;
 7696: }
 7697: section[class^="role-"]>h1 {
 7698:   position: relative;
 7699:   margin: 0px;
 7700:   padding-top: 10px;
 7701:   padding-left: 40px;
 7702: }
 7703: section[class^="role-"]>h1:before {
 7704:   position: absolute;
 7705:   left: -5px;
 7706:   top: 5px;
 7707: }
 7708: section.role-activity>h1:before {
 7709:   content:url('/adm/daxe/images/section_icons/activity.png');
 7710: }
 7711: section.role-advice>h1:before {
 7712:   content:url('/adm/daxe/images/section_icons/advice.png');
 7713: }
 7714: section.role-bibliography>h1:before {
 7715:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 7716: }
 7717: section.role-citation>h1:before {
 7718:   content:url('/adm/daxe/images/section_icons/citation.png');
 7719: }
 7720: section.role-conclusion>h1:before {
 7721:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 7722: }
 7723: section.role-definition>h1:before {
 7724:   content:url('/adm/daxe/images/section_icons/definition.png');
 7725: }
 7726: section.role-demonstration>h1:before {
 7727:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 7728: }
 7729: section.role-example>h1:before {
 7730:   content:url('/adm/daxe/images/section_icons/example.png');
 7731: }
 7732: section.role-explanation>h1:before {
 7733:   content:url('/adm/daxe/images/section_icons/explanation.png');
 7734: }
 7735: section.role-introduction>h1:before {
 7736:   content:url('/adm/daxe/images/section_icons/introduction.png');
 7737: }
 7738: section.role-method>h1:before {
 7739:   content:url('/adm/daxe/images/section_icons/method.png');
 7740: }
 7741: section.role-more_information>h1:before {
 7742:   content:url('/adm/daxe/images/section_icons/more_information.png');
 7743: }
 7744: section.role-objectives>h1:before {
 7745:   content:url('/adm/daxe/images/section_icons/objectives.png');
 7746: }
 7747: section.role-prerequisites>h1:before {
 7748:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 7749: }
 7750: section.role-remark>h1:before {
 7751:   content:url('/adm/daxe/images/section_icons/remark.png');
 7752: }
 7753: section.role-reminder>h1:before {
 7754:   content:url('/adm/daxe/images/section_icons/reminder.png');
 7755: }
 7756: section.role-summary>h1:before {
 7757:   content:url('/adm/daxe/images/section_icons/summary.png');
 7758: }
 7759: section.role-syntax>h1:before {
 7760:   content:url('/adm/daxe/images/section_icons/syntax.png');
 7761: }
 7762: section.role-warning>h1:before {
 7763:   content:url('/adm/daxe/images/section_icons/warning.png');
 7764: }
 7765: 
 7766: END
 7767: }
 7768: 
 7769: =pod
 7770: 
 7771: =item * &headtag()
 7772: 
 7773: Returns a uniform footer for LON-CAPA web pages.
 7774: 
 7775: Inputs: $title - optional title for the head
 7776:         $head_extra - optional extra HTML to put inside the <head>
 7777:         $args - optional arguments
 7778:             force_register - if is true call registerurl so the remote is 
 7779:                              informed
 7780:             redirect       -> array ref of
 7781:                                    1- seconds before redirect occurs
 7782:                                    2- url to redirect to
 7783:                                    3- whether the side effect should occur
 7784:                            (side effect of setting 
 7785:                                $env{'internal.head.redirect'} to the url 
 7786:                                redirected too)
 7787:             domain         -> force to color decorate a page for a specific
 7788:                                domain
 7789:             function       -> force usage of a specific rolish color scheme
 7790:             bgcolor        -> override the default page bgcolor
 7791:             no_auto_mt_title
 7792:                            -> prevent &mt()ing the title arg
 7793: 
 7794: =cut
 7795: 
 7796: sub headtag {
 7797:     my ($title,$head_extra,$args) = @_;
 7798:     
 7799:     my $function = $args->{'function'} || &get_users_function();
 7800:     my $domain   = $args->{'domain'}   || &determinedomain();
 7801:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7802:     my $httphost = $args->{'use_absolute'};
 7803:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7804: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7805: 		   #time(),
 7806: 		   $env{'environment.color.timestamp'},
 7807: 		   $function,$domain,$bgcolor);
 7808: 
 7809:     $url = '/adm/css/'.&escape($url).'.css';
 7810: 
 7811:     my $result =
 7812: 	'<head>'.
 7813: 	&font_settings($args);
 7814: 
 7815:     my $inhibitprint;
 7816:     if ($args->{'print_suppress'}) {
 7817:         $inhibitprint = &print_suppression();
 7818:     }
 7819: 
 7820:     if (!$args->{'frameset'}) {
 7821: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7822:     }
 7823:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7824:         $result .= Apache::lonxml::display_title();
 7825:     }
 7826:     if (!$args->{'no_nav_bar'} 
 7827: 	&& !$args->{'only_body'}
 7828: 	&& !$args->{'frameset'}) {
 7829: 	$result .= &help_menu_js($httphost);
 7830:         $result.=&modal_window();
 7831:         $result.=&togglebox_script();
 7832:         $result.=&wishlist_window();
 7833:         $result.=&LCprogressbarUpdate_script();
 7834:     } else {
 7835:         if ($args->{'add_modal'}) {
 7836:            $result.=&modal_window();
 7837:         }
 7838:         if ($args->{'add_wishlist'}) {
 7839:            $result.=&wishlist_window();
 7840:         }
 7841:         if ($args->{'add_togglebox'}) {
 7842:            $result.=&togglebox_script();
 7843:         }
 7844:         if ($args->{'add_progressbar'}) {
 7845:            $result.=&LCprogressbarUpdate_script();
 7846:         }
 7847:     }
 7848:     if (ref($args->{'redirect'})) {
 7849: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7850: 	$url = &Apache::lonenc::check_encrypt($url);
 7851: 	if (!$inhibit_continue) {
 7852: 	    $env{'internal.head.redirect'} = $url;
 7853: 	}
 7854: 	$result.=<<ADDMETA
 7855: <meta http-equiv="pragma" content="no-cache" />
 7856: <meta http-equiv="Refresh" content="$time; url=$url" />
 7857: ADDMETA
 7858:     } else {
 7859:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7860:             my $requrl = $env{'request.uri'};
 7861:             if ($requrl eq '') {
 7862:                 $requrl = $ENV{'REQUEST_URI'};
 7863:                 $requrl =~ s/\?.+$//;
 7864:             }
 7865:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7866:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7867:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7868:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7869:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7870:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7871:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7872:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7873:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7874:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7875:                             if (($newserver) && ($newserver ne $lonhost)) {
 7876:                                 my $numsec = 5;
 7877:                                 my $timeout = $numsec * 1000;
 7878:                                 my ($newurl,$locknum,%locks,$msg);
 7879:                                 if ($env{'request.role.adv'}) {
 7880:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7881:                                 }
 7882:                                 my $disable_submit = 0;
 7883:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7884:                                     $disable_submit = 1;
 7885:                                 }
 7886:                                 if ($locknum) {
 7887:                                     my @lockinfo = sort(values(%locks));
 7888:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7889:                                            join(", ",sort(values(%locks)))."\\n".
 7890:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7891:                                 } else {
 7892:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7893:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7894:                                     }
 7895:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7896:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7897:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7898:                                         $newurl .= '&role='.$env{'request.role'};
 7899:                                     }
 7900:                                     if ($env{'request.symb'}) {
 7901:                                         $newurl .= '&symb='.$env{'request.symb'};
 7902:                                     } else {
 7903:                                         $newurl .= '&origurl='.$requrl;
 7904:                                     }
 7905:                                 }
 7906:                                 &js_escape(\$msg);
 7907:                                 $result.=<<OFFLOAD
 7908: <meta http-equiv="pragma" content="no-cache" />
 7909: <script type="text/javascript">
 7910: // <![CDATA[
 7911: function LC_Offload_Now() {
 7912:     var dest = "$newurl";
 7913:     if (dest != '') {
 7914:         window.location.href="$newurl";
 7915:     }
 7916: }
 7917: \$(document).ready(function () {
 7918:     window.alert('$msg');
 7919:     if ($disable_submit) {
 7920:         \$(".LC_hwk_submit").prop("disabled", true);
 7921:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7922:     }
 7923:     setTimeout('LC_Offload_Now()', $timeout);
 7924: });
 7925: // ]]>
 7926: </script>
 7927: OFFLOAD
 7928:                             }
 7929:                         }
 7930:                     }
 7931:                 }
 7932:             }
 7933:         }
 7934:     }
 7935:     if (!defined($title)) {
 7936: 	$title = 'The LearningOnline Network with CAPA';
 7937:     }
 7938:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7939:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7940: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7941:     if (!$args->{'frameset'}) {
 7942:         $result .= ' /';
 7943:     }
 7944:     $result .= '>' 
 7945:         .$inhibitprint
 7946: 	.$head_extra;
 7947:     if ($env{'browser.mobile'}) {
 7948:         $result .= '
 7949: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7950: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7951:     }
 7952:     return $result.'</head>';
 7953: }
 7954: 
 7955: =pod
 7956: 
 7957: =item * &font_settings()
 7958: 
 7959: Returns neccessary <meta> to set the proper encoding
 7960: 
 7961: Inputs: optional reference to HASH -- $args passed to &headtag()
 7962: 
 7963: =cut
 7964: 
 7965: sub font_settings {
 7966:     my ($args) = @_;
 7967:     my $headerstring='';
 7968:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7969:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7970:         $headerstring.=
 7971:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7972:         if (!$args->{'frameset'}) {
 7973: 	    $headerstring.= ' /';
 7974:         }
 7975: 	$headerstring .= '>'."\n";
 7976:     }
 7977:     return $headerstring;
 7978: }
 7979: 
 7980: =pod
 7981: 
 7982: =item * &print_suppression()
 7983: 
 7984: In course context returns css which causes the body to be blank when media="print",
 7985: if printout generation is unavailable for the current resource.
 7986: 
 7987: This could be because:
 7988: 
 7989: (a) printstartdate is in the future
 7990: 
 7991: (b) printenddate is in the past
 7992: 
 7993: (c) there is an active exam block with "printout"
 7994: functionality blocked
 7995: 
 7996: Users with pav, pfo or evb privileges are exempt.
 7997: 
 7998: Inputs: none
 7999: 
 8000: =cut
 8001: 
 8002: 
 8003: sub print_suppression {
 8004:     my $noprint;
 8005:     if ($env{'request.course.id'}) {
 8006:         my $scope = $env{'request.course.id'};
 8007:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8008:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8009:             return;
 8010:         }
 8011:         if ($env{'request.course.sec'} ne '') {
 8012:             $scope .= "/$env{'request.course.sec'}";
 8013:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8014:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8015:                 return;
 8016:             }
 8017:         }
 8018:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8019:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8020:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8021:         if ($blocked) {
 8022:             my $checkrole = "cm./$cdom/$cnum";
 8023:             if ($env{'request.course.sec'} ne '') {
 8024:                 $checkrole .= "/$env{'request.course.sec'}";
 8025:             }
 8026:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8027:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8028:                 $noprint = 1;
 8029:             }
 8030:         }
 8031:         unless ($noprint) {
 8032:             my $symb = &Apache::lonnet::symbread();
 8033:             if ($symb ne '') {
 8034:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8035:                 if (ref($navmap)) {
 8036:                     my $res = $navmap->getBySymb($symb);
 8037:                     if (ref($res)) {
 8038:                         if (!$res->resprintable()) {
 8039:                             $noprint = 1;
 8040:                         }
 8041:                     }
 8042:                 }
 8043:             }
 8044:         }
 8045:         if ($noprint) {
 8046:             return <<"ENDSTYLE";
 8047: <style type="text/css" media="print">
 8048:     body { display:none }
 8049: </style>
 8050: ENDSTYLE
 8051:         }
 8052:     }
 8053:     return;
 8054: }
 8055: 
 8056: =pod
 8057: 
 8058: =item * &xml_begin()
 8059: 
 8060: Returns the needed doctype and <html>
 8061: 
 8062: Inputs: none
 8063: 
 8064: =cut
 8065: 
 8066: sub xml_begin {
 8067:     my ($is_frameset) = @_;
 8068:     my $output='';
 8069: 
 8070:     if ($env{'browser.mathml'}) {
 8071: 	$output='<?xml version="1.0"?>'
 8072:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8073: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8074:             
 8075: #	    .'<!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">] >'
 8076: 	    .'<!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">'
 8077:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8078: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8079:     } elsif ($is_frameset) {
 8080:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8081:                 '<html>'."\n";
 8082:     } else {
 8083: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8084:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8085:     }
 8086:     return $output;
 8087: }
 8088: 
 8089: =pod
 8090: 
 8091: =item * &start_page()
 8092: 
 8093: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8094: 
 8095: Inputs:
 8096: 
 8097: =over 4
 8098: 
 8099: $title - optional title for the page
 8100: 
 8101: $head_extra - optional extra HTML to incude inside the <head>
 8102: 
 8103: $args - additional optional args supported are:
 8104: 
 8105: =over 8
 8106: 
 8107:              only_body      -> is true will set &bodytag() onlybodytag
 8108:                                     arg on
 8109:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8110:              add_entries    -> additional attributes to add to the  <body>
 8111:              domain         -> force to color decorate a page for a 
 8112:                                     specific domain
 8113:              function       -> force usage of a specific rolish color
 8114:                                     scheme
 8115:              redirect       -> see &headtag()
 8116:              bgcolor        -> override the default page bg color
 8117:              js_ready       -> return a string ready for being used in 
 8118:                                     a javascript writeln
 8119:              html_encode    -> return a string ready for being used in 
 8120:                                     a html attribute
 8121:              force_register -> if is true will turn on the &bodytag()
 8122:                                     $forcereg arg
 8123:              frameset       -> if true will start with a <frameset>
 8124:                                     rather than <body>
 8125:              skip_phases    -> hash ref of 
 8126:                                     head -> skip the <html><head> generation
 8127:                                     body -> skip all <body> generation
 8128:              no_auto_mt_title -> prevent &mt()ing the title arg
 8129:              inherit_jsmath -> when creating popup window in a page,
 8130:                                     should it have jsmath forced on by the
 8131:                                     current page
 8132:              bread_crumbs ->             Array containing breadcrumbs
 8133:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8134:              group          -> includes the current group, if page is for a 
 8135:                                specific group  
 8136: 
 8137: =back
 8138: 
 8139: =back
 8140: 
 8141: =cut
 8142: 
 8143: sub start_page {
 8144:     my ($title,$head_extra,$args) = @_;
 8145:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8146: 
 8147:     $env{'internal.start_page'}++;
 8148:     my ($result,@advtools);
 8149: 
 8150:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8151:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8152:     }
 8153:     
 8154:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8155: 	if ($args->{'frameset'}) {
 8156: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8157: 						$args->{'add_entries'});
 8158: 	    $result .= "\n<frameset $attr_string>\n";
 8159:         } else {
 8160:             $result .=
 8161:                 &bodytag($title, 
 8162:                          $args->{'function'},       $args->{'add_entries'},
 8163:                          $args->{'only_body'},      $args->{'domain'},
 8164:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8165:                          $args->{'bgcolor'},        $args,
 8166:                          \@advtools);
 8167:         }
 8168:     }
 8169: 
 8170:     if ($args->{'js_ready'}) {
 8171: 		$result = &js_ready($result);
 8172:     }
 8173:     if ($args->{'html_encode'}) {
 8174: 		$result = &html_encode($result);
 8175:     }
 8176: 
 8177:     # Preparation for new and consistent functionlist at top of screen
 8178:     # if ($args->{'functionlist'}) {
 8179:     #            $result .= &build_functionlist();
 8180:     #}
 8181: 
 8182:     # Don't add anything more if only_body wanted or in const space
 8183:     return $result if    $args->{'only_body'} 
 8184:                       || $env{'request.state'} eq 'construct';
 8185: 
 8186:     #Breadcrumbs
 8187:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8188: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8189: 		#if any br links exists, add them to the breadcrumbs
 8190: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8191: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8192: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8193: 			}
 8194: 		}
 8195:                 # if @advtools array contains items add then to the breadcrumbs
 8196:                 if (@advtools > 0) {
 8197:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8198:                 }
 8199: 
 8200: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8201: 		if(exists($args->{'bread_crumbs_component'})){
 8202: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 8203: 		}else{
 8204: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 8205: 		}
 8206:     }
 8207:     return $result;
 8208: }
 8209: 
 8210: sub end_page {
 8211:     my ($args) = @_;
 8212:     $env{'internal.end_page'}++;
 8213:     my $result;
 8214:     if ($args->{'discussion'}) {
 8215: 	my ($target,$parser);
 8216: 	if (ref($args->{'discussion'})) {
 8217: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8218: 				$args->{'discussion'}{'parser'});
 8219: 	}
 8220: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8221:     }
 8222:     if ($args->{'frameset'}) {
 8223: 	$result .= '</frameset>';
 8224:     } else {
 8225: 	$result .= &endbodytag($args);
 8226:     }
 8227:     unless ($args->{'notbody'}) {
 8228:         $result .= "\n</html>";
 8229:     }
 8230: 
 8231:     if ($args->{'js_ready'}) {
 8232: 	$result = &js_ready($result);
 8233:     }
 8234: 
 8235:     if ($args->{'html_encode'}) {
 8236: 	$result = &html_encode($result);
 8237:     }
 8238: 
 8239:     return $result;
 8240: }
 8241: 
 8242: sub wishlist_window {
 8243:     return(<<'ENDWISHLIST');
 8244: <script type="text/javascript">
 8245: // <![CDATA[
 8246: // <!-- BEGIN LON-CAPA Internal
 8247: function set_wishlistlink(title, path) {
 8248:     if (!title) {
 8249:         title = document.title;
 8250:         title = title.replace(/^LON-CAPA /,'');
 8251:     }
 8252:     title = encodeURIComponent(title);
 8253:     title = title.replace("'","\\\'");
 8254:     if (!path) {
 8255:         path = location.pathname;
 8256:     }
 8257:     path = encodeURIComponent(path);
 8258:     path = path.replace("'","\\\'");
 8259:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8260:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8261: }
 8262: // END LON-CAPA Internal -->
 8263: // ]]>
 8264: </script>
 8265: ENDWISHLIST
 8266: }
 8267: 
 8268: sub modal_window {
 8269:     return(<<'ENDMODAL');
 8270: <script type="text/javascript">
 8271: // <![CDATA[
 8272: // <!-- BEGIN LON-CAPA Internal
 8273: var modalWindow = {
 8274: 	parent:"body",
 8275: 	windowId:null,
 8276: 	content:null,
 8277: 	width:null,
 8278: 	height:null,
 8279: 	close:function()
 8280: 	{
 8281: 	        $(".LCmodal-window").remove();
 8282: 	        $(".LCmodal-overlay").remove();
 8283: 	},
 8284: 	open:function()
 8285: 	{
 8286: 		var modal = "";
 8287: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8288: 		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;\">";
 8289: 		modal += this.content;
 8290: 		modal += "</div>";	
 8291: 
 8292: 		$(this.parent).append(modal);
 8293: 
 8294: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8295: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8296: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8297: 	}
 8298: };
 8299: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8300: 	{
 8301:                 source = source.replace("'","&#39;");
 8302: 		modalWindow.windowId = "myModal";
 8303: 		modalWindow.width = width;
 8304: 		modalWindow.height = height;
 8305: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8306: 		modalWindow.open();
 8307: 	};
 8308: // END LON-CAPA Internal -->
 8309: // ]]>
 8310: </script>
 8311: ENDMODAL
 8312: }
 8313: 
 8314: sub modal_link {
 8315:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8316:     unless ($width) { $width=480; }
 8317:     unless ($height) { $height=400; }
 8318:     unless ($scrolling) { $scrolling='yes'; }
 8319:     unless ($transparency) { $transparency='true'; }
 8320: 
 8321:     my $target_attr;
 8322:     if (defined($target)) {
 8323:         $target_attr = 'target="'.$target.'"';
 8324:     }
 8325:     return <<"ENDLINK";
 8326: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8327:            $linktext</a>
 8328: ENDLINK
 8329: }
 8330: 
 8331: sub modal_adhoc_script {
 8332:     my ($funcname,$width,$height,$content)=@_;
 8333:     return (<<ENDADHOC);
 8334: <script type="text/javascript">
 8335: // <![CDATA[
 8336:         var $funcname = function()
 8337:         {
 8338:                 modalWindow.windowId = "myModal";
 8339:                 modalWindow.width = $width;
 8340:                 modalWindow.height = $height;
 8341:                 modalWindow.content = '$content';
 8342:                 modalWindow.open();
 8343:         };  
 8344: // ]]>
 8345: </script>
 8346: ENDADHOC
 8347: }
 8348: 
 8349: sub modal_adhoc_inner {
 8350:     my ($funcname,$width,$height,$content)=@_;
 8351:     my $innerwidth=$width-20;
 8352:     $content=&js_ready(
 8353:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8354:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8355:                  $content.
 8356:                  &end_scrollbox().
 8357:                  &end_page()
 8358:              );
 8359:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8360: }
 8361: 
 8362: sub modal_adhoc_window {
 8363:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8364:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8365:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8366: }
 8367: 
 8368: sub modal_adhoc_launch {
 8369:     my ($funcname,$width,$height,$content)=@_;
 8370:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8371: <script type="text/javascript">
 8372: // <![CDATA[
 8373: $funcname();
 8374: // ]]>
 8375: </script>
 8376: ENDLAUNCH
 8377: }
 8378: 
 8379: sub modal_adhoc_close {
 8380:     return (<<ENDCLOSE);
 8381: <script type="text/javascript">
 8382: // <![CDATA[
 8383: modalWindow.close();
 8384: // ]]>
 8385: </script>
 8386: ENDCLOSE
 8387: }
 8388: 
 8389: sub togglebox_script {
 8390:    return(<<ENDTOGGLE);
 8391: <script type="text/javascript"> 
 8392: // <![CDATA[
 8393: function LCtoggleDisplay(id,hidetext,showtext) {
 8394:    link = document.getElementById(id + "link").childNodes[0];
 8395:    with (document.getElementById(id).style) {
 8396:       if (display == "none" ) {
 8397:           display = "inline";
 8398:           link.nodeValue = hidetext;
 8399:         } else {
 8400:           display = "none";
 8401:           link.nodeValue = showtext;
 8402:        }
 8403:    }
 8404: }
 8405: // ]]>
 8406: </script>
 8407: ENDTOGGLE
 8408: }
 8409: 
 8410: sub start_togglebox {
 8411:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8412:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8413:     unless ($showtext) { $showtext=&mt('show'); }
 8414:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8415:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8416:     return &start_data_table().
 8417:            &start_data_table_header_row().
 8418:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8419:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8420:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8421:            &end_data_table_header_row().
 8422:            '<tr id="'.$id.'" style="display:none""><td>';
 8423: }
 8424: 
 8425: sub end_togglebox {
 8426:     return '</td></tr>'.&end_data_table();
 8427: }
 8428: 
 8429: sub LCprogressbar_script {
 8430:    my ($id)=@_;
 8431:    return(<<ENDPROGRESS);
 8432: <script type="text/javascript">
 8433: // <![CDATA[
 8434: \$('#progressbar$id').progressbar({
 8435:   value: 0,
 8436:   change: function(event, ui) {
 8437:     var newVal = \$(this).progressbar('option', 'value');
 8438:     \$('.pblabel', this).text(LCprogressTxt);
 8439:   }
 8440: });
 8441: // ]]>
 8442: </script>
 8443: ENDPROGRESS
 8444: }
 8445: 
 8446: sub LCprogressbarUpdate_script {
 8447:    return(<<ENDPROGRESSUPDATE);
 8448: <style type="text/css">
 8449: .ui-progressbar { position:relative; }
 8450: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8451: </style>
 8452: <script type="text/javascript">
 8453: // <![CDATA[
 8454: var LCprogressTxt='---';
 8455: 
 8456: function LCupdateProgress(percent,progresstext,id) {
 8457:    LCprogressTxt=progresstext;
 8458:    \$('#progressbar'+id).progressbar('value',percent);
 8459: }
 8460: // ]]>
 8461: </script>
 8462: ENDPROGRESSUPDATE
 8463: }
 8464: 
 8465: my $LClastpercent;
 8466: my $LCidcnt;
 8467: my $LCcurrentid;
 8468: 
 8469: sub LCprogressbar {
 8470:     my ($r)=(@_);
 8471:     $LClastpercent=0;
 8472:     $LCidcnt++;
 8473:     $LCcurrentid=$$.'_'.$LCidcnt;
 8474:     my $starting=&mt('Starting');
 8475:     my $content=(<<ENDPROGBAR);
 8476:   <div id="progressbar$LCcurrentid">
 8477:     <span class="pblabel">$starting</span>
 8478:   </div>
 8479: ENDPROGBAR
 8480:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8481: }
 8482: 
 8483: sub LCprogressbarUpdate {
 8484:     my ($r,$val,$text)=@_;
 8485:     unless ($val) { 
 8486:        if ($LClastpercent) {
 8487:            $val=$LClastpercent;
 8488:        } else {
 8489:            $val=0;
 8490:        }
 8491:     }
 8492:     if ($val<0) { $val=0; }
 8493:     if ($val>100) { $val=0; }
 8494:     $LClastpercent=$val;
 8495:     unless ($text) { $text=$val.'%'; }
 8496:     $text=&js_ready($text);
 8497:     &r_print($r,<<ENDUPDATE);
 8498: <script type="text/javascript">
 8499: // <![CDATA[
 8500: LCupdateProgress($val,'$text','$LCcurrentid');
 8501: // ]]>
 8502: </script>
 8503: ENDUPDATE
 8504: }
 8505: 
 8506: sub LCprogressbarClose {
 8507:     my ($r)=@_;
 8508:     $LClastpercent=0;
 8509:     &r_print($r,<<ENDCLOSE);
 8510: <script type="text/javascript">
 8511: // <![CDATA[
 8512: \$("#progressbar$LCcurrentid").hide('slow'); 
 8513: // ]]>
 8514: </script>
 8515: ENDCLOSE
 8516: }
 8517: 
 8518: sub r_print {
 8519:     my ($r,$to_print)=@_;
 8520:     if ($r) {
 8521:       $r->print($to_print);
 8522:       $r->rflush();
 8523:     } else {
 8524:       print($to_print);
 8525:     }
 8526: }
 8527: 
 8528: sub html_encode {
 8529:     my ($result) = @_;
 8530: 
 8531:     $result = &HTML::Entities::encode($result,'<>&"');
 8532:     
 8533:     return $result;
 8534: }
 8535: 
 8536: sub js_ready {
 8537:     my ($result) = @_;
 8538: 
 8539:     $result =~ s/[\n\r]/ /xmsg;
 8540:     $result =~ s/\\/\\\\/xmsg;
 8541:     $result =~ s/'/\\'/xmsg;
 8542:     $result =~ s{</}{<\\/}xmsg;
 8543:     
 8544:     return $result;
 8545: }
 8546: 
 8547: sub validate_page {
 8548:     if (  exists($env{'internal.start_page'})
 8549: 	  &&     $env{'internal.start_page'} > 1) {
 8550: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8551: 				 $env{'internal.start_page'}.' '.
 8552: 				 $ENV{'request.filename'});
 8553:     }
 8554:     if (  exists($env{'internal.end_page'})
 8555: 	  &&     $env{'internal.end_page'} > 1) {
 8556: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8557: 				 $env{'internal.end_page'}.' '.
 8558: 				 $env{'request.filename'});
 8559:     }
 8560:     if (     exists($env{'internal.start_page'})
 8561: 	&& ! exists($env{'internal.end_page'})) {
 8562: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8563: 				 $env{'request.filename'});
 8564:     }
 8565:     if (   ! exists($env{'internal.start_page'})
 8566: 	&&   exists($env{'internal.end_page'})) {
 8567: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8568: 				 $env{'request.filename'});
 8569:     }
 8570: }
 8571: 
 8572: 
 8573: sub start_scrollbox {
 8574:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8575:     unless ($outerwidth) { $outerwidth='520px'; }
 8576:     unless ($width) { $width='500px'; }
 8577:     unless ($height) { $height='200px'; }
 8578:     my ($table_id,$div_id,$tdcol);
 8579:     if ($id ne '') {
 8580:         $table_id = ' id="table_'.$id.'"';
 8581:         $div_id = ' id="div_'.$id.'"';
 8582:     }
 8583:     if ($bgcolor ne '') {
 8584:         $tdcol = "background-color: $bgcolor;";
 8585:     }
 8586:     my $nicescroll_js;
 8587:     if ($env{'browser.mobile'}) {
 8588:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8589:     }
 8590:     return <<"END";
 8591: $nicescroll_js
 8592: 
 8593: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8594: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8595: END
 8596: }
 8597: 
 8598: sub end_scrollbox {
 8599:     return '</div></td></tr></table>';
 8600: }
 8601: 
 8602: sub nicescroll_javascript {
 8603:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8604:     my %options;
 8605:     if (ref($cursor) eq 'HASH') {
 8606:         %options = %{$cursor};
 8607:     }
 8608:     unless ($options{'railalign'} =~ /^left|right$/) {
 8609:         $options{'railalign'} = 'left';
 8610:     }
 8611:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8612:         my $function  = &get_users_function();
 8613:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8614:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8615:             $options{'cursorcolor'} = '#00F';
 8616:         }
 8617:     }
 8618:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8619:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8620:             $options{'cursoropacity'}='1.0';
 8621:         }
 8622:     } else {
 8623:         $options{'cursoropacity'}='1.0';
 8624:     }
 8625:     if ($options{'cursorfixedheight'} eq 'none') {
 8626:         delete($options{'cursorfixedheight'});
 8627:     } else {
 8628:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8629:     }
 8630:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8631:         delete($options{'railoffset'});
 8632:     }
 8633:     my @niceoptions;
 8634:     while (my($key,$value) = each(%options)) {
 8635:         if ($value =~ /^\{.+\}$/) {
 8636:             push(@niceoptions,$key.':'.$value);
 8637:         } else {
 8638:             push(@niceoptions,$key.':"'.$value.'"');
 8639:         }
 8640:     }
 8641:     my $nicescroll_js = '
 8642: $(document).ready(
 8643:       function() {
 8644:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8645:       }
 8646: );
 8647: ';
 8648:     if ($framecheck) {
 8649:         $nicescroll_js .= '
 8650: function expand_div(caller) {
 8651:     if (top === self) {
 8652:         document.getElementById("'.$id.'").style.width = "auto";
 8653:         document.getElementById("'.$id.'").style.height = "auto";
 8654:     } else {
 8655:         try {
 8656:             if (parent.frames) {
 8657:                 if (parent.frames.length > 1) {
 8658:                     var framesrc = parent.frames[1].location.href;
 8659:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8660:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8661:                         document.getElementById("'.$id.'").style.width = "auto";
 8662:                         document.getElementById("'.$id.'").style.height = "auto";
 8663:                     }
 8664:                 }
 8665:             }
 8666:         } catch (e) {
 8667:             return;
 8668:         }
 8669:     }
 8670:     return;
 8671: }
 8672: ';
 8673:     }
 8674:     if ($needjsready) {
 8675:         $nicescroll_js = '
 8676: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8677:     } else {
 8678:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8679:     }
 8680:     return $nicescroll_js;
 8681: }
 8682: 
 8683: sub simple_error_page {
 8684:     my ($r,$title,$msg,$args) = @_;
 8685:     if (ref($args) eq 'HASH') {
 8686:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8687:     } else {
 8688:         $msg = &mt($msg);
 8689:     }
 8690: 
 8691:     my $page =
 8692: 	&Apache::loncommon::start_page($title).
 8693: 	'<p class="LC_error">'.$msg.'</p>'.
 8694: 	&Apache::loncommon::end_page();
 8695:     if (ref($r)) {
 8696: 	$r->print($page);
 8697: 	return;
 8698:     }
 8699:     return $page;
 8700: }
 8701: 
 8702: {
 8703:     my @row_count;
 8704: 
 8705:     sub start_data_table_count {
 8706:         unshift(@row_count, 0);
 8707:         return;
 8708:     }
 8709: 
 8710:     sub end_data_table_count {
 8711:         shift(@row_count);
 8712:         return;
 8713:     }
 8714: 
 8715:     sub start_data_table {
 8716: 	my ($add_class,$id) = @_;
 8717: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8718:         my $table_id;
 8719:         if (defined($id)) {
 8720:             $table_id = ' id="'.$id.'"';
 8721:         }
 8722: 	&start_data_table_count();
 8723: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8724:     }
 8725: 
 8726:     sub end_data_table {
 8727: 	&end_data_table_count();
 8728: 	return '</table>'."\n";;
 8729:     }
 8730: 
 8731:     sub start_data_table_row {
 8732: 	my ($add_class, $id) = @_;
 8733: 	$row_count[0]++;
 8734: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8735: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8736:         $id = (' id="'.$id.'"') unless ($id eq '');
 8737:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8738:     }
 8739:     
 8740:     sub continue_data_table_row {
 8741: 	my ($add_class, $id) = @_;
 8742: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8743: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8744:         $id = (' id="'.$id.'"') unless ($id eq '');
 8745:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8746:     }
 8747: 
 8748:     sub end_data_table_row {
 8749: 	return '</tr>'."\n";;
 8750:     }
 8751: 
 8752:     sub start_data_table_empty_row {
 8753: #	$row_count[0]++;
 8754: 	return  '<tr class="LC_empty_row" >'."\n";;
 8755:     }
 8756: 
 8757:     sub end_data_table_empty_row {
 8758: 	return '</tr>'."\n";;
 8759:     }
 8760: 
 8761:     sub start_data_table_header_row {
 8762: 	return  '<tr class="LC_header_row">'."\n";;
 8763:     }
 8764: 
 8765:     sub end_data_table_header_row {
 8766: 	return '</tr>'."\n";;
 8767:     }
 8768: 
 8769:     sub data_table_caption {
 8770:         my $caption = shift;
 8771:         return "<caption class=\"LC_caption\">$caption</caption>";
 8772:     }
 8773: }
 8774: 
 8775: =pod
 8776: 
 8777: =item * &inhibit_menu_check($arg)
 8778: 
 8779: Checks for a inhibitmenu state and generates output to preserve it
 8780: 
 8781: Inputs:         $arg - can be any of
 8782:                      - undef - in which case the return value is a string 
 8783:                                to add  into arguments list of a uri
 8784:                      - 'input' - in which case the return value is a HTML
 8785:                                  <form> <input> field of type hidden to
 8786:                                  preserve the value
 8787:                      - a url - in which case the return value is the url with
 8788:                                the neccesary cgi args added to preserve the
 8789:                                inhibitmenu state
 8790:                      - a ref to a url - no return value, but the string is
 8791:                                         updated to include the neccessary cgi
 8792:                                         args to preserve the inhibitmenu state
 8793: 
 8794: =cut
 8795: 
 8796: sub inhibit_menu_check {
 8797:     my ($arg) = @_;
 8798:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8799:     if ($arg eq 'input') {
 8800: 	if ($env{'form.inhibitmenu'}) {
 8801: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8802: 	} else {
 8803: 	    return
 8804: 	}
 8805:     }
 8806:     if ($env{'form.inhibitmenu'}) {
 8807: 	if (ref($arg)) {
 8808: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8809: 	} elsif ($arg eq '') {
 8810: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8811: 	} else {
 8812: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8813: 	}
 8814:     }
 8815:     if (!ref($arg)) {
 8816: 	return $arg;
 8817:     }
 8818: }
 8819: 
 8820: ###############################################
 8821: 
 8822: =pod
 8823: 
 8824: =back
 8825: 
 8826: =head1 User Information Routines
 8827: 
 8828: =over 4
 8829: 
 8830: =item * &get_users_function()
 8831: 
 8832: Used by &bodytag to determine the current users primary role.
 8833: Returns either 'student','coordinator','admin', or 'author'.
 8834: 
 8835: =cut
 8836: 
 8837: ###############################################
 8838: sub get_users_function {
 8839:     my $function = 'norole';
 8840:     if ($env{'request.role'}=~/^(st)/) {
 8841:         $function='student';
 8842:     }
 8843:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8844:         $function='coordinator';
 8845:     }
 8846:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8847:         $function='admin';
 8848:     }
 8849:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8850:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8851:         $function='author';
 8852:     }
 8853:     return $function;
 8854: }
 8855: 
 8856: ###############################################
 8857: 
 8858: =pod
 8859: 
 8860: =item * &show_course()
 8861: 
 8862: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8863: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8864: 
 8865: Inputs:
 8866: None
 8867: 
 8868: Outputs:
 8869: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8870: 
 8871: =cut
 8872: 
 8873: ###############################################
 8874: sub show_course {
 8875:     my $course = !$env{'user.adv'};
 8876:     if (!$env{'user.adv'}) {
 8877:         foreach my $env (keys(%env)) {
 8878:             next if ($env !~ m/^user\.priv\./);
 8879:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8880:                 $course = 0;
 8881:                 last;
 8882:             }
 8883:         }
 8884:     }
 8885:     return $course;
 8886: }
 8887: 
 8888: ###############################################
 8889: 
 8890: =pod
 8891: 
 8892: =item * &check_user_status()
 8893: 
 8894: Determines current status of supplied role for a
 8895: specific user. Roles can be active, previous or future.
 8896: 
 8897: Inputs: 
 8898: user's domain, user's username, course's domain,
 8899: course's number, optional section ID.
 8900: 
 8901: Outputs:
 8902: role status: active, previous or future. 
 8903: 
 8904: =cut
 8905: 
 8906: sub check_user_status {
 8907:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8908:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8909:     my @uroles = keys(%userinfo);
 8910:     my $srchstr;
 8911:     my $active_chk = 'none';
 8912:     my $now = time;
 8913:     if (@uroles > 0) {
 8914:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8915:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8916:         } else {
 8917:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8918:         }
 8919:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8920:             my $role_end = 0;
 8921:             my $role_start = 0;
 8922:             $active_chk = 'active';
 8923:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8924:                 $role_end = $1;
 8925:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8926:                     $role_start = $1;
 8927:                 }
 8928:             }
 8929:             if ($role_start > 0) {
 8930:                 if ($now < $role_start) {
 8931:                     $active_chk = 'future';
 8932:                 }
 8933:             }
 8934:             if ($role_end > 0) {
 8935:                 if ($now > $role_end) {
 8936:                     $active_chk = 'previous';
 8937:                 }
 8938:             }
 8939:         }
 8940:     }
 8941:     return $active_chk;
 8942: }
 8943: 
 8944: ###############################################
 8945: 
 8946: =pod
 8947: 
 8948: =item * &get_sections()
 8949: 
 8950: Determines all the sections for a course including
 8951: sections with students and sections containing other roles.
 8952: Incoming parameters: 
 8953: 
 8954: 1. domain
 8955: 2. course number 
 8956: 3. reference to array containing roles for which sections should 
 8957: be gathered (optional).
 8958: 4. reference to array containing status types for which sections 
 8959: should be gathered (optional).
 8960: 
 8961: If the third argument is undefined, sections are gathered for any role. 
 8962: If the fourth argument is undefined, sections are gathered for any status.
 8963: Permissible values are 'active' or 'future' or 'previous'.
 8964:  
 8965: Returns section hash (keys are section IDs, values are
 8966: number of users in each section), subject to the
 8967: optional roles filter, optional status filter 
 8968: 
 8969: =cut
 8970: 
 8971: ###############################################
 8972: sub get_sections {
 8973:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8974:     if (!defined($cdom) || !defined($cnum)) {
 8975:         my $cid =  $env{'request.course.id'};
 8976: 
 8977: 	return if (!defined($cid));
 8978: 
 8979:         $cdom = $env{'course.'.$cid.'.domain'};
 8980:         $cnum = $env{'course.'.$cid.'.num'};
 8981:     }
 8982: 
 8983:     my %sectioncount;
 8984:     my $now = time;
 8985: 
 8986:     my $check_students = 1;
 8987:     my $only_students = 0;
 8988:     if (ref($possible_roles) eq 'ARRAY') {
 8989:         if (grep(/^st$/,@{$possible_roles})) {
 8990:             if (@{$possible_roles} == 1) {
 8991:                 $only_students = 1;
 8992:             }
 8993:         } else {
 8994:             $check_students = 0;
 8995:         }
 8996:     }
 8997: 
 8998:     if ($check_students) { 
 8999: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9000: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9001: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9002:         my $start_index = &Apache::loncoursedata::CL_START();
 9003:         my $end_index = &Apache::loncoursedata::CL_END();
 9004:         my $status;
 9005: 	while (my ($student,$data) = each(%$classlist)) {
 9006: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9007: 				                     $data->[$status_index],
 9008:                                                      $data->[$start_index],
 9009:                                                      $data->[$end_index]);
 9010:             if ($stu_status eq 'Active') {
 9011:                 $status = 'active';
 9012:             } elsif ($end < $now) {
 9013:                 $status = 'previous';
 9014:             } elsif ($start > $now) {
 9015:                 $status = 'future';
 9016:             } 
 9017: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9018:                 if ((!defined($possible_status)) || (($status ne '') && 
 9019:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9020: 		    $sectioncount{$section}++;
 9021:                 }
 9022: 	    }
 9023: 	}
 9024:     }
 9025:     if ($only_students) {
 9026:         return %sectioncount;
 9027:     }
 9028:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9029:     foreach my $user (sort(keys(%courseroles))) {
 9030: 	if ($user !~ /^(\w{2})/) { next; }
 9031: 	my ($role) = ($user =~ /^(\w{2})/);
 9032: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9033: 	my ($section,$status);
 9034: 	if ($role eq 'cr' &&
 9035: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9036: 	    $section=$1;
 9037: 	}
 9038: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9039: 	if (!defined($section) || $section eq '-1') { next; }
 9040:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9041:         if ($end == -1 && $start == -1) {
 9042:             next; #deleted role
 9043:         }
 9044:         if (!defined($possible_status)) { 
 9045:             $sectioncount{$section}++;
 9046:         } else {
 9047:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9048:                 $status = 'active';
 9049:             } elsif ($end < $now) {
 9050:                 $status = 'future';
 9051:             } elsif ($start > $now) {
 9052:                 $status = 'previous';
 9053:             }
 9054:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9055:                 $sectioncount{$section}++;
 9056:             }
 9057:         }
 9058:     }
 9059:     return %sectioncount;
 9060: }
 9061: 
 9062: ###############################################
 9063: 
 9064: =pod
 9065: 
 9066: =item * &get_course_users()
 9067: 
 9068: Retrieves usernames:domains for users in the specified course
 9069: with specific role(s), and access status. 
 9070: 
 9071: Incoming parameters:
 9072: 1. course domain
 9073: 2. course number
 9074: 3. access status: users must have - either active, 
 9075: previous, future, or all.
 9076: 4. reference to array of permissible roles
 9077: 5. reference to array of section restrictions (optional)
 9078: 6. reference to results object (hash of hashes).
 9079: 7. reference to optional userdata hash
 9080: 8. reference to optional statushash
 9081: 9. flag if privileged users (except those set to unhide in
 9082:    course settings) should be excluded    
 9083: Keys of top level results hash are roles.
 9084: Keys of inner hashes are username:domain, with 
 9085: values set to access type.
 9086: Optional userdata hash returns an array with arguments in the 
 9087: same order as loncoursedata::get_classlist() for student data.
 9088: 
 9089: Optional statushash returns
 9090: 
 9091: Entries for end, start, section and status are blank because
 9092: of the possibility of multiple values for non-student roles.
 9093: 
 9094: =cut
 9095: 
 9096: ###############################################
 9097: 
 9098: sub get_course_users {
 9099:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9100:     my %idx = ();
 9101:     my %seclists;
 9102: 
 9103:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9104:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9105:     $idx{end} = &Apache::loncoursedata::CL_END();
 9106:     $idx{start} = &Apache::loncoursedata::CL_START();
 9107:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9108:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9109:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9110:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9111: 
 9112:     if (grep(/^st$/,@{$roles})) {
 9113:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9114:         my $now = time;
 9115:         foreach my $student (keys(%{$classlist})) {
 9116:             my $match = 0;
 9117:             my $secmatch = 0;
 9118:             my $section = $$classlist{$student}[$idx{section}];
 9119:             my $status = $$classlist{$student}[$idx{status}];
 9120:             if ($section eq '') {
 9121:                 $section = 'none';
 9122:             }
 9123:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9124:                 if (grep(/^all$/,@{$sections})) {
 9125:                     $secmatch = 1;
 9126:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9127:                     if (grep(/^none$/,@{$sections})) {
 9128:                         $secmatch = 1;
 9129:                     }
 9130:                 } else {  
 9131: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9132: 		        $secmatch = 1;
 9133:                     }
 9134: 		}
 9135:                 if (!$secmatch) {
 9136:                     next;
 9137:                 }
 9138:             }
 9139:             if (defined($$types{'active'})) {
 9140:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9141:                     push(@{$$users{st}{$student}},'active');
 9142:                     $match = 1;
 9143:                 }
 9144:             }
 9145:             if (defined($$types{'previous'})) {
 9146:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9147:                     push(@{$$users{st}{$student}},'previous');
 9148:                     $match = 1;
 9149:                 }
 9150:             }
 9151:             if (defined($$types{'future'})) {
 9152:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9153:                     push(@{$$users{st}{$student}},'future');
 9154:                     $match = 1;
 9155:                 }
 9156:             }
 9157:             if ($match) {
 9158:                 push(@{$seclists{$student}},$section);
 9159:                 if (ref($userdata) eq 'HASH') {
 9160:                     $$userdata{$student} = $$classlist{$student};
 9161:                 }
 9162:                 if (ref($statushash) eq 'HASH') {
 9163:                     $statushash->{$student}{'st'}{$section} = $status;
 9164:                 }
 9165:             }
 9166:         }
 9167:     }
 9168:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9169:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9170:         my $now = time;
 9171:         my %displaystatus = ( previous => 'Expired',
 9172:                               active   => 'Active',
 9173:                               future   => 'Future',
 9174:                             );
 9175:         my (%nothide,@possdoms);
 9176:         if ($hidepriv) {
 9177:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9178:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9179:                 if ($user !~ /:/) {
 9180:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9181:                 } else {
 9182:                     $nothide{$user} = 1;
 9183:                 }
 9184:             }
 9185:             my @possdoms = ($cdom);
 9186:             if ($coursehash{'checkforpriv'}) {
 9187:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9188:             }
 9189:         }
 9190:         foreach my $person (sort(keys(%coursepersonnel))) {
 9191:             my $match = 0;
 9192:             my $secmatch = 0;
 9193:             my $status;
 9194:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9195:             $user =~ s/:$//;
 9196:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9197:             if ($end == -1 || $start == -1) {
 9198:                 next;
 9199:             }
 9200:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9201:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9202:                 my ($uname,$udom) = split(/:/,$user);
 9203:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9204:                     if (grep(/^all$/,@{$sections})) {
 9205:                         $secmatch = 1;
 9206:                     } elsif ($usec eq '') {
 9207:                         if (grep(/^none$/,@{$sections})) {
 9208:                             $secmatch = 1;
 9209:                         }
 9210:                     } else {
 9211:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9212:                             $secmatch = 1;
 9213:                         }
 9214:                     }
 9215:                     if (!$secmatch) {
 9216:                         next;
 9217:                     }
 9218:                 }
 9219:                 if ($usec eq '') {
 9220:                     $usec = 'none';
 9221:                 }
 9222:                 if ($uname ne '' && $udom ne '') {
 9223:                     if ($hidepriv) {
 9224:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9225:                             (!$nothide{$uname.':'.$udom})) {
 9226:                             next;
 9227:                         }
 9228:                     }
 9229:                     if ($end > 0 && $end < $now) {
 9230:                         $status = 'previous';
 9231:                     } elsif ($start > $now) {
 9232:                         $status = 'future';
 9233:                     } else {
 9234:                         $status = 'active';
 9235:                     }
 9236:                     foreach my $type (keys(%{$types})) { 
 9237:                         if ($status eq $type) {
 9238:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9239:                                 push(@{$$users{$role}{$user}},$type);
 9240:                             }
 9241:                             $match = 1;
 9242:                         }
 9243:                     }
 9244:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9245:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9246: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9247:                         }
 9248:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9249:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9250:                         }
 9251:                         if (ref($statushash) eq 'HASH') {
 9252:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9253:                         }
 9254:                     }
 9255:                 }
 9256:             }
 9257:         }
 9258:         if (grep(/^ow$/,@{$roles})) {
 9259:             if ((defined($cdom)) && (defined($cnum))) {
 9260:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9261:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9262:                     my $owner = $csettings{'internal.courseowner'};
 9263:                     next if ($owner eq '');
 9264:                     my ($ownername,$ownerdom);
 9265:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9266:                         $ownername = $1;
 9267:                         $ownerdom = $2;
 9268:                     } else {
 9269:                         $ownername = $owner;
 9270:                         $ownerdom = $cdom;
 9271:                         $owner = $ownername.':'.$ownerdom;
 9272:                     }
 9273:                     @{$$users{'ow'}{$owner}} = 'any';
 9274:                     if (defined($userdata) && 
 9275: 			!exists($$userdata{$owner})) {
 9276: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9277:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9278:                             push(@{$seclists{$owner}},'none');
 9279:                         }
 9280:                         if (ref($statushash) eq 'HASH') {
 9281:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9282:                         }
 9283: 		    }
 9284:                 }
 9285:             }
 9286:         }
 9287:         foreach my $user (keys(%seclists)) {
 9288:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9289:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9290:         }
 9291:     }
 9292:     return;
 9293: }
 9294: 
 9295: sub get_user_info {
 9296:     my ($udom,$uname,$idx,$userdata) = @_;
 9297:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9298: 	&plainname($uname,$udom,'lastname');
 9299:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9300:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9301:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9302:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9303:     return;
 9304: }
 9305: 
 9306: ###############################################
 9307: 
 9308: =pod
 9309: 
 9310: =item * &get_user_quota()
 9311: 
 9312: Retrieves quota assigned for storage of user files.
 9313: Default is to report quota for portfolio files.
 9314: 
 9315: Incoming parameters:
 9316: 1. user's username
 9317: 2. user's domain
 9318: 3. quota name - portfolio, author, or course
 9319:    (if no quota name provided, defaults to portfolio).
 9320: 4. crstype - official, unofficial, textbook or community, if quota name is
 9321:    course
 9322: 
 9323: Returns:
 9324: 1. Disk quota (in MB) assigned to student.
 9325: 2. (Optional) Type of setting: custom or default
 9326:    (individually assigned or default for user's 
 9327:    institutional status).
 9328: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9329:    or student - types as defined in localenroll::inst_usertypes 
 9330:    for user's domain, which determines default quota for user.
 9331: 4. (Optional) - Default quota which would apply to the user.
 9332: 
 9333: If a value has been stored in the user's environment, 
 9334: it will return that, otherwise it returns the maximal default
 9335: defined for the user's institutional status(es) in the domain.
 9336: 
 9337: =cut
 9338: 
 9339: ###############################################
 9340: 
 9341: 
 9342: sub get_user_quota {
 9343:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9344:     my ($quota,$quotatype,$settingstatus,$defquota);
 9345:     if (!defined($udom)) {
 9346:         $udom = $env{'user.domain'};
 9347:     }
 9348:     if (!defined($uname)) {
 9349:         $uname = $env{'user.name'};
 9350:     }
 9351:     if (($udom eq '' || $uname eq '') ||
 9352:         ($udom eq 'public') && ($uname eq 'public')) {
 9353:         $quota = 0;
 9354:         $quotatype = 'default';
 9355:         $defquota = 0; 
 9356:     } else {
 9357:         my $inststatus;
 9358:         if ($quotaname eq 'course') {
 9359:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9360:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9361:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9362:             } else {
 9363:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9364:                 $quota = $cenv{'internal.uploadquota'};
 9365:             }
 9366:         } else {
 9367:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9368:                 if ($quotaname eq 'author') {
 9369:                     $quota = $env{'environment.authorquota'};
 9370:                 } else {
 9371:                     $quota = $env{'environment.portfolioquota'};
 9372:                 }
 9373:                 $inststatus = $env{'environment.inststatus'};
 9374:             } else {
 9375:                 my %userenv = 
 9376:                     &Apache::lonnet::get('environment',['portfolioquota',
 9377:                                          'authorquota','inststatus'],$udom,$uname);
 9378:                 my ($tmp) = keys(%userenv);
 9379:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9380:                     if ($quotaname eq 'author') {
 9381:                         $quota = $userenv{'authorquota'};
 9382:                     } else {
 9383:                         $quota = $userenv{'portfolioquota'};
 9384:                     }
 9385:                     $inststatus = $userenv{'inststatus'};
 9386:                 } else {
 9387:                     undef(%userenv);
 9388:                 }
 9389:             }
 9390:         }
 9391:         if ($quota eq '' || wantarray) {
 9392:             if ($quotaname eq 'course') {
 9393:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9394:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9395:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
 9396:                     $defquota = $domdefs{$crstype.'quota'};
 9397:                 }
 9398:                 if ($defquota eq '') {
 9399:                     $defquota = 500;
 9400:                 }
 9401:             } else {
 9402:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9403:             }
 9404:             if ($quota eq '') {
 9405:                 $quota = $defquota;
 9406:                 $quotatype = 'default';
 9407:             } else {
 9408:                 $quotatype = 'custom';
 9409:             }
 9410:         }
 9411:     }
 9412:     if (wantarray) {
 9413:         return ($quota,$quotatype,$settingstatus,$defquota);
 9414:     } else {
 9415:         return $quota;
 9416:     }
 9417: }
 9418: 
 9419: ###############################################
 9420: 
 9421: =pod
 9422: 
 9423: =item * &default_quota()
 9424: 
 9425: Retrieves default quota assigned for storage of user portfolio files,
 9426: given an (optional) user's institutional status.
 9427: 
 9428: Incoming parameters:
 9429: 
 9430: 1. domain
 9431: 2. (Optional) institutional status(es).  This is a : separated list of 
 9432:    status types (e.g., faculty, staff, student etc.)
 9433:    which apply to the user for whom the default is being retrieved.
 9434:    If the institutional status string in undefined, the domain
 9435:    default quota will be returned.
 9436: 3.  quota name - portfolio, author, or course
 9437:    (if no quota name provided, defaults to portfolio).
 9438: 
 9439: Returns:
 9440: 
 9441: 1. Default disk quota (in MB) for user portfolios in the domain.
 9442: 2. (Optional) institutional type which determined the value of the
 9443:    default quota.
 9444: 
 9445: If a value has been stored in the domain's configuration db,
 9446: it will return that, otherwise it returns 20 (for backwards 
 9447: compatibility with domains which have not set up a configuration
 9448: db file; the original statically defined portfolio quota was 20 MB). 
 9449: 
 9450: If the user's status includes multiple types (e.g., staff and student),
 9451: the largest default quota which applies to the user determines the
 9452: default quota returned.
 9453: 
 9454: =cut
 9455: 
 9456: ###############################################
 9457: 
 9458: 
 9459: sub default_quota {
 9460:     my ($udom,$inststatus,$quotaname) = @_;
 9461:     my ($defquota,$settingstatus);
 9462:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9463:                                             ['quotas'],$udom);
 9464:     my $key = 'defaultquota';
 9465:     if ($quotaname eq 'author') {
 9466:         $key = 'authorquota';
 9467:     }
 9468:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9469:         if ($inststatus ne '') {
 9470:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9471:             foreach my $item (@statuses) {
 9472:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9473:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9474:                         if ($defquota eq '') {
 9475:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9476:                             $settingstatus = $item;
 9477:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9478:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9479:                             $settingstatus = $item;
 9480:                         }
 9481:                     }
 9482:                 } elsif ($key eq 'defaultquota') {
 9483:                     if ($quotahash{'quotas'}{$item} ne '') {
 9484:                         if ($defquota eq '') {
 9485:                             $defquota = $quotahash{'quotas'}{$item};
 9486:                             $settingstatus = $item;
 9487:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9488:                             $defquota = $quotahash{'quotas'}{$item};
 9489:                             $settingstatus = $item;
 9490:                         }
 9491:                     }
 9492:                 }
 9493:             }
 9494:         }
 9495:         if ($defquota eq '') {
 9496:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9497:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9498:             } elsif ($key eq 'defaultquota') {
 9499:                 $defquota = $quotahash{'quotas'}{'default'};
 9500:             }
 9501:             $settingstatus = 'default';
 9502:             if ($defquota eq '') {
 9503:                 if ($quotaname eq 'author') {
 9504:                     $defquota = 500;
 9505:                 }
 9506:             }
 9507:         }
 9508:     } else {
 9509:         $settingstatus = 'default';
 9510:         if ($quotaname eq 'author') {
 9511:             $defquota = 500;
 9512:         } else {
 9513:             $defquota = 20;
 9514:         }
 9515:     }
 9516:     if (wantarray) {
 9517:         return ($defquota,$settingstatus);
 9518:     } else {
 9519:         return $defquota;
 9520:     }
 9521: }
 9522: 
 9523: ###############################################
 9524: 
 9525: =pod
 9526: 
 9527: =item * &excess_filesize_warning()
 9528: 
 9529: Returns warning message if upload of file to authoring space, or copying
 9530: of existing file within authoring space will cause quota for the authoring
 9531: space to be exceeded.
 9532: 
 9533: Same, if upload of a file directly to a course/community via Course Editor
 9534: will cause quota for uploaded content for the course to be exceeded.
 9535: 
 9536: Inputs: 7 
 9537: 1. username or coursenum
 9538: 2. domain
 9539: 3. context ('author' or 'course')
 9540: 4. filename of file for which action is being requested
 9541: 5. filesize (kB) of file
 9542: 6. action being taken: copy or upload.
 9543: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9544: 
 9545: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9546:          otherwise return null.
 9547: 
 9548: =back
 9549: 
 9550: =cut
 9551: 
 9552: sub excess_filesize_warning {
 9553:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9554:     my $current_disk_usage = 0;
 9555:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9556:     if ($context eq 'author') {
 9557:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9558:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9559:     } else {
 9560:         foreach my $subdir ('docs','supplemental') {
 9561:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9562:         }
 9563:     }
 9564:     $disk_quota = int($disk_quota * 1000);
 9565:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9566:         return '<p class="LC_warning">'.
 9567:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9568:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9569:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9570:                             $disk_quota,$current_disk_usage).
 9571:                '</p>';
 9572:     }
 9573:     return;
 9574: }
 9575: 
 9576: ###############################################
 9577: 
 9578: 
 9579: 
 9580: 
 9581: sub get_secgrprole_info {
 9582:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9583:     my %sections_count = &get_sections($cdom,$cnum);
 9584:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9585:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9586:     my @groups = sort(keys(%curr_groups));
 9587:     my $allroles = [];
 9588:     my $rolehash;
 9589:     my $accesshash = {
 9590:                      active => 'Currently has access',
 9591:                      future => 'Will have future access',
 9592:                      previous => 'Previously had access',
 9593:                   };
 9594:     if ($needroles) {
 9595:         $rolehash = {'all' => 'all'};
 9596:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9597: 	if (&Apache::lonnet::error(%user_roles)) {
 9598: 	    undef(%user_roles);
 9599: 	}
 9600:         foreach my $item (keys(%user_roles)) {
 9601:             my ($role)=split(/\:/,$item,2);
 9602:             if ($role eq 'cr') { next; }
 9603:             if ($role =~ /^cr/) {
 9604:                 $$rolehash{$role} = (split('/',$role))[3];
 9605:             } else {
 9606:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9607:             }
 9608:         }
 9609:         foreach my $key (sort(keys(%{$rolehash}))) {
 9610:             push(@{$allroles},$key);
 9611:         }
 9612:         push (@{$allroles},'st');
 9613:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9614:     }
 9615:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9616: }
 9617: 
 9618: sub user_picker {
 9619:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9620:     my $currdom = $dom;
 9621:     my %curr_selected = (
 9622:                         srchin => 'dom',
 9623:                         srchby => 'lastname',
 9624:                       );
 9625:     my $srchterm;
 9626:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9627:         if ($srch->{'srchby'} ne '') {
 9628:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9629:         }
 9630:         if ($srch->{'srchin'} ne '') {
 9631:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9632:         }
 9633:         if ($srch->{'srchtype'} ne '') {
 9634:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9635:         }
 9636:         if ($srch->{'srchdomain'} ne '') {
 9637:             $currdom = $srch->{'srchdomain'};
 9638:         }
 9639:         $srchterm = $srch->{'srchterm'};
 9640:     }
 9641:     my %html_lt=&Apache::lonlocal::texthash(
 9642:                     'usr'       => 'Search criteria',
 9643:                     'doma'      => 'Domain/institution to search',
 9644:                     'uname'     => 'username',
 9645:                     'lastname'  => 'last name',
 9646:                     'lastfirst' => 'last name, first name',
 9647:                     'crs'       => 'in this course',
 9648:                     'dom'       => 'in selected LON-CAPA domain', 
 9649:                     'alc'       => 'all LON-CAPA',
 9650:                     'instd'     => 'in institutional directory for selected domain',
 9651:                     'exact'     => 'is',
 9652:                     'contains'  => 'contains',
 9653:                     'begins'    => 'begins with',
 9654:                                        );
 9655:     my %js_lt=&Apache::lonlocal::texthash(
 9656:                     'youm'      => "You must include some text to search for.",
 9657:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9658:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9659:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9660:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9661:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9662:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9663:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9664:                                        );
 9665:     &html_escape(\%html_lt);
 9666:     &js_escape(\%js_lt);
 9667:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9668:     my $srchinsel = ' <select name="srchin">';
 9669: 
 9670:     my @srchins = ('crs','dom','alc','instd');
 9671: 
 9672:     foreach my $option (@srchins) {
 9673:         # FIXME 'alc' option unavailable until 
 9674:         #       loncreateuser::print_user_query_page()
 9675:         #       has been completed.
 9676:         next if ($option eq 'alc');
 9677:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9678:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9679:         if ($curr_selected{'srchin'} eq $option) {
 9680:             $srchinsel .= ' 
 9681:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9682:         } else {
 9683:             $srchinsel .= '
 9684:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9685:         }
 9686:     }
 9687:     $srchinsel .= "\n  </select>\n";
 9688: 
 9689:     my $srchbysel =  ' <select name="srchby">';
 9690:     foreach my $option ('lastname','lastfirst','uname') {
 9691:         if ($curr_selected{'srchby'} eq $option) {
 9692:             $srchbysel .= '
 9693:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9694:         } else {
 9695:             $srchbysel .= '
 9696:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9697:          }
 9698:     }
 9699:     $srchbysel .= "\n  </select>\n";
 9700: 
 9701:     my $srchtypesel = ' <select name="srchtype">';
 9702:     foreach my $option ('begins','contains','exact') {
 9703:         if ($curr_selected{'srchtype'} eq $option) {
 9704:             $srchtypesel .= '
 9705:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9706:         } else {
 9707:             $srchtypesel .= '
 9708:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9709:         }
 9710:     }
 9711:     $srchtypesel .= "\n  </select>\n";
 9712: 
 9713:     my ($newuserscript,$new_user_create);
 9714:     my $context_dom = $env{'request.role.domain'};
 9715:     if ($context eq 'requestcrs') {
 9716:         if ($env{'form.coursedom'} ne '') { 
 9717:             $context_dom = $env{'form.coursedom'};
 9718:         }
 9719:     }
 9720:     if ($forcenewuser) {
 9721:         if (ref($srch) eq 'HASH') {
 9722:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9723:                 if ($cancreate) {
 9724:                     $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>';
 9725:                 } else {
 9726:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9727:                     my %usertypetext = (
 9728:                         official   => 'institutional',
 9729:                         unofficial => 'non-institutional',
 9730:                     );
 9731:                     $new_user_create = '<p class="LC_warning">'
 9732:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9733:                                       .' '
 9734:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9735:                                           ,'<a href="'.$helplink.'">','</a>')
 9736:                                       .'</p><br />';
 9737:                 }
 9738:             }
 9739:         }
 9740: 
 9741:         $newuserscript = <<"ENDSCRIPT";
 9742: 
 9743: function setSearch(createnew,callingForm) {
 9744:     if (createnew == 1) {
 9745:         for (var i=0; i<callingForm.srchby.length; i++) {
 9746:             if (callingForm.srchby.options[i].value == 'uname') {
 9747:                 callingForm.srchby.selectedIndex = i;
 9748:             }
 9749:         }
 9750:         for (var i=0; i<callingForm.srchin.length; i++) {
 9751:             if ( callingForm.srchin.options[i].value == 'dom') {
 9752: 		callingForm.srchin.selectedIndex = i;
 9753:             }
 9754:         }
 9755:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9756:             if (callingForm.srchtype.options[i].value == 'exact') {
 9757:                 callingForm.srchtype.selectedIndex = i;
 9758:             }
 9759:         }
 9760:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9761:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9762:                 callingForm.srchdomain.selectedIndex = i;
 9763:             }
 9764:         }
 9765:     }
 9766: }
 9767: ENDSCRIPT
 9768: 
 9769:     }
 9770: 
 9771:     my $output = <<"END_BLOCK";
 9772: <script type="text/javascript">
 9773: // <![CDATA[
 9774: function validateEntry(callingForm) {
 9775: 
 9776:     var checkok = 1;
 9777:     var srchin;
 9778:     for (var i=0; i<callingForm.srchin.length; i++) {
 9779: 	if ( callingForm.srchin[i].checked ) {
 9780: 	    srchin = callingForm.srchin[i].value;
 9781: 	}
 9782:     }
 9783: 
 9784:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9785:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9786:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9787:     var srchterm =  callingForm.srchterm.value;
 9788:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9789:     var msg = "";
 9790: 
 9791:     if (srchterm == "") {
 9792:         checkok = 0;
 9793:         msg += "$js_lt{'youm'}\\n";
 9794:     }
 9795: 
 9796:     if (srchtype== 'begins') {
 9797:         if (srchterm.length < 2) {
 9798:             checkok = 0;
 9799:             msg += "$js_lt{'thte'}\\n";
 9800:         }
 9801:     }
 9802: 
 9803:     if (srchtype== 'contains') {
 9804:         if (srchterm.length < 3) {
 9805:             checkok = 0;
 9806:             msg += "$js_lt{'thet'}\\n";
 9807:         }
 9808:     }
 9809:     if (srchin == 'instd') {
 9810:         if (srchdomain == '') {
 9811:             checkok = 0;
 9812:             msg += "$js_lt{'yomc'}\\n";
 9813:         }
 9814:     }
 9815:     if (srchin == 'dom') {
 9816:         if (srchdomain == '') {
 9817:             checkok = 0;
 9818:             msg += "$js_lt{'ymcd'}\\n";
 9819:         }
 9820:     }
 9821:     if (srchby == 'lastfirst') {
 9822:         if (srchterm.indexOf(",") == -1) {
 9823:             checkok = 0;
 9824:             msg += "$js_lt{'whus'}\\n";
 9825:         }
 9826:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9827:             checkok = 0;
 9828:             msg += "$js_lt{'whse'}\\n";
 9829:         }
 9830:     }
 9831:     if (checkok == 0) {
 9832:         alert("$js_lt{'thfo'}\\n"+msg);
 9833:         return;
 9834:     }
 9835:     if (checkok == 1) {
 9836:         callingForm.submit();
 9837:     }
 9838: }
 9839: 
 9840: $newuserscript
 9841: 
 9842: // ]]>
 9843: </script>
 9844: 
 9845: $new_user_create
 9846: 
 9847: END_BLOCK
 9848: 
 9849:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9850:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9851:                $domform.
 9852:                &Apache::lonhtmlcommon::row_closure().
 9853:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9854:                $srchbysel.
 9855:                $srchtypesel. 
 9856:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9857:                $srchinsel.
 9858:                &Apache::lonhtmlcommon::row_closure(1). 
 9859:                &Apache::lonhtmlcommon::end_pick_box().
 9860:                '<br />';
 9861:     return $output;
 9862: }
 9863: 
 9864: sub user_rule_check {
 9865:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9866:     my ($response,%inst_response);
 9867:     if (ref($usershash) eq 'HASH') {
 9868:         if (keys(%{$usershash}) > 1) {
 9869:             my (%by_username,%by_id,%userdoms);
 9870:             my $checkid; 
 9871:             if (ref($checks) eq 'HASH') {
 9872:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9873:                     $checkid = 1;
 9874:                 }
 9875:             }
 9876:             foreach my $user (keys(%{$usershash})) {
 9877:                 my ($uname,$udom) = split(/:/,$user);
 9878:                 if ($checkid) {
 9879:                     if (ref($usershash->{$user}) eq 'HASH') {
 9880:                         if ($usershash->{$user}->{'id'} ne '') {
 9881:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
 9882:                             $userdoms{$udom} = 1;
 9883:                             if (ref($inst_results) eq 'HASH') {
 9884:                                 $inst_results->{$uname.':'.$udom} = {};
 9885:                             }
 9886:                         }
 9887:                     }
 9888:                 } else {
 9889:                     $by_username{$udom}{$uname} = 1;
 9890:                     $userdoms{$udom} = 1;
 9891:                     if (ref($inst_results) eq 'HASH') {
 9892:                         $inst_results->{$uname.':'.$udom} = {};
 9893:                     }
 9894:                 }
 9895:             }
 9896:             foreach my $udom (keys(%userdoms)) {
 9897:                 if (!$got_rules->{$udom}) {
 9898:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9899:                                                              ['usercreation'],$udom);
 9900:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9901:                         foreach my $item ('username','id') {
 9902:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9903:                                 $$curr_rules{$udom}{$item} =
 9904:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9905:                             }
 9906:                         }
 9907:                     }
 9908:                     $got_rules->{$udom} = 1;
 9909:                 }
 9910:             }
 9911:             if ($checkid) {
 9912:                 foreach my $udom (keys(%by_id)) {
 9913:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9914:                     if ($outcome eq 'ok') {
 9915:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9916:                             my $uname = $by_id{$udom}{$id};
 9917:                             $inst_response{$uname.':'.$udom} = $outcome;
 9918:                         }
 9919:                         if (ref($results) eq 'HASH') {
 9920:                             foreach my $uname (keys(%{$results})) {
 9921:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9922:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9923:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9924:                                 }
 9925:                             }
 9926:                         }
 9927:                     }
 9928:                 }
 9929:             } else {
 9930:                 foreach my $udom (keys(%by_username)) {
 9931:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9932:                     if ($outcome eq 'ok') {
 9933:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9934:                             $inst_response{$uname.':'.$udom} = $outcome;
 9935:                         }
 9936:                         if (ref($results) eq 'HASH') {
 9937:                             foreach my $uname (keys(%{$results})) {
 9938:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9939:                             }
 9940:                         }
 9941:                     }
 9942:                 }
 9943:             }
 9944:         } elsif (keys(%{$usershash}) == 1) {
 9945:             my $user = (keys(%{$usershash}))[0];
 9946:             my ($uname,$udom) = split(/:/,$user);
 9947:             if (($udom ne '') && ($uname ne '')) {
 9948:                 if (ref($usershash->{$user}) eq 'HASH') {
 9949:                     if (ref($checks) eq 'HASH') {
 9950:                         if (defined($checks->{'username'})) {
 9951:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
 9952:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9953:                         } elsif (defined($checks->{'id'})) {
 9954:                             if ($usershash->{$user}->{'id'} ne '') {
 9955:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9956:                                     &Apache::lonnet::get_instuser($udom,undef,
 9957:                                                                   $usershash->{$user}->{'id'});
 9958:                             } else {
 9959:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9960:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9961:                             }
 9962:                         }
 9963:                     } else {
 9964:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9965:                             &Apache::lonnet::get_instuser($udom,$uname);
 9966:                        return;
 9967:                     }
 9968:                     if (!$got_rules->{$udom}) {
 9969:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9970:                                                                  ['usercreation'],$udom);
 9971:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9972:                             foreach my $item ('username','id') {
 9973:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9974:                                    $$curr_rules{$udom}{$item} = 
 9975:                                        $domconfig{'usercreation'}{$item.'_rule'};
 9976:                                 }
 9977:                             }
 9978:                         }
 9979:                         $got_rules->{$udom} = 1;
 9980:                     }
 9981:                 }
 9982:             } else {
 9983:                 return;
 9984:             }
 9985:         } else {
 9986:             return;
 9987:         }
 9988:         foreach my $user (keys(%{$usershash})) {
 9989:             my ($uname,$udom) = split(/:/,$user);
 9990:             next if (($udom eq '') || ($uname eq ''));
 9991:             my $id;
 9992:             if (ref($inst_results) eq 'HASH') {
 9993:                 if (ref($inst_results->{$user}) eq 'HASH') {
 9994:                     $id = $inst_results->{$user}->{'id'};
 9995:                 }
 9996:             }
 9997:             if ($id eq '') { 
 9998:                 if (ref($usershash->{$user})) {
 9999:                     $id = $usershash->{$user}->{'id'};
10000:                 }
10001:             }
10002:             foreach my $item (keys(%{$checks})) {
10003:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10004:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10005:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10006:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10007:                                                                              $$curr_rules{$udom}{$item});
10008:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10009:                                 if ($rule_check{$rule}) {
10010:                                     $$rulematch{$user}{$item} = $rule;
10011:                                     if ($inst_response{$user} eq 'ok') {
10012:                                         if (ref($inst_results) eq 'HASH') {
10013:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10014:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10015:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10016:                                                 } elsif ($item eq 'id') {
10017:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10018:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10019:                                                     }
10020:                                                 }
10021:                                             }
10022:                                         }
10023:                                     }
10024:                                     last;
10025:                                 }
10026:                             }
10027:                         }
10028:                     }
10029:                 }
10030:             }
10031:         }
10032:     }
10033:     return;
10034: }
10035: 
10036: sub user_rule_formats {
10037:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10038:     my %text = ( 
10039:                  'username' => 'Usernames',
10040:                  'id'       => 'IDs',
10041:                );
10042:     my $output;
10043:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10044:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10045:         if (@{$ruleorder} > 0) {
10046:             $output = '<br />'.
10047:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10048:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10049:                       ' <ul>';
10050:             foreach my $rule (@{$ruleorder}) {
10051:                 if (ref($curr_rules) eq 'ARRAY') {
10052:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10053:                         if (ref($rules->{$rule}) eq 'HASH') {
10054:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10055:                                         $rules->{$rule}{'desc'}.'</li>';
10056:                         }
10057:                     }
10058:                 }
10059:             }
10060:             $output .= '</ul>';
10061:         }
10062:     }
10063:     return $output;
10064: }
10065: 
10066: sub instrule_disallow_msg {
10067:     my ($checkitem,$domdesc,$count,$mode) = @_;
10068:     my $response;
10069:     my %text = (
10070:                   item   => 'username',
10071:                   items  => 'usernames',
10072:                   match  => 'matches',
10073:                   do     => 'does',
10074:                   action => 'a username',
10075:                   one    => 'one',
10076:                );
10077:     if ($count > 1) {
10078:         $text{'item'} = 'usernames';
10079:         $text{'match'} ='match';
10080:         $text{'do'} = 'do';
10081:         $text{'action'} = 'usernames',
10082:         $text{'one'} = 'ones';
10083:     }
10084:     if ($checkitem eq 'id') {
10085:         $text{'items'} = 'IDs';
10086:         $text{'item'} = 'ID';
10087:         $text{'action'} = 'an ID';
10088:         if ($count > 1) {
10089:             $text{'item'} = 'IDs';
10090:             $text{'action'} = 'IDs';
10091:         }
10092:     }
10093:     $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 />';
10094:     if ($mode eq 'upload') {
10095:         if ($checkitem eq 'username') {
10096:             $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'}.");
10097:         } elsif ($checkitem eq 'id') {
10098:             $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.");
10099:         }
10100:     } elsif ($mode eq 'selfcreate') {
10101:         if ($checkitem eq 'id') {
10102:             $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.");
10103:         }
10104:     } else {
10105:         if ($checkitem eq 'username') {
10106:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10107:         } elsif ($checkitem eq 'id') {
10108:             $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.");
10109:         }
10110:     }
10111:     return $response;
10112: }
10113: 
10114: sub personal_data_fieldtitles {
10115:     my %fieldtitles = &Apache::lonlocal::texthash (
10116:                         id => 'Student/Employee ID',
10117:                         permanentemail => 'E-mail address',
10118:                         lastname => 'Last Name',
10119:                         firstname => 'First Name',
10120:                         middlename => 'Middle Name',
10121:                         generation => 'Generation',
10122:                         gen => 'Generation',
10123:                         inststatus => 'Affiliation',
10124:                    );
10125:     return %fieldtitles;
10126: }
10127: 
10128: sub sorted_inst_types {
10129:     my ($dom) = @_;
10130:     my ($usertypes,$order);
10131:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10132:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10133:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10134:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10135:     } else {
10136:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10137:     }
10138:     my $othertitle = &mt('All users');
10139:     if ($env{'request.course.id'}) {
10140:         $othertitle  = &mt('Any users');
10141:     }
10142:     my @types;
10143:     if (ref($order) eq 'ARRAY') {
10144:         @types = @{$order};
10145:     }
10146:     if (@types == 0) {
10147:         if (ref($usertypes) eq 'HASH') {
10148:             @types = sort(keys(%{$usertypes}));
10149:         }
10150:     }
10151:     if (keys(%{$usertypes}) > 0) {
10152:         $othertitle = &mt('Other users');
10153:     }
10154:     return ($othertitle,$usertypes,\@types);
10155: }
10156: 
10157: sub get_institutional_codes {
10158:     my ($settings,$allcourses,$LC_code) = @_;
10159: # Get complete list of course sections to update
10160:     my @currsections = ();
10161:     my @currxlists = ();
10162:     my $coursecode = $$settings{'internal.coursecode'};
10163: 
10164:     if ($$settings{'internal.sectionnums'} ne '') {
10165:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10166:     }
10167: 
10168:     if ($$settings{'internal.crosslistings'} ne '') {
10169:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10170:     }
10171: 
10172:     if (@currxlists > 0) {
10173:         foreach (@currxlists) {
10174:             if (m/^([^:]+):(\w*)$/) {
10175:                 unless (grep/^$1$/,@{$allcourses}) {
10176:                     push @{$allcourses},$1;
10177:                     $$LC_code{$1} = $2;
10178:                 }
10179:             }
10180:         }
10181:     }
10182:  
10183:     if (@currsections > 0) {
10184:         foreach (@currsections) {
10185:             if (m/^(\w+):(\w*)$/) {
10186:                 my $sec = $coursecode.$1;
10187:                 my $lc_sec = $2;
10188:                 unless (grep/^$sec$/,@{$allcourses}) {
10189:                     push @{$allcourses},$sec;
10190:                     $$LC_code{$sec} = $lc_sec;
10191:                 }
10192:             }
10193:         }
10194:     }
10195:     return;
10196: }
10197: 
10198: sub get_standard_codeitems {
10199:     return ('Year','Semester','Department','Number','Section');
10200: }
10201: 
10202: =pod
10203: 
10204: =head1 Slot Helpers
10205: 
10206: =over 4
10207: 
10208: =item * sorted_slots()
10209: 
10210: Sorts an array of slot names in order of an optional sort key,
10211: default sort is by slot start time (earliest first). 
10212: 
10213: Inputs:
10214: 
10215: =over 4
10216: 
10217: slotsarr  - Reference to array of unsorted slot names.
10218: 
10219: slots     - Reference to hash of hash, where outer hash keys are slot names.
10220: 
10221: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10222: 
10223: =back
10224: 
10225: Returns:
10226: 
10227: =over 4
10228: 
10229: sorted   - An array of slot names sorted by a specified sort key 
10230:            (default sort key is start time of the slot).
10231: 
10232: =back
10233: 
10234: =cut
10235: 
10236: 
10237: sub sorted_slots {
10238:     my ($slotsarr,$slots,$sortkey) = @_;
10239:     if ($sortkey eq '') {
10240:         $sortkey = 'starttime';
10241:     }
10242:     my @sorted;
10243:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10244:         @sorted =
10245:             sort {
10246:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10247:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10248:                      }
10249:                      if (ref($slots->{$a})) { return -1;}
10250:                      if (ref($slots->{$b})) { return 1;}
10251:                      return 0;
10252:                  } @{$slotsarr};
10253:     }
10254:     return @sorted;
10255: }
10256: 
10257: =pod
10258: 
10259: =item * get_future_slots()
10260: 
10261: Inputs:
10262: 
10263: =over 4
10264: 
10265: cnum - course number
10266: 
10267: cdom - course domain
10268: 
10269: now - current UNIX time
10270: 
10271: symb - optional symb
10272: 
10273: =back
10274: 
10275: Returns:
10276: 
10277: =over 4
10278: 
10279: sorted_reservable - ref to array of student_schedulable slots currently 
10280:                     reservable, ordered by end date of reservation period.
10281: 
10282: reservable_now - ref to hash of student_schedulable slots currently
10283:                  reservable.
10284: 
10285:     Keys in inner hash are:
10286:     (a) symb: either blank or symb to which slot use is restricted.
10287:     (b) endreserve: end date of reservation period. 
10288: 
10289: sorted_future - ref to array of student_schedulable slots reservable in
10290:                 the future, ordered by start date of reservation period.
10291: 
10292: future_reservable - ref to hash of student_schedulable slots reservable
10293:                     in the future.
10294: 
10295:     Keys in inner hash are:
10296:     (a) symb: either blank or symb to which slot use is restricted.
10297:     (b) startreserve:  start date of reservation period.
10298: 
10299: =back
10300: 
10301: =cut
10302: 
10303: sub get_future_slots {
10304:     my ($cnum,$cdom,$now,$symb) = @_;
10305:     my $map;
10306:     if ($symb) {
10307:         ($map) = &Apache::lonnet::decode_symb($symb);
10308:     }
10309:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10310:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10311:     foreach my $slot (keys(%slots)) {
10312:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10313:         if ($symb) {
10314:             if ($slots{$slot}->{'symb'} ne '') {
10315:                 my $canuse;
10316:                 my %oksymbs;
10317:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10318:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10319:                 if ($oksymbs{$symb}) {
10320:                     $canuse = 1;
10321:                 } else {
10322:                     foreach my $item (@slotsymbs) {
10323:                         if ($item =~ /\.(page|sequence)$/) {
10324:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10325:                             if (($map ne '') && ($map eq $sloturl)) {
10326:                                 $canuse = 1;
10327:                                 last;
10328:                             }
10329:                         }
10330:                     }
10331:                 }
10332:                 next unless ($canuse);
10333:             }
10334:         }
10335:         if (($slots{$slot}->{'starttime'} > $now) &&
10336:             ($slots{$slot}->{'endtime'} > $now)) {
10337:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10338:                 my $userallowed = 0;
10339:                 if ($slots{$slot}->{'allowedsections'}) {
10340:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10341:                     if (!defined($env{'request.role.sec'})
10342:                         && grep(/^No section assigned$/,@allowed_sec)) {
10343:                         $userallowed=1;
10344:                     } else {
10345:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10346:                             $userallowed=1;
10347:                         }
10348:                     }
10349:                     unless ($userallowed) {
10350:                         if (defined($env{'request.course.groups'})) {
10351:                             my @groups = split(/:/,$env{'request.course.groups'});
10352:                             foreach my $group (@groups) {
10353:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10354:                                     $userallowed=1;
10355:                                     last;
10356:                                 }
10357:                             }
10358:                         }
10359:                     }
10360:                 }
10361:                 if ($slots{$slot}->{'allowedusers'}) {
10362:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10363:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10364:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10365:                         $userallowed = 1;
10366:                     }
10367:                 }
10368:                 next unless($userallowed);
10369:             }
10370:             my $startreserve = $slots{$slot}->{'startreserve'};
10371:             my $endreserve = $slots{$slot}->{'endreserve'};
10372:             my $symb = $slots{$slot}->{'symb'};
10373:             if (($startreserve < $now) &&
10374:                 (!$endreserve || $endreserve > $now)) {
10375:                 my $lastres = $endreserve;
10376:                 if (!$lastres) {
10377:                     $lastres = $slots{$slot}->{'starttime'};
10378:                 }
10379:                 $reservable_now{$slot} = {
10380:                                            symb       => $symb,
10381:                                            endreserve => $lastres
10382:                                          };
10383:             } elsif (($startreserve > $now) &&
10384:                      (!$endreserve || $endreserve > $startreserve)) {
10385:                 $future_reservable{$slot} = {
10386:                                               symb         => $symb,
10387:                                               startreserve => $startreserve
10388:                                             };
10389:             }
10390:         }
10391:     }
10392:     my @unsorted_reservable = keys(%reservable_now);
10393:     if (@unsorted_reservable > 0) {
10394:         @sorted_reservable = 
10395:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10396:     }
10397:     my @unsorted_future = keys(%future_reservable);
10398:     if (@unsorted_future > 0) {
10399:         @sorted_future =
10400:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10401:     }
10402:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10403: }
10404: 
10405: =pod
10406: 
10407: =back
10408: 
10409: =head1 HTTP Helpers
10410: 
10411: =over 4
10412: 
10413: =item * &get_unprocessed_cgi($query,$possible_names)
10414: 
10415: Modify the %env hash to contain unprocessed CGI form parameters held in
10416: $query.  The parameters listed in $possible_names (an array reference),
10417: will be set in $env{'form.name'} if they do not already exist.
10418: 
10419: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10420: $possible_names is an ref to an array of form element names.  As an example:
10421: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10422: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10423: 
10424: =cut
10425: 
10426: sub get_unprocessed_cgi {
10427:   my ($query,$possible_names)= @_;
10428:   # $Apache::lonxml::debug=1;
10429:   foreach my $pair (split(/&/,$query)) {
10430:     my ($name, $value) = split(/=/,$pair);
10431:     $name = &unescape($name);
10432:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10433:       $value =~ tr/+/ /;
10434:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10435:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10436:     }
10437:   }
10438: }
10439: 
10440: =pod
10441: 
10442: =item * &cacheheader() 
10443: 
10444: returns cache-controlling header code
10445: 
10446: =cut
10447: 
10448: sub cacheheader {
10449:     unless ($env{'request.method'} eq 'GET') { return ''; }
10450:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10451:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10452:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10453:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10454:     return $output;
10455: }
10456: 
10457: =pod
10458: 
10459: =item * &no_cache($r) 
10460: 
10461: specifies header code to not have cache
10462: 
10463: =cut
10464: 
10465: sub no_cache {
10466:     my ($r) = @_;
10467:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10468: 	$env{'request.method'} ne 'GET') { return ''; }
10469:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10470:     $r->no_cache(1);
10471:     $r->header_out("Expires" => $date);
10472:     $r->header_out("Pragma" => "no-cache");
10473: }
10474: 
10475: sub content_type {
10476:     my ($r,$type,$charset) = @_;
10477:     if ($r) {
10478: 	#  Note that printout.pl calls this with undef for $r.
10479: 	&no_cache($r);
10480:     }
10481:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10482:     unless ($charset) {
10483: 	$charset=&Apache::lonlocal::current_encoding;
10484:     }
10485:     if ($charset) { $type.='; charset='.$charset; }
10486:     if ($r) {
10487: 	$r->content_type($type);
10488:     } else {
10489: 	print("Content-type: $type\n\n");
10490:     }
10491: }
10492: 
10493: =pod
10494: 
10495: =item * &add_to_env($name,$value) 
10496: 
10497: adds $name to the %env hash with value
10498: $value, if $name already exists, the entry is converted to an array
10499: reference and $value is added to the array.
10500: 
10501: =cut
10502: 
10503: sub add_to_env {
10504:   my ($name,$value)=@_;
10505:   if (defined($env{$name})) {
10506:     if (ref($env{$name})) {
10507:       #already have multiple values
10508:       push(@{ $env{$name} },$value);
10509:     } else {
10510:       #first time seeing multiple values, convert hash entry to an arrayref
10511:       my $first=$env{$name};
10512:       undef($env{$name});
10513:       push(@{ $env{$name} },$first,$value);
10514:     }
10515:   } else {
10516:     $env{$name}=$value;
10517:   }
10518: }
10519: 
10520: =pod
10521: 
10522: =item * &get_env_multiple($name) 
10523: 
10524: gets $name from the %env hash, it seemlessly handles the cases where multiple
10525: values may be defined and end up as an array ref.
10526: 
10527: returns an array of values
10528: 
10529: =cut
10530: 
10531: sub get_env_multiple {
10532:     my ($name) = @_;
10533:     my @values;
10534:     if (defined($env{$name})) {
10535:         # exists is it an array
10536:         if (ref($env{$name})) {
10537:             @values=@{ $env{$name} };
10538:         } else {
10539:             $values[0]=$env{$name};
10540:         }
10541:     }
10542:     return(@values);
10543: }
10544: 
10545: sub ask_for_embedded_content {
10546:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10547:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10548:         %currsubfile,%unused,$rem);
10549:     my $counter = 0;
10550:     my $numnew = 0;
10551:     my $numremref = 0;
10552:     my $numinvalid = 0;
10553:     my $numpathchg = 0;
10554:     my $numexisting = 0;
10555:     my $numunused = 0;
10556:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10557:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10558:     my $heading = &mt('Upload embedded files');
10559:     my $buttontext = &mt('Upload');
10560: 
10561:     if ($env{'request.course.id'}) {
10562:         if ($actionurl eq '/adm/dependencies') {
10563:             $navmap = Apache::lonnavmaps::navmap->new();
10564:         }
10565:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10566:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10567:     }
10568:     if (($actionurl eq '/adm/portfolio') || 
10569:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10570:         my $current_path='/';
10571:         if ($env{'form.currentpath'}) {
10572:             $current_path = $env{'form.currentpath'};
10573:         }
10574:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10575:             $udom = $cdom;
10576:             $uname = $cnum;
10577:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10578:         } else {
10579:             $udom = $env{'user.domain'};
10580:             $uname = $env{'user.name'};
10581:             $url = '/userfiles/portfolio';
10582:         }
10583:         $toplevel = $url.'/';
10584:         $url .= $current_path;
10585:         $getpropath = 1;
10586:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10587:              ($actionurl eq '/adm/imsimport')) { 
10588:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10589:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10590:         $toplevel = $url;
10591:         if ($rest ne '') {
10592:             $url .= $rest;
10593:         }
10594:     } elsif ($actionurl eq '/adm/coursedocs') {
10595:         if (ref($args) eq 'HASH') {
10596:             $url = $args->{'docs_url'};
10597:             $toplevel = $url;
10598:             if ($args->{'context'} eq 'paste') {
10599:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10600:                 ($path) = 
10601:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10602:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10603:                 $fileloc =~ s{^/}{};
10604:             }
10605:         }
10606:     } elsif ($actionurl eq '/adm/dependencies')  {
10607:         if ($env{'request.course.id'} ne '') {
10608:             if (ref($args) eq 'HASH') {
10609:                 $url = $args->{'docs_url'};
10610:                 $title = $args->{'docs_title'};
10611:                 $toplevel = $url; 
10612:                 unless ($toplevel =~ m{^/}) {
10613:                     $toplevel = "/$url";
10614:                 }
10615:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10616:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10617:                     $path = $1;
10618:                 } else {
10619:                     ($path) =
10620:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10621:                 }
10622:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10623:                     $fileloc = $toplevel;
10624:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10625:                     my ($udom,$uname,$fname) =
10626:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10627:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10628:                 } else {
10629:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10630:                 }
10631:                 $fileloc =~ s{^/}{};
10632:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10633:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10634:             }
10635:         }
10636:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10637:         $udom = $cdom;
10638:         $uname = $cnum;
10639:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10640:         $toplevel = $url;
10641:         $path = $url;
10642:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10643:         $fileloc =~ s{^/}{};
10644:     }
10645:     foreach my $file (keys(%{$allfiles})) {
10646:         my $embed_file;
10647:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10648:             $embed_file = $1;
10649:         } else {
10650:             $embed_file = $file;
10651:         }
10652:         my ($absolutepath,$cleaned_file);
10653:         if ($embed_file =~ m{^\w+://}) {
10654:             $cleaned_file = $embed_file;
10655:             $newfiles{$cleaned_file} = 1;
10656:             $mapping{$cleaned_file} = $embed_file;
10657:         } else {
10658:             $cleaned_file = &clean_path($embed_file);
10659:             if ($embed_file =~ m{^/}) {
10660:                 $absolutepath = $embed_file;
10661:             }
10662:             if ($cleaned_file =~ m{/}) {
10663:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10664:                 $path = &check_for_traversal($path,$url,$toplevel);
10665:                 my $item = $fname;
10666:                 if ($path ne '') {
10667:                     $item = $path.'/'.$fname;
10668:                     $subdependencies{$path}{$fname} = 1;
10669:                 } else {
10670:                     $dependencies{$item} = 1;
10671:                 }
10672:                 if ($absolutepath) {
10673:                     $mapping{$item} = $absolutepath;
10674:                 } else {
10675:                     $mapping{$item} = $embed_file;
10676:                 }
10677:             } else {
10678:                 $dependencies{$embed_file} = 1;
10679:                 if ($absolutepath) {
10680:                     $mapping{$cleaned_file} = $absolutepath;
10681:                 } else {
10682:                     $mapping{$cleaned_file} = $embed_file;
10683:                 }
10684:             }
10685:         }
10686:     }
10687:     my $dirptr = 16384;
10688:     foreach my $path (keys(%subdependencies)) {
10689:         $currsubfile{$path} = {};
10690:         if (($actionurl eq '/adm/portfolio') || 
10691:             ($actionurl eq '/adm/coursegrp_portfolio')) {
10692:             my ($sublistref,$listerror) =
10693:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10694:             if (ref($sublistref) eq 'ARRAY') {
10695:                 foreach my $line (@{$sublistref}) {
10696:                     my ($file_name,$rest) = split(/\&/,$line,2);
10697:                     $currsubfile{$path}{$file_name} = 1;
10698:                 }
10699:             }
10700:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10701:             if (opendir(my $dir,$url.'/'.$path)) {
10702:                 my @subdir_list = grep(!/^\./,readdir($dir));
10703:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10704:             }
10705:         } elsif (($actionurl eq '/adm/dependencies') ||
10706:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10707:                   ($args->{'context'} eq 'paste')) ||
10708:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10709:             if ($env{'request.course.id'} ne '') {
10710:                 my $dir;
10711:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10712:                     $dir = $fileloc;
10713:                 } else {
10714:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10715:                 }
10716:                 if ($dir ne '') {
10717:                     my ($sublistref,$listerror) =
10718:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10719:                     if (ref($sublistref) eq 'ARRAY') {
10720:                         foreach my $line (@{$sublistref}) {
10721:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10722:                                 undef,$mtime)=split(/\&/,$line,12);
10723:                             unless (($testdir&$dirptr) ||
10724:                                     ($file_name =~ /^\.\.?$/)) {
10725:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10726:                             }
10727:                         }
10728:                     }
10729:                 }
10730:             }
10731:         }
10732:         foreach my $file (keys(%{$subdependencies{$path}})) {
10733:             if (exists($currsubfile{$path}{$file})) {
10734:                 my $item = $path.'/'.$file;
10735:                 unless ($mapping{$item} eq $item) {
10736:                     $pathchanges{$item} = 1;
10737:                 }
10738:                 $existing{$item} = 1;
10739:                 $numexisting ++;
10740:             } else {
10741:                 $newfiles{$path.'/'.$file} = 1;
10742:             }
10743:         }
10744:         if ($actionurl eq '/adm/dependencies') {
10745:             foreach my $path (keys(%currsubfile)) {
10746:                 if (ref($currsubfile{$path}) eq 'HASH') {
10747:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10748:                          unless ($subdependencies{$path}{$file}) {
10749:                              next if (($rem ne '') &&
10750:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10751:                                        (ref($navmap) &&
10752:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10753:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10754:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10755:                              $unused{$path.'/'.$file} = 1; 
10756:                          }
10757:                     }
10758:                 }
10759:             }
10760:         }
10761:     }
10762:     my %currfile;
10763:     if (($actionurl eq '/adm/portfolio') ||
10764:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10765:         my ($dirlistref,$listerror) =
10766:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10767:         if (ref($dirlistref) eq 'ARRAY') {
10768:             foreach my $line (@{$dirlistref}) {
10769:                 my ($file_name,$rest) = split(/\&/,$line,2);
10770:                 $currfile{$file_name} = 1;
10771:             }
10772:         }
10773:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10774:         if (opendir(my $dir,$url)) {
10775:             my @dir_list = grep(!/^\./,readdir($dir));
10776:             map {$currfile{$_} = 1;} @dir_list;
10777:         }
10778:     } elsif (($actionurl eq '/adm/dependencies') ||
10779:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10780:               ($args->{'context'} eq 'paste')) ||
10781:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10782:         if ($env{'request.course.id'} ne '') {
10783:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10784:             if ($dir ne '') {
10785:                 my ($dirlistref,$listerror) =
10786:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10787:                 if (ref($dirlistref) eq 'ARRAY') {
10788:                     foreach my $line (@{$dirlistref}) {
10789:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10790:                             $size,undef,$mtime)=split(/\&/,$line,12);
10791:                         unless (($testdir&$dirptr) ||
10792:                                 ($file_name =~ /^\.\.?$/)) {
10793:                             $currfile{$file_name} = [$size,$mtime];
10794:                         }
10795:                     }
10796:                 }
10797:             }
10798:         }
10799:     }
10800:     foreach my $file (keys(%dependencies)) {
10801:         if (exists($currfile{$file})) {
10802:             unless ($mapping{$file} eq $file) {
10803:                 $pathchanges{$file} = 1;
10804:             }
10805:             $existing{$file} = 1;
10806:             $numexisting ++;
10807:         } else {
10808:             $newfiles{$file} = 1;
10809:         }
10810:     }
10811:     foreach my $file (keys(%currfile)) {
10812:         unless (($file eq $filename) ||
10813:                 ($file eq $filename.'.bak') ||
10814:                 ($dependencies{$file})) {
10815:             if ($actionurl eq '/adm/dependencies') {
10816:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10817:                     next if (($rem ne '') &&
10818:                              (($env{"httpref.$rem".$file} ne '') ||
10819:                               (ref($navmap) &&
10820:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10821:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10822:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10823:                 }
10824:             }
10825:             $unused{$file} = 1;
10826:         }
10827:     }
10828:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10829:         ($args->{'context'} eq 'paste')) {
10830:         $counter = scalar(keys(%existing));
10831:         $numpathchg = scalar(keys(%pathchanges));
10832:         return ($output,$counter,$numpathchg,\%existing);
10833:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
10834:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10835:         $counter = scalar(keys(%existing));
10836:         $numpathchg = scalar(keys(%pathchanges));
10837:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10838:     }
10839:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10840:         if ($actionurl eq '/adm/dependencies') {
10841:             next if ($embed_file =~ m{^\w+://});
10842:         }
10843:         $upload_output .= &start_data_table_row().
10844:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10845:                           '<span class="LC_filename">'.$embed_file.'</span>';
10846:         unless ($mapping{$embed_file} eq $embed_file) {
10847:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10848:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10849:         }
10850:         $upload_output .= '</td>';
10851:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10852:             $upload_output.='<td align="right">'.
10853:                             '<span class="LC_info LC_fontsize_medium">'.
10854:                             &mt("URL points to web address").'</span>';
10855:             $numremref++;
10856:         } elsif ($args->{'error_on_invalid_names'}
10857:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10858:             $upload_output.='<td align="right"><span class="LC_warning">'.
10859:                             &mt('Invalid characters').'</span>';
10860:             $numinvalid++;
10861:         } else {
10862:             $upload_output .= '<td>'.
10863:                               &embedded_file_element('upload_embedded',$counter,
10864:                                                      $embed_file,\%mapping,
10865:                                                      $allfiles,$codebase,'upload');
10866:             $counter ++;
10867:             $numnew ++;
10868:         }
10869:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10870:     }
10871:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10872:         if ($actionurl eq '/adm/dependencies') {
10873:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10874:             $modify_output .= &start_data_table_row().
10875:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10876:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10877:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10878:                               '<td>'.$size.'</td>'.
10879:                               '<td>'.$mtime.'</td>'.
10880:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10881:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10882:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10883:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10884:                               &embedded_file_element('upload_embedded',$counter,
10885:                                                      $embed_file,\%mapping,
10886:                                                      $allfiles,$codebase,'modify').
10887:                               '</div></td>'.
10888:                               &end_data_table_row()."\n";
10889:             $counter ++;
10890:         } else {
10891:             $upload_output .= &start_data_table_row().
10892:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10893:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10894:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10895:                               &Apache::loncommon::end_data_table_row()."\n";
10896:         }
10897:     }
10898:     my $delidx = $counter;
10899:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10900:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10901:         $delete_output .= &start_data_table_row().
10902:                           '<td><img src="'.&icon($oldfile).'" />'.
10903:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10904:                           '<td>'.$size.'</td>'.
10905:                           '<td>'.$mtime.'</td>'.
10906:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10907:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10908:                           &embedded_file_element('upload_embedded',$delidx,
10909:                                                  $oldfile,\%mapping,$allfiles,
10910:                                                  $codebase,'delete').'</td>'.
10911:                           &end_data_table_row()."\n"; 
10912:         $numunused ++;
10913:         $delidx ++;
10914:     }
10915:     if ($upload_output) {
10916:         $upload_output = &start_data_table().
10917:                          $upload_output.
10918:                          &end_data_table()."\n";
10919:     }
10920:     if ($modify_output) {
10921:         $modify_output = &start_data_table().
10922:                          &start_data_table_header_row().
10923:                          '<th>'.&mt('File').'</th>'.
10924:                          '<th>'.&mt('Size (KB)').'</th>'.
10925:                          '<th>'.&mt('Modified').'</th>'.
10926:                          '<th>'.&mt('Upload replacement?').'</th>'.
10927:                          &end_data_table_header_row().
10928:                          $modify_output.
10929:                          &end_data_table()."\n";
10930:     }
10931:     if ($delete_output) {
10932:         $delete_output = &start_data_table().
10933:                          &start_data_table_header_row().
10934:                          '<th>'.&mt('File').'</th>'.
10935:                          '<th>'.&mt('Size (KB)').'</th>'.
10936:                          '<th>'.&mt('Modified').'</th>'.
10937:                          '<th>'.&mt('Delete?').'</th>'.
10938:                          &end_data_table_header_row().
10939:                          $delete_output.
10940:                          &end_data_table()."\n";
10941:     }
10942:     my $applies = 0;
10943:     if ($numremref) {
10944:         $applies ++;
10945:     }
10946:     if ($numinvalid) {
10947:         $applies ++;
10948:     }
10949:     if ($numexisting) {
10950:         $applies ++;
10951:     }
10952:     if ($counter || $numunused) {
10953:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10954:                   ' method="post" enctype="multipart/form-data">'."\n".
10955:                   $state.'<h3>'.$heading.'</h3>'; 
10956:         if ($actionurl eq '/adm/dependencies') {
10957:             if ($numnew) {
10958:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10959:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10960:                            $upload_output.'<br />'."\n";
10961:             }
10962:             if ($numexisting) {
10963:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10964:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10965:                            $modify_output.'<br />'."\n";
10966:                            $buttontext = &mt('Save changes');
10967:             }
10968:             if ($numunused) {
10969:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10970:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10971:                            $delete_output.'<br />'."\n";
10972:                            $buttontext = &mt('Save changes');
10973:             }
10974:         } else {
10975:             $output .= $upload_output.'<br />'."\n";
10976:         }
10977:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10978:                    $counter.'" />'."\n";
10979:         if ($actionurl eq '/adm/dependencies') { 
10980:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10981:                        $numnew.'" />'."\n";
10982:         } elsif ($actionurl eq '') {
10983:             $output .=  '<input type="hidden" name="phase" value="three" />';
10984:         }
10985:     } elsif ($applies) {
10986:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10987:         if ($applies > 1) {
10988:             $output .=  
10989:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10990:             if ($numremref) {
10991:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10992:             }
10993:             if ($numinvalid) {
10994:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10995:             }
10996:             if ($numexisting) {
10997:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10998:             }
10999:             $output .= '</ul><br />';
11000:         } elsif ($numremref) {
11001:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11002:         } elsif ($numinvalid) {
11003:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11004:         } elsif ($numexisting) {
11005:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11006:         }
11007:         $output .= $upload_output.'<br />';
11008:     }
11009:     my ($pathchange_output,$chgcount);
11010:     $chgcount = $counter;
11011:     if (keys(%pathchanges) > 0) {
11012:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11013:             if ($counter) {
11014:                 $output .= &embedded_file_element('pathchange',$chgcount,
11015:                                                   $embed_file,\%mapping,
11016:                                                   $allfiles,$codebase,'change');
11017:             } else {
11018:                 $pathchange_output .= 
11019:                     &start_data_table_row().
11020:                     '<td><input type ="checkbox" name="namechange" value="'.
11021:                     $chgcount.'" checked="checked" /></td>'.
11022:                     '<td>'.$mapping{$embed_file}.'</td>'.
11023:                     '<td>'.$embed_file.
11024:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11025:                                            \%mapping,$allfiles,$codebase,'change').
11026:                     '</td>'.&end_data_table_row();
11027:             }
11028:             $numpathchg ++;
11029:             $chgcount ++;
11030:         }
11031:     }
11032:     if (($counter) || ($numunused)) {
11033:         if ($numpathchg) {
11034:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11035:                        $numpathchg.'" />'."\n";
11036:         }
11037:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11038:             ($actionurl eq '/adm/imsimport')) {
11039:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11040:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11041:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11042:         } elsif ($actionurl eq '/adm/dependencies') {
11043:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11044:         }
11045:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11046:     } elsif ($numpathchg) {
11047:         my %pathchange = ();
11048:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11049:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11050:             $output .= '<p>'.&mt('or').'</p>'; 
11051:         }
11052:     }
11053:     return ($output,$counter,$numpathchg);
11054: }
11055: 
11056: =pod
11057: 
11058: =item * clean_path($name)
11059: 
11060: Performs clean-up of directories, subdirectories and filename in an
11061: embedded object, referenced in an HTML file which is being uploaded
11062: to a course or portfolio, where 
11063: "Upload embedded images/multimedia files if HTML file" checkbox was
11064: checked.
11065: 
11066: Clean-up is similar to replacements in lonnet::clean_filename()
11067: except each / between sub-directory and next level is preserved.
11068: 
11069: =cut
11070: 
11071: sub clean_path {
11072:     my ($embed_file) = @_;
11073:     $embed_file =~s{^/+}{};
11074:     my @contents;
11075:     if ($embed_file =~ m{/}) {
11076:         @contents = split(/\//,$embed_file);
11077:     } else {
11078:         @contents = ($embed_file);
11079:     }
11080:     my $lastidx = scalar(@contents)-1;
11081:     for (my $i=0; $i<=$lastidx; $i++) { 
11082:         $contents[$i]=~s{\\}{/}g;
11083:         $contents[$i]=~s/\s+/\_/g;
11084:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11085:         if ($i == $lastidx) {
11086:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11087:         }
11088:     }
11089:     if ($lastidx > 0) {
11090:         return join('/',@contents);
11091:     } else {
11092:         return $contents[0];
11093:     }
11094: }
11095: 
11096: sub embedded_file_element {
11097:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11098:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11099:                    (ref($codebase) eq 'HASH'));
11100:     my $output;
11101:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11102:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11103:     }
11104:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11105:                &escape($embed_file).'" />';
11106:     unless (($context eq 'upload_embedded') && 
11107:             ($mapping->{$embed_file} eq $embed_file)) {
11108:         $output .='
11109:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11110:     }
11111:     my $attrib;
11112:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11113:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11114:     }
11115:     $output .=
11116:         "\n\t\t".
11117:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11118:         $attrib.'" />';
11119:     if (exists($codebase->{$mapping->{$embed_file}})) {
11120:         $output .=
11121:             "\n\t\t".
11122:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11123:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11124:     }
11125:     return $output;
11126: }
11127: 
11128: sub get_dependency_details {
11129:     my ($currfile,$currsubfile,$embed_file) = @_;
11130:     my ($size,$mtime,$showsize,$showmtime);
11131:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11132:         if ($embed_file =~ m{/}) {
11133:             my ($path,$fname) = split(/\//,$embed_file);
11134:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11135:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11136:             }
11137:         } else {
11138:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11139:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11140:             }
11141:         }
11142:         $showsize = $size/1024.0;
11143:         $showsize = sprintf("%.1f",$showsize);
11144:         if ($mtime > 0) {
11145:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11146:         }
11147:     }
11148:     return ($showsize,$showmtime);
11149: }
11150: 
11151: sub ask_embedded_js {
11152:     return <<"END";
11153: <script type="text/javascript"">
11154: // <![CDATA[
11155: function toggleBrowse(counter) {
11156:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11157:     var fileid = document.getElementById('embedded_item_'+counter);
11158:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11159:     if (chkboxid.checked == true) {
11160:         uploaddivid.style.display='block';
11161:     } else {
11162:         uploaddivid.style.display='none';
11163:         fileid.value = '';
11164:     }
11165: }
11166: // ]]>
11167: </script>
11168: 
11169: END
11170: }
11171: 
11172: sub upload_embedded {
11173:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11174:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11175:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11176:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11177:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11178:         my $orig_uploaded_filename =
11179:             $env{'form.embedded_item_'.$i.'.filename'};
11180:         foreach my $type ('orig','ref','attrib','codebase') {
11181:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11182:                 $env{'form.embedded_'.$type.'_'.$i} =
11183:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11184:             }
11185:         }
11186:         my ($path,$fname) =
11187:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11188:         # no path, whole string is fname
11189:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11190:         $fname = &Apache::lonnet::clean_filename($fname);
11191:         # See if there is anything left
11192:         next if ($fname eq '');
11193: 
11194:         # Check if file already exists as a file or directory.
11195:         my ($state,$msg);
11196:         if ($context eq 'portfolio') {
11197:             my $port_path = $dirpath;
11198:             if ($group ne '') {
11199:                 $port_path = "groups/$group/$port_path";
11200:             }
11201:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11202:                                               $fname,$group,'embedded_item_'.$i,
11203:                                               $dir_root,$port_path,$disk_quota,
11204:                                               $current_disk_usage,$uname,$udom);
11205:             if ($state eq 'will_exceed_quota'
11206:                 || $state eq 'file_locked') {
11207:                 $output .= $msg;
11208:                 next;
11209:             }
11210:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11211:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11212:             if ($state eq 'exists') {
11213:                 $output .= $msg;
11214:                 next;
11215:             }
11216:         }
11217:         # Check if extension is valid
11218:         if (($fname =~ /\.(\w+)$/) &&
11219:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11220:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11221:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11222:             next;
11223:         } elsif (($fname =~ /\.(\w+)$/) &&
11224:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11225:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11226:             next;
11227:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11228:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11229:             next;
11230:         }
11231:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11232:         my $subdir = $path;
11233:         $subdir =~ s{/+$}{};
11234:         if ($context eq 'portfolio') {
11235:             my $result;
11236:             if ($state eq 'existingfile') {
11237:                 $result=
11238:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11239:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11240:             } else {
11241:                 $result=
11242:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11243:                                                     $dirpath.
11244:                                                     $env{'form.currentpath'}.$subdir);
11245:                 if ($result !~ m|^/uploaded/|) {
11246:                     $output .= '<span class="LC_error">'
11247:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11248:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11249:                                .'</span><br />';
11250:                     next;
11251:                 } else {
11252:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11253:                                $path.$fname.'</span>').'<br />';     
11254:                 }
11255:             }
11256:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11257:             my $extendedsubdir = $dirpath.'/'.$subdir;
11258:             $extendedsubdir =~ s{/+$}{};
11259:             my $result =
11260:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11261:             if ($result !~ m|^/uploaded/|) {
11262:                 $output .= '<span class="LC_error">'
11263:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11264:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11265:                            .'</span><br />';
11266:                     next;
11267:             } else {
11268:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11269:                            $path.$fname.'</span>').'<br />';
11270:                 if ($context eq 'syllabus') {
11271:                     &Apache::lonnet::make_public_indefinitely($result);
11272:                 }
11273:             }
11274:         } else {
11275: # Save the file
11276:             my $target = $env{'form.embedded_item_'.$i};
11277:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11278:             my $dest = $fullpath.$fname;
11279:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11280:             my @parts=split(/\//,"$dirpath/$path");
11281:             my $count;
11282:             my $filepath = $dir_root;
11283:             foreach my $subdir (@parts) {
11284:                 $filepath .= "/$subdir";
11285:                 if (!-e $filepath) {
11286:                     mkdir($filepath,0770);
11287:                 }
11288:             }
11289:             my $fh;
11290:             if (!open($fh,'>'.$dest)) {
11291:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11292:                 $output .= '<span class="LC_error">'.
11293:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11294:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11295:                            '</span><br />';
11296:             } else {
11297:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11298:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11299:                     $output .= '<span class="LC_error">'.
11300:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11301:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11302:                               '</span><br />';
11303:                 } else {
11304:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11305:                                $url.'</span>').'<br />';
11306:                     unless ($context eq 'testbank') {
11307:                         $footer .= &mt('View embedded file: [_1]',
11308:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11309:                     }
11310:                 }
11311:                 close($fh);
11312:             }
11313:         }
11314:         if ($env{'form.embedded_ref_'.$i}) {
11315:             $pathchange{$i} = 1;
11316:         }
11317:     }
11318:     if ($output) {
11319:         $output = '<p>'.$output.'</p>';
11320:     }
11321:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11322:     $returnflag = 'ok';
11323:     my $numpathchgs = scalar(keys(%pathchange));
11324:     if ($numpathchgs > 0) {
11325:         if ($context eq 'portfolio') {
11326:             $output .= '<p>'.&mt('or').'</p>';
11327:         } elsif ($context eq 'testbank') {
11328:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11329:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11330:             $returnflag = 'modify_orightml';
11331:         }
11332:     }
11333:     return ($output.$footer,$returnflag,$numpathchgs);
11334: }
11335: 
11336: sub modify_html_form {
11337:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11338:     my $end = 0;
11339:     my $modifyform;
11340:     if ($context eq 'upload_embedded') {
11341:         return unless (ref($pathchange) eq 'HASH');
11342:         if ($env{'form.number_embedded_items'}) {
11343:             $end += $env{'form.number_embedded_items'};
11344:         }
11345:         if ($env{'form.number_pathchange_items'}) {
11346:             $end += $env{'form.number_pathchange_items'};
11347:         }
11348:         if ($end) {
11349:             for (my $i=0; $i<$end; $i++) {
11350:                 if ($i < $env{'form.number_embedded_items'}) {
11351:                     next unless($pathchange->{$i});
11352:                 }
11353:                 $modifyform .=
11354:                     &start_data_table_row().
11355:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11356:                     'checked="checked" /></td>'.
11357:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11358:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11359:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11360:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11361:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11362:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11363:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11364:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11365:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11366:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11367:                     &end_data_table_row();
11368:             }
11369:         }
11370:     } else {
11371:         $modifyform = $pathchgtable;
11372:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11373:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11374:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11375:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11376:         }
11377:     }
11378:     if ($modifyform) {
11379:         if ($actionurl eq '/adm/dependencies') {
11380:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11381:         }
11382:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11383:                '<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".
11384:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11385:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11386:                '</ol></p>'."\n".'<p>'.
11387:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11388:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11389:                &start_data_table()."\n".
11390:                &start_data_table_header_row().
11391:                '<th>'.&mt('Change?').'</th>'.
11392:                '<th>'.&mt('Current reference').'</th>'.
11393:                '<th>'.&mt('Required reference').'</th>'.
11394:                &end_data_table_header_row()."\n".
11395:                $modifyform.
11396:                &end_data_table().'<br />'."\n".$hiddenstate.
11397:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11398:                '</form>'."\n";
11399:     }
11400:     return;
11401: }
11402: 
11403: sub modify_html_refs {
11404:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11405:     my $container;
11406:     if ($context eq 'portfolio') {
11407:         $container = $env{'form.container'};
11408:     } elsif ($context eq 'coursedoc') {
11409:         $container = $env{'form.primaryurl'};
11410:     } elsif ($context eq 'manage_dependencies') {
11411:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11412:         $container = "/$container";
11413:     } elsif ($context eq 'syllabus') {
11414:         $container = $url;
11415:     } else {
11416:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11417:     }
11418:     my (%allfiles,%codebase,$output,$content);
11419:     my @changes = &get_env_multiple('form.namechange');
11420:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11421:         if (wantarray) {
11422:             return ('',0,0); 
11423:         } else {
11424:             return;
11425:         }
11426:     }
11427:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11428:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11429:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11430:             if (wantarray) {
11431:                 return ('',0,0);
11432:             } else {
11433:                 return;
11434:             }
11435:         } 
11436:         $content = &Apache::lonnet::getfile($container);
11437:         if ($content eq '-1') {
11438:             if (wantarray) {
11439:                 return ('',0,0);
11440:             } else {
11441:                 return;
11442:             }
11443:         }
11444:     } else {
11445:         unless ($container =~ /^\Q$dir_root\E/) {
11446:             if (wantarray) {
11447:                 return ('',0,0);
11448:             } else {
11449:                 return;
11450:             }
11451:         } 
11452:         if (open(my $fh,"<$container")) {
11453:             $content = join('', <$fh>);
11454:             close($fh);
11455:         } else {
11456:             if (wantarray) {
11457:                 return ('',0,0);
11458:             } else {
11459:                 return;
11460:             }
11461:         }
11462:     }
11463:     my ($count,$codebasecount) = (0,0);
11464:     my $mm = new File::MMagic;
11465:     my $mime_type = $mm->checktype_contents($content);
11466:     if ($mime_type eq 'text/html') {
11467:         my $parse_result = 
11468:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11469:                                                     \%codebase,\$content);
11470:         if ($parse_result eq 'ok') {
11471:             foreach my $i (@changes) {
11472:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11473:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11474:                 if ($allfiles{$ref}) {
11475:                     my $newname =  $orig;
11476:                     my ($attrib_regexp,$codebase);
11477:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11478:                     if ($attrib_regexp =~ /:/) {
11479:                         $attrib_regexp =~ s/\:/|/g;
11480:                     }
11481:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11482:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11483:                         $count += $numchg;
11484:                         $allfiles{$newname} = $allfiles{$ref};
11485:                         delete($allfiles{$ref});
11486:                     }
11487:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11488:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11489:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11490:                         $codebasecount ++;
11491:                     }
11492:                 }
11493:             }
11494:             my $skiprewrites;
11495:             if ($count || $codebasecount) {
11496:                 my $saveresult;
11497:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11498:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11499:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11500:                     if ($url eq $container) {
11501:                         my ($fname) = ($container =~ m{/([^/]+)$});
11502:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11503:                                             $count,'<span class="LC_filename">'.
11504:                                             $fname.'</span>').'</p>';
11505:                     } else {
11506:                          $output = '<p class="LC_error">'.
11507:                                    &mt('Error: update failed for: [_1].',
11508:                                    '<span class="LC_filename">'.
11509:                                    $container.'</span>').'</p>';
11510:                     }
11511:                     if ($context eq 'syllabus') {
11512:                         unless ($saveresult eq 'ok') {
11513:                             $skiprewrites = 1;
11514:                         }
11515:                     }
11516:                 } else {
11517:                     if (open(my $fh,">$container")) {
11518:                         print $fh $content;
11519:                         close($fh);
11520:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11521:                                   $count,'<span class="LC_filename">'.
11522:                                   $container.'</span>').'</p>';
11523:                     } else {
11524:                          $output = '<p class="LC_error">'.
11525:                                    &mt('Error: could not update [_1].',
11526:                                    '<span class="LC_filename">'.
11527:                                    $container.'</span>').'</p>';
11528:                     }
11529:                 }
11530:             }
11531:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11532:                 my ($actionurl,$state);
11533:                 $actionurl = "/public/$udom/$uname/syllabus";
11534:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11535:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11536:                                               \%codebase,
11537:                                               {'context' => 'rewrites',
11538:                                                'ignore_remote_references' => 1,});
11539:                 if (ref($mapping) eq 'HASH') {
11540:                     my $rewrites = 0;
11541:                     foreach my $key (keys(%{$mapping})) {
11542:                         next if ($key =~ m{^https?://});
11543:                         my $ref = $mapping->{$key};
11544:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11545:                         my $attrib;
11546:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11547:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11548:                         }
11549:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11550:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11551:                             $rewrites += $numchg;
11552:                         }
11553:                     }
11554:                     if ($rewrites) {
11555:                         my $saveresult; 
11556:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11557:                         if ($url eq $container) {
11558:                             my ($fname) = ($container =~ m{/([^/]+)$});
11559:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11560:                                             $count,'<span class="LC_filename">'.
11561:                                             $fname.'</span>').'</p>';
11562:                         } else {
11563:                             $output .= '<p class="LC_error">'.
11564:                                        &mt('Error: could not update links in [_1].',
11565:                                        '<span class="LC_filename">'.
11566:                                        $container.'</span>').'</p>';
11567: 
11568:                         }
11569:                     }
11570:                 }
11571:             }
11572:         } else {
11573:             &logthis('Failed to parse '.$container.
11574:                      ' to modify references: '.$parse_result);
11575:         }
11576:     }
11577:     if (wantarray) {
11578:         return ($output,$count,$codebasecount);
11579:     } else {
11580:         return $output;
11581:     }
11582: }
11583: 
11584: sub check_for_existing {
11585:     my ($path,$fname,$element) = @_;
11586:     my ($state,$msg);
11587:     if (-d $path.'/'.$fname) {
11588:         $state = 'exists';
11589:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11590:     } elsif (-e $path.'/'.$fname) {
11591:         $state = 'exists';
11592:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11593:     }
11594:     if ($state eq 'exists') {
11595:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11596:     }
11597:     return ($state,$msg);
11598: }
11599: 
11600: sub check_for_upload {
11601:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11602:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11603:     my $filesize = length($env{'form.'.$element});
11604:     if (!$filesize) {
11605:         my $msg = '<span class="LC_error">'.
11606:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11607:                       '<span class="LC_filename">'.$fname.'</span>',
11608:                       $filesize).'<br />'.
11609:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11610:                   '</span>';
11611:         return ('zero_bytes',$msg);
11612:     }
11613:     $filesize =  $filesize/1000; #express in k (1024?)
11614:     my $getpropath = 1;
11615:     my ($dirlistref,$listerror) =
11616:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11617:     my $found_file = 0;
11618:     my $locked_file = 0;
11619:     my @lockers;
11620:     my $navmap;
11621:     if ($env{'request.course.id'}) {
11622:         $navmap = Apache::lonnavmaps::navmap->new();
11623:     }
11624:     if (ref($dirlistref) eq 'ARRAY') {
11625:         foreach my $line (@{$dirlistref}) {
11626:             my ($file_name,$rest)=split(/\&/,$line,2);
11627:             if ($file_name eq $fname){
11628:                 $file_name = $path.$file_name;
11629:                 if ($group ne '') {
11630:                     $file_name = $group.$file_name;
11631:                 }
11632:                 $found_file = 1;
11633:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11634:                     foreach my $lock (@lockers) {
11635:                         if (ref($lock) eq 'ARRAY') {
11636:                             my ($symb,$crsid) = @{$lock};
11637:                             if ($crsid eq $env{'request.course.id'}) {
11638:                                 if (ref($navmap)) {
11639:                                     my $res = $navmap->getBySymb($symb);
11640:                                     foreach my $part (@{$res->parts()}) { 
11641:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11642:                                         unless (($slot_status == $res->RESERVED) ||
11643:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11644:                                             $locked_file = 1;
11645:                                         }
11646:                                     }
11647:                                 } else {
11648:                                     $locked_file = 1;
11649:                                 }
11650:                             } else {
11651:                                 $locked_file = 1;
11652:                             }
11653:                         }
11654:                    }
11655:                 } else {
11656:                     my @info = split(/\&/,$rest);
11657:                     my $currsize = $info[6]/1000;
11658:                     if ($currsize < $filesize) {
11659:                         my $extra = $filesize - $currsize;
11660:                         if (($current_disk_usage + $extra) > $disk_quota) {
11661:                             my $msg = '<p class="LC_warning">'.
11662:                                       &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.',
11663:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11664:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11665:                                                    $disk_quota,$current_disk_usage).'</p>';
11666:                             return ('will_exceed_quota',$msg);
11667:                         }
11668:                     }
11669:                 }
11670:             }
11671:         }
11672:     }
11673:     if (($current_disk_usage + $filesize) > $disk_quota){
11674:         my $msg = '<p class="LC_warning">'.
11675:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11676:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11677:         return ('will_exceed_quota',$msg);
11678:     } elsif ($found_file) {
11679:         if ($locked_file) {
11680:             my $msg = '<p class="LC_warning">';
11681:             $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>');
11682:             $msg .= '</p>';
11683:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11684:             return ('file_locked',$msg);
11685:         } else {
11686:             my $msg = '<p class="LC_error">';
11687:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11688:             $msg .= '</p>';
11689:             return ('existingfile',$msg);
11690:         }
11691:     }
11692: }
11693: 
11694: sub check_for_traversal {
11695:     my ($path,$url,$toplevel) = @_;
11696:     my @parts=split(/\//,$path);
11697:     my $cleanpath;
11698:     my $fullpath = $url;
11699:     for (my $i=0;$i<@parts;$i++) {
11700:         next if ($parts[$i] eq '.');
11701:         if ($parts[$i] eq '..') {
11702:             $fullpath =~ s{([^/]+/)$}{};
11703:         } else {
11704:             $fullpath .= $parts[$i].'/';
11705:         }
11706:     }
11707:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11708:         $cleanpath = $1;
11709:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11710:         my $curr_toprel = $1;
11711:         my @parts = split(/\//,$curr_toprel);
11712:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11713:         my @urlparts = split(/\//,$url_toprel);
11714:         my $doubledots;
11715:         my $startdiff = -1;
11716:         for (my $i=0; $i<@urlparts; $i++) {
11717:             if ($startdiff == -1) {
11718:                 unless ($urlparts[$i] eq $parts[$i]) {
11719:                     $startdiff = $i;
11720:                     $doubledots .= '../';
11721:                 }
11722:             } else {
11723:                 $doubledots .= '../';
11724:             }
11725:         }
11726:         if ($startdiff > -1) {
11727:             $cleanpath = $doubledots;
11728:             for (my $i=$startdiff; $i<@parts; $i++) {
11729:                 $cleanpath .= $parts[$i].'/';
11730:             }
11731:         }
11732:     }
11733:     $cleanpath =~ s{(/)$}{};
11734:     return $cleanpath;
11735: }
11736: 
11737: sub is_archive_file {
11738:     my ($mimetype) = @_;
11739:     if (($mimetype eq 'application/octet-stream') ||
11740:         ($mimetype eq 'application/x-stuffit') ||
11741:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11742:         return 1;
11743:     }
11744:     return;
11745: }
11746: 
11747: sub decompress_form {
11748:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11749:     my %lt = &Apache::lonlocal::texthash (
11750:         this => 'This file is an archive file.',
11751:         camt => 'This file is a Camtasia archive file.',
11752:         itsc => 'Its contents are as follows:',
11753:         youm => 'You may wish to extract its contents.',
11754:         extr => 'Extract contents',
11755:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11756:         proa => 'Process automatically?',
11757:         yes  => 'Yes',
11758:         no   => 'No',
11759:         fold => 'Title for folder containing movie',
11760:         movi => 'Title for page containing embedded movie', 
11761:     );
11762:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11763:     my ($is_camtasia,$topdir,%toplevel,@paths);
11764:     my $info = &list_archive_contents($fileloc,\@paths);
11765:     if (@paths) {
11766:         foreach my $path (@paths) {
11767:             $path =~ s{^/}{};
11768:             if ($path =~ m{^([^/]+)/$}) {
11769:                 $topdir = $1;
11770:             }
11771:             if ($path =~ m{^([^/]+)/}) {
11772:                 $toplevel{$1} = $path;
11773:             } else {
11774:                 $toplevel{$path} = $path;
11775:             }
11776:         }
11777:     }
11778:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11779:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11780:                         "$topdir/media/",
11781:                         "$topdir/media/$topdir.mp4",
11782:                         "$topdir/media/FirstFrame.png",
11783:                         "$topdir/media/player.swf",
11784:                         "$topdir/media/swfobject.js",
11785:                         "$topdir/media/expressInstall.swf");
11786:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11787:                          "$topdir/$topdir.mp4",
11788:                          "$topdir/$topdir\_config.xml",
11789:                          "$topdir/$topdir\_controller.swf",
11790:                          "$topdir/$topdir\_embed.css",
11791:                          "$topdir/$topdir\_First_Frame.png",
11792:                          "$topdir/$topdir\_player.html",
11793:                          "$topdir/$topdir\_Thumbnails.png",
11794:                          "$topdir/playerProductInstall.swf",
11795:                          "$topdir/scripts/",
11796:                          "$topdir/scripts/config_xml.js",
11797:                          "$topdir/scripts/handlebars.js",
11798:                          "$topdir/scripts/jquery-1.7.1.min.js",
11799:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11800:                          "$topdir/scripts/modernizr.js",
11801:                          "$topdir/scripts/player-min.js",
11802:                          "$topdir/scripts/swfobject.js",
11803:                          "$topdir/skins/",
11804:                          "$topdir/skins/configuration_express.xml",
11805:                          "$topdir/skins/express_show/",
11806:                          "$topdir/skins/express_show/player-min.css",
11807:                          "$topdir/skins/express_show/spritesheet.png");
11808:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11809:                          "$topdir/$topdir.mp4",
11810:                          "$topdir/$topdir\_config.xml",
11811:                          "$topdir/$topdir\_controller.swf",
11812:                          "$topdir/$topdir\_embed.css",
11813:                          "$topdir/$topdir\_First_Frame.png",
11814:                          "$topdir/$topdir\_player.html",
11815:                          "$topdir/$topdir\_Thumbnails.png",
11816:                          "$topdir/playerProductInstall.swf",
11817:                          "$topdir/scripts/",
11818:                          "$topdir/scripts/config_xml.js",
11819:                          "$topdir/scripts/techsmith-smart-player.min.js",
11820:                          "$topdir/skins/",
11821:                          "$topdir/skins/configuration_express.xml",
11822:                          "$topdir/skins/express_show/",
11823:                          "$topdir/skins/express_show/spritesheet.min.css",
11824:                          "$topdir/skins/express_show/spritesheet.png",
11825:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11826:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11827:         if (@diffs == 0) {
11828:             $is_camtasia = 6;
11829:         } else {
11830:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11831:             if (@diffs == 0) {
11832:                 $is_camtasia = 8;
11833:             } else {
11834:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11835:                 if (@diffs == 0) {
11836:                     $is_camtasia = 8;
11837:                 }
11838:             }
11839:         }
11840:     }
11841:     my $output;
11842:     if ($is_camtasia) {
11843:         $output = <<"ENDCAM";
11844: <script type="text/javascript" language="Javascript">
11845: // <![CDATA[
11846: 
11847: function camtasiaToggle() {
11848:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11849:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11850:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11851:                 document.getElementById('camtasia_titles').style.display='block';
11852:             } else {
11853:                 document.getElementById('camtasia_titles').style.display='none';
11854:             }
11855:         }
11856:     }
11857:     return;
11858: }
11859: 
11860: // ]]>
11861: </script>
11862: <p>$lt{'camt'}</p>
11863: ENDCAM
11864:     } else {
11865:         $output = '<p>'.$lt{'this'};
11866:         if ($info eq '') {
11867:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11868:         } else {
11869:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11870:                        '<div><pre>'.$info.'</pre></div>';
11871:         }
11872:     }
11873:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11874:     my $duplicates;
11875:     my $num = 0;
11876:     if (ref($dirlist) eq 'ARRAY') {
11877:         foreach my $item (@{$dirlist}) {
11878:             if (ref($item) eq 'ARRAY') {
11879:                 if (exists($toplevel{$item->[0]})) {
11880:                     $duplicates .= 
11881:                         &start_data_table_row().
11882:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11883:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11884:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11885:                         'value="1" />'.&mt('Yes').'</label>'.
11886:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11887:                         '<td>'.$item->[0].'</td>';
11888:                     if ($item->[2]) {
11889:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11890:                     } else {
11891:                         $duplicates .= '<td>'.&mt('File').'</td>';
11892:                     }
11893:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11894:                                    '<td>'.
11895:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11896:                                    '</td>'.
11897:                                    &end_data_table_row();
11898:                     $num ++;
11899:                 }
11900:             }
11901:         }
11902:     }
11903:     my $itemcount;
11904:     if (@paths > 0) {
11905:         $itemcount = scalar(@paths);
11906:     } else {
11907:         $itemcount = 1;
11908:     }
11909:     if ($is_camtasia) {
11910:         $output .= $lt{'auto'}.'<br />'.
11911:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11912:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11913:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11914:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11915:                    $lt{'no'}.'</label></span><br />'.
11916:                    '<div id="camtasia_titles" style="display:block">'.
11917:                    &Apache::lonhtmlcommon::start_pick_box().
11918:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11919:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11920:                    &Apache::lonhtmlcommon::row_closure().
11921:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11922:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11923:                    &Apache::lonhtmlcommon::row_closure(1).
11924:                    &Apache::lonhtmlcommon::end_pick_box().
11925:                    '</div>';
11926:     }
11927:     $output .= 
11928:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11929:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11930:         "\n";
11931:     if ($duplicates ne '') {
11932:         $output .= '<p><span class="LC_warning">'.
11933:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11934:                    &start_data_table().
11935:                    &start_data_table_header_row().
11936:                    '<th>'.&mt('Overwrite?').'</th>'.
11937:                    '<th>'.&mt('Name').'</th>'.
11938:                    '<th>'.&mt('Type').'</th>'.
11939:                    '<th>'.&mt('Size').'</th>'.
11940:                    '<th>'.&mt('Last modified').'</th>'.
11941:                    &end_data_table_header_row().
11942:                    $duplicates.
11943:                    &end_data_table().
11944:                    '</p>';
11945:     }
11946:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11947:     if (ref($hiddenelements) eq 'HASH') {
11948:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11949:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11950:         }
11951:     }
11952:     $output .= <<"END";
11953: <br />
11954: <input type="submit" name="decompress" value="$lt{'extr'}" />
11955: </form>
11956: $noextract
11957: END
11958:     return $output;
11959: }
11960: 
11961: sub decompression_utility {
11962:     my ($program) = @_;
11963:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11964:     my $location;
11965:     if (grep(/^\Q$program\E$/,@utilities)) { 
11966:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11967:                          '/usr/sbin/') {
11968:             if (-x $dir.$program) {
11969:                 $location = $dir.$program;
11970:                 last;
11971:             }
11972:         }
11973:     }
11974:     return $location;
11975: }
11976: 
11977: sub list_archive_contents {
11978:     my ($file,$pathsref) = @_;
11979:     my (@cmd,$output);
11980:     my $needsregexp;
11981:     if ($file =~ /\.zip$/) {
11982:         @cmd = (&decompression_utility('unzip'),"-l");
11983:         $needsregexp = 1;
11984:     } elsif (($file =~ m/\.tar\.gz$/) ||
11985:              ($file =~ /\.tgz$/)) {
11986:         @cmd = (&decompression_utility('tar'),"-ztf");
11987:     } elsif ($file =~ /\.tar\.bz2$/) {
11988:         @cmd = (&decompression_utility('tar'),"-jtf");
11989:     } elsif ($file =~ m|\.tar$|) {
11990:         @cmd = (&decompression_utility('tar'),"-tf");
11991:     }
11992:     if (@cmd) {
11993:         undef($!);
11994:         undef($@);
11995:         if (open(my $fh,"-|", @cmd, $file)) {
11996:             while (my $line = <$fh>) {
11997:                 $output .= $line;
11998:                 chomp($line);
11999:                 my $item;
12000:                 if ($needsregexp) {
12001:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12002:                 } else {
12003:                     $item = $line;
12004:                 }
12005:                 if ($item ne '') {
12006:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12007:                         push(@{$pathsref},$item);
12008:                     } 
12009:                 }
12010:             }
12011:             close($fh);
12012:         }
12013:     }
12014:     return $output;
12015: }
12016: 
12017: sub decompress_uploaded_file {
12018:     my ($file,$dir) = @_;
12019:     &Apache::lonnet::appenv({'cgi.file' => $file});
12020:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12021:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12022:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12023:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12024:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12025:     my $decompressed = $env{'cgi.decompressed'};
12026:     &Apache::lonnet::delenv('cgi.file');
12027:     &Apache::lonnet::delenv('cgi.dir');
12028:     &Apache::lonnet::delenv('cgi.decompressed');
12029:     return ($decompressed,$result);
12030: }
12031: 
12032: sub process_decompression {
12033:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12034:     my ($dir,$error,$warning,$output);
12035:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12036:         $error = &mt('Filename not a supported archive file type.').
12037:                  '<br />'.&mt('Filename should end with one of: [_1].',
12038:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12039:     } else {
12040:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12041:         if ($docuhome eq 'no_host') {
12042:             $error = &mt('Could not determine home server for course.');
12043:         } else {
12044:             my @ids=&Apache::lonnet::current_machine_ids();
12045:             my $currdir = "$dir_root/$destination";
12046:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12047:                 $dir = &LONCAPA::propath($docudom,$docuname).
12048:                        "$dir_root/$destination";
12049:             } else {
12050:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12051:                        "$dir_root/$docudom/$docuname/$destination";
12052:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12053:                     $error = &mt('Archive file not found.');
12054:                 }
12055:             }
12056:             my (@to_overwrite,@to_skip);
12057:             if ($env{'form.archive_overwrite_total'} > 0) {
12058:                 my $total = $env{'form.archive_overwrite_total'};
12059:                 for (my $i=0; $i<$total; $i++) {
12060:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12061:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12062:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12063:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12064:                     }
12065:                 }
12066:             }
12067:             my $numskip = scalar(@to_skip);
12068:             if (($numskip > 0) && 
12069:                 ($numskip == $env{'form.archive_itemcount'})) {
12070:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12071:             } elsif ($dir eq '') {
12072:                 $error = &mt('Directory containing archive file unavailable.');
12073:             } elsif (!$error) {
12074:                 my ($decompressed,$display);
12075:                 if ($numskip > 0) {
12076:                     my $tempdir = time.'_'.$$.int(rand(10000));
12077:                     mkdir("$dir/$tempdir",0755);
12078:                     system("mv $dir/$file $dir/$tempdir/$file");
12079:                     ($decompressed,$display) = 
12080:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12081:                     foreach my $item (@to_skip) {
12082:                         if (($item ne '') && ($item !~ /\.\./)) {
12083:                             if (-f "$dir/$tempdir/$item") { 
12084:                                 unlink("$dir/$tempdir/$item");
12085:                             } elsif (-d "$dir/$tempdir/$item") {
12086:                                 system("rm -rf $dir/$tempdir/$item");
12087:                             }
12088:                         }
12089:                     }
12090:                     system("mv $dir/$tempdir/* $dir");
12091:                     rmdir("$dir/$tempdir");   
12092:                 } else {
12093:                     ($decompressed,$display) = 
12094:                         &decompress_uploaded_file($file,$dir);
12095:                 }
12096:                 if ($decompressed eq 'ok') {
12097:                     $output = '<p class="LC_info">'.
12098:                               &mt('Files extracted successfully from archive.').
12099:                               '</p>'."\n";
12100:                     my ($warning,$result,@contents);
12101:                     my ($newdirlistref,$newlisterror) =
12102:                         &Apache::lonnet::dirlist($currdir,$docudom,
12103:                                                  $docuname,1);
12104:                     my (%is_dir,%changes,@newitems);
12105:                     my $dirptr = 16384;
12106:                     if (ref($newdirlistref) eq 'ARRAY') {
12107:                         foreach my $dir_line (@{$newdirlistref}) {
12108:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12109:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12110:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12111:                                 push(@newitems,$item);
12112:                                 if ($dirptr&$testdir) {
12113:                                     $is_dir{$item} = 1;
12114:                                 }
12115:                                 $changes{$item} = 1;
12116:                             }
12117:                         }
12118:                     }
12119:                     if (keys(%changes) > 0) {
12120:                         foreach my $item (sort(@newitems)) {
12121:                             if ($changes{$item}) {
12122:                                 push(@contents,$item);
12123:                             }
12124:                         }
12125:                     }
12126:                     if (@contents > 0) {
12127:                         my $wantform;
12128:                         unless ($env{'form.autoextract_camtasia'}) {
12129:                             $wantform = 1;
12130:                         }
12131:                         my (%children,%parent,%dirorder,%titles);
12132:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12133:                                                                 $currdir,\%is_dir,
12134:                                                                 \%children,\%parent,
12135:                                                                 \@contents,\%dirorder,
12136:                                                                 \%titles,$wantform);
12137:                         if ($datatable ne '') {
12138:                             $output .= &archive_options_form('decompressed',$datatable,
12139:                                                              $count,$hiddenelem);
12140:                             my $startcount = 6;
12141:                             $output .= &archive_javascript($startcount,$count,
12142:                                                            \%titles,\%children);
12143:                         }
12144:                         if ($env{'form.autoextract_camtasia'}) {
12145:                             my $version = $env{'form.autoextract_camtasia'};
12146:                             my %displayed;
12147:                             my $total = 1;
12148:                             $env{'form.archive_directory'} = [];
12149:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12150:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12151:                                 $path =~ s{/$}{};
12152:                                 my $item;
12153:                                 if ($path ne '') {
12154:                                     $item = "$path/$titles{$i}";
12155:                                 } else {
12156:                                     $item = $titles{$i};
12157:                                 }
12158:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12159:                                 if ($item eq $contents[0]) {
12160:                                     push(@{$env{'form.archive_directory'}},$i);
12161:                                     $env{'form.archive_'.$i} = 'display';
12162:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12163:                                     $displayed{'folder'} = $i;
12164:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12165:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12166:                                     $env{'form.archive_'.$i} = 'display';
12167:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12168:                                     $displayed{'web'} = $i;
12169:                                 } else {
12170:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12171:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12172:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12173:                                         push(@{$env{'form.archive_directory'}},$i);
12174:                                     }
12175:                                     $env{'form.archive_'.$i} = 'dependency';
12176:                                 }
12177:                                 $total ++;
12178:                             }
12179:                             for (my $i=1; $i<$total; $i++) {
12180:                                 next if ($i == $displayed{'web'});
12181:                                 next if ($i == $displayed{'folder'});
12182:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12183:                             }
12184:                             $env{'form.phase'} = 'decompress_cleanup';
12185:                             $env{'form.archivedelete'} = 1;
12186:                             $env{'form.archive_count'} = $total-1;
12187:                             $output .=
12188:                                 &process_extracted_files('coursedocs',$docudom,
12189:                                                          $docuname,$destination,
12190:                                                          $dir_root,$hiddenelem);
12191:                         }
12192:                     } else {
12193:                         $warning = &mt('No new items extracted from archive file.');
12194:                     }
12195:                 } else {
12196:                     $output = $display;
12197:                     $error = &mt('An error occurred during extraction from the archive file.');
12198:                 }
12199:             }
12200:         }
12201:     }
12202:     if ($error) {
12203:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12204:                    $error.'</p>'."\n";
12205:     }
12206:     if ($warning) {
12207:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12208:     }
12209:     return $output;
12210: }
12211: 
12212: sub get_extracted {
12213:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12214:         $titles,$wantform) = @_;
12215:     my $count = 0;
12216:     my $depth = 0;
12217:     my $datatable;
12218:     my @hierarchy;
12219:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12220:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12221:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12222:     foreach my $item (@{$contents}) {
12223:         $count ++;
12224:         @{$dirorder->{$count}} = @hierarchy;
12225:         $titles->{$count} = $item;
12226:         &archive_hierarchy($depth,$count,$parent,$children);
12227:         if ($wantform) {
12228:             $datatable .= &archive_row($is_dir->{$item},$item,
12229:                                        $currdir,$depth,$count);
12230:         }
12231:         if ($is_dir->{$item}) {
12232:             $depth ++;
12233:             push(@hierarchy,$count);
12234:             $parent->{$depth} = $count;
12235:             $datatable .=
12236:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12237:                                            \$depth,\$count,\@hierarchy,$dirorder,
12238:                                            $children,$parent,$titles,$wantform);
12239:             $depth --;
12240:             pop(@hierarchy);
12241:         }
12242:     }
12243:     return ($count,$datatable);
12244: }
12245: 
12246: sub recurse_extracted_archive {
12247:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12248:         $children,$parent,$titles,$wantform) = @_;
12249:     my $result='';
12250:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12251:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12252:             (ref($dirorder) eq 'HASH')) {
12253:         return $result;
12254:     }
12255:     my $dirptr = 16384;
12256:     my ($newdirlistref,$newlisterror) =
12257:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12258:     if (ref($newdirlistref) eq 'ARRAY') {
12259:         foreach my $dir_line (@{$newdirlistref}) {
12260:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12261:             unless ($item =~ /^\.+$/) {
12262:                 $$count ++;
12263:                 @{$dirorder->{$$count}} = @{$hierarchy};
12264:                 $titles->{$$count} = $item;
12265:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12266: 
12267:                 my $is_dir;
12268:                 if ($dirptr&$testdir) {
12269:                     $is_dir = 1;
12270:                 }
12271:                 if ($wantform) {
12272:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12273:                 }
12274:                 if ($is_dir) {
12275:                     $$depth ++;
12276:                     push(@{$hierarchy},$$count);
12277:                     $parent->{$$depth} = $$count;
12278:                     $result .=
12279:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12280:                                                    $docuname,$depth,$count,
12281:                                                    $hierarchy,$dirorder,$children,
12282:                                                    $parent,$titles,$wantform);
12283:                     $$depth --;
12284:                     pop(@{$hierarchy});
12285:                 }
12286:             }
12287:         }
12288:     }
12289:     return $result;
12290: }
12291: 
12292: sub archive_hierarchy {
12293:     my ($depth,$count,$parent,$children) =@_;
12294:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12295:         if (exists($parent->{$depth})) {
12296:              $children->{$parent->{$depth}} .= $count.':';
12297:         }
12298:     }
12299:     return;
12300: }
12301: 
12302: sub archive_row {
12303:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12304:     my ($name) = ($item =~ m{([^/]+)$});
12305:     my %choices = &Apache::lonlocal::texthash (
12306:                                        'display'    => 'Add as file',
12307:                                        'dependency' => 'Include as dependency',
12308:                                        'discard'    => 'Discard',
12309:                                       );
12310:     if ($is_dir) {
12311:         $choices{'display'} = &mt('Add as folder'); 
12312:     }
12313:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12314:     my $offset = 0;
12315:     foreach my $action ('display','dependency','discard') {
12316:         $offset ++;
12317:         if ($action ne 'display') {
12318:             $offset ++;
12319:         }  
12320:         $output .= '<td><span class="LC_nobreak">'.
12321:                    '<label><input type="radio" name="archive_'.$count.
12322:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12323:         my $text = $choices{$action};
12324:         if ($is_dir) {
12325:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12326:             if ($action eq 'display') {
12327:                 $text = &mt('Add as folder');
12328:             }
12329:         } else {
12330:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12331: 
12332:         }
12333:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12334:         if ($action eq 'dependency') {
12335:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12336:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12337:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12338:                        '<option value=""></option>'."\n".
12339:                        '</select>'."\n".
12340:                        '</div>';
12341:         } elsif ($action eq 'display') {
12342:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12343:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12344:                        '</div>';
12345:         }
12346:         $output .= '</td>';
12347:     }
12348:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12349:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12350:     for (my $i=0; $i<$depth; $i++) {
12351:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12352:     }
12353:     if ($is_dir) {
12354:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12355:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12356:     } else {
12357:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12358:     }
12359:     $output .= '&nbsp;'.$name.'</td>'."\n".
12360:                &end_data_table_row();
12361:     return $output;
12362: }
12363: 
12364: sub archive_options_form {
12365:     my ($form,$display,$count,$hiddenelem) = @_;
12366:     my %lt = &Apache::lonlocal::texthash(
12367:                perm => 'Permanently remove archive file?',
12368:                hows => 'How should each extracted item be incorporated in the course?',
12369:                cont => 'Content actions for all',
12370:                addf => 'Add as folder/file',
12371:                incd => 'Include as dependency for a displayed file',
12372:                disc => 'Discard',
12373:                no   => 'No',
12374:                yes  => 'Yes',
12375:                save => 'Save',
12376:     );
12377:     my $output = <<"END";
12378: <form name="$form" method="post" action="">
12379: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12380: <label>
12381:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12382: </label>
12383: &nbsp;
12384: <label>
12385:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12386: </span>
12387: </p>
12388: <input type="hidden" name="phase" value="decompress_cleanup" />
12389: <br />$lt{'hows'}
12390: <div class="LC_columnSection">
12391:   <fieldset>
12392:     <legend>$lt{'cont'}</legend>
12393:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12394:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12395:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12396:   </fieldset>
12397: </div>
12398: END
12399:     return $output.
12400:            &start_data_table()."\n".
12401:            $display."\n".
12402:            &end_data_table()."\n".
12403:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12404:            $hiddenelem.
12405:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12406:            '</form>';
12407: }
12408: 
12409: sub archive_javascript {
12410:     my ($startcount,$numitems,$titles,$children) = @_;
12411:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12412:     my $maintitle = $env{'form.comment'};
12413:     my $scripttag = <<START;
12414: <script type="text/javascript">
12415: // <![CDATA[
12416: 
12417: function checkAll(form,prefix) {
12418:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12419:     for (var i=0; i < form.elements.length; i++) {
12420:         var id = form.elements[i].id;
12421:         if ((id != '') && (id != undefined)) {
12422:             if (idstr.test(id)) {
12423:                 if (form.elements[i].type == 'radio') {
12424:                     form.elements[i].checked = true;
12425:                     var nostart = i-$startcount;
12426:                     var offset = nostart%7;
12427:                     var count = (nostart-offset)/7;    
12428:                     dependencyCheck(form,count,offset);
12429:                 }
12430:             }
12431:         }
12432:     }
12433: }
12434: 
12435: function propagateCheck(form,count) {
12436:     if (count > 0) {
12437:         var startelement = $startcount + ((count-1) * 7);
12438:         for (var j=1; j<6; j++) {
12439:             if ((j != 2) && (j != 4)) {
12440:                 var item = startelement + j; 
12441:                 if (form.elements[item].type == 'radio') {
12442:                     if (form.elements[item].checked) {
12443:                         containerCheck(form,count,j);
12444:                         break;
12445:                     }
12446:                 }
12447:             }
12448:         }
12449:     }
12450: }
12451: 
12452: numitems = $numitems
12453: var titles = new Array(numitems);
12454: var parents = new Array(numitems);
12455: for (var i=0; i<numitems; i++) {
12456:     parents[i] = new Array;
12457: }
12458: var maintitle = '$maintitle';
12459: 
12460: START
12461: 
12462:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12463:         my @contents = split(/:/,$children->{$container});
12464:         for (my $i=0; $i<@contents; $i ++) {
12465:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12466:         }
12467:     }
12468: 
12469:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12470:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12471:     }
12472: 
12473:     $scripttag .= <<END;
12474: 
12475: function containerCheck(form,count,offset) {
12476:     if (count > 0) {
12477:         dependencyCheck(form,count,offset);
12478:         var item = (offset+$startcount)+7*(count-1);
12479:         form.elements[item].checked = true;
12480:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12481:             if (parents[count].length > 0) {
12482:                 for (var j=0; j<parents[count].length; j++) {
12483:                     containerCheck(form,parents[count][j],offset);
12484:                 }
12485:             }
12486:         }
12487:     }
12488: }
12489: 
12490: function dependencyCheck(form,count,offset) {
12491:     if (count > 0) {
12492:         var chosen = (offset+$startcount)+7*(count-1);
12493:         var depitem = $startcount + ((count-1) * 7) + 4;
12494:         var currtype = form.elements[depitem].type;
12495:         if (form.elements[chosen].value == 'dependency') {
12496:             document.getElementById('arc_depon_'+count).style.display='block'; 
12497:             form.elements[depitem].options.length = 0;
12498:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12499:             for (var i=1; i<=numitems; i++) {
12500:                 if (i == count) {
12501:                     continue;
12502:                 }
12503:                 var startelement = $startcount + (i-1) * 7;
12504:                 for (var j=1; j<6; j++) {
12505:                     if ((j != 2) && (j!= 4)) {
12506:                         var item = startelement + j;
12507:                         if (form.elements[item].type == 'radio') {
12508:                             if (form.elements[item].checked) {
12509:                                 if (form.elements[item].value == 'display') {
12510:                                     var n = form.elements[depitem].options.length;
12511:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12512:                                 }
12513:                             }
12514:                         }
12515:                     }
12516:                 }
12517:             }
12518:         } else {
12519:             document.getElementById('arc_depon_'+count).style.display='none';
12520:             form.elements[depitem].options.length = 0;
12521:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12522:         }
12523:         titleCheck(form,count,offset);
12524:     }
12525: }
12526: 
12527: function propagateSelect(form,count,offset) {
12528:     if (count > 0) {
12529:         var item = (1+offset+$startcount)+7*(count-1);
12530:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12531:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12532:             if (parents[count].length > 0) {
12533:                 for (var j=0; j<parents[count].length; j++) {
12534:                     containerSelect(form,parents[count][j],offset,picked);
12535:                 }
12536:             }
12537:         }
12538:     }
12539: }
12540: 
12541: function containerSelect(form,count,offset,picked) {
12542:     if (count > 0) {
12543:         var item = (offset+$startcount)+7*(count-1);
12544:         if (form.elements[item].type == 'radio') {
12545:             if (form.elements[item].value == 'dependency') {
12546:                 if (form.elements[item+1].type == 'select-one') {
12547:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12548:                         if (form.elements[item+1].options[i].value == picked) {
12549:                             form.elements[item+1].selectedIndex = i;
12550:                             break;
12551:                         }
12552:                     }
12553:                 }
12554:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12555:                     if (parents[count].length > 0) {
12556:                         for (var j=0; j<parents[count].length; j++) {
12557:                             containerSelect(form,parents[count][j],offset,picked);
12558:                         }
12559:                     }
12560:                 }
12561:             }
12562:         }
12563:     }
12564: }
12565: 
12566: function titleCheck(form,count,offset) {
12567:     if (count > 0) {
12568:         var chosen = (offset+$startcount)+7*(count-1);
12569:         var depitem = $startcount + ((count-1) * 7) + 2;
12570:         var currtype = form.elements[depitem].type;
12571:         if (form.elements[chosen].value == 'display') {
12572:             document.getElementById('arc_title_'+count).style.display='block';
12573:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12574:                 document.getElementById('archive_title_'+count).value=maintitle;
12575:             }
12576:         } else {
12577:             document.getElementById('arc_title_'+count).style.display='none';
12578:             if (currtype == 'text') { 
12579:                 document.getElementById('archive_title_'+count).value='';
12580:             }
12581:         }
12582:     }
12583:     return;
12584: }
12585: 
12586: // ]]>
12587: </script>
12588: END
12589:     return $scripttag;
12590: }
12591: 
12592: sub process_extracted_files {
12593:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12594:     my $numitems = $env{'form.archive_count'};
12595:     return unless ($numitems);
12596:     my @ids=&Apache::lonnet::current_machine_ids();
12597:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12598:         %folders,%containers,%mapinner,%prompttofetch);
12599:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12600:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12601:         $prefix = &LONCAPA::propath($docudom,$docuname);
12602:         $pathtocheck = "$dir_root/$destination";
12603:         $dir = $dir_root;
12604:         $ishome = 1;
12605:     } else {
12606:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12607:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12608:         $dir = "$dir_root/$docudom/$docuname";    
12609:     }
12610:     my $currdir = "$dir_root/$destination";
12611:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12612:     if ($env{'form.folderpath'}) {
12613:         my @items = split('&',$env{'form.folderpath'});
12614:         $folders{'0'} = $items[-2];
12615:         if ($env{'form.folderpath'} =~ /\:1$/) {
12616:             $containers{'0'}='page';
12617:         } else {  
12618:             $containers{'0'}='sequence';
12619:         }
12620:     }
12621:     my @archdirs = &get_env_multiple('form.archive_directory');
12622:     if ($numitems) {
12623:         for (my $i=1; $i<=$numitems; $i++) {
12624:             my $path = $env{'form.archive_content_'.$i};
12625:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12626:                 my $item = $1;
12627:                 $toplevelitems{$item} = $i;
12628:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12629:                     $is_dir{$item} = 1;
12630:                 }
12631:             }
12632:         }
12633:     }
12634:     my ($output,%children,%parent,%titles,%dirorder,$result);
12635:     if (keys(%toplevelitems) > 0) {
12636:         my @contents = sort(keys(%toplevelitems));
12637:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12638:                                            \%parent,\@contents,\%dirorder,\%titles);
12639:     }
12640:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12641:     if ($numitems) {
12642:         for (my $i=1; $i<=$numitems; $i++) {
12643:             next if ($env{'form.archive_'.$i} eq 'dependency');
12644:             my $path = $env{'form.archive_content_'.$i};
12645:             if ($path =~ /^\Q$pathtocheck\E/) {
12646:                 if ($env{'form.archive_'.$i} eq 'discard') {
12647:                     if ($prefix ne '' && $path ne '') {
12648:                         if (-e $prefix.$path) {
12649:                             if ((@archdirs > 0) && 
12650:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12651:                                 $todeletedir{$prefix.$path} = 1;
12652:                             } else {
12653:                                 $todelete{$prefix.$path} = 1;
12654:                             }
12655:                         }
12656:                     }
12657:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12658:                     my ($docstitle,$title,$url,$outer);
12659:                     ($title) = ($path =~ m{/([^/]+)$});
12660:                     $docstitle = $env{'form.archive_title_'.$i};
12661:                     if ($docstitle eq '') {
12662:                         $docstitle = $title;
12663:                     }
12664:                     $outer = 0;
12665:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12666:                         if (@{$dirorder{$i}} > 0) {
12667:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12668:                                 if ($env{'form.archive_'.$item} eq 'display') {
12669:                                     $outer = $item;
12670:                                     last;
12671:                                 }
12672:                             }
12673:                         }
12674:                     }
12675:                     my ($errtext,$fatal) = 
12676:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12677:                                                '/'.$folders{$outer}.'.'.
12678:                                                $containers{$outer});
12679:                     next if ($fatal);
12680:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12681:                         if ($context eq 'coursedocs') {
12682:                             $mapinner{$i} = time;
12683:                             $folders{$i} = 'default_'.$mapinner{$i};
12684:                             $containers{$i} = 'sequence';
12685:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12686:                                       $folders{$i}.'.'.$containers{$i};
12687:                             my $newidx = &LONCAPA::map::getresidx();
12688:                             $LONCAPA::map::resources[$newidx]=
12689:                                 $docstitle.':'.$url.':false:normal:res';
12690:                             push(@LONCAPA::map::order,$newidx);
12691:                             my ($outtext,$errtext) =
12692:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12693:                                                         $docuname.'/'.$folders{$outer}.
12694:                                                         '.'.$containers{$outer},1,1);
12695:                             $newseqid{$i} = $newidx;
12696:                             unless ($errtext) {
12697:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12698:                             }
12699:                         }
12700:                     } else {
12701:                         if ($context eq 'coursedocs') {
12702:                             my $newidx=&LONCAPA::map::getresidx();
12703:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12704:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12705:                                       $title;
12706:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12707:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12708:                             }
12709:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12710:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12711:                             }
12712:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12713:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12714:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12715:                                 unless ($ishome) {
12716:                                     my $fetch = "$newdest{$i}/$title";
12717:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12718:                                     $prompttofetch{$fetch} = 1;
12719:                                 }
12720:                             }
12721:                             $LONCAPA::map::resources[$newidx]=
12722:                                 $docstitle.':'.$url.':false:normal:res';
12723:                             push(@LONCAPA::map::order, $newidx);
12724:                             my ($outtext,$errtext)=
12725:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12726:                                                         $docuname.'/'.$folders{$outer}.
12727:                                                         '.'.$containers{$outer},1,1);
12728:                             unless ($errtext) {
12729:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12730:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12731:                                 }
12732:                             }
12733:                         }
12734:                     }
12735:                 }
12736:             } else {
12737:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12738:             }
12739:         }
12740:         for (my $i=1; $i<=$numitems; $i++) {
12741:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12742:             my $path = $env{'form.archive_content_'.$i};
12743:             if ($path =~ /^\Q$pathtocheck\E/) {
12744:                 my ($title) = ($path =~ m{/([^/]+)$});
12745:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12746:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12747:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12748:                         my ($itemidx,$fullpath,$relpath);
12749:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12750:                             my $container = $dirorder{$referrer{$i}}->[-1];
12751:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12752:                                 if ($dirorder{$i}->[$j] eq $container) {
12753:                                     $itemidx = $j;
12754:                                 }
12755:                             }
12756:                         }
12757:                         if ($itemidx eq '') {
12758:                             $itemidx =  0;
12759:                         } 
12760:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12761:                             if ($mapinner{$referrer{$i}}) {
12762:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12763:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12764:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12765:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12766:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12767:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12768:                                             if (!-e $fullpath) {
12769:                                                 mkdir($fullpath,0755);
12770:                                             }
12771:                                         }
12772:                                     } else {
12773:                                         last;
12774:                                     }
12775:                                 }
12776:                             }
12777:                         } elsif ($newdest{$referrer{$i}}) {
12778:                             $fullpath = $newdest{$referrer{$i}};
12779:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12780:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12781:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12782:                                     last;
12783:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12784:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12785:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12786:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12787:                                         if (!-e $fullpath) {
12788:                                             mkdir($fullpath,0755);
12789:                                         }
12790:                                     }
12791:                                 } else {
12792:                                     last;
12793:                                 }
12794:                             }
12795:                         }
12796:                         if ($fullpath ne '') {
12797:                             if (-e "$prefix$path") {
12798:                                 system("mv $prefix$path $fullpath/$title");
12799:                             }
12800:                             if (-e "$fullpath/$title") {
12801:                                 my $showpath;
12802:                                 if ($relpath ne '') {
12803:                                     $showpath = "$relpath/$title";
12804:                                 } else {
12805:                                     $showpath = "/$title";
12806:                                 } 
12807:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12808:                             } 
12809:                             unless ($ishome) {
12810:                                 my $fetch = "$fullpath/$title";
12811:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
12812:                                 $prompttofetch{$fetch} = 1;
12813:                             }
12814:                         }
12815:                     }
12816:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12817:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12818:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12819:                 }
12820:             } else {
12821:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12822:             }
12823:         }
12824:         if (keys(%todelete)) {
12825:             foreach my $key (keys(%todelete)) {
12826:                 unlink($key);
12827:             }
12828:         }
12829:         if (keys(%todeletedir)) {
12830:             foreach my $key (keys(%todeletedir)) {
12831:                 rmdir($key);
12832:             }
12833:         }
12834:         foreach my $dir (sort(keys(%is_dir))) {
12835:             if (($pathtocheck ne '') && ($dir ne ''))  {
12836:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12837:             }
12838:         }
12839:         if ($result ne '') {
12840:             $output .= '<ul>'."\n".
12841:                        $result."\n".
12842:                        '</ul>';
12843:         }
12844:         unless ($ishome) {
12845:             my $replicationfail;
12846:             foreach my $item (keys(%prompttofetch)) {
12847:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12848:                 unless ($fetchresult eq 'ok') {
12849:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12850:                 }
12851:             }
12852:             if ($replicationfail) {
12853:                 $output .= '<p class="LC_error">'.
12854:                            &mt('Course home server failed to retrieve:').'<ul>'.
12855:                            $replicationfail.
12856:                            '</ul></p>';
12857:             }
12858:         }
12859:     } else {
12860:         $warning = &mt('No items found in archive.');
12861:     }
12862:     if ($error) {
12863:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12864:                    $error.'</p>'."\n";
12865:     }
12866:     if ($warning) {
12867:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12868:     }
12869:     return $output;
12870: }
12871: 
12872: sub cleanup_empty_dirs {
12873:     my ($path) = @_;
12874:     if (($path ne '') && (-d $path)) {
12875:         if (opendir(my $dirh,$path)) {
12876:             my @dircontents = grep(!/^\./,readdir($dirh));
12877:             my $numitems = 0;
12878:             foreach my $item (@dircontents) {
12879:                 if (-d "$path/$item") {
12880:                     &cleanup_empty_dirs("$path/$item");
12881:                     if (-e "$path/$item") {
12882:                         $numitems ++;
12883:                     }
12884:                 } else {
12885:                     $numitems ++;
12886:                 }
12887:             }
12888:             if ($numitems == 0) {
12889:                 rmdir($path);
12890:             }
12891:             closedir($dirh);
12892:         }
12893:     }
12894:     return;
12895: }
12896: 
12897: =pod
12898: 
12899: =item * &get_folder_hierarchy()
12900: 
12901: Provides hierarchy of names of folders/sub-folders containing the current
12902: item,
12903: 
12904: Inputs: 3
12905:      - $navmap - navmaps object
12906: 
12907:      - $map - url for map (either the trigger itself, or map containing
12908:                            the resource, which is the trigger).
12909: 
12910:      - $showitem - 1 => show title for map itself; 0 => do not show.
12911: 
12912: Outputs: 1 @pathitems - array of folder/subfolder names.
12913: 
12914: =cut
12915: 
12916: sub get_folder_hierarchy {
12917:     my ($navmap,$map,$showitem) = @_;
12918:     my @pathitems;
12919:     if (ref($navmap)) {
12920:         my $mapres = $navmap->getResourceByUrl($map);
12921:         if (ref($mapres)) {
12922:             my $pcslist = $mapres->map_hierarchy();
12923:             if ($pcslist ne '') {
12924:                 my @pcs = split(/,/,$pcslist);
12925:                 foreach my $pc (@pcs) {
12926:                     if ($pc == 1) {
12927:                         push(@pathitems,&mt('Main Content'));
12928:                     } else {
12929:                         my $res = $navmap->getByMapPc($pc);
12930:                         if (ref($res)) {
12931:                             my $title = $res->compTitle();
12932:                             $title =~ s/\W+/_/g;
12933:                             if ($title ne '') {
12934:                                 push(@pathitems,$title);
12935:                             }
12936:                         }
12937:                     }
12938:                 }
12939:             }
12940:             if ($showitem) {
12941:                 if ($mapres->{ID} eq '0.0') {
12942:                     push(@pathitems,&mt('Main Content'));
12943:                 } else {
12944:                     my $maptitle = $mapres->compTitle();
12945:                     $maptitle =~ s/\W+/_/g;
12946:                     if ($maptitle ne '') {
12947:                         push(@pathitems,$maptitle);
12948:                     }
12949:                 }
12950:             }
12951:         }
12952:     }
12953:     return @pathitems;
12954: }
12955: 
12956: =pod
12957: 
12958: =item * &get_turnedin_filepath()
12959: 
12960: Determines path in a user's portfolio file for storage of files uploaded
12961: to a specific essayresponse or dropbox item.
12962: 
12963: Inputs: 3 required + 1 optional.
12964: $symb is symb for resource, $uname and $udom are for current user (required).
12965: $caller is optional (can be "submission", if routine is called when storing
12966: an upoaded file when "Submit Answer" button was pressed).
12967: 
12968: Returns array containing $path and $multiresp. 
12969: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12970: than one file upload item.  Callers of routine should append partid as a 
12971: subdirectory to $path in cases where $multiresp is 1.
12972: 
12973: Called by: homework/essayresponse.pm and homework/structuretags.pm
12974: 
12975: =cut
12976: 
12977: sub get_turnedin_filepath {
12978:     my ($symb,$uname,$udom,$caller) = @_;
12979:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12980:     my $turnindir;
12981:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12982:     $turnindir = $userhash{'turnindir'};
12983:     my ($path,$multiresp);
12984:     if ($turnindir eq '') {
12985:         if ($caller eq 'submission') {
12986:             $turnindir = &mt('turned in');
12987:             $turnindir =~ s/\W+/_/g;
12988:             my %newhash = (
12989:                             'turnindir' => $turnindir,
12990:                           );
12991:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12992:         }
12993:     }
12994:     if ($turnindir ne '') {
12995:         $path = '/'.$turnindir.'/';
12996:         my ($multipart,$turnin,@pathitems);
12997:         my $navmap = Apache::lonnavmaps::navmap->new();
12998:         if (defined($navmap)) {
12999:             my $mapres = $navmap->getResourceByUrl($map);
13000:             if (ref($mapres)) {
13001:                 my $pcslist = $mapres->map_hierarchy();
13002:                 if ($pcslist ne '') {
13003:                     foreach my $pc (split(/,/,$pcslist)) {
13004:                         my $res = $navmap->getByMapPc($pc);
13005:                         if (ref($res)) {
13006:                             my $title = $res->compTitle();
13007:                             $title =~ s/\W+/_/g;
13008:                             if ($title ne '') {
13009:                                 if (($pc > 1) && (length($title) > 12)) {
13010:                                     $title = substr($title,0,12);
13011:                                 }
13012:                                 push(@pathitems,$title);
13013:                             }
13014:                         }
13015:                     }
13016:                 }
13017:                 my $maptitle = $mapres->compTitle();
13018:                 $maptitle =~ s/\W+/_/g;
13019:                 if ($maptitle ne '') {
13020:                     if (length($maptitle) > 12) {
13021:                         $maptitle = substr($maptitle,0,12);
13022:                     }
13023:                     push(@pathitems,$maptitle);
13024:                 }
13025:                 unless ($env{'request.state'} eq 'construct') {
13026:                     my $res = $navmap->getBySymb($symb);
13027:                     if (ref($res)) {
13028:                         my $partlist = $res->parts();
13029:                         my $totaluploads = 0;
13030:                         if (ref($partlist) eq 'ARRAY') {
13031:                             foreach my $part (@{$partlist}) {
13032:                                 my @types = $res->responseType($part);
13033:                                 my @ids = $res->responseIds($part);
13034:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13035:                                     if ($types[$i] eq 'essay') {
13036:                                         my $partid = $part.'_'.$ids[$i];
13037:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13038:                                             $totaluploads ++;
13039:                                         }
13040:                                     }
13041:                                 }
13042:                             }
13043:                             if ($totaluploads > 1) {
13044:                                 $multiresp = 1;
13045:                             }
13046:                         }
13047:                     }
13048:                 }
13049:             } else {
13050:                 return;
13051:             }
13052:         } else {
13053:             return;
13054:         }
13055:         my $restitle=&Apache::lonnet::gettitle($symb);
13056:         $restitle =~ s/\W+/_/g;
13057:         if ($restitle eq '') {
13058:             $restitle = ($resurl =~ m{/[^/]+$});
13059:             if ($restitle eq '') {
13060:                 $restitle = time;
13061:             }
13062:         }
13063:         if (length($restitle) > 12) {
13064:             $restitle = substr($restitle,0,12);
13065:         }
13066:         push(@pathitems,$restitle);
13067:         $path .= join('/',@pathitems);
13068:     }
13069:     return ($path,$multiresp);
13070: }
13071: 
13072: =pod
13073: 
13074: =back
13075: 
13076: =head1 CSV Upload/Handling functions
13077: 
13078: =over 4
13079: 
13080: =item * &upfile_store($r)
13081: 
13082: Store uploaded file, $r should be the HTTP Request object,
13083: needs $env{'form.upfile'}
13084: returns $datatoken to be put into hidden field
13085: 
13086: =cut
13087: 
13088: sub upfile_store {
13089:     my $r=shift;
13090:     $env{'form.upfile'}=~s/\r/\n/gs;
13091:     $env{'form.upfile'}=~s/\f/\n/gs;
13092:     $env{'form.upfile'}=~s/\n+/\n/gs;
13093:     $env{'form.upfile'}=~s/\n+$//gs;
13094: 
13095:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13096: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13097:     {
13098:         my $datafile = $r->dir_config('lonDaemons').
13099:                            '/tmp/'.$datatoken.'.tmp';
13100:         if ( open(my $fh,">$datafile") ) {
13101:             print $fh $env{'form.upfile'};
13102:             close($fh);
13103:         }
13104:     }
13105:     return $datatoken;
13106: }
13107: 
13108: =pod
13109: 
13110: =item * &load_tmp_file($r)
13111: 
13112: Load uploaded file from tmp, $r should be the HTTP Request object,
13113: needs $env{'form.datatoken'},
13114: sets $env{'form.upfile'} to the contents of the file
13115: 
13116: =cut
13117: 
13118: sub load_tmp_file {
13119:     my $r=shift;
13120:     my @studentdata=();
13121:     {
13122:         my $studentfile = $r->dir_config('lonDaemons').
13123:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13124:         if ( open(my $fh,"<$studentfile") ) {
13125:             @studentdata=<$fh>;
13126:             close($fh);
13127:         }
13128:     }
13129:     $env{'form.upfile'}=join('',@studentdata);
13130: }
13131: 
13132: =pod
13133: 
13134: =item * &upfile_record_sep()
13135: 
13136: Separate uploaded file into records
13137: returns array of records,
13138: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13139: 
13140: =cut
13141: 
13142: sub upfile_record_sep {
13143:     if ($env{'form.upfiletype'} eq 'xml') {
13144:     } else {
13145: 	my @records;
13146: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13147: 	    if ($line=~/^\s*$/) { next; }
13148: 	    push(@records,$line);
13149: 	}
13150: 	return @records;
13151:     }
13152: }
13153: 
13154: =pod
13155: 
13156: =item * &record_sep($record)
13157: 
13158: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13159: 
13160: =cut
13161: 
13162: sub takeleft {
13163:     my $index=shift;
13164:     return substr('0000'.$index,-4,4);
13165: }
13166: 
13167: sub record_sep {
13168:     my $record=shift;
13169:     my %components=();
13170:     if ($env{'form.upfiletype'} eq 'xml') {
13171:     } elsif ($env{'form.upfiletype'} eq 'space') {
13172:         my $i=0;
13173:         foreach my $field (split(/\s+/,$record)) {
13174:             $field=~s/^(\"|\')//;
13175:             $field=~s/(\"|\')$//;
13176:             $components{&takeleft($i)}=$field;
13177:             $i++;
13178:         }
13179:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13180:         my $i=0;
13181:         foreach my $field (split(/\t/,$record)) {
13182:             $field=~s/^(\"|\')//;
13183:             $field=~s/(\"|\')$//;
13184:             $components{&takeleft($i)}=$field;
13185:             $i++;
13186:         }
13187:     } else {
13188:         my $separator=',';
13189:         if ($env{'form.upfiletype'} eq 'semisv') {
13190:             $separator=';';
13191:         }
13192:         my $i=0;
13193: # the character we are looking for to indicate the end of a quote or a record 
13194:         my $looking_for=$separator;
13195: # do not add the characters to the fields
13196:         my $ignore=0;
13197: # we just encountered a separator (or the beginning of the record)
13198:         my $just_found_separator=1;
13199: # store the field we are working on here
13200:         my $field='';
13201: # work our way through all characters in record
13202:         foreach my $character ($record=~/(.)/g) {
13203:             if ($character eq $looking_for) {
13204:                if ($character ne $separator) {
13205: # Found the end of a quote, again looking for separator
13206:                   $looking_for=$separator;
13207:                   $ignore=1;
13208:                } else {
13209: # Found a separator, store away what we got
13210:                   $components{&takeleft($i)}=$field;
13211: 	          $i++;
13212:                   $just_found_separator=1;
13213:                   $ignore=0;
13214:                   $field='';
13215:                }
13216:                next;
13217:             }
13218: # single or double quotation marks after a separator indicate beginning of a quote
13219: # we are now looking for the end of the quote and need to ignore separators
13220:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13221:                $looking_for=$character;
13222:                next;
13223:             }
13224: # ignore would be true after we reached the end of a quote
13225:             if ($ignore) { next; }
13226:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13227:             $field.=$character;
13228:             $just_found_separator=0; 
13229:         }
13230: # catch the very last entry, since we never encountered the separator
13231:         $components{&takeleft($i)}=$field;
13232:     }
13233:     return %components;
13234: }
13235: 
13236: ######################################################
13237: ######################################################
13238: 
13239: =pod
13240: 
13241: =item * &upfile_select_html()
13242: 
13243: Return HTML code to select a file from the users machine and specify 
13244: the file type.
13245: 
13246: =cut
13247: 
13248: ######################################################
13249: ######################################################
13250: sub upfile_select_html {
13251:     my %Types = (
13252:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13253:                  semisv => &mt('Semicolon separated values'),
13254:                  space => &mt('Space separated'),
13255:                  tab   => &mt('Tabulator separated'),
13256: #                 xml   => &mt('HTML/XML'),
13257:                  );
13258:     my $Str = '<input type="file" name="upfile" size="50" />'.
13259:         '<br />'.&mt('Type').': <select name="upfiletype">';
13260:     foreach my $type (sort(keys(%Types))) {
13261:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13262:     }
13263:     $Str .= "</select>\n";
13264:     return $Str;
13265: }
13266: 
13267: sub get_samples {
13268:     my ($records,$toget) = @_;
13269:     my @samples=({});
13270:     my $got=0;
13271:     foreach my $rec (@$records) {
13272: 	my %temp = &record_sep($rec);
13273: 	if (! grep(/\S/, values(%temp))) { next; }
13274: 	if (%temp) {
13275: 	    $samples[$got]=\%temp;
13276: 	    $got++;
13277: 	    if ($got == $toget) { last; }
13278: 	}
13279:     }
13280:     return \@samples;
13281: }
13282: 
13283: ######################################################
13284: ######################################################
13285: 
13286: =pod
13287: 
13288: =item * &csv_print_samples($r,$records)
13289: 
13290: Prints a table of sample values from each column uploaded $r is an
13291: Apache Request ref, $records is an arrayref from
13292: &Apache::loncommon::upfile_record_sep
13293: 
13294: =cut
13295: 
13296: ######################################################
13297: ######################################################
13298: sub csv_print_samples {
13299:     my ($r,$records) = @_;
13300:     my $samples = &get_samples($records,5);
13301: 
13302:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13303:               &start_data_table_header_row());
13304:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13305:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13306:     $r->print(&end_data_table_header_row());
13307:     foreach my $hash (@$samples) {
13308: 	$r->print(&start_data_table_row());
13309: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13310: 	    $r->print('<td>');
13311: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13312: 	    $r->print('</td>');
13313: 	}
13314: 	$r->print(&end_data_table_row());
13315:     }
13316:     $r->print(&end_data_table().'<br />'."\n");
13317: }
13318: 
13319: ######################################################
13320: ######################################################
13321: 
13322: =pod
13323: 
13324: =item * &csv_print_select_table($r,$records,$d)
13325: 
13326: Prints a table to create associations between values and table columns.
13327: 
13328: $r is an Apache Request ref,
13329: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13330: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13331: 
13332: =cut
13333: 
13334: ######################################################
13335: ######################################################
13336: sub csv_print_select_table {
13337:     my ($r,$records,$d) = @_;
13338:     my $i=0;
13339:     my $samples = &get_samples($records,1);
13340:     $r->print(&mt('Associate columns with student attributes.')."\n".
13341: 	      &start_data_table().&start_data_table_header_row().
13342:               '<th>'.&mt('Attribute').'</th>'.
13343:               '<th>'.&mt('Column').'</th>'.
13344:               &end_data_table_header_row()."\n");
13345:     foreach my $array_ref (@$d) {
13346: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13347: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13348: 
13349: 	$r->print('<td><select name="f'.$i.'"'.
13350: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13351: 	$r->print('<option value="none"></option>');
13352: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13353: 	    $r->print('<option value="'.$sample.'"'.
13354:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13355:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13356: 	}
13357: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13358: 	$i++;
13359:     }
13360:     $r->print(&end_data_table());
13361:     $i--;
13362:     return $i;
13363: }
13364: 
13365: ######################################################
13366: ######################################################
13367: 
13368: =pod
13369: 
13370: =item * &csv_samples_select_table($r,$records,$d)
13371: 
13372: Prints a table of sample values from the upload and can make associate samples to internal names.
13373: 
13374: $r is an Apache Request ref,
13375: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13376: $d is an array of 2 element arrays (internal name, displayed name)
13377: 
13378: =cut
13379: 
13380: ######################################################
13381: ######################################################
13382: sub csv_samples_select_table {
13383:     my ($r,$records,$d) = @_;
13384:     my $i=0;
13385:     #
13386:     my $max_samples = 5;
13387:     my $samples = &get_samples($records,$max_samples);
13388:     $r->print(&start_data_table().
13389:               &start_data_table_header_row().'<th>'.
13390:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13391:               &end_data_table_header_row());
13392: 
13393:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13394: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13395: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13396: 	foreach my $option (@$d) {
13397: 	    my ($value,$display,$defaultcol)=@{ $option };
13398: 	    $r->print('<option value="'.$value.'"'.
13399:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13400:                       $display.'</option>');
13401: 	}
13402: 	$r->print('</select></td><td>');
13403: 	foreach my $line (0..($max_samples-1)) {
13404: 	    if (defined($samples->[$line]{$key})) { 
13405: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13406: 	    }
13407: 	}
13408: 	$r->print('</td>'.&end_data_table_row());
13409: 	$i++;
13410:     }
13411:     $r->print(&end_data_table());
13412:     $i--;
13413:     return($i);
13414: }
13415: 
13416: ######################################################
13417: ######################################################
13418: 
13419: =pod
13420: 
13421: =item * &clean_excel_name($name)
13422: 
13423: Returns a replacement for $name which does not contain any illegal characters.
13424: 
13425: =cut
13426: 
13427: ######################################################
13428: ######################################################
13429: sub clean_excel_name {
13430:     my ($name) = @_;
13431:     $name =~ s/[:\*\?\/\\]//g;
13432:     if (length($name) > 31) {
13433:         $name = substr($name,0,31);
13434:     }
13435:     return $name;
13436: }
13437: 
13438: =pod
13439: 
13440: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13441: 
13442: Returns either 1 or undef
13443: 
13444: 1 if the part is to be hidden, undef if it is to be shown
13445: 
13446: Arguments are:
13447: 
13448: $id the id of the part to be checked
13449: $symb, optional the symb of the resource to check
13450: $udom, optional the domain of the user to check for
13451: $uname, optional the username of the user to check for
13452: 
13453: =cut
13454: 
13455: sub check_if_partid_hidden {
13456:     my ($id,$symb,$udom,$uname) = @_;
13457:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13458: 					 $symb,$udom,$uname);
13459:     my $truth=1;
13460:     #if the string starts with !, then the list is the list to show not hide
13461:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13462:     my @hiddenlist=split(/,/,$hiddenparts);
13463:     foreach my $checkid (@hiddenlist) {
13464: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13465:     }
13466:     return !$truth;
13467: }
13468: 
13469: 
13470: ############################################################
13471: ############################################################
13472: 
13473: =pod
13474: 
13475: =back 
13476: 
13477: =head1 cgi-bin script and graphing routines
13478: 
13479: =over 4
13480: 
13481: =item * &get_cgi_id()
13482: 
13483: Inputs: none
13484: 
13485: Returns an id which can be used to pass environment variables
13486: to various cgi-bin scripts.  These environment variables will
13487: be removed from the users environment after a given time by
13488: the routine &Apache::lonnet::transfer_profile_to_env.
13489: 
13490: =cut
13491: 
13492: ############################################################
13493: ############################################################
13494: my $uniq=0;
13495: sub get_cgi_id {
13496:     $uniq=($uniq+1)%100000;
13497:     return (time.'_'.$$.'_'.$uniq);
13498: }
13499: 
13500: ############################################################
13501: ############################################################
13502: 
13503: =pod
13504: 
13505: =item * &DrawBarGraph()
13506: 
13507: Facilitates the plotting of data in a (stacked) bar graph.
13508: Puts plot definition data into the users environment in order for 
13509: graph.png to plot it.  Returns an <img> tag for the plot.
13510: The bars on the plot are labeled '1','2',...,'n'.
13511: 
13512: Inputs:
13513: 
13514: =over 4
13515: 
13516: =item $Title: string, the title of the plot
13517: 
13518: =item $xlabel: string, text describing the X-axis of the plot
13519: 
13520: =item $ylabel: string, text describing the Y-axis of the plot
13521: 
13522: =item $Max: scalar, the maximum Y value to use in the plot
13523: If $Max is < any data point, the graph will not be rendered.
13524: 
13525: =item $colors: array ref holding the colors to be used for the data sets when
13526: they are plotted.  If undefined, default values will be used.
13527: 
13528: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13529: 
13530: =item @Values: An array of array references.  Each array reference holds data
13531: to be plotted in a stacked bar chart.
13532: 
13533: =item If the final element of @Values is a hash reference the key/value
13534: pairs will be added to the graph definition.
13535: 
13536: =back
13537: 
13538: Returns:
13539: 
13540: An <img> tag which references graph.png and the appropriate identifying
13541: information for the plot.
13542: 
13543: =cut
13544: 
13545: ############################################################
13546: ############################################################
13547: sub DrawBarGraph {
13548:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13549:     #
13550:     if (! defined($colors)) {
13551:         $colors = ['#33ff00', 
13552:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13553:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13554:                   ]; 
13555:     }
13556:     my $extra_settings = {};
13557:     if (ref($Values[-1]) eq 'HASH') {
13558:         $extra_settings = pop(@Values);
13559:     }
13560:     #
13561:     my $identifier = &get_cgi_id();
13562:     my $id = 'cgi.'.$identifier;        
13563:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13564:         return '';
13565:     }
13566:     #
13567:     my @Labels;
13568:     if (defined($labels)) {
13569:         @Labels = @$labels;
13570:     } else {
13571:         for (my $i=0;$i<@{$Values[0]};$i++) {
13572:             push (@Labels,$i+1);
13573:         }
13574:     }
13575:     #
13576:     my $NumBars = scalar(@{$Values[0]});
13577:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13578:     my %ValuesHash;
13579:     my $NumSets=1;
13580:     foreach my $array (@Values) {
13581:         next if (! ref($array));
13582:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13583:             join(',',@$array);
13584:     }
13585:     #
13586:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13587:     if ($NumBars < 3) {
13588:         $width = 120+$NumBars*32;
13589:         $xskip = 1;
13590:         $bar_width = 30;
13591:     } elsif ($NumBars < 5) {
13592:         $width = 120+$NumBars*20;
13593:         $xskip = 1;
13594:         $bar_width = 20;
13595:     } elsif ($NumBars < 10) {
13596:         $width = 120+$NumBars*15;
13597:         $xskip = 1;
13598:         $bar_width = 15;
13599:     } elsif ($NumBars <= 25) {
13600:         $width = 120+$NumBars*11;
13601:         $xskip = 5;
13602:         $bar_width = 8;
13603:     } elsif ($NumBars <= 50) {
13604:         $width = 120+$NumBars*8;
13605:         $xskip = 5;
13606:         $bar_width = 4;
13607:     } else {
13608:         $width = 120+$NumBars*8;
13609:         $xskip = 5;
13610:         $bar_width = 4;
13611:     }
13612:     #
13613:     $Max = 1 if ($Max < 1);
13614:     if ( int($Max) < $Max ) {
13615:         $Max++;
13616:         $Max = int($Max);
13617:     }
13618:     $Title  = '' if (! defined($Title));
13619:     $xlabel = '' if (! defined($xlabel));
13620:     $ylabel = '' if (! defined($ylabel));
13621:     $ValuesHash{$id.'.title'}    = &escape($Title);
13622:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13623:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13624:     $ValuesHash{$id.'.y_max_value'} = $Max;
13625:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13626:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13627:     $ValuesHash{$id.'.PlotType'} = 'bar';
13628:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13629:     $ValuesHash{$id.'.height'}   = $height;
13630:     $ValuesHash{$id.'.width'}    = $width;
13631:     $ValuesHash{$id.'.xskip'}    = $xskip;
13632:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13633:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13634:     #
13635:     # Deal with other parameters
13636:     while (my ($key,$value) = each(%$extra_settings)) {
13637:         $ValuesHash{$id.'.'.$key} = $value;
13638:     }
13639:     #
13640:     &Apache::lonnet::appenv(\%ValuesHash);
13641:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13642: }
13643: 
13644: ############################################################
13645: ############################################################
13646: 
13647: =pod
13648: 
13649: =item * &DrawXYGraph()
13650: 
13651: Facilitates the plotting of data in an XY graph.
13652: Puts plot definition data into the users environment in order for 
13653: graph.png to plot it.  Returns an <img> tag for the plot.
13654: 
13655: Inputs:
13656: 
13657: =over 4
13658: 
13659: =item $Title: string, the title of the plot
13660: 
13661: =item $xlabel: string, text describing the X-axis of the plot
13662: 
13663: =item $ylabel: string, text describing the Y-axis of the plot
13664: 
13665: =item $Max: scalar, the maximum Y value to use in the plot
13666: If $Max is < any data point, the graph will not be rendered.
13667: 
13668: =item $colors: Array ref containing the hex color codes for the data to be 
13669: plotted in.  If undefined, default values will be used.
13670: 
13671: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13672: 
13673: =item $Ydata: Array ref containing Array refs.  
13674: Each of the contained arrays will be plotted as a separate curve.
13675: 
13676: =item %Values: hash indicating or overriding any default values which are 
13677: passed to graph.png.  
13678: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13679: 
13680: =back
13681: 
13682: Returns:
13683: 
13684: An <img> tag which references graph.png and the appropriate identifying
13685: information for the plot.
13686: 
13687: =cut
13688: 
13689: ############################################################
13690: ############################################################
13691: sub DrawXYGraph {
13692:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13693:     #
13694:     # Create the identifier for the graph
13695:     my $identifier = &get_cgi_id();
13696:     my $id = 'cgi.'.$identifier;
13697:     #
13698:     $Title  = '' if (! defined($Title));
13699:     $xlabel = '' if (! defined($xlabel));
13700:     $ylabel = '' if (! defined($ylabel));
13701:     my %ValuesHash = 
13702:         (
13703:          $id.'.title'  => &escape($Title),
13704:          $id.'.xlabel' => &escape($xlabel),
13705:          $id.'.ylabel' => &escape($ylabel),
13706:          $id.'.y_max_value'=> $Max,
13707:          $id.'.labels'     => join(',',@$Xlabels),
13708:          $id.'.PlotType'   => 'XY',
13709:          );
13710:     #
13711:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13712:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13713:     }
13714:     #
13715:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13716:         return '';
13717:     }
13718:     my $NumSets=1;
13719:     foreach my $array (@{$Ydata}){
13720:         next if (! ref($array));
13721:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13722:     }
13723:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13724:     #
13725:     # Deal with other parameters
13726:     while (my ($key,$value) = each(%Values)) {
13727:         $ValuesHash{$id.'.'.$key} = $value;
13728:     }
13729:     #
13730:     &Apache::lonnet::appenv(\%ValuesHash);
13731:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13732: }
13733: 
13734: ############################################################
13735: ############################################################
13736: 
13737: =pod
13738: 
13739: =item * &DrawXYYGraph()
13740: 
13741: Facilitates the plotting of data in an XY graph with two Y axes.
13742: Puts plot definition data into the users environment in order for 
13743: graph.png to plot it.  Returns an <img> tag for the plot.
13744: 
13745: Inputs:
13746: 
13747: =over 4
13748: 
13749: =item $Title: string, the title of the plot
13750: 
13751: =item $xlabel: string, text describing the X-axis of the plot
13752: 
13753: =item $ylabel: string, text describing the Y-axis of the plot
13754: 
13755: =item $colors: Array ref containing the hex color codes for the data to be 
13756: plotted in.  If undefined, default values will be used.
13757: 
13758: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13759: 
13760: =item $Ydata1: The first data set
13761: 
13762: =item $Min1: The minimum value of the left Y-axis
13763: 
13764: =item $Max1: The maximum value of the left Y-axis
13765: 
13766: =item $Ydata2: The second data set
13767: 
13768: =item $Min2: The minimum value of the right Y-axis
13769: 
13770: =item $Max2: The maximum value of the left Y-axis
13771: 
13772: =item %Values: hash indicating or overriding any default values which are 
13773: passed to graph.png.  
13774: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13775: 
13776: =back
13777: 
13778: Returns:
13779: 
13780: An <img> tag which references graph.png and the appropriate identifying
13781: information for the plot.
13782: 
13783: =cut
13784: 
13785: ############################################################
13786: ############################################################
13787: sub DrawXYYGraph {
13788:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13789:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13790:     #
13791:     # Create the identifier for the graph
13792:     my $identifier = &get_cgi_id();
13793:     my $id = 'cgi.'.$identifier;
13794:     #
13795:     $Title  = '' if (! defined($Title));
13796:     $xlabel = '' if (! defined($xlabel));
13797:     $ylabel = '' if (! defined($ylabel));
13798:     my %ValuesHash = 
13799:         (
13800:          $id.'.title'  => &escape($Title),
13801:          $id.'.xlabel' => &escape($xlabel),
13802:          $id.'.ylabel' => &escape($ylabel),
13803:          $id.'.labels' => join(',',@$Xlabels),
13804:          $id.'.PlotType' => 'XY',
13805:          $id.'.NumSets' => 2,
13806:          $id.'.two_axes' => 1,
13807:          $id.'.y1_max_value' => $Max1,
13808:          $id.'.y1_min_value' => $Min1,
13809:          $id.'.y2_max_value' => $Max2,
13810:          $id.'.y2_min_value' => $Min2,
13811:          );
13812:     #
13813:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13814:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13815:     }
13816:     #
13817:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13818:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13819:         return '';
13820:     }
13821:     my $NumSets=1;
13822:     foreach my $array ($Ydata1,$Ydata2){
13823:         next if (! ref($array));
13824:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13825:     }
13826:     #
13827:     # Deal with other parameters
13828:     while (my ($key,$value) = each(%Values)) {
13829:         $ValuesHash{$id.'.'.$key} = $value;
13830:     }
13831:     #
13832:     &Apache::lonnet::appenv(\%ValuesHash);
13833:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13834: }
13835: 
13836: ############################################################
13837: ############################################################
13838: 
13839: =pod
13840: 
13841: =back 
13842: 
13843: =head1 Statistics helper routines?  
13844: 
13845: Bad place for them but what the hell.
13846: 
13847: =over 4
13848: 
13849: =item * &chartlink()
13850: 
13851: Returns a link to the chart for a specific student.  
13852: 
13853: Inputs:
13854: 
13855: =over 4
13856: 
13857: =item $linktext: The text of the link
13858: 
13859: =item $sname: The students username
13860: 
13861: =item $sdomain: The students domain
13862: 
13863: =back
13864: 
13865: =back
13866: 
13867: =cut
13868: 
13869: ############################################################
13870: ############################################################
13871: sub chartlink {
13872:     my ($linktext, $sname, $sdomain) = @_;
13873:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13874:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13875:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13876:        '">'.$linktext.'</a>';
13877: }
13878: 
13879: #######################################################
13880: #######################################################
13881: 
13882: =pod
13883: 
13884: =head1 Course Environment Routines
13885: 
13886: =over 4
13887: 
13888: =item * &restore_course_settings()
13889: 
13890: =item * &store_course_settings()
13891: 
13892: Restores/Store indicated form parameters from the course environment.
13893: Will not overwrite existing values of the form parameters.
13894: 
13895: Inputs: 
13896: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13897: 
13898: a hash ref describing the data to be stored.  For example:
13899:    
13900: %Save_Parameters = ('Status' => 'scalar',
13901:     'chartoutputmode' => 'scalar',
13902:     'chartoutputdata' => 'scalar',
13903:     'Section' => 'array',
13904:     'Group' => 'array',
13905:     'StudentData' => 'array',
13906:     'Maps' => 'array');
13907: 
13908: Returns: both routines return nothing
13909: 
13910: =back
13911: 
13912: =cut
13913: 
13914: #######################################################
13915: #######################################################
13916: sub store_course_settings {
13917:     return &store_settings($env{'request.course.id'},@_);
13918: }
13919: 
13920: sub store_settings {
13921:     # save to the environment
13922:     # appenv the same items, just to be safe
13923:     my $udom  = $env{'user.domain'};
13924:     my $uname = $env{'user.name'};
13925:     my ($context,$prefix,$Settings) = @_;
13926:     my %SaveHash;
13927:     my %AppHash;
13928:     while (my ($setting,$type) = each(%$Settings)) {
13929:         my $basename = join('.','internal',$context,$prefix,$setting);
13930:         my $envname = 'environment.'.$basename;
13931:         if (exists($env{'form.'.$setting})) {
13932:             # Save this value away
13933:             if ($type eq 'scalar' &&
13934:                 (! exists($env{$envname}) || 
13935:                  $env{$envname} ne $env{'form.'.$setting})) {
13936:                 $SaveHash{$basename} = $env{'form.'.$setting};
13937:                 $AppHash{$envname}   = $env{'form.'.$setting};
13938:             } elsif ($type eq 'array') {
13939:                 my $stored_form;
13940:                 if (ref($env{'form.'.$setting})) {
13941:                     $stored_form = join(',',
13942:                                         map {
13943:                                             &escape($_);
13944:                                         } sort(@{$env{'form.'.$setting}}));
13945:                 } else {
13946:                     $stored_form = 
13947:                         &escape($env{'form.'.$setting});
13948:                 }
13949:                 # Determine if the array contents are the same.
13950:                 if ($stored_form ne $env{$envname}) {
13951:                     $SaveHash{$basename} = $stored_form;
13952:                     $AppHash{$envname}   = $stored_form;
13953:                 }
13954:             }
13955:         }
13956:     }
13957:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13958:                                           $udom,$uname);
13959:     if ($put_result !~ /^(ok|delayed)/) {
13960:         &Apache::lonnet::logthis('unable to save form parameters, '.
13961:                                  'got error:'.$put_result);
13962:     }
13963:     # Make sure these settings stick around in this session, too
13964:     &Apache::lonnet::appenv(\%AppHash);
13965:     return;
13966: }
13967: 
13968: sub restore_course_settings {
13969:     return &restore_settings($env{'request.course.id'},@_);
13970: }
13971: 
13972: sub restore_settings {
13973:     my ($context,$prefix,$Settings) = @_;
13974:     while (my ($setting,$type) = each(%$Settings)) {
13975:         next if (exists($env{'form.'.$setting}));
13976:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13977:             '.'.$setting;
13978:         if (exists($env{$envname})) {
13979:             if ($type eq 'scalar') {
13980:                 $env{'form.'.$setting} = $env{$envname};
13981:             } elsif ($type eq 'array') {
13982:                 $env{'form.'.$setting} = [ 
13983:                                            map { 
13984:                                                &unescape($_); 
13985:                                            } split(',',$env{$envname})
13986:                                            ];
13987:             }
13988:         }
13989:     }
13990: }
13991: 
13992: #######################################################
13993: #######################################################
13994: 
13995: =pod
13996: 
13997: =head1 Domain E-mail Routines  
13998: 
13999: =over 4
14000: 
14001: =item * &build_recipient_list()
14002: 
14003: Build recipient lists for following types of e-mail:
14004: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14005: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14006: module change checking, student/employee ID conflict checks, as
14007: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14008: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14009: 
14010: Inputs:
14011: defmail (scalar - email address of default recipient), 
14012: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14013: requestsmail, updatesmail, or idconflictsmail).
14014: 
14015: defdom (domain for which to retrieve configuration settings),
14016: 
14017: origmail (scalar - email address of recipient from loncapa.conf, 
14018: i.e., predates configuration by DC via domainprefs.pm 
14019: 
14020: Returns: comma separated list of addresses to which to send e-mail.
14021: 
14022: =back
14023: 
14024: =cut
14025: 
14026: ############################################################
14027: ############################################################
14028: sub build_recipient_list {
14029:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14030:     my @recipients;
14031:     my $otheremails;
14032:     my %domconfig =
14033:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14034:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14035:         if (exists($domconfig{'contacts'}{$mailing})) {
14036:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14037:                 my @contacts = ('adminemail','supportemail');
14038:                 foreach my $item (@contacts) {
14039:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14040:                         my $addr = $domconfig{'contacts'}{$item}; 
14041:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14042:                             push(@recipients,$addr);
14043:                         }
14044:                     }
14045:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14046:                 }
14047:             }
14048:         } elsif ($origmail ne '') {
14049:             push(@recipients,$origmail);
14050:         }
14051:     } elsif ($origmail ne '') {
14052:         push(@recipients,$origmail);
14053:     }
14054:     if (defined($defmail)) {
14055:         if ($defmail ne '') {
14056:             push(@recipients,$defmail);
14057:         }
14058:     }
14059:     if ($otheremails) {
14060:         my @others;
14061:         if ($otheremails =~ /,/) {
14062:             @others = split(/,/,$otheremails);
14063:         } else {
14064:             push(@others,$otheremails);
14065:         }
14066:         foreach my $addr (@others) {
14067:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14068:                 push(@recipients,$addr);
14069:             }
14070:         }
14071:     }
14072:     my $recipientlist = join(',',@recipients); 
14073:     return $recipientlist;
14074: }
14075: 
14076: ############################################################
14077: ############################################################
14078: 
14079: =pod
14080: 
14081: =over 4
14082: 
14083: =item * &mime_email()
14084: 
14085: Sends an email with a possible attachment
14086: 
14087: Inputs:
14088: 
14089: =over 4
14090: 
14091: from -              Sender's email address
14092: 
14093: to -                Email address of recipient
14094: 
14095: subject -           Subject of email
14096: 
14097: body -              Body of email
14098: 
14099: cc_string -         Carbon copy email address
14100: 
14101: bcc -               Blind carbon copy email address
14102: 
14103: type -              File type of attachment
14104: 
14105: attachment_path -   Path of file to be attached
14106: 
14107: file_name -         Name of file to be attached
14108: 
14109: attachment_text -   The body of an attachment of type "TEXT"
14110: 
14111: =back
14112: 
14113: =back
14114: 
14115: =cut
14116: 
14117: ############################################################
14118: ############################################################
14119: 
14120: sub mime_email {
14121:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14122:         $file_name, $attachment_text) = @_;
14123:     my $msg = MIME::Lite->new(
14124:              From    => $from,
14125:              To      => $to,
14126:              Subject => $subject,
14127:              Type    =>'TEXT',
14128:              Data    => $body,
14129:              );
14130:     if ($cc_string ne '') {
14131:         $msg->add("Cc" => $cc_string);
14132:     }
14133:     if ($bcc ne '') {
14134:         $msg->add("Bcc" => $bcc);
14135:     }
14136:     $msg->attr("content-type"         => "text/plain");
14137:     $msg->attr("content-type.charset" => "UTF-8");
14138:     # Attach file if given
14139:     if ($attachment_path) {
14140:         unless ($file_name) {
14141:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14142:         }
14143:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14144:         $msg->attach(Type     => $type,
14145:                      Path     => $attachment_path,
14146:                      Filename => $file_name
14147:                      );
14148:     # Otherwise attach text if given
14149:     } elsif ($attachment_text) {
14150:         $msg->attach(Type => 'TEXT',
14151:                      Data => $attachment_text);
14152:     }
14153:     # Send it
14154:     $msg->send('sendmail');
14155: }
14156: 
14157: ############################################################
14158: ############################################################
14159: 
14160: =pod
14161: 
14162: =head1 Course Catalog Routines
14163: 
14164: =over 4
14165: 
14166: =item * &gather_categories()
14167: 
14168: Converts category definitions - keys of categories hash stored in  
14169: coursecategories in configuration.db on the primary library server in a 
14170: domain - to an array.  Also generates javascript and idx hash used to 
14171: generate Domain Coordinator interface for editing Course Categories.
14172: 
14173: Inputs:
14174: 
14175: categories (reference to hash of category definitions).
14176: 
14177: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14178:       categories and subcategories).
14179: 
14180: idx (reference to hash of counters used in Domain Coordinator interface for 
14181:       editing Course Categories).
14182: 
14183: jsarray (reference to array of categories used to create Javascript arrays for
14184:          Domain Coordinator interface for editing Course Categories).
14185: 
14186: Returns: nothing
14187: 
14188: Side effects: populates cats, idx and jsarray. 
14189: 
14190: =cut
14191: 
14192: sub gather_categories {
14193:     my ($categories,$cats,$idx,$jsarray) = @_;
14194:     my %counters;
14195:     my $num = 0;
14196:     foreach my $item (keys(%{$categories})) {
14197:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14198:         if ($container eq '' && $depth == 0) {
14199:             $cats->[$depth][$categories->{$item}] = $cat;
14200:         } else {
14201:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14202:         }
14203:         my ($escitem,$tail) = split(/:/,$item,2);
14204:         if ($counters{$tail} eq '') {
14205:             $counters{$tail} = $num;
14206:             $num ++;
14207:         }
14208:         if (ref($idx) eq 'HASH') {
14209:             $idx->{$item} = $counters{$tail};
14210:         }
14211:         if (ref($jsarray) eq 'ARRAY') {
14212:             push(@{$jsarray->[$counters{$tail}]},$item);
14213:         }
14214:     }
14215:     return;
14216: }
14217: 
14218: =pod
14219: 
14220: =item * &extract_categories()
14221: 
14222: Used to generate breadcrumb trails for course categories.
14223: 
14224: Inputs:
14225: 
14226: categories (reference to hash of category definitions).
14227: 
14228: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14229:       categories and subcategories).
14230: 
14231: trails (reference to array of breacrumb trails for each category).
14232: 
14233: allitems (reference to hash - key is category key 
14234:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14235: 
14236: idx (reference to hash of counters used in Domain Coordinator interface for
14237:       editing Course Categories).
14238: 
14239: jsarray (reference to array of categories used to create Javascript arrays for
14240:          Domain Coordinator interface for editing Course Categories).
14241: 
14242: subcats (reference to hash of arrays containing all subcategories within each 
14243:          category, -recursive)
14244: 
14245: Returns: nothing
14246: 
14247: Side effects: populates trails and allitems hash references.
14248: 
14249: =cut
14250: 
14251: sub extract_categories {
14252:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14253:     if (ref($categories) eq 'HASH') {
14254:         &gather_categories($categories,$cats,$idx,$jsarray);
14255:         if (ref($cats->[0]) eq 'ARRAY') {
14256:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14257:                 my $name = $cats->[0][$i];
14258:                 my $item = &escape($name).'::0';
14259:                 my $trailstr;
14260:                 if ($name eq 'instcode') {
14261:                     $trailstr = &mt('Official courses (with institutional codes)');
14262:                 } elsif ($name eq 'communities') {
14263:                     $trailstr = &mt('Communities');
14264:                 } else {
14265:                     $trailstr = $name;
14266:                 }
14267:                 if ($allitems->{$item} eq '') {
14268:                     push(@{$trails},$trailstr);
14269:                     $allitems->{$item} = scalar(@{$trails})-1;
14270:                 }
14271:                 my @parents = ($name);
14272:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14273:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14274:                         my $category = $cats->[1]{$name}[$j];
14275:                         if (ref($subcats) eq 'HASH') {
14276:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14277:                         }
14278:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14279:                     }
14280:                 } else {
14281:                     if (ref($subcats) eq 'HASH') {
14282:                         $subcats->{$item} = [];
14283:                     }
14284:                 }
14285:             }
14286:         }
14287:     }
14288:     return;
14289: }
14290: 
14291: =pod
14292: 
14293: =item * &recurse_categories()
14294: 
14295: Recursively used to generate breadcrumb trails for course categories.
14296: 
14297: Inputs:
14298: 
14299: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14300:       categories and subcategories).
14301: 
14302: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14303: 
14304: category (current course category, for which breadcrumb trail is being generated).
14305: 
14306: trails (reference to array of breadcrumb trails for each category).
14307: 
14308: allitems (reference to hash - key is category key
14309:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14310: 
14311: parents (array containing containers directories for current category, 
14312:          back to top level). 
14313: 
14314: Returns: nothing
14315: 
14316: Side effects: populates trails and allitems hash references
14317: 
14318: =cut
14319: 
14320: sub recurse_categories {
14321:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14322:     my $shallower = $depth - 1;
14323:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14324:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14325:             my $name = $cats->[$depth]{$category}[$k];
14326:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14327:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14328:             if ($allitems->{$item} eq '') {
14329:                 push(@{$trails},$trailstr);
14330:                 $allitems->{$item} = scalar(@{$trails})-1;
14331:             }
14332:             my $deeper = $depth+1;
14333:             push(@{$parents},$category);
14334:             if (ref($subcats) eq 'HASH') {
14335:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14336:                 for (my $j=@{$parents}; $j>=0; $j--) {
14337:                     my $higher;
14338:                     if ($j > 0) {
14339:                         $higher = &escape($parents->[$j]).':'.
14340:                                   &escape($parents->[$j-1]).':'.$j;
14341:                     } else {
14342:                         $higher = &escape($parents->[$j]).'::'.$j;
14343:                     }
14344:                     push(@{$subcats->{$higher}},$subcat);
14345:                 }
14346:             }
14347:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14348:                                 $subcats);
14349:             pop(@{$parents});
14350:         }
14351:     } else {
14352:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14353:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14354:         if ($allitems->{$item} eq '') {
14355:             push(@{$trails},$trailstr);
14356:             $allitems->{$item} = scalar(@{$trails})-1;
14357:         }
14358:     }
14359:     return;
14360: }
14361: 
14362: =pod
14363: 
14364: =item * &assign_categories_table()
14365: 
14366: Create a datatable for display of hierarchical categories in a domain,
14367: with checkboxes to allow a course to be categorized. 
14368: 
14369: Inputs:
14370: 
14371: cathash - reference to hash of categories defined for the domain (from
14372:           configuration.db)
14373: 
14374: currcat - scalar with an & separated list of categories assigned to a course. 
14375: 
14376: type    - scalar contains course type (Course or Community).
14377: 
14378: Returns: $output (markup to be displayed) 
14379: 
14380: =cut
14381: 
14382: sub assign_categories_table {
14383:     my ($cathash,$currcat,$type) = @_;
14384:     my $output;
14385:     if (ref($cathash) eq 'HASH') {
14386:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14387:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14388:         $maxdepth = scalar(@cats);
14389:         if (@cats > 0) {
14390:             my $itemcount = 0;
14391:             if (ref($cats[0]) eq 'ARRAY') {
14392:                 my @currcategories;
14393:                 if ($currcat ne '') {
14394:                     @currcategories = split('&',$currcat);
14395:                 }
14396:                 my $table;
14397:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14398:                     my $parent = $cats[0][$i];
14399:                     next if ($parent eq 'instcode');
14400:                     if ($type eq 'Community') {
14401:                         next unless ($parent eq 'communities');
14402:                     } else {
14403:                         next if ($parent eq 'communities');
14404:                     }
14405:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14406:                     my $item = &escape($parent).'::0';
14407:                     my $checked = '';
14408:                     if (@currcategories > 0) {
14409:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14410:                             $checked = ' checked="checked"';
14411:                         }
14412:                     }
14413:                     my $parent_title = $parent;
14414:                     if ($parent eq 'communities') {
14415:                         $parent_title = &mt('Communities');
14416:                     }
14417:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14418:                               '<input type="checkbox" name="usecategory" value="'.
14419:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
14420:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14421:                     my $depth = 1;
14422:                     push(@path,$parent);
14423:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14424:                     pop(@path);
14425:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14426:                     $itemcount ++;
14427:                 }
14428:                 if ($itemcount) {
14429:                     $output = &Apache::loncommon::start_data_table().
14430:                               $table.
14431:                               &Apache::loncommon::end_data_table();
14432:                 }
14433:             }
14434:         }
14435:     }
14436:     return $output;
14437: }
14438: 
14439: =pod
14440: 
14441: =item * &assign_category_rows()
14442: 
14443: Create a datatable row for display of nested categories in a domain,
14444: with checkboxes to allow a course to be categorized,called recursively.
14445: 
14446: Inputs:
14447: 
14448: itemcount - track row number for alternating colors
14449: 
14450: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14451:       categories and subcategories.
14452: 
14453: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14454: 
14455: parent - parent of current category item
14456: 
14457: path - Array containing all categories back up through the hierarchy from the
14458:        current category to the top level.
14459: 
14460: currcategories - reference to array of current categories assigned to the course
14461: 
14462: Returns: $output (markup to be displayed).
14463: 
14464: =cut
14465: 
14466: sub assign_category_rows {
14467:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14468:     my ($text,$name,$item,$chgstr);
14469:     if (ref($cats) eq 'ARRAY') {
14470:         my $maxdepth = scalar(@{$cats});
14471:         if (ref($cats->[$depth]) eq 'HASH') {
14472:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14473:                 my $numchildren = @{$cats->[$depth]{$parent}};
14474:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14475:                 $text .= '<td><table class="LC_data_table">';
14476:                 for (my $j=0; $j<$numchildren; $j++) {
14477:                     $name = $cats->[$depth]{$parent}[$j];
14478:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14479:                     my $deeper = $depth+1;
14480:                     my $checked = '';
14481:                     if (ref($currcategories) eq 'ARRAY') {
14482:                         if (@{$currcategories} > 0) {
14483:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14484:                                 $checked = ' checked="checked"';
14485:                             }
14486:                         }
14487:                     }
14488:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14489:                              '<input type="checkbox" name="usecategory" value="'.
14490:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
14491:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14492:                              '</td><td>';
14493:                     if (ref($path) eq 'ARRAY') {
14494:                         push(@{$path},$name);
14495:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14496:                         pop(@{$path});
14497:                     }
14498:                     $text .= '</td></tr>';
14499:                 }
14500:                 $text .= '</table></td>';
14501:             }
14502:         }
14503:     }
14504:     return $text;
14505: }
14506: 
14507: =pod
14508: 
14509: =back
14510: 
14511: =cut
14512: 
14513: ############################################################
14514: ############################################################
14515: 
14516: 
14517: sub commit_customrole {
14518:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14519:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14520:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14521:                          ($end?', ending '.localtime($end):'').': <b>'.
14522:               &Apache::lonnet::assigncustomrole(
14523:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14524:                  '</b><br />';
14525:     return $output;
14526: }
14527: 
14528: sub commit_standardrole {
14529:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14530:     my ($output,$logmsg,$linefeed);
14531:     if ($context eq 'auto') {
14532:         $linefeed = "\n";
14533:     } else {
14534:         $linefeed = "<br />\n";
14535:     }  
14536:     if ($three eq 'st') {
14537:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14538:                                          $one,$two,$sec,$context,$credits);
14539:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14540:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14541:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14542:         } else {
14543:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14544:                ($start?', '.&mt('starting').' '.localtime($start):'').
14545:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14546:             if ($context eq 'auto') {
14547:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14548:             } else {
14549:                $output .= '<b>'.$result.'</b>'.$linefeed.
14550:                &mt('Add to classlist').': <b>ok</b>';
14551:             }
14552:             $output .= $linefeed;
14553:         }
14554:     } else {
14555:         $output = &mt('Assigning').' '.$three.' in '.$url.
14556:                ($start?', '.&mt('starting').' '.localtime($start):'').
14557:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14558:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14559:         if ($context eq 'auto') {
14560:             $output .= $result.$linefeed;
14561:         } else {
14562:             $output .= '<b>'.$result.'</b>'.$linefeed;
14563:         }
14564:     }
14565:     return $output;
14566: }
14567: 
14568: sub commit_studentrole {
14569:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14570:         $credits) = @_;
14571:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14572:     if ($context eq 'auto') {
14573:         $linefeed = "\n";
14574:     } else {
14575:         $linefeed = '<br />'."\n";
14576:     }
14577:     if (defined($one) && defined($two)) {
14578:         my $cid=$one.'_'.$two;
14579:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14580:         my $secchange = 0;
14581:         my $expire_role_result;
14582:         my $modify_section_result;
14583:         if ($oldsec ne '-1') { 
14584:             if ($oldsec ne $sec) {
14585:                 $secchange = 1;
14586:                 my $now = time;
14587:                 my $uurl='/'.$cid;
14588:                 $uurl=~s/\_/\//g;
14589:                 if ($oldsec) {
14590:                     $uurl.='/'.$oldsec;
14591:                 }
14592:                 $oldsecurl = $uurl;
14593:                 $expire_role_result = 
14594:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14595:                 if ($env{'request.course.sec'} ne '') { 
14596:                     if ($expire_role_result eq 'refused') {
14597:                         my @roles = ('st');
14598:                         my @statuses = ('previous');
14599:                         my @roledoms = ($one);
14600:                         my $withsec = 1;
14601:                         my %roleshash = 
14602:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14603:                                               \@statuses,\@roles,\@roledoms,$withsec);
14604:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14605:                             my ($oldstart,$oldend) = 
14606:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14607:                             if ($oldend > 0 && $oldend <= $now) {
14608:                                 $expire_role_result = 'ok';
14609:                             }
14610:                         }
14611:                     }
14612:                 }
14613:                 $result = $expire_role_result;
14614:             }
14615:         }
14616:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14617:             $modify_section_result = 
14618:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14619:                                                            undef,undef,undef,$sec,
14620:                                                            $end,$start,'','',$cid,
14621:                                                            '',$context,$credits);
14622:             if ($modify_section_result =~ /^ok/) {
14623:                 if ($secchange == 1) {
14624:                     if ($sec eq '') {
14625:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14626:                     } else {
14627:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14628:                     }
14629:                 } elsif ($oldsec eq '-1') {
14630:                     if ($sec eq '') {
14631:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14632:                     } else {
14633:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14634:                     }
14635:                 } else {
14636:                     if ($sec eq '') {
14637:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14638:                     } else {
14639:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14640:                     }
14641:                 }
14642:             } else {
14643:                 if ($secchange) { 
14644:                     $$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;
14645:                 } else {
14646:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14647:                 }
14648:             }
14649:             $result = $modify_section_result;
14650:         } elsif ($secchange == 1) {
14651:             if ($oldsec eq '') {
14652:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14653:             } else {
14654:                 $$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;
14655:             }
14656:             if ($expire_role_result eq 'refused') {
14657:                 my $newsecurl = '/'.$cid;
14658:                 $newsecurl =~ s/\_/\//g;
14659:                 if ($sec ne '') {
14660:                     $newsecurl.='/'.$sec;
14661:                 }
14662:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14663:                     if ($sec eq '') {
14664:                         $$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;
14665:                     } else {
14666:                         $$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;
14667:                     }
14668:                 }
14669:             }
14670:         }
14671:     } else {
14672:         $$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;
14673:         $result = "error: incomplete course id\n";
14674:     }
14675:     return $result;
14676: }
14677: 
14678: sub show_role_extent {
14679:     my ($scope,$context,$role) = @_;
14680:     $scope =~ s{^/}{};
14681:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14682:     push(@courseroles,'co');
14683:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14684:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14685:         $scope =~ s{/}{_};
14686:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14687:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14688:         my ($audom,$auname) = split(/\//,$scope);
14689:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14690:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14691:     } else {
14692:         $scope =~ s{/$}{};
14693:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14694:                    &Apache::lonnet::domain($scope,'description').'</span>');
14695:     }
14696: }
14697: 
14698: ############################################################
14699: ############################################################
14700: 
14701: sub check_clone {
14702:     my ($args,$linefeed) = @_;
14703:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14704:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14705:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14706:     my $clonemsg;
14707:     my $can_clone = 0;
14708:     my $lctype = lc($args->{'crstype'});
14709:     if ($lctype ne 'community') {
14710:         $lctype = 'course';
14711:     }
14712:     if ($clonehome eq 'no_host') {
14713:         if ($args->{'crstype'} eq 'Community') {
14714:             $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'});
14715:         } else {
14716:             $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'});
14717:         }     
14718:     } else {
14719: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14720:         if ($args->{'crstype'} eq 'Community') {
14721:             if ($clonedesc{'type'} ne 'Community') {
14722:                  $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'});
14723:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14724:             }
14725:         }
14726: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14727:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14728: 	    $can_clone = 1;
14729: 	} else {
14730: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14731: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14732:             if ($clonehash{'cloners'} eq '') {
14733:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14734:                 if ($domdefs{'canclone'}) {
14735:                     unless ($domdefs{'canclone'} eq 'none') {
14736:                         if ($domdefs{'canclone'} eq 'domain') {
14737:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14738:                                 $can_clone = 1;
14739:                             }
14740:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
14741:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14742:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14743:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14744:                                 $can_clone = 1;
14745:                             }
14746:                         }
14747:                     }
14748:                 }
14749:             } else {
14750: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14751:                 if (grep(/^\*$/,@cloners)) {
14752:                     $can_clone = 1;
14753:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14754:                     $can_clone = 1;
14755:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14756:                     $can_clone = 1;
14757:                 }
14758:                 unless ($can_clone) {
14759:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
14760:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14761:                         my (%gotdomdefaults,%gotcodedefaults);
14762:                         foreach my $cloner (@cloners) {
14763:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14764:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14765:                                 my (%codedefaults,@code_order);
14766:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14767:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14768:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14769:                                     }
14770:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14771:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14772:                                     }
14773:                                 } else {
14774:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14775:                                                                             \%codedefaults,
14776:                                                                             \@code_order);
14777:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14778:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14779:                                 }
14780:                                 if (@code_order > 0) {
14781:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14782:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14783:                                                                                 $args->{'crscode'})) {
14784:                                         $can_clone = 1;
14785:                                         last;
14786:                                     }
14787:                                 }
14788:                             }
14789:                         }
14790:                     }
14791:                 }
14792:             }
14793:             unless ($can_clone) {
14794:                 my $ccrole = 'cc';
14795:                 if ($args->{'crstype'} eq 'Community') {
14796:                     $ccrole = 'co';
14797:                 }
14798: 	        my %roleshash =
14799: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
14800: 					          $args->{'ccdomain'},
14801:                                                   'userroles',['active'],[$ccrole],
14802: 					          [$args->{'clonedomain'}]);
14803: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14804:                     $can_clone = 1;
14805:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14806:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14807:                     $can_clone = 1;
14808:                 }
14809:             }
14810:             unless ($can_clone) {
14811:                 if ($args->{'crstype'} eq 'Community') {
14812:                     $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'});
14813:                 } else {
14814:                     $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'});
14815:                 }
14816: 	    }
14817:         }
14818:     }
14819:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14820: }
14821: 
14822: sub construct_course {
14823:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14824:     my $outcome;
14825:     my $linefeed =  '<br />'."\n";
14826:     if ($context eq 'auto') {
14827:         $linefeed = "\n";
14828:     }
14829: 
14830: #
14831: # Are we cloning?
14832: #
14833:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14834:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14835: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14836: 	if ($context ne 'auto') {
14837:             if ($clonemsg ne '') {
14838: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14839:             }
14840: 	}
14841: 	$outcome .= $clonemsg.$linefeed;
14842: 
14843:         if (!$can_clone) {
14844: 	    return (0,$outcome);
14845: 	}
14846:     }
14847: 
14848: #
14849: # Open course
14850: #
14851:     my $crstype = lc($args->{'crstype'});
14852:     my %cenv=();
14853:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14854:                                              $args->{'cdescr'},
14855:                                              $args->{'curl'},
14856:                                              $args->{'course_home'},
14857:                                              $args->{'nonstandard'},
14858:                                              $args->{'crscode'},
14859:                                              $args->{'ccuname'}.':'.
14860:                                              $args->{'ccdomain'},
14861:                                              $args->{'crstype'},
14862:                                              $cnum,$context,$category);
14863: 
14864:     # Note: The testing routines depend on this being output; see 
14865:     # Utils::Course. This needs to at least be output as a comment
14866:     # if anyone ever decides to not show this, and Utils::Course::new
14867:     # will need to be suitably modified.
14868:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14869:     if ($$courseid =~ /^error:/) {
14870:         return (0,$outcome);
14871:     }
14872: 
14873: #
14874: # Check if created correctly
14875: #
14876:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14877:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14878:     if ($crsuhome eq 'no_host') {
14879:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14880:         return (0,$outcome);
14881:     }
14882:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14883: 
14884: #
14885: # Do the cloning
14886: #   
14887:     if ($can_clone && $cloneid) {
14888: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14889: 	if ($context ne 'auto') {
14890: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14891: 	}
14892: 	$outcome .= $clonemsg.$linefeed;
14893: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14894: # Copy all files
14895: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14896: # Restore URL
14897: 	$cenv{'url'}=$oldcenv{'url'};
14898: # Restore title
14899: 	$cenv{'description'}=$oldcenv{'description'};
14900: # Restore creation date, creator and creation context.
14901:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14902:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14903:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14904: # Mark as cloned
14905: 	$cenv{'clonedfrom'}=$cloneid;
14906: # Need to clone grading mode
14907:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14908:         $cenv{'grading'}=$newenv{'grading'};
14909: # Do not clone these environment entries
14910:         &Apache::lonnet::del('environment',
14911:                   ['default_enrollment_start_date',
14912:                    'default_enrollment_end_date',
14913:                    'question.email',
14914:                    'policy.email',
14915:                    'comment.email',
14916:                    'pch.users.denied',
14917:                    'plc.users.denied',
14918:                    'hidefromcat',
14919:                    'checkforpriv',
14920:                    'categories',
14921:                    'internal.uniquecode'],
14922:                    $$crsudom,$$crsunum);
14923:         if ($args->{'textbook'}) {
14924:             $cenv{'internal.textbook'} = $args->{'textbook'};
14925:         }
14926:     }
14927: 
14928: #
14929: # Set environment (will override cloned, if existing)
14930: #
14931:     my @sections = ();
14932:     my @xlists = ();
14933:     if ($args->{'crstype'}) {
14934:         $cenv{'type'}=$args->{'crstype'};
14935:     }
14936:     if ($args->{'crsid'}) {
14937:         $cenv{'courseid'}=$args->{'crsid'};
14938:     }
14939:     if ($args->{'crscode'}) {
14940:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14941:     }
14942:     if ($args->{'crsquota'} ne '') {
14943:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14944:     } else {
14945:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14946:     }
14947:     if ($args->{'ccuname'}) {
14948:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14949:                                         ':'.$args->{'ccdomain'};
14950:     } else {
14951:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14952:     }
14953:     if ($args->{'defaultcredits'}) {
14954:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14955:     }
14956:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14957:     if ($args->{'crssections'}) {
14958:         $cenv{'internal.sectionnums'} = '';
14959:         if ($args->{'crssections'} =~ m/,/) {
14960:             @sections = split/,/,$args->{'crssections'};
14961:         } else {
14962:             $sections[0] = $args->{'crssections'};
14963:         }
14964:         if (@sections > 0) {
14965:             foreach my $item (@sections) {
14966:                 my ($sec,$gp) = split/:/,$item;
14967:                 my $class = $args->{'crscode'}.$sec;
14968:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14969:                 $cenv{'internal.sectionnums'} .= $item.',';
14970:                 unless ($addcheck eq 'ok') {
14971:                     push @badclasses, $class;
14972:                 }
14973:             }
14974:             $cenv{'internal.sectionnums'} =~ s/,$//;
14975:         }
14976:     }
14977: # do not hide course coordinator from staff listing, 
14978: # even if privileged
14979:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14980: # add course coordinator's domain to domains to check for privileged users
14981: # if different to course domain
14982:     if ($$crsudom ne $args->{'ccdomain'}) {
14983:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14984:     }
14985: # add crosslistings
14986:     if ($args->{'crsxlist'}) {
14987:         $cenv{'internal.crosslistings'}='';
14988:         if ($args->{'crsxlist'} =~ m/,/) {
14989:             @xlists = split/,/,$args->{'crsxlist'};
14990:         } else {
14991:             $xlists[0] = $args->{'crsxlist'};
14992:         }
14993:         if (@xlists > 0) {
14994:             foreach my $item (@xlists) {
14995:                 my ($xl,$gp) = split/:/,$item;
14996:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14997:                 $cenv{'internal.crosslistings'} .= $item.',';
14998:                 unless ($addcheck eq 'ok') {
14999:                     push @badclasses, $xl;
15000:                 }
15001:             }
15002:             $cenv{'internal.crosslistings'} =~ s/,$//;
15003:         }
15004:     }
15005:     if ($args->{'autoadds'}) {
15006:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15007:     }
15008:     if ($args->{'autodrops'}) {
15009:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15010:     }
15011: # check for notification of enrollment changes
15012:     my @notified = ();
15013:     if ($args->{'notify_owner'}) {
15014:         if ($args->{'ccuname'} ne '') {
15015:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15016:         }
15017:     }
15018:     if ($args->{'notify_dc'}) {
15019:         if ($uname ne '') { 
15020:             push(@notified,$uname.':'.$udom);
15021:         }
15022:     }
15023:     if (@notified > 0) {
15024:         my $notifylist;
15025:         if (@notified > 1) {
15026:             $notifylist = join(',',@notified);
15027:         } else {
15028:             $notifylist = $notified[0];
15029:         }
15030:         $cenv{'internal.notifylist'} = $notifylist;
15031:     }
15032:     if (@badclasses > 0) {
15033:         my %lt=&Apache::lonlocal::texthash(
15034:                 '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',
15035:                 'dnhr' => 'does not have rights to access enrollment in these classes',
15036:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
15037:         );
15038:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
15039:                            ' ('.$lt{'adby'}.')';
15040:         if ($context eq 'auto') {
15041:             $outcome .= $badclass_msg.$linefeed;
15042:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15043:             foreach my $item (@badclasses) {
15044:                 if ($context eq 'auto') {
15045:                     $outcome .= " - $item\n";
15046:                 } else {
15047:                     $outcome .= "<li>$item</li>\n";
15048:                 }
15049:             }
15050:             if ($context eq 'auto') {
15051:                 $outcome .= $linefeed;
15052:             } else {
15053:                 $outcome .= "</ul><br /><br /></div>\n";
15054:             }
15055:         } 
15056:     }
15057:     if ($args->{'no_end_date'}) {
15058:         $args->{'endaccess'} = 0;
15059:     }
15060:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15061:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15062:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15063:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15064:     if ($args->{'showphotos'}) {
15065:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15066:     }
15067:     $cenv{'internal.authtype'} = $args->{'authtype'};
15068:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15069:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15070:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15071:             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'); 
15072:             if ($context eq 'auto') {
15073:                 $outcome .= $krb_msg;
15074:             } else {
15075:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15076:             }
15077:             $outcome .= $linefeed;
15078:         }
15079:     }
15080:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15081:        if ($args->{'setpolicy'}) {
15082:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15083:        }
15084:        if ($args->{'setcontent'}) {
15085:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15086:        }
15087:     }
15088:     if ($args->{'reshome'}) {
15089: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15090: 	$cenv{'reshome'}=~s/\/+$/\//;
15091:     }
15092: #
15093: # course has keyed access
15094: #
15095:     if ($args->{'setkeys'}) {
15096:        $cenv{'keyaccess'}='yes';
15097:     }
15098: # if specified, key authority is not course, but user
15099: # only active if keyaccess is yes
15100:     if ($args->{'keyauth'}) {
15101: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15102: 	$user = &LONCAPA::clean_username($user);
15103: 	$domain = &LONCAPA::clean_username($domain);
15104: 	if ($user ne '' && $domain ne '') {
15105: 	    $cenv{'keyauth'}=$user.':'.$domain;
15106: 	}
15107:     }
15108: 
15109: #
15110: #  generate and store uniquecode (available to course requester), if course should have one.
15111: #
15112:     if ($args->{'uniquecode'}) {
15113:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15114:         if ($code) {
15115:             $cenv{'internal.uniquecode'} = $code;
15116:             my %crsinfo =
15117:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15118:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15119:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15120:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15121:             } 
15122:             if (ref($coderef)) {
15123:                 $$coderef = $code;
15124:             }
15125:         }
15126:     }
15127: 
15128:     if ($args->{'disresdis'}) {
15129:         $cenv{'pch.roles.denied'}='st';
15130:     }
15131:     if ($args->{'disablechat'}) {
15132:         $cenv{'plc.roles.denied'}='st';
15133:     }
15134: 
15135:     # Record we've not yet viewed the Course Initialization Helper for this 
15136:     # course
15137:     $cenv{'course.helper.not.run'} = 1;
15138:     #
15139:     # Use new Randomseed
15140:     #
15141:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15142:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15143:     #
15144:     # The encryption code and receipt prefix for this course
15145:     #
15146:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15147:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15148:     #
15149:     # By default, use standard grading
15150:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15151: 
15152:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15153:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15154: #
15155: # Open all assignments
15156: #
15157:     if ($args->{'openall'}) {
15158:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15159:        my %storecontent = ($storeunder         => time,
15160:                            $storeunder.'.type' => 'date_start');
15161:        
15162:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15163:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15164:    }
15165: #
15166: # Set first page
15167: #
15168:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15169: 	    || ($cloneid)) {
15170: 	use LONCAPA::map;
15171: 	$outcome .= &mt('Setting first resource').': ';
15172: 
15173: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15174:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15175: 
15176:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15177:         my $title; my $url;
15178:         if ($args->{'firstres'} eq 'syl') {
15179: 	    $title=&mt('Syllabus');
15180:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15181:         } else {
15182:             $title=&mt('Table of Contents');
15183:             $url='/adm/navmaps';
15184:         }
15185: 
15186:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15187: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15188: 
15189: 	if ($errtext) { $fatal=2; }
15190:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15191:     }
15192: 
15193:     return (1,$outcome);
15194: }
15195: 
15196: sub make_unique_code {
15197:     my ($cdom,$cnum) = @_;
15198:     # get lock on uniquecodes db
15199:     my $lockhash = {
15200:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15201:                                                   ':'.$env{'user.domain'},
15202:                    };
15203:     my $tries = 0;
15204:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15205:     my ($code,$error);
15206:   
15207:     while (($gotlock ne 'ok') && ($tries<3)) {
15208:         $tries ++;
15209:         sleep 1;
15210:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15211:     }
15212:     if ($gotlock eq 'ok') {
15213:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15214:         my $gotcode;
15215:         my $attempts = 0;
15216:         while ((!$gotcode) && ($attempts < 100)) {
15217:             $code = &generate_code();
15218:             if (!exists($currcodes{$code})) {
15219:                 $gotcode = 1;
15220:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15221:                     $error = 'nostore';
15222:                 }
15223:             }
15224:             $attempts ++;
15225:         }
15226:         my @del_lock = ($cnum."\0".'uniquecodes');
15227:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15228:     } else {
15229:         $error = 'nolock';
15230:     }
15231:     return ($code,$error);
15232: }
15233: 
15234: sub generate_code {
15235:     my $code;
15236:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15237:     for (my $i=0; $i<6; $i++) {
15238:         my $lettnum = int (rand 2);
15239:         my $item = '';
15240:         if ($lettnum) {
15241:             $item = $letts[int( rand(18) )];
15242:         } else {
15243:             $item = 1+int( rand(8) );
15244:         }
15245:         $code .= $item;
15246:     }
15247:     return $code;
15248: }
15249: 
15250: ############################################################
15251: ############################################################
15252: 
15253: #SD
15254: # only Community and Course, or anything else?
15255: sub course_type {
15256:     my ($cid) = @_;
15257:     if (!defined($cid)) {
15258:         $cid = $env{'request.course.id'};
15259:     }
15260:     if (defined($env{'course.'.$cid.'.type'})) {
15261:         return $env{'course.'.$cid.'.type'};
15262:     } else {
15263:         return 'Course';
15264:     }
15265: }
15266: 
15267: sub group_term {
15268:     my $crstype = &course_type();
15269:     my %names = (
15270:                   'Course' => 'group',
15271:                   'Community' => 'group',
15272:                 );
15273:     return $names{$crstype};
15274: }
15275: 
15276: sub course_types {
15277:     my @types = ('official','unofficial','community','textbook');
15278:     my %typename = (
15279:                          official   => 'Official course',
15280:                          unofficial => 'Unofficial course',
15281:                          community  => 'Community',
15282:                          textbook   => 'Textbook course',
15283:                    );
15284:     return (\@types,\%typename);
15285: }
15286: 
15287: sub icon {
15288:     my ($file)=@_;
15289:     my $curfext = lc((split(/\./,$file))[-1]);
15290:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15291:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15292:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15293: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15294: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15295: 	            $curfext.".gif") {
15296: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15297: 		$curfext.".gif";
15298: 	}
15299:     }
15300:     return &lonhttpdurl($iconname);
15301: } 
15302: 
15303: sub lonhttpdurl {
15304: #
15305: # Had been used for "small fry" static images on separate port 8080.
15306: # Modify here if lightweight http functionality desired again.
15307: # Currently eliminated due to increasing firewall issues.
15308: #
15309:     my ($url)=@_;
15310:     return $url;
15311: }
15312: 
15313: sub connection_aborted {
15314:     my ($r)=@_;
15315:     $r->print(" ");$r->rflush();
15316:     my $c = $r->connection;
15317:     return $c->aborted();
15318: }
15319: 
15320: #    Escapes strings that may have embedded 's that will be put into
15321: #    strings as 'strings'.
15322: sub escape_single {
15323:     my ($input) = @_;
15324:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15325:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15326:     return $input;
15327: }
15328: 
15329: #  Same as escape_single, but escape's "'s  This 
15330: #  can be used for  "strings"
15331: sub escape_double {
15332:     my ($input) = @_;
15333:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15334:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15335:     return $input;
15336: }
15337:  
15338: #   Escapes the last element of a full URL.
15339: sub escape_url {
15340:     my ($url)   = @_;
15341:     my @urlslices = split(/\//, $url,-1);
15342:     my $lastitem = &escape(pop(@urlslices));
15343:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15344: }
15345: 
15346: sub compare_arrays {
15347:     my ($arrayref1,$arrayref2) = @_;
15348:     my (@difference,%count);
15349:     @difference = ();
15350:     %count = ();
15351:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15352:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15353:         foreach my $element (keys(%count)) {
15354:             if ($count{$element} == 1) {
15355:                 push(@difference,$element);
15356:             }
15357:         }
15358:     }
15359:     return @difference;
15360: }
15361: 
15362: # -------------------------------------------------------- Initialize user login
15363: sub init_user_environment {
15364:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15365:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15366: 
15367:     my $public=($username eq 'public' && $domain eq 'public');
15368: 
15369: # See if old ID present, if so, remove
15370: 
15371:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15372:     my $now=time;
15373: 
15374:     if ($public) {
15375: 	my $max_public=100;
15376: 	my $oldest;
15377: 	my $oldest_time=0;
15378: 	for(my $next=1;$next<=$max_public;$next++) {
15379: 	    if (-e $lonids."/publicuser_$next.id") {
15380: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15381: 		if ($mtime<$oldest_time || !$oldest_time) {
15382: 		    $oldest_time=$mtime;
15383: 		    $oldest=$next;
15384: 		}
15385: 	    } else {
15386: 		$cookie="publicuser_$next";
15387: 		last;
15388: 	    }
15389: 	}
15390: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15391:     } else {
15392: 	# if this isn't a robot, kill any existing non-robot sessions
15393: 	if (!$args->{'robot'}) {
15394: 	    opendir(DIR,$lonids);
15395: 	    while ($filename=readdir(DIR)) {
15396: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15397: 		    unlink($lonids.'/'.$filename);
15398: 		}
15399: 	    }
15400: 	    closedir(DIR);
15401: # If there is a undeleted lockfile for the user's paste buffer remove it.
15402:             my $namespace = 'nohist_courseeditor';
15403:             my $lockingkey = 'paste'."\0".'locked_num';
15404:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15405:                                                 $domain,$username);
15406:             if (exists($lockhash{$lockingkey})) {
15407:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15408:                 unless ($delresult eq 'ok') {
15409:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15410:                 }
15411:             }
15412: 	}
15413: # Give them a new cookie
15414: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15415: 		                   : $now.$$.int(rand(10000)));
15416: 	$cookie="$username\_$id\_$domain\_$authhost";
15417:     
15418: # Initialize roles
15419: 
15420: 	($userroles,$firstaccenv,$timerintenv) = 
15421:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15422:     }
15423: # ------------------------------------ Check browser type and MathML capability
15424: 
15425:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15426:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15427: 
15428: # ------------------------------------------------------------- Get environment
15429: 
15430:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15431:     my ($tmp) = keys(%userenv);
15432:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15433:     } else {
15434: 	undef(%userenv);
15435:     }
15436:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15437: 	$form->{'interface'}=$userenv{'interface'};
15438:     }
15439:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15440: 
15441: # --------------- Do not trust query string to be put directly into environment
15442:     foreach my $option ('interface','localpath','localres') {
15443:         $form->{$option}=~s/[\n\r\=]//gs;
15444:     }
15445: # --------------------------------------------------------- Write first profile
15446: 
15447:     {
15448: 	my %initial_env = 
15449: 	    ("user.name"          => $username,
15450: 	     "user.domain"        => $domain,
15451: 	     "user.home"          => $authhost,
15452: 	     "browser.type"       => $clientbrowser,
15453: 	     "browser.version"    => $clientversion,
15454: 	     "browser.mathml"     => $clientmathml,
15455: 	     "browser.unicode"    => $clientunicode,
15456: 	     "browser.os"         => $clientos,
15457:              "browser.mobile"     => $clientmobile,
15458:              "browser.info"       => $clientinfo,
15459:              "browser.osversion"  => $clientosversion,
15460: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15461: 	     "request.course.fn"  => '',
15462: 	     "request.course.uri" => '',
15463: 	     "request.course.sec" => '',
15464: 	     "request.role"       => 'cm',
15465: 	     "request.role.adv"   => $env{'user.adv'},
15466: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15467: 
15468:         if ($form->{'localpath'}) {
15469: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15470: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15471:         }
15472: 	
15473: 	if ($form->{'interface'}) {
15474: 	    $form->{'interface'}=~s/\W//gs;
15475: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15476: 	    $env{'browser.interface'}=$form->{'interface'};
15477: 	}
15478: 
15479:         if ($form->{'iptoken'}) {
15480:             my $lonhost = $r->dir_config('lonHostID');
15481:             $initial_env{"user.noloadbalance"} = $lonhost;
15482:             $env{'user.noloadbalance'} = $lonhost;
15483:         }
15484: 
15485:         my %is_adv = ( is_adv => $env{'user.adv'} );
15486:         my %domdef;
15487:         unless ($domain eq 'public') {
15488:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
15489:         }
15490: 
15491:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
15492:             $userenv{'availabletools.'.$tool} = 
15493:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15494:                                                   undef,\%userenv,\%domdef,\%is_adv);
15495:         }
15496: 
15497:         foreach my $crstype ('official','unofficial','community','textbook') {
15498:             $userenv{'canrequest.'.$crstype} =
15499:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
15500:                                                   'reload','requestcourses',
15501:                                                   \%userenv,\%domdef,\%is_adv);
15502:         }
15503: 
15504:         $userenv{'canrequest.author'} =
15505:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15506:                                         'reload','requestauthor',
15507:                                         \%userenv,\%domdef,\%is_adv);
15508:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15509:                                              $domain,$username);
15510:         my $reqstatus = $reqauthor{'author_status'};
15511:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
15512:             if (ref($reqauthor{'author'}) eq 'HASH') {
15513:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15514:                                                   $reqauthor{'author'}{'timestamp'};
15515:             }
15516:         }
15517: 
15518: 	$env{'user.environment'} = "$lonids/$cookie.id";
15519: 
15520: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15521: 		 &GDBM_WRCREAT(),0640)) {
15522: 	    &_add_to_env(\%disk_env,\%initial_env);
15523: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15524: 	    &_add_to_env(\%disk_env,$userroles);
15525:             if (ref($firstaccenv) eq 'HASH') {
15526:                 &_add_to_env(\%disk_env,$firstaccenv);
15527:             }
15528:             if (ref($timerintenv) eq 'HASH') {
15529:                 &_add_to_env(\%disk_env,$timerintenv);
15530:             }
15531: 	    if (ref($args->{'extra_env'})) {
15532: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15533: 	    }
15534: 	    untie(%disk_env);
15535: 	} else {
15536: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15537: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15538: 	    return 'error: '.$!;
15539: 	}
15540:     }
15541:     $env{'request.role'}='cm';
15542:     $env{'request.role.adv'}=$env{'user.adv'};
15543:     $env{'browser.type'}=$clientbrowser;
15544: 
15545:     return $cookie;
15546: 
15547: }
15548: 
15549: sub _add_to_env {
15550:     my ($idf,$env_data,$prefix) = @_;
15551:     if (ref($env_data) eq 'HASH') {
15552:         while (my ($key,$value) = each(%$env_data)) {
15553: 	    $idf->{$prefix.$key} = $value;
15554: 	    $env{$prefix.$key}   = $value;
15555:         }
15556:     }
15557: }
15558: 
15559: # --- Get the symbolic name of a problem and the url
15560: sub get_symb {
15561:     my ($request,$silent) = @_;
15562:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15563:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15564:     if ($symb eq '') {
15565:         if (!$silent) {
15566:             if (ref($request)) { 
15567:                 $request->print("Unable to handle ambiguous references:$url:.");
15568:             }
15569:             return ();
15570:         }
15571:     }
15572:     &Apache::lonenc::check_decrypt(\$symb);
15573:     return ($symb);
15574: }
15575: 
15576: # --------------------------------------------------------------Get annotation
15577: 
15578: sub get_annotation {
15579:     my ($symb,$enc) = @_;
15580: 
15581:     my $key = $symb;
15582:     if (!$enc) {
15583:         $key =
15584:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15585:     }
15586:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15587:     return $annotation{$key};
15588: }
15589: 
15590: sub clean_symb {
15591:     my ($symb,$delete_enc) = @_;
15592: 
15593:     &Apache::lonenc::check_decrypt(\$symb);
15594:     my $enc = $env{'request.enc'};
15595:     if ($delete_enc) {
15596:         delete($env{'request.enc'});
15597:     }
15598: 
15599:     return ($symb,$enc);
15600: }
15601: 
15602: ############################################################
15603: ############################################################
15604: 
15605: =pod
15606: 
15607: =head1 Routines for building display used to search for courses
15608: 
15609: 
15610: =over 4
15611: 
15612: =item * &build_filters()
15613: 
15614: Create markup for a table used to set filters to use when selecting
15615: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15616: and quotacheck.pl
15617: 
15618: 
15619: Inputs:
15620: 
15621: filterlist - anonymous array of fields to include as potential filters 
15622: 
15623: crstype - course type
15624: 
15625: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15626:               to pop-open a course selector (will contain "extra element"). 
15627: 
15628: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15629: 
15630: filter - anonymous hash of criteria and their values
15631: 
15632: action - form action
15633: 
15634: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15635: 
15636: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15637: 
15638: cloneruname - username of owner of new course who wants to clone
15639: 
15640: clonerudom - domain of owner of new course who wants to clone
15641: 
15642: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
15643: 
15644: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15645: 
15646: codedom - domain
15647: 
15648: formname - value of form element named "form". 
15649: 
15650: fixeddom - domain, if fixed.
15651: 
15652: prevphase - value to assign to form element named "phase" when going back to the previous screen  
15653: 
15654: cnameelement - name of form element in form on opener page which will receive title of selected course 
15655: 
15656: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15657: 
15658: cdomelement - name of form element in form on opener page which will receive domain of selected course
15659: 
15660: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15661: 
15662: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15663: 
15664: clonewarning - warning message about missing information for intended course owner when DC creates a course
15665: 
15666: 
15667: Returns: $output - HTML for display of search criteria, and hidden form elements.
15668: 
15669: 
15670: Side Effects: None
15671: 
15672: =cut
15673: 
15674: # ---------------------------------------------- search for courses based on last activity etc.
15675: 
15676: sub build_filters {
15677:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15678:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15679:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15680:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15681:         $clonetext,$clonewarning) = @_;
15682:     my ($list,$jscript);
15683:     my $onchange = 'javascript:updateFilters(this)';
15684:     my ($domainselectform,$sincefilterform,$createdfilterform,
15685:         $ownerdomselectform,$persondomselectform,$instcodeform,
15686:         $typeselectform,$instcodetitle);
15687:     if ($formname eq '') {
15688:         $formname = $caller;
15689:     }
15690:     foreach my $item (@{$filterlist}) {
15691:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15692:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15693:             if ($item eq 'domainfilter') {
15694:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15695:             } elsif ($item eq 'coursefilter') {
15696:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15697:             } elsif ($item eq 'ownerfilter') {
15698:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15699:             } elsif ($item eq 'ownerdomfilter') {
15700:                 $filter->{'ownerdomfilter'} =
15701:                     &LONCAPA::clean_domain($filter->{$item});
15702:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15703:                                                        'ownerdomfilter',1);
15704:             } elsif ($item eq 'personfilter') {
15705:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15706:             } elsif ($item eq 'persondomfilter') {
15707:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15708:                                                         'persondomfilter',1);
15709:             } else {
15710:                 $filter->{$item} =~ s/\W//g;
15711:             }
15712:             if (!$filter->{$item}) {
15713:                 $filter->{$item} = '';
15714:             }
15715:         }
15716:         if ($item eq 'domainfilter') {
15717:             my $allow_blank = 1;
15718:             if ($formname eq 'portform') {
15719:                 $allow_blank=0;
15720:             } elsif ($formname eq 'studentform') {
15721:                 $allow_blank=0;
15722:             }
15723:             if ($fixeddom) {
15724:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15725:                                     ' value="'.$codedom.'" />'.
15726:                                     &Apache::lonnet::domain($codedom,'description');
15727:             } else {
15728:                 $domainselectform = &select_dom_form($filter->{$item},
15729:                                                      'domainfilter',
15730:                                                       $allow_blank,'',$onchange);
15731:             }
15732:         } else {
15733:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15734:         }
15735:     }
15736: 
15737:     # last course activity filter and selection
15738:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15739: 
15740:     # course created filter and selection
15741:     if (exists($filter->{'createdfilter'})) {
15742:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15743:     }
15744: 
15745:     my %lt = &Apache::lonlocal::texthash(
15746:                 'cac' => "$crstype Activity",
15747:                 'ccr' => "$crstype Created",
15748:                 'cde' => "$crstype Title",
15749:                 'cdo' => "$crstype Domain",
15750:                 'ins' => 'Institutional Code',
15751:                 'inc' => 'Institutional Categorization',
15752:                 'cow' => "$crstype Owner/Co-owner",
15753:                 'cop' => "$crstype Personnel Includes",
15754:                 'cog' => 'Type',
15755:              );
15756: 
15757:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15758:         my $typeval = 'Course';
15759:         if ($crstype eq 'Community') {
15760:             $typeval = 'Community';
15761:         }
15762:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15763:     } else {
15764:         $typeselectform =  '<select name="type" size="1"';
15765:         if ($onchange) {
15766:             $typeselectform .= ' onchange="'.$onchange.'"';
15767:         }
15768:         $typeselectform .= '>'."\n";
15769:         foreach my $posstype ('Course','Community') {
15770:             $typeselectform.='<option value="'.$posstype.'"'.
15771:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15772:         }
15773:         $typeselectform.="</select>";
15774:     }
15775: 
15776:     my ($cloneableonlyform,$cloneabletitle);
15777:     if (exists($filter->{'cloneableonly'})) {
15778:         my $cloneableon = '';
15779:         my $cloneableoff = ' checked="checked"';
15780:         if ($filter->{'cloneableonly'}) {
15781:             $cloneableon = $cloneableoff;
15782:             $cloneableoff = '';
15783:         }
15784:         $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>';
15785:         if ($formname eq 'ccrs') {
15786:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15787:         } else {
15788:             $cloneabletitle = &mt('Cloneable by you');
15789:         }
15790:     }
15791:     my $officialjs;
15792:     if ($crstype eq 'Course') {
15793:         if (exists($filter->{'instcodefilter'})) {
15794: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15795: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15796:             if ($codedom) { 
15797:                 $officialjs = 1;
15798:                 ($instcodeform,$jscript,$$numtitlesref) =
15799:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15800:                                                                   $officialjs,$codetitlesref);
15801:                 if ($jscript) {
15802:                     $jscript = '<script type="text/javascript">'."\n".
15803:                                '// <![CDATA['."\n".
15804:                                $jscript."\n".
15805:                                '// ]]>'."\n".
15806:                                '</script>'."\n";
15807:                 }
15808:             }
15809:             if ($instcodeform eq '') {
15810:                 $instcodeform =
15811:                     '<input type="text" name="instcodefilter" size="10" value="'.
15812:                     $list->{'instcodefilter'}.'" />';
15813:                 $instcodetitle = $lt{'ins'};
15814:             } else {
15815:                 $instcodetitle = $lt{'inc'};
15816:             }
15817:             if ($fixeddom) {
15818:                 $instcodetitle .= '<br />('.$codedom.')';
15819:             }
15820:         }
15821:     }
15822:     my $output = qq|
15823: <form method="post" name="filterpicker" action="$action">
15824: <input type="hidden" name="form" value="$formname" />
15825: |;
15826:     if ($formname eq 'modifycourse') {
15827:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15828:                    '<input type="hidden" name="prevphase" value="'.
15829:                    $prevphase.'" />'."\n";
15830:     } elsif ($formname eq 'quotacheck') {
15831:         $output .= qq|
15832: <input type="hidden" name="sortby" value="" />
15833: <input type="hidden" name="sortorder" value="" />
15834: |;
15835:     } else {
15836:         my $name_input;
15837:         if ($cnameelement ne '') {
15838:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15839:                           $cnameelement.'" />';
15840:         }
15841:         $output .= qq|
15842: <input type="hidden" name="cnumelement" value="$cnumelement" />
15843: <input type="hidden" name="cdomelement" value="$cdomelement" />
15844: $name_input
15845: $roleelement
15846: $multelement
15847: $typeelement
15848: |;
15849:         if ($formname eq 'portform') {
15850:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15851:         }
15852:     }
15853:     if ($fixeddom) {
15854:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15855:     }
15856:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15857:     if ($sincefilterform) {
15858:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15859:                   .$sincefilterform
15860:                   .&Apache::lonhtmlcommon::row_closure();
15861:     }
15862:     if ($createdfilterform) {
15863:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15864:                   .$createdfilterform
15865:                   .&Apache::lonhtmlcommon::row_closure();
15866:     }
15867:     if ($domainselectform) {
15868:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15869:                   .$domainselectform
15870:                   .&Apache::lonhtmlcommon::row_closure();
15871:     }
15872:     if ($typeselectform) {
15873:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15874:             $output .= $typeselectform;
15875:         } else {
15876:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15877:                       .$typeselectform
15878:                       .&Apache::lonhtmlcommon::row_closure();
15879:         }
15880:     }
15881:     if ($instcodeform) {
15882:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15883:                   .$instcodeform
15884:                   .&Apache::lonhtmlcommon::row_closure();
15885:     }
15886:     if (exists($filter->{'ownerfilter'})) {
15887:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15888:                    '<table><tr><td>'.&mt('Username').'<br />'.
15889:                    '<input type="text" name="ownerfilter" size="20" value="'.
15890:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15891:                    $ownerdomselectform.'</td></tr></table>'.
15892:                    &Apache::lonhtmlcommon::row_closure();
15893:     }
15894:     if (exists($filter->{'personfilter'})) {
15895:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15896:                    '<table><tr><td>'.&mt('Username').'<br />'.
15897:                    '<input type="text" name="personfilter" size="20" value="'.
15898:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15899:                    $persondomselectform.'</td></tr></table>'.
15900:                    &Apache::lonhtmlcommon::row_closure();
15901:     }
15902:     if (exists($filter->{'coursefilter'})) {
15903:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15904:                   .'<input type="text" name="coursefilter" size="25" value="'
15905:                   .$list->{'coursefilter'}.'" />'
15906:                   .&Apache::lonhtmlcommon::row_closure();
15907:     }
15908:     if ($cloneableonlyform) {
15909:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15910:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15911:     }
15912:     if (exists($filter->{'descriptfilter'})) {
15913:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15914:                   .'<input type="text" name="descriptfilter" size="40" value="'
15915:                   .$list->{'descriptfilter'}.'" />'
15916:                   .&Apache::lonhtmlcommon::row_closure(1);
15917:     }
15918:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15919:                '<input type="hidden" name="updater" value="" />'."\n".
15920:                '<input type="submit" name="gosearch" value="'.
15921:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15922:     return $jscript.$clonewarning.$output;
15923: }
15924: 
15925: =pod 
15926: 
15927: =item * &timebased_select_form()
15928: 
15929: Create markup for a dropdown list used to select a time-based
15930: filter e.g., Course Activity, Course Created, when searching for courses
15931: or communities
15932: 
15933: Inputs:
15934: 
15935: item - name of form element (sincefilter or createdfilter)
15936: 
15937: filter - anonymous hash of criteria and their values
15938: 
15939: Returns: HTML for a select box contained a blank, then six time selections,
15940:          with value set in incoming form variables currently selected. 
15941: 
15942: Side Effects: None
15943: 
15944: =cut
15945: 
15946: sub timebased_select_form {
15947:     my ($item,$filter) = @_;
15948:     if (ref($filter) eq 'HASH') {
15949:         $filter->{$item} =~ s/[^\d-]//g;
15950:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15951:         return &select_form(
15952:                             $filter->{$item},
15953:                             $item,
15954:                             {      '-1' => '',
15955:                                 '86400' => &mt('today'),
15956:                                '604800' => &mt('last week'),
15957:                               '2592000' => &mt('last month'),
15958:                               '7776000' => &mt('last three months'),
15959:                              '15552000' => &mt('last six months'),
15960:                              '31104000' => &mt('last year'),
15961:                     'select_form_order' =>
15962:                            ['-1','86400','604800','2592000','7776000',
15963:                             '15552000','31104000']});
15964:     }
15965: }
15966: 
15967: =pod
15968: 
15969: =item * &js_changer()
15970: 
15971: Create script tag containing Javascript used to submit course search form
15972: when course type or domain is changed, and also to hide 'Searching ...' on
15973: page load completion for page showing search result.
15974: 
15975: Inputs: None
15976: 
15977: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
15978: 
15979: Side Effects: None
15980: 
15981: =cut
15982: 
15983: sub js_changer {
15984:     return <<ENDJS;
15985: <script type="text/javascript">
15986: // <![CDATA[
15987: function updateFilters(caller) {
15988:     if (typeof(caller) != "undefined") {
15989:         document.filterpicker.updater.value = caller.name;
15990:     }
15991:     document.filterpicker.submit();
15992: }
15993: 
15994: function hideSearching() {
15995:     if (document.getElementById('searching')) {
15996:         document.getElementById('searching').style.display = 'none';
15997:     }
15998:     return;
15999: }
16000: 
16001: // ]]>
16002: </script>
16003: 
16004: ENDJS
16005: }
16006: 
16007: =pod
16008: 
16009: =item * &search_courses()
16010: 
16011: Process selected filters form course search form and pass to lonnet::courseiddump
16012: to retrieve a hash for which keys are courseIDs which match the selected filters.
16013: 
16014: Inputs:
16015: 
16016: dom - domain being searched 
16017: 
16018: type - course type ('Course' or 'Community' or '.' if any).
16019: 
16020: filter - anonymous hash of criteria and their values
16021: 
16022: numtitles - for institutional codes - number of categories
16023: 
16024: cloneruname - optional username of new course owner
16025: 
16026: clonerudom - optional domain of new course owner
16027: 
16028: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16029:             (used when DC is using course creation form)
16030: 
16031: codetitles - reference to array of titles of components in institutional codes (official courses).
16032: 
16033: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16034:            (and so can clone automatically)
16035: 
16036: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16037: 
16038: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16039:               courses to clone 
16040: 
16041: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16042: 
16043: 
16044: Side Effects: None
16045: 
16046: =cut
16047: 
16048: 
16049: sub search_courses {
16050:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16051:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16052:     my (%courses,%showcourses,$cloner);
16053:     if (($filter->{'ownerfilter'} ne '') ||
16054:         ($filter->{'ownerdomfilter'} ne '')) {
16055:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16056:                                        $filter->{'ownerdomfilter'};
16057:     }
16058:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16059:         if (!$filter->{$item}) {
16060:             $filter->{$item}='.';
16061:         }
16062:     }
16063:     my $now = time;
16064:     my $timefilter =
16065:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16066:     my ($createdbefore,$createdafter);
16067:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16068:         $createdbefore = $now;
16069:         $createdafter = $now-$filter->{'createdfilter'};
16070:     }
16071:     my ($instcodefilter,$regexpok);
16072:     if ($numtitles) {
16073:         if ($env{'form.official'} eq 'on') {
16074:             $instcodefilter =
16075:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16076:             $regexpok = 1;
16077:         } elsif ($env{'form.official'} eq 'off') {
16078:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16079:             unless ($instcodefilter eq '') {
16080:                 $regexpok = -1;
16081:             }
16082:         }
16083:     } else {
16084:         $instcodefilter = $filter->{'instcodefilter'};
16085:     }
16086:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16087:     if ($type eq '') { $type = '.'; }
16088: 
16089:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16090:         $cloner = $cloneruname.':'.$clonerudom;
16091:     }
16092:     %courses = &Apache::lonnet::courseiddump($dom,
16093:                                              $filter->{'descriptfilter'},
16094:                                              $timefilter,
16095:                                              $instcodefilter,
16096:                                              $filter->{'combownerfilter'},
16097:                                              $filter->{'coursefilter'},
16098:                                              undef,undef,$type,$regexpok,undef,undef,
16099:                                              undef,undef,$cloner,$cc_clone,
16100:                                              $filter->{'cloneableonly'},
16101:                                              $createdbefore,$createdafter,undef,
16102:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16103:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16104:         my $ccrole;
16105:         if ($type eq 'Community') {
16106:             $ccrole = 'co';
16107:         } else {
16108:             $ccrole = 'cc';
16109:         }
16110:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16111:                                                      $filter->{'persondomfilter'},
16112:                                                      'userroles',undef,
16113:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16114:                                                      $dom);
16115:         foreach my $role (keys(%rolehash)) {
16116:             my ($cnum,$cdom,$courserole) = split(':',$role);
16117:             my $cid = $cdom.'_'.$cnum;
16118:             if (exists($courses{$cid})) {
16119:                 if (ref($courses{$cid}) eq 'HASH') {
16120:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16121:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16122:                             push (@{$courses{$cid}{roles}},$courserole);
16123:                         }
16124:                     } else {
16125:                         $courses{$cid}{roles} = [$courserole];
16126:                     }
16127:                     $showcourses{$cid} = $courses{$cid};
16128:                 }
16129:             }
16130:         }
16131:         %courses = %showcourses;
16132:     }
16133:     return %courses;
16134: }
16135: 
16136: =pod
16137: 
16138: =back
16139: 
16140: =head1 Routines for version requirements for current course.
16141: 
16142: =over 4
16143: 
16144: =item * &check_release_required()
16145: 
16146: Compares required LON-CAPA version with version on server, and
16147: if required version is newer looks for a server with the required version.
16148: 
16149: Looks first at servers in user's owen domain; if none suitable, looks at
16150: servers in course's domain are permitted to host sessions for user's domain.
16151: 
16152: Inputs:
16153: 
16154: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16155: 
16156: $courseid - Course ID of current course
16157: 
16158: $rolecode - User's current role in course (for switchserver query string).
16159: 
16160: $required - LON-CAPA version needed by course (format: Major.Minor).
16161: 
16162: 
16163: Returns:
16164: 
16165: $switchserver - query string tp append to /adm/switchserver call (if 
16166:                 current server's LON-CAPA version is too old. 
16167: 
16168: $warning - Message is displayed if no suitable server could be found.
16169: 
16170: =cut
16171: 
16172: sub check_release_required {
16173:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16174:     my ($switchserver,$warning);
16175:     if ($required ne '') {
16176:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16177:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16178:         if ($reqdmajor ne '' && $reqdminor ne '') {
16179:             my $otherserver;
16180:             if (($major eq '' && $minor eq '') ||
16181:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16182:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16183:                 my $switchlcrev =
16184:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16185:                                                            $userdomserver);
16186:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16187:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16188:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16189:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16190:                     if ($cdom ne $env{'user.domain'}) {
16191:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16192:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16193:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16194:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16195:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16196:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16197:                         my $canhost =
16198:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16199:                                                               $coursedomserver,
16200:                                                               $remoterev,
16201:                                                               $udomdefaults{'remotesessions'},
16202:                                                               $defdomdefaults{'hostedsessions'});
16203: 
16204:                         if ($canhost) {
16205:                             $otherserver = $coursedomserver;
16206:                         } else {
16207:                             $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.");
16208:                         }
16209:                     } else {
16210:                         $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).");
16211:                     }
16212:                 } else {
16213:                     $otherserver = $userdomserver;
16214:                 }
16215:             }
16216:             if ($otherserver ne '') {
16217:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16218:             }
16219:         }
16220:     }
16221:     return ($switchserver,$warning);
16222: }
16223: 
16224: =pod
16225: 
16226: =item * &check_release_result()
16227: 
16228: Inputs:
16229: 
16230: $switchwarning - Warning message if no suitable server found to host session.
16231: 
16232: $switchserver - query string to append to /adm/switchserver containing lonHostID
16233:                 and current role.
16234: 
16235: Returns: HTML to display with information about requirement to switch server.
16236:          Either displaying warning with link to Roles/Courses screen or
16237:          display link to switchserver.
16238: 
16239: =cut
16240: 
16241: sub check_release_result {
16242:     my ($switchwarning,$switchserver) = @_;
16243:     my $output = &start_page('Selected course unavailable on this server').
16244:                  '<p class="LC_warning">';
16245:     if ($switchwarning) {
16246:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16247:         if (&show_course()) {
16248:             $output .= &mt('Display courses');
16249:         } else {
16250:             $output .= &mt('Display roles');
16251:         }
16252:         $output .= '</a>';
16253:     } elsif ($switchserver) {
16254:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16255:                    '<br />'.
16256:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16257:                    &mt('Switch Server').
16258:                    '</a>';
16259:     }
16260:     $output .= '</p>'.&end_page();
16261:     return $output;
16262: }
16263: 
16264: =pod
16265: 
16266: =item * &needs_coursereinit()
16267: 
16268: Determine if course contents stored for user's session needs to be
16269: refreshed, because content has changed since "Big Hash" last tied.
16270: 
16271: Check for change is made if time last checked is more than 10 minutes ago
16272: (by default).
16273: 
16274: Inputs:
16275: 
16276: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16277: 
16278: $interval (optional) - Time which may elapse (in s) between last check for content
16279:                        change in current course. (default: 600 s).  
16280: 
16281: Returns: an array; first element is:
16282: 
16283: =over 4
16284: 
16285: 'switch' - if content updates mean user's session
16286:            needs to be switched to a server running a newer LON-CAPA version
16287:  
16288: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16289:            on current server hosting user's session                
16290: 
16291: ''       - if no action required.
16292: 
16293: =back
16294: 
16295: If first item element is 'switch':
16296: 
16297: second item is $switchwarning - Warning message if no suitable server found to host session. 
16298: 
16299: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16300:                               and current role. 
16301: 
16302: otherwise: no other elements returned.
16303: 
16304: =back
16305: 
16306: =cut
16307: 
16308: sub needs_coursereinit {
16309:     my ($loncaparev,$interval) = @_;
16310:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16311:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16312:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16313:     my $now = time;
16314:     if ($interval eq '') {
16315:         $interval = 600;
16316:     }
16317:     if (($now-$env{'request.course.timechecked'})>$interval) {
16318:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16319:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16320:         if ($lastchange > $env{'request.course.tied'}) {
16321:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16322:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16323:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16324:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16325:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16326:                                              $curr_reqd_hash{'internal.releaserequired'}});
16327:                     my ($switchserver,$switchwarning) =
16328:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16329:                                                 $curr_reqd_hash{'internal.releaserequired'});
16330:                     if ($switchwarning ne '' || $switchserver ne '') {
16331:                         return ('switch',$switchwarning,$switchserver);
16332:                     }
16333:                 }
16334:             }
16335:             return ('update');
16336:         }
16337:     }
16338:     return ();
16339: }
16340: 
16341: sub update_content_constraints {
16342:     my ($cdom,$cnum,$chome,$cid) = @_;
16343:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16344:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16345:     my %checkresponsetypes;
16346:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16347:         my ($item,$name,$value,$valmatch) = split(/:/,$key);
16348:         if ($item eq 'resourcetag') {
16349:             if ($name eq 'responsetype') {
16350:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16351:             }
16352:         }
16353:     }
16354:     my $navmap = Apache::lonnavmaps::navmap->new();
16355:     if (defined($navmap)) {
16356:         my %allresponses;
16357:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16358:             my %responses = $res->responseTypes();
16359:             foreach my $key (keys(%responses)) {
16360:                 next unless(exists($checkresponsetypes{$key}));
16361:                 $allresponses{$key} += $responses{$key};
16362:             }
16363:         }
16364:         foreach my $key (keys(%allresponses)) {
16365:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16366:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16367:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16368:             }
16369:         }
16370:         undef($navmap);
16371:     }
16372:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16373:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16374:     }
16375:     return;
16376: }
16377: 
16378: sub allmaps_incourse {
16379:     my ($cdom,$cnum,$chome,$cid) = @_;
16380:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16381:         $cid = $env{'request.course.id'};
16382:         $cdom = $env{'course.'.$cid.'.domain'};
16383:         $cnum = $env{'course.'.$cid.'.num'};
16384:         $chome = $env{'course.'.$cid.'.home'};
16385:     }
16386:     my %allmaps = ();
16387:     my $lastchange =
16388:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16389:     if ($lastchange > $env{'request.course.tied'}) {
16390:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16391:         unless ($ferr) {
16392:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16393:         }
16394:     }
16395:     my $navmap = Apache::lonnavmaps::navmap->new();
16396:     if (defined($navmap)) {
16397:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16398:             $allmaps{$res->src()} = 1;
16399:         }
16400:     }
16401:     return \%allmaps;
16402: }
16403: 
16404: sub parse_supplemental_title {
16405:     my ($title) = @_;
16406: 
16407:     my ($foldertitle,$renametitle);
16408:     if ($title =~ /&amp;&amp;&amp;/) {
16409:         $title = &HTML::Entites::decode($title);
16410:     }
16411:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16412:         $renametitle=$4;
16413:         my ($time,$uname,$udom) = ($1,$2,$3);
16414:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16415:         my $name =  &plainname($uname,$udom);
16416:         $name = &HTML::Entities::encode($name,'"<>&\'');
16417:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16418:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16419:             $name.': <br />'.$foldertitle;
16420:     }
16421:     if (wantarray) {
16422:         return ($title,$foldertitle,$renametitle);
16423:     }
16424:     return $title;
16425: }
16426: 
16427: sub recurse_supplemental {
16428:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16429:     if ($suppmap) {
16430:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16431:         if ($fatal) {
16432:             $errors ++;
16433:         } else {
16434:             if ($#LONCAPA::map::resources > 0) {
16435:                 foreach my $res (@LONCAPA::map::resources) {
16436:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16437:                     if (($src ne '') && ($status eq 'res')) {
16438:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16439:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16440:                         } else {
16441:                             $numfiles ++;
16442:                         }
16443:                     }
16444:                 }
16445:             }
16446:         }
16447:     }
16448:     return ($numfiles,$errors);
16449: }
16450: 
16451: sub symb_to_docspath {
16452:     my ($symb) = @_;
16453:     return unless ($symb);
16454:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16455:     if ($resurl=~/\.(sequence|page)$/) {
16456:         $mapurl=$resurl;
16457:     } elsif ($resurl eq 'adm/navmaps') {
16458:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16459:     }
16460:     my $mapresobj;
16461:     my $navmap = Apache::lonnavmaps::navmap->new();
16462:     if (ref($navmap)) {
16463:         $mapresobj = $navmap->getResourceByUrl($mapurl);
16464:     }
16465:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16466:     my $type=$2;
16467:     my $path;
16468:     if (ref($mapresobj)) {
16469:         my $pcslist = $mapresobj->map_hierarchy();
16470:         if ($pcslist ne '') {
16471:             foreach my $pc (split(/,/,$pcslist)) {
16472:                 next if ($pc <= 1);
16473:                 my $res = $navmap->getByMapPc($pc);
16474:                 if (ref($res)) {
16475:                     my $thisurl = $res->src();
16476:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16477:                     my $thistitle = $res->title();
16478:                     $path .= '&'.
16479:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16480:                              &escape($thistitle).
16481:                              ':'.$res->randompick().
16482:                              ':'.$res->randomout().
16483:                              ':'.$res->encrypted().
16484:                              ':'.$res->randomorder().
16485:                              ':'.$res->is_page();
16486:                 }
16487:             }
16488:         }
16489:         $path =~ s/^\&//;
16490:         my $maptitle = $mapresobj->title();
16491:         if ($mapurl eq 'default') {
16492:             $maptitle = 'Main Content';
16493:         }
16494:         $path .= (($path ne '')? '&' : '').
16495:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16496:                  &escape($maptitle).
16497:                  ':'.$mapresobj->randompick().
16498:                  ':'.$mapresobj->randomout().
16499:                  ':'.$mapresobj->encrypted().
16500:                  ':'.$mapresobj->randomorder().
16501:                  ':'.$mapresobj->is_page();
16502:     } else {
16503:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16504:         my $ispage = (($type eq 'page')? 1 : '');
16505:         if ($mapurl eq 'default') {
16506:             $maptitle = 'Main Content';
16507:         }
16508:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16509:                 &escape($maptitle).':::::'.$ispage;
16510:     }
16511:     unless ($mapurl eq 'default') {
16512:         $path = 'default&'.
16513:                 &escape('Main Content').
16514:                 ':::::&'.$path;
16515:     }
16516:     return $path;
16517: }
16518: 
16519: sub captcha_display {
16520:     my ($context,$lonhost) = @_;
16521:     my ($output,$error);
16522:     my ($captcha,$pubkey,$privkey,$version) = 
16523:         &get_captcha_config($context,$lonhost);
16524:     if ($captcha eq 'original') {
16525:         $output = &create_captcha();
16526:         unless ($output) {
16527:             $error = 'captcha';
16528:         }
16529:     } elsif ($captcha eq 'recaptcha') {
16530:         $output = &create_recaptcha($pubkey,$version);
16531:         unless ($output) {
16532:             $error = 'recaptcha';
16533:         }
16534:     }
16535:     return ($output,$error,$captcha,$version);
16536: }
16537: 
16538: sub captcha_response {
16539:     my ($context,$lonhost) = @_;
16540:     my ($captcha_chk,$captcha_error);
16541:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16542:     if ($captcha eq 'original') {
16543:         ($captcha_chk,$captcha_error) = &check_captcha();
16544:     } elsif ($captcha eq 'recaptcha') {
16545:         $captcha_chk = &check_recaptcha($privkey,$version);
16546:     } else {
16547:         $captcha_chk = 1;
16548:     }
16549:     return ($captcha_chk,$captcha_error);
16550: }
16551: 
16552: sub get_captcha_config {
16553:     my ($context,$lonhost) = @_;
16554:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16555:     my $hostname = &Apache::lonnet::hostname($lonhost);
16556:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16557:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16558:     if ($context eq 'usercreation') {
16559:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16560:         if (ref($domconfig{$context}) eq 'HASH') {
16561:             $hashtocheck = $domconfig{$context}{'cancreate'};
16562:             if (ref($hashtocheck) eq 'HASH') {
16563:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16564:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16565:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16566:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16567:                     }
16568:                     if ($privkey && $pubkey) {
16569:                         $captcha = 'recaptcha';
16570:                         $version = $hashtocheck->{'recaptchaversion'};
16571:                         if ($version ne '2') {
16572:                             $version = 1;
16573:                         }
16574:                     } else {
16575:                         $captcha = 'original';
16576:                     }
16577:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16578:                     $captcha = 'original';
16579:                 }
16580:             }
16581:         } else {
16582:             $captcha = 'captcha';
16583:         }
16584:     } elsif ($context eq 'login') {
16585:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16586:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16587:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16588:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16589:             if ($privkey && $pubkey) {
16590:                 $captcha = 'recaptcha';
16591:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16592:                 if ($version ne '2') {
16593:                     $version = 1; 
16594:                 }
16595:             } else {
16596:                 $captcha = 'original';
16597:             }
16598:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16599:             $captcha = 'original';
16600:         }
16601:     }
16602:     return ($captcha,$pubkey,$privkey,$version);
16603: }
16604: 
16605: sub create_captcha {
16606:     my %captcha_params = &captcha_settings();
16607:     my ($output,$maxtries,$tries) = ('',10,0);
16608:     while ($tries < $maxtries) {
16609:         $tries ++;
16610:         my $captcha = Authen::Captcha->new (
16611:                                            output_folder => $captcha_params{'output_dir'},
16612:                                            data_folder   => $captcha_params{'db_dir'},
16613:                                           );
16614:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16615: 
16616:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16617:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16618:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16619:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16620:                       '<br />'.
16621:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16622:             last;
16623:         }
16624:     }
16625:     return $output;
16626: }
16627: 
16628: sub captcha_settings {
16629:     my %captcha_params = (
16630:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16631:                            www_output_dir => "/captchaspool",
16632:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16633:                            numchars       => '5',
16634:                          );
16635:     return %captcha_params;
16636: }
16637: 
16638: sub check_captcha {
16639:     my ($captcha_chk,$captcha_error);
16640:     my $code = $env{'form.code'};
16641:     my $md5sum = $env{'form.crypt'};
16642:     my %captcha_params = &captcha_settings();
16643:     my $captcha = Authen::Captcha->new(
16644:                       output_folder => $captcha_params{'output_dir'},
16645:                       data_folder   => $captcha_params{'db_dir'},
16646:                   );
16647:     $captcha_chk = $captcha->check_code($code,$md5sum);
16648:     my %captcha_hash = (
16649:                         0       => 'Code not checked (file error)',
16650:                        -1      => 'Failed: code expired',
16651:                        -2      => 'Failed: invalid code (not in database)',
16652:                        -3      => 'Failed: invalid code (code does not match crypt)',
16653:     );
16654:     if ($captcha_chk != 1) {
16655:         $captcha_error = $captcha_hash{$captcha_chk}
16656:     }
16657:     return ($captcha_chk,$captcha_error);
16658: }
16659: 
16660: sub create_recaptcha {
16661:     my ($pubkey,$version) = @_;
16662:     if ($version >= 2) {
16663:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16664:     } else {
16665:         my $use_ssl;
16666:         if ($ENV{'SERVER_PORT'} == 443) {
16667:             $use_ssl = 1;
16668:         }
16669:         my $captcha = Captcha::reCAPTCHA->new;
16670:         return $captcha->get_options_setter({theme => 'white'})."\n".
16671:                $captcha->get_html($pubkey,undef,$use_ssl).
16672:                &mt('If the text is hard to read, [_1] will replace them.',
16673:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16674:                '<br /><br />';
16675:     }
16676: }
16677: 
16678: sub check_recaptcha {
16679:     my ($privkey,$version) = @_;
16680:     my $captcha_chk;
16681:     if ($version >= 2) {
16682:         my $ua = LWP::UserAgent->new;
16683:         $ua->timeout(10);
16684:         my %info = (
16685:                      secret   => $privkey, 
16686:                      response => $env{'form.g-recaptcha-response'},
16687:                      remoteip => $ENV{'REMOTE_ADDR'},
16688:                    );
16689:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16690:         if ($response->is_success)  {
16691:             my $data = JSON::DWIW->from_json($response->decoded_content);
16692:             if (ref($data) eq 'HASH') {
16693:                 if ($data->{'success'}) {
16694:                     $captcha_chk = 1;
16695:                 }
16696:             }
16697:         }
16698:     } else {
16699:         my $captcha = Captcha::reCAPTCHA->new;
16700:         my $captcha_result =
16701:             $captcha->check_answer(
16702:                                     $privkey,
16703:                                     $ENV{'REMOTE_ADDR'},
16704:                                     $env{'form.recaptcha_challenge_field'},
16705:                                     $env{'form.recaptcha_response_field'},
16706:                                   );
16707:         if ($captcha_result->{is_valid}) {
16708:             $captcha_chk = 1;
16709:         }
16710:     }
16711:     return $captcha_chk;
16712: }
16713: 
16714: sub emailusername_info {
16715:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
16716:     my %titles = &Apache::lonlocal::texthash (
16717:                      lastname      => 'Last Name',
16718:                      firstname     => 'First Name',
16719:                      institution   => 'School/college/university',
16720:                      location      => "School's city, state/province, country",
16721:                      web           => "School's web address",
16722:                      officialemail => 'E-mail address at institution (if different)',
16723:                  );
16724:     return (\@fields,\%titles);
16725: }
16726: 
16727: sub cleanup_html {
16728:     my ($incoming) = @_;
16729:     my $outgoing;
16730:     if ($incoming ne '') {
16731:         $outgoing = $incoming;
16732:         $outgoing =~ s/;/&#059;/g;
16733:         $outgoing =~ s/\#/&#035;/g;
16734:         $outgoing =~ s/\&/&#038;/g;
16735:         $outgoing =~ s/</&#060;/g;
16736:         $outgoing =~ s/>/&#062;/g;
16737:         $outgoing =~ s/\(/&#040/g;
16738:         $outgoing =~ s/\)/&#041;/g;
16739:         $outgoing =~ s/"/&#034;/g;
16740:         $outgoing =~ s/'/&#039;/g;
16741:         $outgoing =~ s/\$/&#036;/g;
16742:         $outgoing =~ s{/}{&#047;}g;
16743:         $outgoing =~ s/=/&#061;/g;
16744:         $outgoing =~ s/\\/&#092;/g
16745:     }
16746:     return $outgoing;
16747: }
16748: 
16749: # Checks for critical messages and returns a redirect url if one exists.
16750: # $interval indicates how often to check for messages.
16751: sub critical_redirect {
16752:     my ($interval) = @_;
16753:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16754:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
16755:                                         $env{'user.name'});
16756:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16757:         my $redirecturl;
16758:         if ($what[0]) {
16759: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16760: 	        $redirecturl='/adm/email?critical=display';
16761: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
16762:                 return (1, $url);
16763:             }
16764:         }
16765:     } 
16766:     return ();
16767: }
16768: 
16769: # Use:
16770: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16771: #
16772: ##################################################
16773: #          password associated functions         #
16774: ##################################################
16775: sub des_keys {
16776:     # Make a new key for DES encryption.
16777:     # Each key has two parts which are returned separately.
16778:     # Please note:  Each key must be passed through the &hex function
16779:     # before it is output to the web browser.  The hex versions cannot
16780:     # be used to decrypt.
16781:     my @hexstr=('0','1','2','3','4','5','6','7',
16782:                 '8','9','a','b','c','d','e','f');
16783:     my $lkey='';
16784:     for (0..7) {
16785:         $lkey.=$hexstr[rand(15)];
16786:     }
16787:     my $ukey='';
16788:     for (0..7) {
16789:         $ukey.=$hexstr[rand(15)];
16790:     }
16791:     return ($lkey,$ukey);
16792: }
16793: 
16794: sub des_decrypt {
16795:     my ($key,$cyphertext) = @_;
16796:     my $keybin=pack("H16",$key);
16797:     my $cypher;
16798:     if ($Crypt::DES::VERSION>=2.03) {
16799:         $cypher=new Crypt::DES $keybin;
16800:     } else {
16801:         $cypher=new DES $keybin;
16802:     }
16803:     my $plaintext='';
16804:     my $cypherlength = length($cyphertext);
16805:     my $numchunks = int($cypherlength/32);
16806:     for (my $j=0; $j<$numchunks; $j++) {
16807:         my $start = $j*32;
16808:         my $cypherblock = substr($cyphertext,$start,32);
16809:         my $chunk =
16810:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16811:         $chunk .=
16812:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16813:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16814:         $plaintext .= $chunk;
16815:     }
16816:     return $plaintext;
16817: }
16818: 
16819: 1;
16820: __END__;
16821: 

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