File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1286: download - view: text, annotated - select for diffs
Thu Aug 3 16:22:09 2017 UTC (6 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Self-creation of user accounts using e-mail verification.
  - Options set by domain coordinator for account requests verified by e-mail
    for: processing, restrictions on permitted e-mail addresses, and choice
    of username can be set to different values, depending on requester's
    (self-reported) institutional status.
  - Setting which status types can be self-reported by requesters using
    e-mail verification moved from
    "Default authentication/language/timezone/portal/types" panel to
    "Users self-creating accounts" panel.
  - Web form used to request account prompts user for appropriate responses
    depending on self-reported status, and e-mail and username constraints.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1286 2017/08/03 16:22:09 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use LONCAPA::LWPReq;
   75: use DateTime::TimeZone;
   76: use DateTime::Locale;
   77: use Encode();
   78: use Text::Aspell;
   79: use Authen::Captcha;
   80: use Captcha::reCAPTCHA;
   81: use JSON::DWIW;
   82: use LWP::UserAgent;
   83: use Crypt::DES;
   84: use DynaLoader; # for Crypt::DES version
   85: use MIME::Lite;
   86: use MIME::Types;
   87: 
   88: # ---------------------------------------------- Designs
   89: use vars qw(%defaultdesign);
   90: 
   91: my $readit;
   92: 
   93: 
   94: ##
   95: ## Global Variables
   96: ##
   97: 
   98: 
   99: # ----------------------------------------------- SSI with retries:
  100: #
  101: 
  102: =pod
  103: 
  104: =head1 Server Side include with retries:
  105: 
  106: =over 4
  107: 
  108: =item * &ssi_with_retries(resource,retries form)
  109: 
  110: Performs an ssi with some number of retries.  Retries continue either
  111: until the result is ok or until the retry count supplied by the
  112: caller is exhausted.  
  113: 
  114: Inputs:
  115: 
  116: =over 4
  117: 
  118: resource   - Identifies the resource to insert.
  119: 
  120: retries    - Count of the number of retries allowed.
  121: 
  122: form       - Hash that identifies the rendering options.
  123: 
  124: =back
  125: 
  126: Returns:
  127: 
  128: =over 4
  129: 
  130: content    - The content of the response.  If retries were exhausted this is empty.
  131: 
  132: response   - The response from the last attempt (which may or may not have been successful.
  133: 
  134: =back
  135: 
  136: =back
  137: 
  138: =cut
  139: 
  140: sub ssi_with_retries {
  141:     my ($resource, $retries, %form) = @_;
  142: 
  143: 
  144:     my $ok = 0;			# True if we got a good response.
  145:     my $content;
  146:     my $response;
  147: 
  148:     # Try to get the ssi done. within the retries count:
  149: 
  150:     do {
  151: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  152: 	$ok      = $response->is_success;
  153:         if (!$ok) {
  154:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  155:         }
  156: 	$retries--;
  157:     } while (!$ok && ($retries > 0));
  158: 
  159:     if (!$ok) {
  160: 	$content = '';		# On error return an empty content.
  161:     }
  162:     return ($content, $response);
  163: 
  164: }
  165: 
  166: 
  167: 
  168: # ----------------------------------------------- Filetypes/Languages/Copyright
  169: my %language;
  170: my %supported_language;
  171: my %supported_codes;
  172: my %latex_language;		# For choosing hyphenation in <transl..>
  173: my %latex_language_bykey;	# for choosing hyphenation from metadata
  174: my %cprtag;
  175: my %scprtag;
  176: my %fe; my %fd; my %fm;
  177: my %category_extensions;
  178: 
  179: # ---------------------------------------------- Thesaurus variables
  180: #
  181: # %Keywords:
  182: #      A hash used by &keyword to determine if a word is considered a keyword.
  183: # $thesaurus_db_file 
  184: #      Scalar containing the full path to the thesaurus database.
  185: 
  186: my %Keywords;
  187: my $thesaurus_db_file;
  188: 
  189: #
  190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  191: # thesaurus.tab, and filecategories.tab.
  192: #
  193: BEGIN {
  194:     # Variable initialization
  195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  196:     #
  197:     unless ($readit) {
  198: # ------------------------------------------------------------------- languages
  199:     {
  200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  201:                                    '/language.tab';
  202:         if ( open(my $fh,"<$langtabfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  207:                 $language{$key}=$val.' - '.$enc;
  208:                 if ($sup) {
  209:                     $supported_language{$key}=$sup;
  210: 		    $supported_codes{$key}   = $code;
  211:                 }
  212: 		if ($latex) {
  213: 		    $latex_language_bykey{$key} = $latex;
  214: 		    $latex_language{$code} = $latex;
  215: 		}
  216:             }
  217:             close($fh);
  218:         }
  219:     }
  220: # ------------------------------------------------------------------ copyrights
  221:     {
  222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  223:                                   '/copyright.tab';
  224:         if ( open (my $fh,"<$copyrightfile") ) {
  225:             while (my $line = <$fh>) {
  226:                 next if ($line=~/^\#/);
  227:                 chomp($line);
  228:                 my ($key,$val)=(split(/\s+/,$line,2));
  229:                 $cprtag{$key}=$val;
  230:             }
  231:             close($fh);
  232:         }
  233:     }
  234: # ----------------------------------------------------------- source copyrights
  235:     {
  236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  237:                                   '/source_copyright.tab';
  238:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  239:             while (my $line = <$fh>) {
  240:                 next if ($line =~ /^\#/);
  241:                 chomp($line);
  242:                 my ($key,$val)=(split(/\s+/,$line,2));
  243:                 $scprtag{$key}=$val;
  244:             }
  245:             close($fh);
  246:         }
  247:     }
  248: 
  249: # -------------------------------------------------------------- default domain designs
  250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  251:     my $designfile = $designdir.'/default.tab';
  252:     if ( open (my $fh,"<$designfile") ) {
  253:         while (my $line = <$fh>) {
  254:             next if ($line =~ /^\#/);
  255:             chomp($line);
  256:             my ($key,$val)=(split(/\=/,$line));
  257:             if ($val) { $defaultdesign{$key}=$val; }
  258:         }
  259:         close($fh);
  260:     }
  261: 
  262: # ------------------------------------------------------------- file categories
  263:     {
  264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  265:                                   '/filecategories.tab';
  266:         if ( open (my $fh,"<$categoryfile") ) {
  267: 	    while (my $line = <$fh>) {
  268: 		next if ($line =~ /^\#/);
  269: 		chomp($line);
  270:                 my ($extension,$category)=(split(/\s+/,$line,2));
  271:                 push(@{$category_extensions{lc($category)}},$extension);
  272:             }
  273:             close($fh);
  274:         }
  275: 
  276:     }
  277: # ------------------------------------------------------------------ file types
  278:     {
  279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  280:                '/filetypes.tab';
  281:         if ( open (my $fh,"<$typesfile") ) {
  282:             while (my $line = <$fh>) {
  283: 		next if ($line =~ /^\#/);
  284: 		chomp($line);
  285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  286:                 if ($descr ne '') {
  287:                     $fe{$ending}=lc($emb);
  288:                     $fd{$ending}=$descr;
  289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  290:                 }
  291:             }
  292:             close($fh);
  293:         }
  294:     }
  295:     &Apache::lonnet::logthis(
  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
  297:     $readit=1;
  298:     }  # end of unless($readit) 
  299:     
  300: }
  301: 
  302: ###############################################################
  303: ##           HTML and Javascript Helper Functions            ##
  304: ###############################################################
  305: 
  306: =pod 
  307: 
  308: =head1 HTML and Javascript Functions
  309: 
  310: =over 4
  311: 
  312: =item * &browser_and_searcher_javascript()
  313: 
  314: X<browsing, javascript>X<searching, javascript>Returns a string
  315: containing javascript with two functions, C<openbrowser> and
  316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  317: tags.
  318: 
  319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  320: 
  321: inputs: formname, elementname, only, omit
  322: 
  323: formname and elementname indicate the name of the html form and name of
  324: the element that the results of the browsing selection are to be placed in. 
  325: 
  326: Specifying 'only' will restrict the browser to displaying only files
  327: with the given extension.  Can be a comma separated list.
  328: 
  329: Specifying 'omit' will restrict the browser to NOT displaying files
  330: with the given extension.  Can be a comma separated list.
  331: 
  332: =item * &opensearcher(formname,elementname) [javascript]
  333: 
  334: Inputs: formname, elementname
  335: 
  336: formname and elementname specify the name of the html form and the name
  337: of the element the selection from the search results will be placed in.
  338: 
  339: =cut
  340: 
  341: sub browser_and_searcher_javascript {
  342:     my ($mode)=@_;
  343:     if (!defined($mode)) { $mode='edit'; }
  344:     my $resurl=&escape_single(&lastresurl());
  345:     return <<END;
  346: // <!-- BEGIN LON-CAPA Internal
  347:     var editbrowser = null;
  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
  349:         var url = '$resurl/?';
  350:         if (editbrowser == null) {
  351:             url += 'launch=1&';
  352:         }
  353:         url += 'catalogmode=interactive&';
  354:         url += 'mode=$mode&';
  355:         url += 'inhibitmenu=yes&';
  356:         url += 'form=' + formname + '&';
  357:         if (only != null) {
  358:             url += 'only=' + only + '&';
  359:         } else {
  360:             url += 'only=&';
  361: 	}
  362:         if (omit != null) {
  363:             url += 'omit=' + omit + '&';
  364:         } else {
  365:             url += 'omit=&';
  366: 	}
  367:         if (titleelement != null) {
  368:             url += 'titleelement=' + titleelement + '&';
  369:         } else {
  370: 	    url += 'titleelement=&';
  371: 	}
  372:         url += 'element=' + elementname + '';
  373:         var title = 'Browser';
  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  375:         options += ',width=700,height=600';
  376:         editbrowser = open(url,title,options,'1');
  377:         editbrowser.focus();
  378:     }
  379:     var editsearcher;
  380:     function opensearcher(formname,elementname,titleelement) {
  381:         var url = '/adm/searchcat?';
  382:         if (editsearcher == null) {
  383:             url += 'launch=1&';
  384:         }
  385:         url += 'catalogmode=interactive&';
  386:         url += 'mode=$mode&';
  387:         url += 'form=' + formname + '&';
  388:         if (titleelement != null) {
  389:             url += 'titleelement=' + titleelement + '&';
  390:         } else {
  391: 	    url += 'titleelement=&';
  392: 	}
  393:         url += 'element=' + elementname + '';
  394:         var title = 'Search';
  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  396:         options += ',width=700,height=600';
  397:         editsearcher = open(url,title,options,'1');
  398:         editsearcher.focus();
  399:     }
  400: // END LON-CAPA Internal -->
  401: END
  402: }
  403: 
  404: sub lastresurl {
  405:     if ($env{'environment.lastresurl'}) {
  406: 	return $env{'environment.lastresurl'}
  407:     } else {
  408: 	return '/res';
  409:     }
  410: }
  411: 
  412: sub storeresurl {
  413:     my $resurl=&Apache::lonnet::clutter(shift);
  414:     unless ($resurl=~/^\/res/) { return 0; }
  415:     $resurl=~s/\/$//;
  416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  418:     return 1;
  419: }
  420: 
  421: sub studentbrowser_javascript {
  422:    unless (
  423:             (($env{'request.course.id'}) && 
  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  426: 					  '/'.$env{'request.course.sec'})
  427: 	      ))
  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
  429:           ) { return ''; }  
  430:    return (<<'ENDSTDBRW');
  431: <script type="text/javascript" language="Javascript">
  432: // <![CDATA[
  433:     var stdeditbrowser;
  434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  435:         var url = '/adm/pickstudent?';
  436:         var filter;
  437: 	if (!ignorefilter) {
  438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  439: 	}
  440:         if (filter != null) {
  441:            if (filter != '') {
  442:                url += 'filter='+filter+'&';
  443: 	   }
  444:         }
  445:         url += 'form=' + formname + '&unameelement='+uname+
  446:                                     '&udomelement='+udom+
  447:                                     '&clicker='+clicker;
  448: 	if (roleflag) { url+="&roles=1"; }
  449:         if (courseadvonly) { url+="&courseadvonly=1"; }
  450:         var title = 'Student_Browser';
  451:         var options = 'scrollbars=1,resizable=1,menubar=0';
  452:         options += ',width=700,height=600';
  453:         stdeditbrowser = open(url,title,options,'1');
  454:         stdeditbrowser.focus();
  455:     }
  456: // ]]>
  457: </script>
  458: ENDSTDBRW
  459: }
  460: 
  461: sub resourcebrowser_javascript {
  462:    unless ($env{'request.course.id'}) { return ''; }
  463:    return (<<'ENDRESBRW');
  464: <script type="text/javascript" language="Javascript">
  465: // <![CDATA[
  466:     var reseditbrowser;
  467:     function openresbrowser(formname,reslink) {
  468:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  469:         var title = 'Resource_Browser';
  470:         var options = 'scrollbars=1,resizable=1,menubar=0';
  471:         options += ',width=700,height=500';
  472:         reseditbrowser = open(url,title,options,'1');
  473:         reseditbrowser.focus();
  474:     }
  475: // ]]>
  476: </script>
  477: ENDRESBRW
  478: }
  479: 
  480: sub selectstudent_link {
  481:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  482:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  483:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  484:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  485:    if ($env{'request.course.id'}) {  
  486:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  487: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  488: 					'/'.$env{'request.course.sec'})) {
  489: 	   return '';
  490:        }
  491:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  492:        if ($courseadvonly)  {
  493:            $callargs .= ",'',1,1";
  494:        }
  495:        return '<span class="LC_nobreak">'.
  496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  497:               &mt('Select User').'</a></span>';
  498:    }
  499:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  500:        $callargs .= ",'',1"; 
  501:        return '<span class="LC_nobreak">'.
  502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  503:               &mt('Select User').'</a></span>';
  504:    }
  505:    return '';
  506: }
  507: 
  508: sub selectresource_link {
  509:    my ($form,$reslink,$arg)=@_;
  510:    
  511:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  512:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  513:    unless ($env{'request.course.id'}) { return $arg; }
  514:    return '<span class="LC_nobreak">'.
  515:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  516:               $arg.'</a></span>';
  517: }
  518: 
  519: 
  520: 
  521: sub authorbrowser_javascript {
  522:     return <<"ENDAUTHORBRW";
  523: <script type="text/javascript" language="JavaScript">
  524: // <![CDATA[
  525: var stdeditbrowser;
  526: 
  527: function openauthorbrowser(formname,udom) {
  528:     var url = '/adm/pickauthor?';
  529:     url += 'form='+formname+'&roledom='+udom;
  530:     var title = 'Author_Browser';
  531:     var options = 'scrollbars=1,resizable=1,menubar=0';
  532:     options += ',width=700,height=600';
  533:     stdeditbrowser = open(url,title,options,'1');
  534:     stdeditbrowser.focus();
  535: }
  536: 
  537: // ]]>
  538: </script>
  539: ENDAUTHORBRW
  540: }
  541: 
  542: sub coursebrowser_javascript {
  543:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  544:         $credits_element,$instcode) = @_;
  545:     my $wintitle = 'Course_Browser';
  546:     if ($crstype eq 'Community') {
  547:         $wintitle = 'Community_Browser';
  548:     }
  549:     my $id_functions = &javascript_index_functions();
  550:     my $output = '
  551: <script type="text/javascript" language="JavaScript">
  552: // <![CDATA[
  553:     var stdeditbrowser;'."\n";
  554: 
  555:     $output .= <<"ENDSTDBRW";
  556:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  557:         var url = '/adm/pickcourse?';
  558:         var formid = getFormIdByName(formname);
  559:         var domainfilter = getDomainFromSelectbox(formname,udom);
  560:         if (domainfilter != null) {
  561:            if (domainfilter != '') {
  562:                url += 'domainfilter='+domainfilter+'&';
  563: 	   }
  564:         }
  565:         url += 'form=' + formname + '&cnumelement='+uname+
  566: 	                            '&cdomelement='+udom+
  567:                                     '&cnameelement='+desc;
  568:         if (extra_element !=null && extra_element != '') {
  569:             if (formname == 'rolechoice' || formname == 'studentform') {
  570:                 url += '&roleelement='+extra_element;
  571:                 if (domainfilter == null || domainfilter == '') {
  572:                     url += '&domainfilter='+extra_element;
  573:                 }
  574:             }
  575:             else {
  576:                 if (formname == 'portform') {
  577:                     url += '&setroles='+extra_element;
  578:                 } else {
  579:                     if (formname == 'rules') {
  580:                         url += '&fixeddom='+extra_element; 
  581:                     }
  582:                 }
  583:             }     
  584:         }
  585:         if (type != null && type != '') {
  586:             url += '&type='+type;
  587:         }
  588:         if (type_elem != null && type_elem != '') {
  589:             url += '&typeelement='+type_elem;
  590:         }
  591:         if (formname == 'ccrs') {
  592:             var ownername = document.forms[formid].ccuname.value;
  593:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  594:             url += '&cloner='+ownername+':'+ownerdom;
  595:             if (type == 'Course') {
  596:                 url += '&crscode='+document.forms[formid].crscode.value;
  597:             }
  598:         }
  599:         if (formname == 'requestcrs') {
  600:             url += '&crsdom=$domainfilter&crscode=$instcode';
  601:         }
  602:         if (multflag !=null && multflag != '') {
  603:             url += '&multiple='+multflag;
  604:         }
  605:         var title = '$wintitle';
  606:         var options = 'scrollbars=1,resizable=1,menubar=0';
  607:         options += ',width=700,height=600';
  608:         stdeditbrowser = open(url,title,options,'1');
  609:         stdeditbrowser.focus();
  610:     }
  611: $id_functions
  612: ENDSTDBRW
  613:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  614:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  615:                                       $credits_element);
  616:     }
  617:     $output .= '
  618: // ]]>
  619: </script>';
  620:     return $output;
  621: }
  622: 
  623: sub javascript_index_functions {
  624:     return <<"ENDJS";
  625: 
  626: function getFormIdByName(formname) {
  627:     for (var i=0;i<document.forms.length;i++) {
  628:         if (document.forms[i].name == formname) {
  629:             return i;
  630:         }
  631:     }
  632:     return -1;
  633: }
  634: 
  635: function getIndexByName(formid,item) {
  636:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  637:         if (document.forms[formid].elements[i].name == item) {
  638:             return i;
  639:         }
  640:     }
  641:     return -1;
  642: }
  643: 
  644: function getDomainFromSelectbox(formname,udom) {
  645:     var userdom;
  646:     var formid = getFormIdByName(formname);
  647:     if (formid > -1) {
  648:         var domid = getIndexByName(formid,udom);
  649:         if (domid > -1) {
  650:             if (document.forms[formid].elements[domid].type == 'select-one') {
  651:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  652:             }
  653:             if (document.forms[formid].elements[domid].type == 'hidden') {
  654:                 userdom=document.forms[formid].elements[domid].value;
  655:             }
  656:         }
  657:     }
  658:     return userdom;
  659: }
  660: 
  661: ENDJS
  662: 
  663: }
  664: 
  665: sub javascript_array_indexof {
  666:     return <<ENDJS;
  667: <script type="text/javascript" language="JavaScript">
  668: // <![CDATA[
  669: 
  670: if (!Array.prototype.indexOf) {
  671:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  672:         "use strict";
  673:         if (this === void 0 || this === null) {
  674:             throw new TypeError();
  675:         }
  676:         var t = Object(this);
  677:         var len = t.length >>> 0;
  678:         if (len === 0) {
  679:             return -1;
  680:         }
  681:         var n = 0;
  682:         if (arguments.length > 0) {
  683:             n = Number(arguments[1]);
  684:             if (n !== n) { // shortcut for verifying if it is NaN
  685:                 n = 0;
  686:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  687:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  688:             }
  689:         }
  690:         if (n >= len) {
  691:             return -1;
  692:         }
  693:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  694:         for (; k < len; k++) {
  695:             if (k in t && t[k] === searchElement) {
  696:                 return k;
  697:             }
  698:         }
  699:         return -1;
  700:     }
  701: }
  702: 
  703: // ]]>
  704: </script>
  705: 
  706: ENDJS
  707: 
  708: }
  709: 
  710: sub userbrowser_javascript {
  711:     my $id_functions = &javascript_index_functions();
  712:     return <<"ENDUSERBRW";
  713: 
  714: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  715:     var url = '/adm/pickuser?';
  716:     var userdom = getDomainFromSelectbox(formname,udom);
  717:     if (userdom != null) {
  718:        if (userdom != '') {
  719:            url += 'srchdom='+userdom+'&';
  720:        }
  721:     }
  722:     url += 'form=' + formname + '&unameelement='+uname+
  723:                                 '&udomelement='+udom+
  724:                                 '&ulastelement='+ulast+
  725:                                 '&ufirstelement='+ufirst+
  726:                                 '&uemailelement='+uemail+
  727:                                 '&hideudomelement='+hideudom+
  728:                                 '&coursedom='+crsdom;
  729:     if ((caller != null) && (caller != undefined)) {
  730:         url += '&caller='+caller;
  731:     }
  732:     var title = 'User_Browser';
  733:     var options = 'scrollbars=1,resizable=1,menubar=0';
  734:     options += ',width=700,height=600';
  735:     var stdeditbrowser = open(url,title,options,'1');
  736:     stdeditbrowser.focus();
  737: }
  738: 
  739: function fix_domain (formname,udom,origdom,uname) {
  740:     var formid = getFormIdByName(formname);
  741:     if (formid > -1) {
  742:         var unameid = getIndexByName(formid,uname);
  743:         var domid = getIndexByName(formid,udom);
  744:         var hidedomid = getIndexByName(formid,origdom);
  745:         if (hidedomid > -1) {
  746:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  747:             var unameval = document.forms[formid].elements[unameid].value;
  748:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  749:                 if (domid > -1) {
  750:                     var slct = document.forms[formid].elements[domid];
  751:                     if (slct.type == 'select-one') {
  752:                         var i;
  753:                         for (i=0;i<slct.length;i++) {
  754:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  755:                         }
  756:                     }
  757:                     if (slct.type == 'hidden') {
  758:                         slct.value = fixeddom;
  759:                     }
  760:                 }
  761:             }
  762:         }
  763:     }
  764:     return;
  765: }
  766: 
  767: $id_functions
  768: ENDUSERBRW
  769: }
  770: 
  771: sub setsec_javascript {
  772:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  773:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  774:         $communityrolestr);
  775:     if ($role_element ne '') {
  776:         my @allroles = ('st','ta','ep','in','ad');
  777:         foreach my $crstype ('Course','Community') {
  778:             if ($crstype eq 'Community') {
  779:                 foreach my $role (@allroles) {
  780:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  781:                 }
  782:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  783:             } else {
  784:                 foreach my $role (@allroles) {
  785:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  786:                 }
  787:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  788:             }
  789:         }
  790:         $rolestr = '"'.join('","',@allroles).'"';
  791:         $courserolestr = '"'.join('","',@courserolenames).'"';
  792:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  793:     }
  794:     my $setsections = qq|
  795: function setSect(sectionlist) {
  796:     var sectionsArray = new Array();
  797:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  798:         sectionsArray = sectionlist.split(",");
  799:     }
  800:     var numSections = sectionsArray.length;
  801:     document.$formname.$sec_element.length = 0;
  802:     if (numSections == 0) {
  803:         document.$formname.$sec_element.multiple=false;
  804:         document.$formname.$sec_element.size=1;
  805:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  806:     } else {
  807:         if (numSections == 1) {
  808:             document.$formname.$sec_element.multiple=false;
  809:             document.$formname.$sec_element.size=1;
  810:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  811:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  812:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  813:         } else {
  814:             for (var i=0; i<numSections; i++) {
  815:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  816:             }
  817:             document.$formname.$sec_element.multiple=true
  818:             if (numSections < 3) {
  819:                 document.$formname.$sec_element.size=numSections;
  820:             } else {
  821:                 document.$formname.$sec_element.size=3;
  822:             }
  823:             document.$formname.$sec_element.options[0].selected = false
  824:         }
  825:     }
  826: }
  827: 
  828: function setRole(crstype) {
  829: |;
  830:     if ($role_element eq '') {
  831:         $setsections .= '    return;
  832: }
  833: ';
  834:     } else {
  835:         $setsections .= qq|
  836:     var elementLength = document.$formname.$role_element.length;
  837:     var allroles = Array($rolestr);
  838:     var courserolenames = Array($courserolestr);
  839:     var communityrolenames = Array($communityrolestr);
  840:     if (elementLength != undefined) {
  841:         if (document.$formname.$role_element.options[5].value == 'cc') {
  842:             if (crstype == 'Course') {
  843:                 return;
  844:             } else {
  845:                 allroles[5] = 'co';
  846:                 for (var i=0; i<6; i++) {
  847:                     document.$formname.$role_element.options[i].value = allroles[i];
  848:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  849:                 }
  850:             }
  851:         } else {
  852:             if (crstype == 'Community') {
  853:                 return;
  854:             } else {
  855:                 allroles[5] = 'cc';
  856:                 for (var i=0; i<6; i++) {
  857:                     document.$formname.$role_element.options[i].value = allroles[i];
  858:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  859:                 }
  860:             }
  861:         }
  862:     }
  863:     return;
  864: }
  865: |;
  866:     }
  867:     if ($credits_element) {
  868:         $setsections .= qq|
  869: function setCredits(defaultcredits) {
  870:     document.$formname.$credits_element.value = defaultcredits;
  871:     return;
  872: }
  873: |;
  874:     }
  875:     return $setsections;
  876: }
  877: 
  878: sub selectcourse_link {
  879:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  880:        $typeelement) = @_;
  881:    my $type = $selecttype;
  882:    my $linktext = &mt('Select Course');
  883:    if ($selecttype eq 'Community') {
  884:        $linktext = &mt('Select Community');
  885:    } elsif ($selecttype eq 'Placement') {
  886:        $linktext = &mt('Select Placement Test'); 
  887:    } elsif ($selecttype eq 'Course/Community') {
  888:        $linktext = &mt('Select Course/Community');
  889:        $type = '';
  890:    } elsif ($selecttype eq 'Select') {
  891:        $linktext = &mt('Select');
  892:        $type = '';
  893:    }
  894:    return '<span class="LC_nobreak">'
  895:          ."<a href='"
  896:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  897:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  898:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  899:          ."'>".$linktext.'</a>'
  900:          .'</span>';
  901: }
  902: 
  903: sub selectauthor_link {
  904:    my ($form,$udom)=@_;
  905:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  906:           &mt('Select Author').'</a>';
  907: }
  908: 
  909: sub selectuser_link {
  910:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  911:         $coursedom,$linktext,$caller) = @_;
  912:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  913:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  914:            ');">'.$linktext.'</a>';
  915: }
  916: 
  917: sub check_uncheck_jscript {
  918:     my $jscript = <<"ENDSCRT";
  919: function checkAll(field) {
  920:     if (field.length > 0) {
  921:         for (i = 0; i < field.length; i++) {
  922:             if (!field[i].disabled) { 
  923:                 field[i].checked = true;
  924:             }
  925:         }
  926:     } else {
  927:         if (!field.disabled) { 
  928:             field.checked = true;
  929:         }
  930:     }
  931: }
  932:  
  933: function uncheckAll(field) {
  934:     if (field.length > 0) {
  935:         for (i = 0; i < field.length; i++) {
  936:             field[i].checked = false ;
  937:         }
  938:     } else {
  939:         field.checked = false ;
  940:     }
  941: }
  942: ENDSCRT
  943:     return $jscript;
  944: }
  945: 
  946: sub select_timezone {
  947:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  948:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  949:    if ($includeempty) {
  950:        $output .= '<option value=""';
  951:        if (($selected eq '') || ($selected eq 'local')) {
  952:            $output .= ' selected="selected" ';
  953:        }
  954:        $output .= '> </option>';
  955:    }
  956:    my @timezones = DateTime::TimeZone->all_names;
  957:    foreach my $tzone (@timezones) {
  958:        $output.= '<option value="'.$tzone.'"';
  959:        if ($tzone eq $selected) {
  960:            $output.=' selected="selected"';
  961:        }
  962:        $output.=">$tzone</option>\n";
  963:    }
  964:    $output.="</select>";
  965:    return $output;
  966: }
  967: 
  968: sub select_datelocale {
  969:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  970:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  971:     if ($includeempty) {
  972:         $output .= '<option value=""';
  973:         if ($selected eq '') {
  974:             $output .= ' selected="selected" ';
  975:         }
  976:         $output .= '> </option>';
  977:     }
  978:     my @languages = &Apache::lonlocal::preferred_languages();
  979:     my (@possibles,%locale_names);
  980:     my @locales = DateTime::Locale->ids();
  981:     foreach my $id (@locales) {
  982:         if ($id ne '') {
  983:             my ($en_terr,$native_terr);
  984:             my $loc = DateTime::Locale->load($id);
  985:             if (ref($loc)) {
  986:                 $en_terr = $loc->name();
  987:                 $native_terr = $loc->native_name();
  988:                 if (grep(/^en$/,@languages) || !@languages) {
  989:                     if ($en_terr ne '') {
  990:                         $locale_names{$id} = '('.$en_terr.')';
  991:                     } elsif ($native_terr ne '') {
  992:                         $locale_names{$id} = $native_terr;
  993:                     }
  994:                 } else {
  995:                     if ($native_terr ne '') {
  996:                         $locale_names{$id} = $native_terr.' ';
  997:                     } elsif ($en_terr ne '') {
  998:                         $locale_names{$id} = '('.$en_terr.')';
  999:                     }
 1000:                 }
 1001:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1002:                 push(@possibles,$id);
 1003:             } 
 1004:         }
 1005:     }
 1006:     foreach my $item (sort(@possibles)) {
 1007:         $output.= '<option value="'.$item.'"';
 1008:         if ($item eq $selected) {
 1009:             $output.=' selected="selected"';
 1010:         }
 1011:         $output.=">$item";
 1012:         if ($locale_names{$item} ne '') {
 1013:             $output.='  '.$locale_names{$item};
 1014:         }
 1015:         $output.="</option>\n";
 1016:     }
 1017:     $output.="</select>";
 1018:     return $output;
 1019: }
 1020: 
 1021: sub select_language {
 1022:     my ($name,$selected,$includeempty,$noedit) = @_;
 1023:     my %langchoices;
 1024:     if ($includeempty) {
 1025:         %langchoices = ('' => 'No language preference');
 1026:     }
 1027:     foreach my $id (&languageids()) {
 1028:         my $code = &supportedlanguagecode($id);
 1029:         if ($code) {
 1030:             $langchoices{$code} = &plainlanguagedescription($id);
 1031:         }
 1032:     }
 1033:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1034:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1035: }
 1036: 
 1037: =pod
 1038: 
 1039: 
 1040: =item * &list_languages()
 1041: 
 1042: Returns an array reference that is suitable for use in language prompters.
 1043: Each array element is itself a two element array.  The first element
 1044: is the language code.  The second element a descsriptiuon of the 
 1045: language itself.  This is suitable for use in e.g.
 1046: &Apache::edit::select_arg (once dereferenced that is).
 1047: 
 1048: =cut 
 1049: 
 1050: sub list_languages {
 1051:     my @lang_choices;
 1052: 
 1053:     foreach my $id (&languageids()) {
 1054: 	my $code = &supportedlanguagecode($id);
 1055: 	if ($code) {
 1056: 	    my $selector    = $supported_codes{$id};
 1057: 	    my $description = &plainlanguagedescription($id);
 1058: 	    push(@lang_choices, [$selector, $description]);
 1059: 	}
 1060:     }
 1061:     return \@lang_choices;
 1062: }
 1063: 
 1064: =pod
 1065: 
 1066: =item * &linked_select_forms(...)
 1067: 
 1068: linked_select_forms returns a string containing a <script></script> block
 1069: and html for two <select> menus.  The select menus will be linked in that
 1070: changing the value of the first menu will result in new values being placed
 1071: in the second menu.  The values in the select menu will appear in alphabetical
 1072: order unless a defined order is provided.
 1073: 
 1074: linked_select_forms takes the following ordered inputs:
 1075: 
 1076: =over 4
 1077: 
 1078: =item * $formname, the name of the <form> tag
 1079: 
 1080: =item * $middletext, the text which appears between the <select> tags
 1081: 
 1082: =item * $firstdefault, the default value for the first menu
 1083: 
 1084: =item * $firstselectname, the name of the first <select> tag
 1085: 
 1086: =item * $secondselectname, the name of the second <select> tag
 1087: 
 1088: =item * $hashref, a reference to a hash containing the data for the menus.
 1089: 
 1090: =item * $menuorder, the order of values in the first menu
 1091: 
 1092: =item * $onchangefirst, additional javascript call to execute for an onchange
 1093:         event for the first <select> tag
 1094: 
 1095: =item * $onchangesecond, additional javascript call to execute for an onchange
 1096:         event for the second <select> tag
 1097: 
 1098: =item * $suffix, to differentiate separate uses of select2data javascript
 1099:         objects in a page.
 1100: 
 1101: =back 
 1102: 
 1103: Below is an example of such a hash.  Only the 'text', 'default', and 
 1104: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1105: values for the first select menu.  The text that coincides with the 
 1106: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1107: and text for the second menu are given in the hash pointed to by 
 1108: $menu{$choice1}->{'select2'}.  
 1109: 
 1110:  my %menu = ( A1 => { text =>"Choice A1" ,
 1111:                        default => "B3",
 1112:                        select2 => { 
 1113:                            B1 => "Choice B1",
 1114:                            B2 => "Choice B2",
 1115:                            B3 => "Choice B3",
 1116:                            B4 => "Choice B4"
 1117:                            },
 1118:                        order => ['B4','B3','B1','B2'],
 1119:                    },
 1120:                A2 => { text =>"Choice A2" ,
 1121:                        default => "C2",
 1122:                        select2 => { 
 1123:                            C1 => "Choice C1",
 1124:                            C2 => "Choice C2",
 1125:                            C3 => "Choice C3"
 1126:                            },
 1127:                        order => ['C2','C1','C3'],
 1128:                    },
 1129:                A3 => { text =>"Choice A3" ,
 1130:                        default => "D6",
 1131:                        select2 => { 
 1132:                            D1 => "Choice D1",
 1133:                            D2 => "Choice D2",
 1134:                            D3 => "Choice D3",
 1135:                            D4 => "Choice D4",
 1136:                            D5 => "Choice D5",
 1137:                            D6 => "Choice D6",
 1138:                            D7 => "Choice D7"
 1139:                            },
 1140:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1141:                    }
 1142:                );
 1143: 
 1144: =cut
 1145: 
 1146: sub linked_select_forms {
 1147:     my ($formname,
 1148:         $middletext,
 1149:         $firstdefault,
 1150:         $firstselectname,
 1151:         $secondselectname, 
 1152:         $hashref,
 1153:         $menuorder,
 1154:         $onchangefirst,
 1155:         $onchangesecond,
 1156:         $suffix
 1157:         ) = @_;
 1158:     my $second = "document.$formname.$secondselectname";
 1159:     my $first = "document.$formname.$firstselectname";
 1160:     # output the javascript to do the changing
 1161:     my $result = '';
 1162:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1163:     $result.="// <![CDATA[\n";
 1164:     $result.="var select2data${suffix} = new Object();\n";
 1165:     $" = '","';
 1166:     my $debug = '';
 1167:     foreach my $s1 (sort(keys(%$hashref))) {
 1168:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1169:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1170:             $hashref->{$s1}->{'default'}."');\n";
 1171:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1172:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1173:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1174:             @s2values = @{$hashref->{$s1}->{'order'}};
 1175:         }
 1176:         $result.="\"@s2values\");\n";
 1177:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1178:         my @s2texts;
 1179:         foreach my $value (@s2values) {
 1180:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1181:         }
 1182:         $result.="\"@s2texts\");\n";
 1183:     }
 1184:     $"=' ';
 1185:     $result.= <<"END";
 1186: 
 1187: function select1${suffix}_changed() {
 1188:     // Determine new choice
 1189:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1190:     // update select2
 1191:     var values     = select2data${suffix}[newvalue].values;
 1192:     var texts      = select2data${suffix}[newvalue].texts;
 1193:     var select2def = select2data${suffix}[newvalue].def;
 1194:     var i;
 1195:     // out with the old
 1196:     $second.options.length = 0;
 1197:     // in with the new
 1198:     for (i=0;i<values.length; i++) {
 1199:         $second.options[i] = new Option(values[i]);
 1200:         $second.options[i].value = values[i];
 1201:         $second.options[i].text = texts[i];
 1202:         if (values[i] == select2def) {
 1203:             $second.options[i].selected = true;
 1204:         }
 1205:     }
 1206: }
 1207: // ]]>
 1208: </script>
 1209: END
 1210:     # output the initial values for the selection lists
 1211:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1212:     my @order = sort(keys(%{$hashref}));
 1213:     if (ref($menuorder) eq 'ARRAY') {
 1214:         @order = @{$menuorder};
 1215:     }
 1216:     foreach my $value (@order) {
 1217:         $result.="    <option value=\"$value\" ";
 1218:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1219:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1220:     }
 1221:     $result .= "</select>\n";
 1222:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1223:     $result .= $middletext;
 1224:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1225:     if ($onchangesecond) {
 1226:         $result .= ' onchange="'.$onchangesecond.'"';
 1227:     }
 1228:     $result .= ">\n";
 1229:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1230:     
 1231:     my @secondorder = sort(keys(%select2));
 1232:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1233:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1234:     }
 1235:     foreach my $value (@secondorder) {
 1236:         $result.="    <option value=\"$value\" ";        
 1237:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1238:         $result.=">".&mt($select2{$value})."</option>\n";
 1239:     }
 1240:     $result .= "</select>\n";
 1241:     #    return $debug;
 1242:     return $result;
 1243: }   #  end of sub linked_select_forms {
 1244: 
 1245: =pod
 1246: 
 1247: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1248: 
 1249: Returns a string corresponding to an HTML link to the given help
 1250: $topic, where $topic corresponds to the name of a .tex file in
 1251: /home/httpd/html/adm/help/tex, with underscores replaced by
 1252: spaces. 
 1253: 
 1254: $text will optionally be linked to the same topic, allowing you to
 1255: link text in addition to the graphic. If you do not want to link
 1256: text, but wish to specify one of the later parameters, pass an
 1257: empty string. 
 1258: 
 1259: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1260: the link will not open a new window. If false, the link will open
 1261: a new window using Javascript. (Default is false.) 
 1262: 
 1263: $width and $height are optional numerical parameters that will
 1264: override the width and height of the popped up window, which may
 1265: be useful for certain help topics with big pictures included.
 1266: 
 1267: $imgid is the id of the img tag used for the help icon. This may be
 1268: used in a javascript call to switch the image src.  See 
 1269: lonhtmlcommon::htmlareaselectactive() for an example.
 1270: 
 1271: =cut
 1272: 
 1273: sub help_open_topic {
 1274:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1275:     $text = "" if (not defined $text);
 1276:     $stayOnPage = 0 if (not defined $stayOnPage);
 1277:     $width = 500 if (not defined $width);
 1278:     $height = 400 if (not defined $height);
 1279:     my $filename = $topic;
 1280:     $filename =~ s/ /_/g;
 1281: 
 1282:     my $template = "";
 1283:     my $link;
 1284:     
 1285:     $topic=~s/\W/\_/g;
 1286: 
 1287:     if (!$stayOnPage) {
 1288: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1289:     } elsif ($stayOnPage eq 'popup') {
 1290:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1291:     } else {
 1292: 	$link = "/adm/help/${filename}.hlp";
 1293:     }
 1294: 
 1295:     # Add the text
 1296:     if ($text ne "") {	
 1297: 	$template.='<span class="LC_help_open_topic">'
 1298:                   .'<a target="_top" href="'.$link.'">'
 1299:                   .$text.'</a>';
 1300:     }
 1301: 
 1302:     # (Always) Add the graphic
 1303:     my $title = &mt('Online Help');
 1304:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1305:     if ($imgid ne '') {
 1306:         $imgid = ' id="'.$imgid.'"';
 1307:     }
 1308:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1309:               .'<img src="'.$helpicon.'" border="0"'
 1310:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1311:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1312:               .' /></a>';
 1313:     if ($text ne "") {	
 1314:         $template.='</span>';
 1315:     }
 1316:     return $template;
 1317: 
 1318: }
 1319: 
 1320: # This is a quicky function for Latex cheatsheet editing, since it 
 1321: # appears in at least four places
 1322: sub helpLatexCheatsheet {
 1323:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1324:     my $out;
 1325:     my $addOther = '';
 1326:     if ($topic) {
 1327: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1328:     }
 1329:     $out = '<span>' # Start cheatsheet
 1330: 	  .$addOther
 1331:           .'<span>'
 1332: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1333: 	  .'</span> <span>'
 1334: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1335: 	  .'</span>';
 1336:     unless ($not_author) {
 1337:         $out .= '<span>'
 1338:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1339:                .'</span> <span>'
 1340:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1341: 	       .'</span>';
 1342:     }
 1343:     $out .= '</span>'; # End cheatsheet
 1344:     return $out;
 1345: }
 1346: 
 1347: sub general_help {
 1348:     my $helptopic='Student_Intro';
 1349:     if ($env{'request.role'}=~/^(ca|au)/) {
 1350: 	$helptopic='Authoring_Intro';
 1351:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1352: 	$helptopic='Course_Coordination_Intro';
 1353:     } elsif ($env{'request.role'}=~/^dc/) {
 1354:         $helptopic='Domain_Coordination_Intro';
 1355:     }
 1356:     return $helptopic;
 1357: }
 1358: 
 1359: sub update_help_link {
 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1361:     my $origurl = $ENV{'REQUEST_URI'};
 1362:     $origurl=~s|^/~|/priv/|;
 1363:     my $timestamp = time;
 1364:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1365:         $$datum = &escape($$datum);
 1366:     }
 1367: 
 1368:     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";
 1369:     my $output .= <<"ENDOUTPUT";
 1370: <script type="text/javascript">
 1371: // <![CDATA[
 1372: banner_link = '$banner_link';
 1373: // ]]>
 1374: </script>
 1375: ENDOUTPUT
 1376:     return $output;
 1377: }
 1378: 
 1379: # now just updates the help link and generates a blue icon
 1380: sub help_open_menu {
 1381:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1382: 	= @_;    
 1383:     $stayOnPage = 1;
 1384:     my $output;
 1385:     if ($component_help) {
 1386: 	if (!$text) {
 1387: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1388: 				       $width,$height);
 1389: 	} else {
 1390: 	    my $help_text;
 1391: 	    $help_text=&unescape($topic);
 1392: 	    $output='<table><tr><td>'.
 1393: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1394: 				 $width,$height).'</td></tr></table>';
 1395: 	}
 1396:     }
 1397:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1398:     return $output.$banner_link;
 1399: }
 1400: 
 1401: sub top_nav_help {
 1402:     my ($text) = @_;
 1403:     $text = &mt($text);
 1404:     my $stay_on_page = 1;
 1405: 
 1406:     my ($link,$banner_link);
 1407:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1408:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1409: 	                         : "javascript:helpMenu('open')";
 1410:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1411:     }
 1412:     my $title = &mt('Get help');
 1413:     if ($link) {
 1414:         return <<"END";
 1415: $banner_link
 1416: <a href="$link" title="$title">$text</a>
 1417: END
 1418:     } else {
 1419:         return '&nbsp;'.$text.'&nbsp;';
 1420:     }
 1421: }
 1422: 
 1423: sub help_menu_js {
 1424:     my ($httphost) = @_;
 1425:     my $stayOnPage = 1;
 1426:     my $width = 620;
 1427:     my $height = 600;
 1428:     my $helptopic=&general_help();
 1429:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1430:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1431:     my $start_page =
 1432:         &Apache::loncommon::start_page('Help Menu', undef,
 1433: 				       {'frameset'    => 1,
 1434: 					'js_ready'    => 1,
 1435:                                         'use_absolute' => $httphost,
 1436: 					'add_entries' => {
 1437: 					    'border' => '0', 
 1438: 					    'rows'   => "110,*",},});
 1439:     my $end_page =
 1440:         &Apache::loncommon::end_page({'frameset' => 1,
 1441: 				      'js_ready' => 1,});
 1442: 
 1443:     my $template .= <<"ENDTEMPLATE";
 1444: <script type="text/javascript">
 1445: // <![CDATA[
 1446: // <!-- BEGIN LON-CAPA Internal
 1447: var banner_link = '';
 1448: function helpMenu(target) {
 1449:     var caller = this;
 1450:     if (target == 'open') {
 1451:         var newWindow = null;
 1452:         try {
 1453:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1454:         }
 1455:         catch(error) {
 1456:             writeHelp(caller);
 1457:             return;
 1458:         }
 1459:         if (newWindow) {
 1460:             caller = newWindow;
 1461:         }
 1462:     }
 1463:     writeHelp(caller);
 1464:     return;
 1465: }
 1466: function writeHelp(caller) {
 1467:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1468:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1469:     caller.document.close();
 1470:     caller.focus();
 1471: }
 1472: // END LON-CAPA Internal -->
 1473: // ]]>
 1474: </script>
 1475: ENDTEMPLATE
 1476:     return $template;
 1477: }
 1478: 
 1479: sub help_open_bug {
 1480:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1481:     unless ($env{'user.adv'}) { return ''; }
 1482:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1483:     $text = "" if (not defined $text);
 1484: 	$stayOnPage=1;
 1485:     $width = 600 if (not defined $width);
 1486:     $height = 600 if (not defined $height);
 1487: 
 1488:     $topic=~s/\W+/\+/g;
 1489:     my $link='';
 1490:     my $template='';
 1491:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1492: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1493:     if (!$stayOnPage)
 1494:     {
 1495: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1496:     }
 1497:     else
 1498:     {
 1499: 	$link = $url;
 1500:     }
 1501:     # Add the text
 1502:     if ($text ne "")
 1503:     {
 1504: 	$template .= 
 1505:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1506:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1507:     }
 1508: 
 1509:     # Add the graphic
 1510:     my $title = &mt('Report a Bug');
 1511:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1512:     $template .= <<"ENDTEMPLATE";
 1513:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1514: ENDTEMPLATE
 1515:     if ($text ne '') { $template.='</td></tr></table>' };
 1516:     return $template;
 1517: 
 1518: }
 1519: 
 1520: sub help_open_faq {
 1521:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1522:     unless ($env{'user.adv'}) { return ''; }
 1523:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1524:     $text = "" if (not defined $text);
 1525: 	$stayOnPage=1;
 1526:     $width = 350 if (not defined $width);
 1527:     $height = 400 if (not defined $height);
 1528: 
 1529:     $topic=~s/\W+/\+/g;
 1530:     my $link='';
 1531:     my $template='';
 1532:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1533:     if (!$stayOnPage)
 1534:     {
 1535: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1536:     }
 1537:     else
 1538:     {
 1539: 	$link = $url;
 1540:     }
 1541: 
 1542:     # Add the text
 1543:     if ($text ne "")
 1544:     {
 1545: 	$template .= 
 1546:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1547:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1548:     }
 1549: 
 1550:     # Add the graphic
 1551:     my $title = &mt('View the FAQ');
 1552:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1553:     $template .= <<"ENDTEMPLATE";
 1554:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1555: ENDTEMPLATE
 1556:     if ($text ne '') { $template.='</td></tr></table>' };
 1557:     return $template;
 1558: 
 1559: }
 1560: 
 1561: ###############################################################
 1562: ###############################################################
 1563: 
 1564: =pod
 1565: 
 1566: =item * &change_content_javascript():
 1567: 
 1568: This and the next function allow you to create small sections of an
 1569: otherwise static HTML page that you can update on the fly with
 1570: Javascript, even in Netscape 4.
 1571: 
 1572: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1573: must be written to the HTML page once. It will prove the Javascript
 1574: function "change(name, content)". Calling the change function with the
 1575: name of the section 
 1576: you want to update, matching the name passed to C<changable_area>, and
 1577: the new content you want to put in there, will put the content into
 1578: that area.
 1579: 
 1580: B<Note>: Netscape 4 only reserves enough space for the changable area
 1581: to contain room for the original contents. You need to "make space"
 1582: for whatever changes you wish to make, and be B<sure> to check your
 1583: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1584: it's adequate for updating a one-line status display, but little more.
 1585: This script will set the space to 100% width, so you only need to
 1586: worry about height in Netscape 4.
 1587: 
 1588: Modern browsers are much less limiting, and if you can commit to the
 1589: user not using Netscape 4, this feature may be used freely with
 1590: pretty much any HTML.
 1591: 
 1592: =cut
 1593: 
 1594: sub change_content_javascript {
 1595:     # If we're on Netscape 4, we need to use Layer-based code
 1596:     if ($env{'browser.type'} eq 'netscape' &&
 1597: 	$env{'browser.version'} =~ /^4\./) {
 1598: 	return (<<NETSCAPE4);
 1599: 	function change(name, content) {
 1600: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1601: 	    doc.open();
 1602: 	    doc.write(content);
 1603: 	    doc.close();
 1604: 	}
 1605: NETSCAPE4
 1606:     } else {
 1607: 	# Otherwise, we need to use semi-standards-compliant code
 1608: 	# (technically, "innerHTML" isn't standard but the equivalent
 1609: 	# is really scary, and every useful browser supports it
 1610: 	return (<<DOMBASED);
 1611: 	function change(name, content) {
 1612: 	    element = document.getElementById(name);
 1613: 	    element.innerHTML = content;
 1614: 	}
 1615: DOMBASED
 1616:     }
 1617: }
 1618: 
 1619: =pod
 1620: 
 1621: =item * &changable_area($name,$origContent):
 1622: 
 1623: This provides a "changable area" that can be modified on the fly via
 1624: the Javascript code provided in C<change_content_javascript>. $name is
 1625: the name you will use to reference the area later; do not repeat the
 1626: same name on a given HTML page more then once. $origContent is what
 1627: the area will originally contain, which can be left blank.
 1628: 
 1629: =cut
 1630: 
 1631: sub changable_area {
 1632:     my ($name, $origContent) = @_;
 1633: 
 1634:     if ($env{'browser.type'} eq 'netscape' &&
 1635: 	$env{'browser.version'} =~ /^4\./) {
 1636: 	# If this is netscape 4, we need to use the Layer tag
 1637: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1638:     } else {
 1639: 	return "<span id='$name'>$origContent</span>";
 1640:     }
 1641: }
 1642: 
 1643: =pod
 1644: 
 1645: =item * &viewport_geometry_js 
 1646: 
 1647: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1648: 
 1649: =cut
 1650: 
 1651: 
 1652: sub viewport_geometry_js { 
 1653:     return <<"GEOMETRY";
 1654: var Geometry = {};
 1655: function init_geometry() {
 1656:     if (Geometry.init) { return };
 1657:     Geometry.init=1;
 1658:     if (window.innerHeight) {
 1659:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1660:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1661:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1662:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1663:     }
 1664:     else if (document.documentElement && document.documentElement.clientHeight) {
 1665:         Geometry.getViewportHeight =
 1666:             function() { return document.documentElement.clientHeight; };
 1667:         Geometry.getViewportWidth =
 1668:             function() { return document.documentElement.clientWidth; };
 1669: 
 1670:         Geometry.getHorizontalScroll =
 1671:             function() { return document.documentElement.scrollLeft; };
 1672:         Geometry.getVerticalScroll =
 1673:             function() { return document.documentElement.scrollTop; };
 1674:     }
 1675:     else if (document.body.clientHeight) {
 1676:         Geometry.getViewportHeight =
 1677:             function() { return document.body.clientHeight; };
 1678:         Geometry.getViewportWidth =
 1679:             function() { return document.body.clientWidth; };
 1680:         Geometry.getHorizontalScroll =
 1681:             function() { return document.body.scrollLeft; };
 1682:         Geometry.getVerticalScroll =
 1683:             function() { return document.body.scrollTop; };
 1684:     }
 1685: }
 1686: 
 1687: GEOMETRY
 1688: }
 1689: 
 1690: =pod
 1691: 
 1692: =item * &viewport_size_js()
 1693: 
 1694: 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. 
 1695: 
 1696: =cut
 1697: 
 1698: sub viewport_size_js {
 1699:     my $geometry = &viewport_geometry_js();
 1700:     return <<"DIMS";
 1701: 
 1702: $geometry
 1703: 
 1704: function getViewportDims(width,height) {
 1705:     init_geometry();
 1706:     width.value = Geometry.getViewportWidth();
 1707:     height.value = Geometry.getViewportHeight();
 1708:     return;
 1709: }
 1710: 
 1711: DIMS
 1712: }
 1713: 
 1714: =pod
 1715: 
 1716: =item * &resize_textarea_js()
 1717: 
 1718: emits the needed javascript to resize a textarea to be as big as possible
 1719: 
 1720: creates a function resize_textrea that takes two IDs first should be
 1721: the id of the element to resize, second should be the id of a div that
 1722: surrounds everything that comes after the textarea, this routine needs
 1723: to be attached to the <body> for the onload and onresize events.
 1724: 
 1725: =back
 1726: 
 1727: =cut
 1728: 
 1729: sub resize_textarea_js {
 1730:     my $geometry = &viewport_geometry_js();
 1731:     return <<"RESIZE";
 1732:     <script type="text/javascript">
 1733: // <![CDATA[
 1734: $geometry
 1735: 
 1736: function getX(element) {
 1737:     var x = 0;
 1738:     while (element) {
 1739: 	x += element.offsetLeft;
 1740: 	element = element.offsetParent;
 1741:     }
 1742:     return x;
 1743: }
 1744: function getY(element) {
 1745:     var y = 0;
 1746:     while (element) {
 1747: 	y += element.offsetTop;
 1748: 	element = element.offsetParent;
 1749:     }
 1750:     return y;
 1751: }
 1752: 
 1753: 
 1754: function resize_textarea(textarea_id,bottom_id) {
 1755:     init_geometry();
 1756:     var textarea        = document.getElementById(textarea_id);
 1757:     //alert(textarea);
 1758: 
 1759:     var textarea_top    = getY(textarea);
 1760:     var textarea_height = textarea.offsetHeight;
 1761:     var bottom          = document.getElementById(bottom_id);
 1762:     var bottom_top      = getY(bottom);
 1763:     var bottom_height   = bottom.offsetHeight;
 1764:     var window_height   = Geometry.getViewportHeight();
 1765:     var fudge           = 23;
 1766:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1767:     if (new_height < 300) {
 1768: 	new_height = 300;
 1769:     }
 1770:     textarea.style.height=new_height+'px';
 1771: }
 1772: // ]]>
 1773: </script>
 1774: RESIZE
 1775: 
 1776: }
 1777: 
 1778: sub colorfuleditor_js {
 1779:     my $browse_or_search;
 1780:     my $respath;
 1781:     my ($cnum,$cdom) = &crsauthor_url();
 1782:     if ($cnum) {
 1783:         $respath = "/res/$cdom/$cnum/";
 1784:         my %js_lt = &Apache::lonlocal::texthash(
 1785:             sunm => 'Sub-directory name',
 1786:             save => 'Save page to make this permanent',
 1787:         );
 1788:         &js_escape(\%js_lt);
 1789:         $browse_or_search = <<"END";
 1790: 
 1791:     function toggleChooser(form,element,titleid,only,search) {
 1792:         var disp = 'none';
 1793:         if (document.getElementById('chooser_'+element)) {
 1794:             var curr = document.getElementById('chooser_'+element).style.display;
 1795:             if (curr == 'none') {
 1796:                 disp='inline';
 1797:                 if (form.elements['chooser_'+element].length) {
 1798:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1799:                         form.elements['chooser_'+element][i].checked = false;
 1800:                     }
 1801:                 }
 1802:                 toggleResImport(form,element);
 1803:             }
 1804:             document.getElementById('chooser_'+element).style.display = disp;
 1805:         }
 1806:     }
 1807: 
 1808:     function toggleCrsFile(form,element,numdirs) {
 1809:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1810:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1811:             if (curr == 'none') {
 1812:                 if (numdirs) {
 1813:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1814:                     if (numdirs > 1) {
 1815:                         window['select1'+element+'_changed']();
 1816:                     }
 1817:                 }
 1818:             } 
 1819:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1820:             
 1821:         }
 1822:         if (document.getElementById('chooser_'+element+'_upload')) {
 1823:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1824:             if (document.getElementById('uploadcrsres_'+element)) {
 1825:                 document.getElementById('uploadcrsres_'+element).value = '';
 1826:             }
 1827:         }
 1828:         return;
 1829:     }
 1830: 
 1831:     function toggleCrsUpload(form,element,numcrsdirs) {
 1832:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1833:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1834:         }
 1835:         if (document.getElementById('chooser_'+element+'_upload')) {
 1836:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1837:             if (curr == 'none') {
 1838:                 if (numcrsdirs) {
 1839:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1840:                    form.elements['newsubdir_'+element][0].checked = true;
 1841:                    toggleNewsubdir(form,element);
 1842:                 }
 1843:             }
 1844:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1845:         }
 1846:         return;
 1847:     }
 1848: 
 1849:     function toggleResImport(form,element) {
 1850:         var choices = new Array('crsres','upload');
 1851:         for (var i=0; i<choices.length; i++) {
 1852:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1853:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1854:             }
 1855:         }
 1856:     }
 1857: 
 1858:     function toggleNewsubdir(form,element) {
 1859:         var newsub = form.elements['newsubdir_'+element];
 1860:         if (newsub) {
 1861:             if (newsub.length) {
 1862:                 for (var j=0; j<newsub.length; j++) {
 1863:                     if (newsub[j].checked) {
 1864:                         if (document.getElementById('newsubdirname_'+element)) {
 1865:                             if (newsub[j].value == '1') {
 1866:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1867:                                 if (document.getElementById('newsubdir_'+element)) {
 1868:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1869:                                 }
 1870:                             } else {
 1871:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1872:                                 document.getElementById('newsubdirname_'+element).value = "";
 1873:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1874:                             }
 1875:                         }
 1876:                         break; 
 1877:                     }
 1878:                 }
 1879:             }
 1880:         }
 1881:     }
 1882: 
 1883:     function updateCrsFile(form,element) {
 1884:         var directory = form.elements['coursepath_'+element];
 1885:         var filename = form.elements['coursefile_'+element];
 1886:         var path = directory.options[directory.selectedIndex].value;
 1887:         var file = filename.options[filename.selectedIndex].value;
 1888:         form.elements[element].value = '$respath';
 1889:         if (path == '/') {
 1890:             form.elements[element].value += file;
 1891:         } else {
 1892:             form.elements[element].value += path+'/'+file;
 1893:         }
 1894:         unClean();
 1895:         if (document.getElementById('previewimg_'+element)) {
 1896:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1897:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1898:         }
 1899:         if (document.getElementById('showimg_'+element)) {
 1900:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1901:         }
 1902:         toggleChooser(form,element);
 1903:         return;
 1904:     }
 1905: 
 1906:     function uploadDone(suffix,name) {
 1907:         if (name) {
 1908: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1909:             unClean();
 1910:             toggleChooser(document.forms["lonhomework"],suffix);
 1911:         }
 1912:     }
 1913: 
 1914: \$(document).ready(function(){
 1915: 
 1916:     \$(document).delegate('form :submit', 'click', function( event ) {
 1917:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1918:             var buttonId = this.id;
 1919:             var suffix = buttonId.toString();
 1920:             suffix = suffix.replace(/^crsupload_/,'');
 1921:             event.preventDefault();
 1922:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1923:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1924:             \$(this.form).submit();
 1925:             document.lonhomework.target = '';
 1926:             if (document.getElementById('crsuploadto_'+suffix)) {
 1927:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1928:             }
 1929:             return false;
 1930:         }
 1931:     });
 1932: });
 1933: END
 1934:     }
 1935:     return <<"COLORFULEDIT"
 1936: <script type="text/javascript">
 1937: // <![CDATA[>
 1938:     function fold_box(curDepth, lastresource){
 1939: 
 1940:     // we need a list because there can be several blocks you need to fold in one tag
 1941:         var block = document.getElementsByName('foldblock_'+curDepth);
 1942:     // but there is only one folding button per tag
 1943:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1944: 
 1945:         if(block.item(0).style.display == 'none'){
 1946: 
 1947:             foldbutton.value = '@{[&mt("Hide")]}';
 1948:             for (i = 0; i < block.length; i++){
 1949:                 block.item(i).style.display = '';
 1950:             }
 1951:         }else{
 1952: 
 1953:             foldbutton.value = '@{[&mt("Show")]}';
 1954:             for (i = 0; i < block.length; i++){
 1955:                 // block.item(i).style.visibility = 'collapse';
 1956:                 block.item(i).style.display = 'none';
 1957:             }
 1958:         };
 1959:         saveState(lastresource);
 1960:     }
 1961: 
 1962:     function saveState (lastresource) {
 1963: 
 1964:         var tag_list = getTagList();
 1965:         if(tag_list != null){
 1966:             var timestamp = new Date().getTime();
 1967:             var key = lastresource;
 1968: 
 1969:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1970:             // starting with timestamp
 1971:             var value = timestamp+';';
 1972: 
 1973:             // building the list of key-value pairs
 1974:             for(var i = 0; i < tag_list.length; i++){
 1975:                 value += tag_list[i]+',';
 1976:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1977:             }
 1978: 
 1979:             // only iterate whole storage if nothing to override
 1980:             if(localStorage.getItem(key) == null){        
 1981: 
 1982:                 // prevent storage from growing large
 1983:                 if(localStorage.length > 50){
 1984:                     var regex_getTimestamp = /^(?:\d)+;/;
 1985:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1986:                     var oldest_key;
 1987:                     
 1988:                     for(var i = 1; i < localStorage.length; i++){
 1989:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1990:                             oldest_key = localStorage.key(i);
 1991:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1992:                         }
 1993:                     }
 1994:                     localStorage.removeItem(oldest_key);
 1995:                 }
 1996:             }
 1997:             localStorage.setItem(key,value);
 1998:         }
 1999:     }
 2000: 
 2001:     // restore folding status of blocks (on page load)
 2002:     function restoreState (lastresource) {
 2003:         if(localStorage.getItem(lastresource) != null){
 2004:             var key = lastresource;
 2005:             var value = localStorage.getItem(key);
 2006:             var regex_delTimestamp = /^\d+;/;
 2007: 
 2008:             value.replace(regex_delTimestamp, '');
 2009: 
 2010:             var valueArr = value.split(';');
 2011:             var pairs;
 2012:             var elements;
 2013:             for (var i = 0; i < valueArr.length; i++){
 2014:                 pairs = valueArr[i].split(',');
 2015:                 elements = document.getElementsByName(pairs[0]);
 2016: 
 2017:                 for (var j = 0; j < elements.length; j++){  
 2018:                     elements[j].style.display = pairs[1];
 2019:                     if (pairs[1] == "none"){
 2020:                         var regex_id = /([_\\d]+)\$/;
 2021:                         regex_id.exec(pairs[0]);
 2022:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2023:                     }
 2024:                 }
 2025:             }
 2026:         }
 2027:     }
 2028: 
 2029:     function getTagList () {
 2030:         
 2031:         var stringToSearch = document.lonhomework.innerHTML;
 2032: 
 2033:         var ret = new Array();
 2034:         var regex_findBlock = /(foldblock_.*?)"/g;
 2035:         var tag_list = stringToSearch.match(regex_findBlock);
 2036: 
 2037:         if(tag_list != null){
 2038:             for(var i = 0; i < tag_list.length; i++){            
 2039:                 ret.push(tag_list[i].replace(/"/, ''));
 2040:             }
 2041:         }
 2042:         return ret;
 2043:     }
 2044: 
 2045:     function saveScrollPosition (resource) {
 2046:         var tag_list = getTagList();
 2047: 
 2048:         // we dont always want to jump to the first block
 2049:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2050:         if(\$(window).scrollTop() > 170){
 2051:             if(tag_list != null){
 2052:                 var result;
 2053:                 for(var i = 0; i < tag_list.length; i++){
 2054:                     if(isElementInViewport(tag_list[i])){
 2055:                         result += tag_list[i]+';';
 2056:                     }
 2057:                 }
 2058:                 sessionStorage.setItem('anchor_'+resource, result);
 2059:             }
 2060:         } else {
 2061:             // we dont need to save zero, just delete the item to leave everything tidy
 2062:             sessionStorage.removeItem('anchor_'+resource);
 2063:         }
 2064:     }
 2065: 
 2066:     function restoreScrollPosition(resource){
 2067: 
 2068:         var elem = sessionStorage.getItem('anchor_'+resource);
 2069:         if(elem != null){
 2070:             var tag_list = elem.split(';');
 2071:             var elem_list;
 2072: 
 2073:             for(var i = 0; i < tag_list.length; i++){
 2074:                 elem_list = document.getElementsByName(tag_list[i]);
 2075:                 
 2076:                 if(elem_list.length > 0){
 2077:                     elem = elem_list[0];
 2078:                     break;
 2079:                 }
 2080:             }
 2081:             elem.scrollIntoView();
 2082:         }
 2083:     }
 2084: 
 2085:     function isElementInViewport(el) {
 2086: 
 2087:         // change to last element instead of first
 2088:         var elem = document.getElementsByName(el);
 2089:         var rect = elem[0].getBoundingClientRect();
 2090: 
 2091:         return (
 2092:             rect.top >= 0 &&
 2093:             rect.left >= 0 &&
 2094:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2095:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2096:         );
 2097:     }
 2098:     
 2099:     function autosize(depth){
 2100:         var cmInst = window['cm'+depth];
 2101:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2102: 
 2103:         // is fixed size, switching to dynamic
 2104:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2105:             cmInst.setSize("","auto");
 2106:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2107:             sessionStorage.setItem("autosized_"+depth, "yes");
 2108: 
 2109:         // is dynamic size, switching to fixed
 2110:         } else {
 2111:             cmInst.setSize("","300px");
 2112:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2113:             sessionStorage.removeItem("autosized_"+depth);
 2114:         }
 2115:     }
 2116: 
 2117: $browse_or_search
 2118: 
 2119: // ]]>
 2120: </script>
 2121: COLORFULEDIT
 2122: }
 2123: 
 2124: sub xmleditor_js {
 2125:     return <<XMLEDIT
 2126: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2127: <script type="text/javascript">
 2128: // <![CDATA[>
 2129: 
 2130:     function saveScrollPosition (resource) {
 2131: 
 2132:         var scrollPos = \$(window).scrollTop();
 2133:         sessionStorage.setItem(resource,scrollPos);
 2134:     }
 2135: 
 2136:     function restoreScrollPosition(resource){
 2137: 
 2138:         var scrollPos = sessionStorage.getItem(resource);
 2139:         \$(window).scrollTop(scrollPos);
 2140:     }
 2141: 
 2142:     // unless internet explorer
 2143:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2144: 
 2145:         \$(document).ready(function() {
 2146:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2147:         });
 2148:     }
 2149: 
 2150:     // inserts text at cursor position into codemirror (xml editor only)
 2151:     function insertText(text){
 2152:         cm.focus();
 2153:         var curPos = cm.getCursor();
 2154:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2155:     }
 2156: // ]]>
 2157: </script>
 2158: XMLEDIT
 2159: }
 2160: 
 2161: sub insert_folding_button {
 2162:     my $curDepth = $Apache::lonxml::curdepth;
 2163:     my $lastresource = $env{'request.ambiguous'};
 2164: 
 2165:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2166:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2167: }
 2168: 
 2169: sub crsauthor_url {
 2170:     my ($url) = @_;
 2171:     if ($url eq '') {
 2172:         $url = $ENV{'REQUEST_URI'};
 2173:     }
 2174:     my ($cnum,$cdom);
 2175:     if ($env{'request.course.id'}) {
 2176:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2177:         if ($audom ne '' && $auname ne '') {
 2178:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2179:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2180:                 $cnum = $auname;
 2181:                 $cdom = $audom;
 2182:             }
 2183:         }
 2184:     }
 2185:     return ($cnum,$cdom);
 2186: }
 2187: 
 2188: sub import_crsauthor_form {
 2189:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
 2190:     return (0) unless ($env{'request.course.id'});
 2191:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2192:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2193:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2194:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2195:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2196:     my @ids=&Apache::lonnet::current_machine_ids();
 2197:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2198:     
 2199:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2200:         $is_home = 1;
 2201:     }
 2202:     $relpath = "/priv/$cdom/$cnum";
 2203:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2204:     my %lt = &Apache::lonlocal::texthash (
 2205:         fnam => 'Filename',
 2206:         dire => 'Directory',
 2207:     );
 2208:     my $numdirs = scalar(keys(%files));
 2209:     my (%possexts,$singledir,@singledirfiles);
 2210:     if ($only) {
 2211:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2212:     }
 2213:     my (%nonemptydirs,$possdirs);
 2214:     if ($numdirs > 1) {
 2215:         my @order;
 2216:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2217:             if (ref($files{$key}) eq 'HASH') {
 2218:                 my $shown = $key;
 2219:                 if ($key eq '') {
 2220:                     $shown = '/';
 2221:                 }
 2222:                 my @ordered = ();
 2223:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2224:                     if ($only) {
 2225:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2226:                         unless ($possexts{lc($ext)}) {
 2227:                             next;
 2228:                         }
 2229:                     }
 2230:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2231:                     push(@ordered,$file);
 2232:                 }
 2233:                 if (@ordered) {
 2234:                     push(@order,$key);
 2235:                     $nonemptydirs{$key} = 1;
 2236:                     $selimport_menus{$key}->{'text'} = $shown;
 2237:                     $selimport_menus{$key}->{'default'} = '';
 2238:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2239:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2240:                 }
 2241:             }
 2242:         }
 2243:         $possdirs = scalar(keys(%nonemptydirs));
 2244:         if ($possdirs > 1) {
 2245:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2246:             $output = $lt{'dire'}.
 2247:                       &linked_select_forms($form,'<br />'.
 2248:                                            $lt{'fnam'},'',
 2249:                                            $firstselectname,$secondselectname,
 2250:                                            \%selimport_menus,\@order,
 2251:                                            $onchangefirst,'',$suffix).'<br />';
 2252:         } elsif ($possdirs == 1) {
 2253:             $singledir = (keys(%nonemptydirs))[0];
 2254:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2255:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2256:             }
 2257:             delete($selimport_menus{$singledir});
 2258:         }
 2259:     } elsif ($numdirs == 1) {
 2260:         $singledir = (keys(%files))[0];
 2261:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2262:             if ($only) {
 2263:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2264:                 unless ($possexts{lc($ext)}) {
 2265:                     next;
 2266:                 }
 2267:             }
 2268:             push(@singledirfiles,$file);
 2269:         }
 2270:         if (@singledirfiles) {
 2271:             $possdirs == 1;
 2272:         }
 2273:     }
 2274:     if (($possdirs == 1) && (@singledirfiles)) {
 2275:         my $showdir = $singledir;
 2276:         if ($singledir eq '') {
 2277:             $showdir = '/';
 2278:         }
 2279:         $output = $lt{'dire'}.
 2280:                   '<select name="'.$firstselectname.'">'.
 2281:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2282:                   '</select><br />'.
 2283:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2284:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2285:         foreach my $file (@singledirfiles) {
 2286:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2287:         }
 2288:         $output .= '</select><br />'."\n";
 2289:     }
 2290:     return ($possdirs,$output);
 2291: }
 2292: 
 2293: =pod
 2294: 
 2295: =head1 Excel and CSV file utility routines
 2296: 
 2297: =cut
 2298: 
 2299: ###############################################################
 2300: ###############################################################
 2301: 
 2302: =pod
 2303: 
 2304: =over 4
 2305: 
 2306: =item * &csv_translate($text) 
 2307: 
 2308: Translate $text to allow it to be output as a 'comma separated values' 
 2309: format.
 2310: 
 2311: =cut
 2312: 
 2313: ###############################################################
 2314: ###############################################################
 2315: sub csv_translate {
 2316:     my $text = shift;
 2317:     $text =~ s/\"/\"\"/g;
 2318:     $text =~ s/\n/ /g;
 2319:     return $text;
 2320: }
 2321: 
 2322: ###############################################################
 2323: ###############################################################
 2324: 
 2325: =pod
 2326: 
 2327: =item * &define_excel_formats()
 2328: 
 2329: Define some commonly used Excel cell formats.
 2330: 
 2331: Currently supported formats:
 2332: 
 2333: =over 4
 2334: 
 2335: =item header
 2336: 
 2337: =item bold
 2338: 
 2339: =item h1
 2340: 
 2341: =item h2
 2342: 
 2343: =item h3
 2344: 
 2345: =item h4
 2346: 
 2347: =item i
 2348: 
 2349: =item date
 2350: 
 2351: =back
 2352: 
 2353: Inputs: $workbook
 2354: 
 2355: Returns: $format, a hash reference.
 2356: 
 2357: 
 2358: =cut
 2359: 
 2360: ###############################################################
 2361: ###############################################################
 2362: sub define_excel_formats {
 2363:     my ($workbook) = @_;
 2364:     my $format;
 2365:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2366:                                                 bottom    => 1,
 2367:                                                 align     => 'center');
 2368:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2369:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2370:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2371:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2372:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2373:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2374:     $format->{'date'} = $workbook->add_format(num_format=>
 2375:                                             'mm/dd/yyyy hh:mm:ss');
 2376:     return $format;
 2377: }
 2378: 
 2379: ###############################################################
 2380: ###############################################################
 2381: 
 2382: =pod
 2383: 
 2384: =item * &create_workbook()
 2385: 
 2386: Create an Excel worksheet.  If it fails, output message on the
 2387: request object and return undefs.
 2388: 
 2389: Inputs: Apache request object
 2390: 
 2391: Returns (undef) on failure, 
 2392:     Excel worksheet object, scalar with filename, and formats 
 2393:     from &Apache::loncommon::define_excel_formats on success
 2394: 
 2395: =cut
 2396: 
 2397: ###############################################################
 2398: ###############################################################
 2399: sub create_workbook {
 2400:     my ($r) = @_;
 2401:         #
 2402:     # Create the excel spreadsheet
 2403:     my $filename = '/prtspool/'.
 2404:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2405:         time.'_'.rand(1000000000).'.xls';
 2406:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2407:     if (! defined($workbook)) {
 2408:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2409:         $r->print(
 2410:             '<p class="LC_error">'
 2411:            .&mt('Problems occurred in creating the new Excel file.')
 2412:            .' '.&mt('This error has been logged.')
 2413:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2414:            .'</p>'
 2415:         );
 2416:         return (undef);
 2417:     }
 2418:     #
 2419:     $workbook->set_tempdir(LONCAPA::tempdir());
 2420:     #
 2421:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2422:     return ($workbook,$filename,$format);
 2423: }
 2424: 
 2425: ###############################################################
 2426: ###############################################################
 2427: 
 2428: =pod
 2429: 
 2430: =item * &create_text_file()
 2431: 
 2432: Create a file to write to and eventually make available to the user.
 2433: If file creation fails, outputs an error message on the request object and 
 2434: return undefs.
 2435: 
 2436: Inputs: Apache request object, and file suffix
 2437: 
 2438: Returns (undef) on failure, 
 2439:     Filehandle and filename on success.
 2440: 
 2441: =cut
 2442: 
 2443: ###############################################################
 2444: ###############################################################
 2445: sub create_text_file {
 2446:     my ($r,$suffix) = @_;
 2447:     if (! defined($suffix)) { $suffix = 'txt'; };
 2448:     my $fh;
 2449:     my $filename = '/prtspool/'.
 2450:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2451:         time.'_'.rand(1000000000).'.'.$suffix;
 2452:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2453:     if (! defined($fh)) {
 2454:         $r->log_error("Couldn't open $filename for output $!");
 2455:         $r->print(
 2456:             '<p class="LC_error">'
 2457:            .&mt('Problems occurred in creating the output file.')
 2458:            .' '.&mt('This error has been logged.')
 2459:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2460:            .'</p>'
 2461:         );
 2462:     }
 2463:     return ($fh,$filename)
 2464: }
 2465: 
 2466: 
 2467: =pod 
 2468: 
 2469: =back
 2470: 
 2471: =cut
 2472: 
 2473: ###############################################################
 2474: ##        Home server <option> list generating code          ##
 2475: ###############################################################
 2476: 
 2477: # ------------------------------------------
 2478: 
 2479: sub domain_select {
 2480:     my ($name,$value,$multiple)=@_;
 2481:     my %domains=map { 
 2482: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2483:     } &Apache::lonnet::all_domains();
 2484:     if ($multiple) {
 2485: 	$domains{''}=&mt('Any domain');
 2486: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2487: 	return &multiple_select_form($name,$value,4,\%domains);
 2488:     } else {
 2489: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2490: 	return &select_form($name,$value,\%domains);
 2491:     }
 2492: }
 2493: 
 2494: #-------------------------------------------
 2495: 
 2496: =pod
 2497: 
 2498: =head1 Routines for form select boxes
 2499: 
 2500: =over 4
 2501: 
 2502: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2503: 
 2504: Returns a string containing a <select> element int multiple mode
 2505: 
 2506: 
 2507: Args:
 2508:   $name - name of the <select> element
 2509:   $value - scalar or array ref of values that should already be selected
 2510:   $size - number of rows long the select element is
 2511:   $hash - the elements should be 'option' => 'shown text'
 2512:           (shown text should already have been &mt())
 2513:   $order - (optional) array ref of the order to show the elements in
 2514: 
 2515: =cut
 2516: 
 2517: #-------------------------------------------
 2518: sub multiple_select_form {
 2519:     my ($name,$value,$size,$hash,$order)=@_;
 2520:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2521:     my $output='';
 2522:     if (! defined($size)) {
 2523:         $size = 4;
 2524:         if (scalar(keys(%$hash))<4) {
 2525:             $size = scalar(keys(%$hash));
 2526:         }
 2527:     }
 2528:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2529:     my @order;
 2530:     if (ref($order) eq 'ARRAY')  {
 2531:         @order = @{$order};
 2532:     } else {
 2533:         @order = sort(keys(%$hash));
 2534:     }
 2535:     if (exists($$hash{'select_form_order'})) {
 2536:         @order = @{$$hash{'select_form_order'}};
 2537:     }
 2538:         
 2539:     foreach my $key (@order) {
 2540:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2541:         $output.='selected="selected" ' if ($selected{$key});
 2542:         $output.='>'.$hash->{$key}."</option>\n";
 2543:     }
 2544:     $output.="</select>\n";
 2545:     return $output;
 2546: }
 2547: 
 2548: #-------------------------------------------
 2549: 
 2550: =pod
 2551: 
 2552: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2553: 
 2554: Returns a string containing a <select name='$name' size='1'> form to 
 2555: allow a user to select options from a ref to a hash containing:
 2556: option_name => displayed text. An optional $onchange can include
 2557: a javascript onchange item, e.g., onchange="this.form.submit();".
 2558: An optional arg -- $readonly -- if true will cause the select form
 2559: to be disabled, e.g., for the case where an instructor has a section-
 2560: specific role, and is viewing/modifying parameters. 
 2561: 
 2562: See lonrights.pm for an example invocation and use.
 2563: 
 2564: =cut
 2565: 
 2566: #-------------------------------------------
 2567: sub select_form {
 2568:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2569:     return unless (ref($hashref) eq 'HASH');
 2570:     if ($onchange) {
 2571:         $onchange = ' onchange="'.$onchange.'"';
 2572:     }
 2573:     my $disabled;
 2574:     if ($readonly) {
 2575:         $disabled = ' disabled="disabled"';
 2576:     }
 2577:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2578:     my @keys;
 2579:     if (exists($hashref->{'select_form_order'})) {
 2580: 	@keys=@{$hashref->{'select_form_order'}};
 2581:     } else {
 2582: 	@keys=sort(keys(%{$hashref}));
 2583:     }
 2584:     foreach my $key (@keys) {
 2585:         $selectform.=
 2586: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2587:             ($key eq $def ? 'selected="selected" ' : '').
 2588:                 ">".$hashref->{$key}."</option>\n";
 2589:     }
 2590:     $selectform.="</select>";
 2591:     return $selectform;
 2592: }
 2593: 
 2594: # For display filters
 2595: 
 2596: sub display_filter {
 2597:     my ($context) = @_;
 2598:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2599:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2600:     my $phraseinput = 'hidden';
 2601:     my $includeinput = 'hidden';
 2602:     my ($checked,$includetypestext);
 2603:     if ($env{'form.displayfilter'} eq 'containing') {
 2604:         $phraseinput = 'text'; 
 2605:         if ($context eq 'parmslog') {
 2606:             $includeinput = 'checkbox';
 2607:             if ($env{'form.includetypes'}) {
 2608:                 $checked = ' checked="checked"';
 2609:             }
 2610:             $includetypestext = &mt('Include parameter types');
 2611:         }
 2612:     } else {
 2613:         $includetypestext = '&nbsp;';
 2614:     }
 2615:     my ($additional,$secondid,$thirdid);
 2616:     if ($context eq 'parmslog') {
 2617:         $additional = 
 2618:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2619:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2620:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2621:             '</label>';
 2622:         $secondid = 'includetypes';
 2623:         $thirdid = 'includetypestext';
 2624:     }
 2625:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2626:                                                     '$secondid','$thirdid')";
 2627:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2628: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2629: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2630: 	   '</label></span> <span class="LC_nobreak">'.
 2631:            &mt('Filter: [_1]',
 2632: 	   &select_form($env{'form.displayfilter'},
 2633: 			'displayfilter',
 2634: 			{'currentfolder' => 'Current folder/page',
 2635: 			 'containing' => 'Containing phrase',
 2636: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2637: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2638:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2639:                          '" />'.$additional;
 2640: }
 2641: 
 2642: sub display_filter_js {
 2643:     my $includetext = &mt('Include parameter types');
 2644:     return <<"ENDJS";
 2645:   
 2646: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2647:     var firstType = 'hidden';
 2648:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2649:         firstType = 'text';
 2650:     }
 2651:     firstObject = document.getElementById(firstid);
 2652:     if (typeof(firstObject) == 'object') {
 2653:         if (firstObject.type != firstType) {
 2654:             changeInputType(firstObject,firstType);
 2655:         }
 2656:     }
 2657:     if (context == 'parmslog') {
 2658:         var secondType = 'hidden';
 2659:         if (firstType == 'text') {
 2660:             secondType = 'checkbox';
 2661:         }
 2662:         secondObject = document.getElementById(secondid);  
 2663:         if (typeof(secondObject) == 'object') {
 2664:             if (secondObject.type != secondType) {
 2665:                 changeInputType(secondObject,secondType);
 2666:             }
 2667:         }
 2668:         var textItem = document.getElementById(thirdid);
 2669:         var currtext = textItem.innerHTML;
 2670:         var newtext;
 2671:         if (firstType == 'text') {
 2672:             newtext = '$includetext';
 2673:         } else {
 2674:             newtext = '&nbsp;';
 2675:         }
 2676:         if (currtext != newtext) {
 2677:             textItem.innerHTML = newtext;
 2678:         }
 2679:     }
 2680:     return;
 2681: }
 2682: 
 2683: function changeInputType(oldObject,newType) {
 2684:     var newObject = document.createElement('input');
 2685:     newObject.type = newType;
 2686:     if (oldObject.size) {
 2687:         newObject.size = oldObject.size;
 2688:     }
 2689:     if (oldObject.value) {
 2690:         newObject.value = oldObject.value;
 2691:     }
 2692:     if (oldObject.name) {
 2693:         newObject.name = oldObject.name;
 2694:     }
 2695:     if (oldObject.id) {
 2696:         newObject.id = oldObject.id;
 2697:     }
 2698:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2699:     return;
 2700: }
 2701: 
 2702: ENDJS
 2703: }
 2704: 
 2705: sub gradeleveldescription {
 2706:     my $gradelevel=shift;
 2707:     my %gradelevels=(0 => 'Not specified',
 2708: 		     1 => 'Grade 1',
 2709: 		     2 => 'Grade 2',
 2710: 		     3 => 'Grade 3',
 2711: 		     4 => 'Grade 4',
 2712: 		     5 => 'Grade 5',
 2713: 		     6 => 'Grade 6',
 2714: 		     7 => 'Grade 7',
 2715: 		     8 => 'Grade 8',
 2716: 		     9 => 'Grade 9',
 2717: 		     10 => 'Grade 10',
 2718: 		     11 => 'Grade 11',
 2719: 		     12 => 'Grade 12',
 2720: 		     13 => 'Grade 13',
 2721: 		     14 => '100 Level',
 2722: 		     15 => '200 Level',
 2723: 		     16 => '300 Level',
 2724: 		     17 => '400 Level',
 2725: 		     18 => 'Graduate Level');
 2726:     return &mt($gradelevels{$gradelevel});
 2727: }
 2728: 
 2729: sub select_level_form {
 2730:     my ($deflevel,$name)=@_;
 2731:     unless ($deflevel) { $deflevel=0; }
 2732:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2733:     for (my $i=0; $i<=18; $i++) {
 2734:         $selectform.="<option value=\"$i\" ".
 2735:             ($i==$deflevel ? 'selected="selected" ' : '').
 2736:                 ">".&gradeleveldescription($i)."</option>\n";
 2737:     }
 2738:     $selectform.="</select>";
 2739:     return $selectform;
 2740: }
 2741: 
 2742: #-------------------------------------------
 2743: 
 2744: =pod
 2745: 
 2746: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2747: 
 2748: Returns a string containing a <select name='$name' size='1'> form to 
 2749: allow a user to select the domain to preform an operation in.  
 2750: See loncreateuser.pm for an example invocation and use.
 2751: 
 2752: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2753: selected");
 2754: 
 2755: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2756: 
 2757: 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.
 2758: 
 2759: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2760: 
 2761: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2762: 
 2763: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
 2764: 
 2765: =cut
 2766: 
 2767: #-------------------------------------------
 2768: sub select_dom_form {
 2769:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2770:     if ($onchange) {
 2771:         $onchange = ' onchange="'.$onchange.'"';
 2772:     }
 2773:     if ($disabled) {
 2774:         $disabled = ' disabled="disabled"';
 2775:     }
 2776:     my (@domains,%exclude);
 2777:     if (ref($incdoms) eq 'ARRAY') {
 2778:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2779:     } else {
 2780:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2781:     }
 2782:     if ($includeempty) { @domains=('',@domains); }
 2783:     if (ref($excdoms) eq 'ARRAY') {
 2784:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2785:     }
 2786:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2787:     foreach my $dom (@domains) {
 2788:         next if ($exclude{$dom});
 2789:         $selectdomain.="<option value=\"$dom\" ".
 2790:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2791:         if ($showdomdesc) {
 2792:             if ($dom ne '') {
 2793:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2794:                 if ($domdesc ne '') {
 2795:                     $selectdomain .= ' ('.$domdesc.')';
 2796:                 }
 2797:             } 
 2798:         }
 2799:         $selectdomain .= "</option>\n";
 2800:     }
 2801:     $selectdomain.="</select>";
 2802:     return $selectdomain;
 2803: }
 2804: 
 2805: #-------------------------------------------
 2806: 
 2807: =pod
 2808: 
 2809: =item * &home_server_form_item($domain,$name,$defaultflag)
 2810: 
 2811: input: 4 arguments (two required, two optional) - 
 2812:     $domain - domain of new user
 2813:     $name - name of form element
 2814:     $default - Value of 'default' causes a default item to be first 
 2815:                             option, and selected by default. 
 2816:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2817:                             if 1 server found, or default, if 0 found.
 2818: output: returns 2 items: 
 2819: (a) form element which contains either:
 2820:    (i) <select name="$name">
 2821:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2822:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2823:        </select>
 2824:        form item if there are multiple library servers in $domain, or
 2825:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2826:        if there is only one library server in $domain.
 2827: 
 2828: (b) number of library servers found.
 2829: 
 2830: See loncreateuser.pm for example of use.
 2831: 
 2832: =cut
 2833: 
 2834: #-------------------------------------------
 2835: sub home_server_form_item {
 2836:     my ($domain,$name,$default,$hide) = @_;
 2837:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2838:     my $result;
 2839:     my $numlib = keys(%servers);
 2840:     if ($numlib > 1) {
 2841:         $result .= '<select name="'.$name.'" />'."\n";
 2842:         if ($default) {
 2843:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2844:                        '</option>'."\n";
 2845:         }
 2846:         foreach my $hostid (sort(keys(%servers))) {
 2847:             $result.= '<option value="'.$hostid.'">'.
 2848: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2849:         }
 2850:         $result .= '</select>'."\n";
 2851:     } elsif ($numlib == 1) {
 2852:         my $hostid;
 2853:         foreach my $item (keys(%servers)) {
 2854:             $hostid = $item;
 2855:         }
 2856:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2857:                    $hostid.'" />';
 2858:                    if (!$hide) {
 2859:                        $result .= $hostid.' '.$servers{$hostid};
 2860:                    }
 2861:                    $result .= "\n";
 2862:     } elsif ($default) {
 2863:         $result .= '<input type="hidden" name="'.$name.
 2864:                    '" value="default" />';
 2865:                    if (!$hide) {
 2866:                        $result .= &mt('default');
 2867:                    }
 2868:                    $result .= "\n";
 2869:     }
 2870:     return ($result,$numlib);
 2871: }
 2872: 
 2873: =pod
 2874: 
 2875: =back 
 2876: 
 2877: =cut
 2878: 
 2879: ###############################################################
 2880: ##                  Decoding User Agent                      ##
 2881: ###############################################################
 2882: 
 2883: =pod
 2884: 
 2885: =head1 Decoding the User Agent
 2886: 
 2887: =over 4
 2888: 
 2889: =item * &decode_user_agent()
 2890: 
 2891: Inputs: $r
 2892: 
 2893: Outputs:
 2894: 
 2895: =over 4
 2896: 
 2897: =item * $httpbrowser
 2898: 
 2899: =item * $clientbrowser
 2900: 
 2901: =item * $clientversion
 2902: 
 2903: =item * $clientmathml
 2904: 
 2905: =item * $clientunicode
 2906: 
 2907: =item * $clientos
 2908: 
 2909: =item * $clientmobile
 2910: 
 2911: =item * $clientinfo
 2912: 
 2913: =item * $clientosversion
 2914: 
 2915: =back
 2916: 
 2917: =back 
 2918: 
 2919: =cut
 2920: 
 2921: ###############################################################
 2922: ###############################################################
 2923: sub decode_user_agent {
 2924:     my ($r)=@_;
 2925:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2926:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2927:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2928:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2929:     my $clientbrowser='unknown';
 2930:     my $clientversion='0';
 2931:     my $clientmathml='';
 2932:     my $clientunicode='0';
 2933:     my $clientmobile=0;
 2934:     my $clientosversion='';
 2935:     for (my $i=0;$i<=$#browsertype;$i++) {
 2936:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2937: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2938: 	    $clientbrowser=$bname;
 2939:             $httpbrowser=~/$vreg/i;
 2940: 	    $clientversion=$1;
 2941:             $clientmathml=($clientversion>=$minv);
 2942:             $clientunicode=($clientversion>=$univ);
 2943: 	}
 2944:     }
 2945:     my $clientos='unknown';
 2946:     my $clientinfo;
 2947:     if (($httpbrowser=~/linux/i) ||
 2948:         ($httpbrowser=~/unix/i) ||
 2949:         ($httpbrowser=~/ux/i) ||
 2950:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2951:     if (($httpbrowser=~/vax/i) ||
 2952:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2953:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2954:     if (($httpbrowser=~/mac/i) ||
 2955:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2956:     if ($httpbrowser=~/win/i) {
 2957:         $clientos='win';
 2958:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2959:             $clientosversion = $1;
 2960:         }
 2961:     }
 2962:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2963:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2964:         $clientmobile=lc($1);
 2965:     }
 2966:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2967:         $clientinfo = 'firefox-'.$1;
 2968:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2969:         $clientinfo = 'chromeframe-'.$1;
 2970:     }
 2971:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2972:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2973:             $clientosversion);
 2974: }
 2975: 
 2976: ###############################################################
 2977: ##    Authentication changing form generation subroutines    ##
 2978: ###############################################################
 2979: ##
 2980: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2981: ## hash, and have reasonable default values.
 2982: ##
 2983: ##    formname = the name given in the <form> tag.
 2984: #-------------------------------------------
 2985: 
 2986: =pod
 2987: 
 2988: =head1 Authentication Routines
 2989: 
 2990: =over 4
 2991: 
 2992: =item * &authform_xxxxxx()
 2993: 
 2994: The authform_xxxxxx subroutines provide javascript and html forms which 
 2995: handle some of the conveniences required for authentication forms.  
 2996: This is not an optimal method, but it works.  
 2997: 
 2998: =over 4
 2999: 
 3000: =item * authform_header
 3001: 
 3002: =item * authform_authorwarning
 3003: 
 3004: =item * authform_nochange
 3005: 
 3006: =item * authform_kerberos
 3007: 
 3008: =item * authform_internal
 3009: 
 3010: =item * authform_filesystem
 3011: 
 3012: =back
 3013: 
 3014: See loncreateuser.pm for invocation and use examples.
 3015: 
 3016: =cut
 3017: 
 3018: #-------------------------------------------
 3019: sub authform_header{  
 3020:     my %in = (
 3021:         formname => 'cu',
 3022:         kerb_def_dom => '',
 3023:         @_,
 3024:     );
 3025:     $in{'formname'} = 'document.' . $in{'formname'};
 3026:     my $result='';
 3027: 
 3028: #---------------------------------------------- Code for upper case translation
 3029:     my $Javascript_toUpperCase;
 3030:     unless ($in{kerb_def_dom}) {
 3031:         $Javascript_toUpperCase =<<"END";
 3032:         switch (choice) {
 3033:            case 'krb': currentform.elements[choicearg].value =
 3034:                currentform.elements[choicearg].value.toUpperCase();
 3035:                break;
 3036:            default:
 3037:         }
 3038: END
 3039:     } else {
 3040:         $Javascript_toUpperCase = "";
 3041:     }
 3042: 
 3043:     my $radioval = "'nochange'";
 3044:     if (defined($in{'curr_authtype'})) {
 3045:         if ($in{'curr_authtype'} ne '') {
 3046:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3047:         }
 3048:     }
 3049:     my $argfield = 'null';
 3050:     if (defined($in{'mode'})) {
 3051:         if ($in{'mode'} eq 'modifycourse')  {
 3052:             if (defined($in{'curr_autharg'})) {
 3053:                 if ($in{'curr_autharg'} ne '') {
 3054:                     $argfield = "'$in{'curr_autharg'}'";
 3055:                 }
 3056:             }
 3057:         }
 3058:     }
 3059: 
 3060:     $result.=<<"END";
 3061: var current = new Object();
 3062: current.radiovalue = $radioval;
 3063: current.argfield = $argfield;
 3064: 
 3065: function changed_radio(choice,currentform) {
 3066:     var choicearg = choice + 'arg';
 3067:     // If a radio button in changed, we need to change the argfield
 3068:     if (current.radiovalue != choice) {
 3069:         current.radiovalue = choice;
 3070:         if (current.argfield != null) {
 3071:             currentform.elements[current.argfield].value = '';
 3072:         }
 3073:         if (choice == 'nochange') {
 3074:             current.argfield = null;
 3075:         } else {
 3076:             current.argfield = choicearg;
 3077:             switch(choice) {
 3078:                 case 'krb': 
 3079:                     currentform.elements[current.argfield].value = 
 3080:                         "$in{'kerb_def_dom'}";
 3081:                 break;
 3082:               default:
 3083:                 break;
 3084:             }
 3085:         }
 3086:     }
 3087:     return;
 3088: }
 3089: 
 3090: function changed_text(choice,currentform) {
 3091:     var choicearg = choice + 'arg';
 3092:     if (currentform.elements[choicearg].value !='') {
 3093:         $Javascript_toUpperCase
 3094:         // clear old field
 3095:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3096:             currentform.elements[current.argfield].value = '';
 3097:         }
 3098:         current.argfield = choicearg;
 3099:     }
 3100:     set_auth_radio_buttons(choice,currentform);
 3101:     return;
 3102: }
 3103: 
 3104: function set_auth_radio_buttons(newvalue,currentform) {
 3105:     var numauthchoices = currentform.login.length;
 3106:     if (typeof numauthchoices  == "undefined") {
 3107:         return;
 3108:     } 
 3109:     var i=0;
 3110:     while (i < numauthchoices) {
 3111:         if (currentform.login[i].value == newvalue) { break; }
 3112:         i++;
 3113:     }
 3114:     if (i == numauthchoices) {
 3115:         return;
 3116:     }
 3117:     current.radiovalue = newvalue;
 3118:     currentform.login[i].checked = true;
 3119:     return;
 3120: }
 3121: END
 3122:     return $result;
 3123: }
 3124: 
 3125: sub authform_authorwarning {
 3126:     my $result='';
 3127:     $result='<i>'.
 3128:         &mt('As a general rule, only authors or co-authors should be '.
 3129:             'filesystem authenticated '.
 3130:             '(which allows access to the server filesystem).')."</i>\n";
 3131:     return $result;
 3132: }
 3133: 
 3134: sub authform_nochange {
 3135:     my %in = (
 3136:               formname => 'document.cu',
 3137:               kerb_def_dom => 'MSU.EDU',
 3138:               @_,
 3139:           );
 3140:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3141:     my $result;
 3142:     if (!$authnum) {
 3143:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3144:     } else {
 3145:         $result = '<label>'.&mt('[_1] Do not change login data',
 3146:                   '<input type="radio" name="login" value="nochange" '.
 3147:                   'checked="checked" onclick="'.
 3148:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3149: 	    '</label>';
 3150:     }
 3151:     return $result;
 3152: }
 3153: 
 3154: sub authform_kerberos {
 3155:     my %in = (
 3156:               formname => 'document.cu',
 3157:               kerb_def_dom => 'MSU.EDU',
 3158:               kerb_def_auth => 'krb4',
 3159:               @_,
 3160:               );
 3161:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3162:         $autharg,$jscall,$disabled);
 3163:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3164:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3165:        $check5 = ' checked="checked"';
 3166:     } else {
 3167:        $check4 = ' checked="checked"';
 3168:     }
 3169:     if ($in{'readonly'}) {
 3170:         $disabled = ' disabled="disabled"';
 3171:     }
 3172:     $krbarg = $in{'kerb_def_dom'};
 3173:     if (defined($in{'curr_authtype'})) {
 3174:         if ($in{'curr_authtype'} eq 'krb') {
 3175:             $krbcheck = ' checked="checked"';
 3176:             if (defined($in{'mode'})) {
 3177:                 if ($in{'mode'} eq 'modifyuser') {
 3178:                     $krbcheck = '';
 3179:                 }
 3180:             }
 3181:             if (defined($in{'curr_kerb_ver'})) {
 3182:                 if ($in{'curr_krb_ver'} eq '5') {
 3183:                     $check5 = ' checked="checked"';
 3184:                     $check4 = '';
 3185:                 } else {
 3186:                     $check4 = ' checked="checked"';
 3187:                     $check5 = '';
 3188:                 }
 3189:             }
 3190:             if (defined($in{'curr_autharg'})) {
 3191:                 $krbarg = $in{'curr_autharg'};
 3192:             }
 3193:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3194:                 if (defined($in{'curr_autharg'})) {
 3195:                     $result = 
 3196:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3197:         $in{'curr_autharg'},$krbver);
 3198:                 } else {
 3199:                     $result =
 3200:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3201:                 }
 3202:                 return $result; 
 3203:             }
 3204:         }
 3205:     } else {
 3206:         if ($authnum == 1) {
 3207:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3208:         }
 3209:     }
 3210:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3211:         return;
 3212:     } elsif ($authtype eq '') {
 3213:         if (defined($in{'mode'})) {
 3214:             if ($in{'mode'} eq 'modifycourse') {
 3215:                 if ($authnum == 1) {
 3216:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 3217:                 }
 3218:             }
 3219:         }
 3220:     }
 3221:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3222:     if ($authtype eq '') {
 3223:         $authtype = '<input type="radio" name="login" value="krb" '.
 3224:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3225:                     $krbcheck.$disabled.' />';
 3226:     }
 3227:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3228:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3229:          $in{'curr_authtype'} eq 'krb5') ||
 3230:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3231:          $in{'curr_authtype'} eq 'krb4')) {
 3232:         $result .= &mt
 3233:         ('[_1] Kerberos authenticated with domain [_2] '.
 3234:          '[_3] Version 4 [_4] Version 5 [_5]',
 3235:          '<label>'.$authtype,
 3236:          '</label><input type="text" size="10" name="krbarg" '.
 3237:              'value="'.$krbarg.'" '.
 3238:              'onchange="'.$jscall.'"'.$disabled.' />',
 3239:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 3240:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 3241: 	 '</label>');
 3242:     } elsif ($can_assign{'krb4'}) {
 3243:         $result .= &mt
 3244:         ('[_1] Kerberos authenticated with domain [_2] '.
 3245:          '[_3] Version 4 [_4]',
 3246:          '<label>'.$authtype,
 3247:          '</label><input type="text" size="10" name="krbarg" '.
 3248:              'value="'.$krbarg.'" '.
 3249:              'onchange="'.$jscall.'"'.$disabled.' />',
 3250:          '<label><input type="hidden" name="krbver" value="4" />',
 3251:          '</label>');
 3252:     } elsif ($can_assign{'krb5'}) {
 3253:         $result .= &mt
 3254:         ('[_1] Kerberos authenticated with domain [_2] '.
 3255:          '[_3] Version 5 [_4]',
 3256:          '<label>'.$authtype,
 3257:          '</label><input type="text" size="10" name="krbarg" '.
 3258:              'value="'.$krbarg.'" '.
 3259:              'onchange="'.$jscall.'"'.$disabled.' />',
 3260:          '<label><input type="hidden" name="krbver" value="5" />',
 3261:          '</label>');
 3262:     }
 3263:     return $result;
 3264: }
 3265: 
 3266: sub authform_internal {
 3267:     my %in = (
 3268:                 formname => 'document.cu',
 3269:                 kerb_def_dom => 'MSU.EDU',
 3270:                 @_,
 3271:                 );
 3272:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 3273:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3274:     if ($in{'readonly'}) {
 3275:         $disabled = ' disabled="disabled"';
 3276:     }
 3277:     if (defined($in{'curr_authtype'})) {
 3278:         if ($in{'curr_authtype'} eq 'int') {
 3279:             if ($can_assign{'int'}) {
 3280:                 $intcheck = 'checked="checked" ';
 3281:                 if (defined($in{'mode'})) {
 3282:                     if ($in{'mode'} eq 'modifyuser') {
 3283:                         $intcheck = '';
 3284:                     }
 3285:                 }
 3286:                 if (defined($in{'curr_autharg'})) {
 3287:                     $intarg = $in{'curr_autharg'};
 3288:                 }
 3289:             } else {
 3290:                 $result = &mt('Currently internally authenticated.');
 3291:                 return $result;
 3292:             }
 3293:         }
 3294:     } else {
 3295:         if ($authnum == 1) {
 3296:             $authtype = '<input type="hidden" name="login" value="int" />';
 3297:         }
 3298:     }
 3299:     if (!$can_assign{'int'}) {
 3300:         return;
 3301:     } elsif ($authtype eq '') {
 3302:         if (defined($in{'mode'})) {
 3303:             if ($in{'mode'} eq 'modifycourse') {
 3304:                 if ($authnum == 1) {
 3305:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 3306:                 }
 3307:             }
 3308:         }
 3309:     }
 3310:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3311:     if ($authtype eq '') {
 3312:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3313:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3314:     }
 3315:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3316:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3317:     $result = &mt
 3318:         ('[_1] Internally authenticated (with initial password [_2])',
 3319:          '<label>'.$authtype,'</label>'.$autharg);
 3320:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
 3321:     return $result;
 3322: }
 3323: 
 3324: sub authform_local {
 3325:     my %in = (
 3326:               formname => 'document.cu',
 3327:               kerb_def_dom => 'MSU.EDU',
 3328:               @_,
 3329:               );
 3330:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3331:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3332:     if ($in{'readonly'}) {
 3333:         $disabled = ' disabled="disabled"';
 3334:     } 
 3335:     if (defined($in{'curr_authtype'})) {
 3336:         if ($in{'curr_authtype'} eq 'loc') {
 3337:             if ($can_assign{'loc'}) {
 3338:                 $loccheck = 'checked="checked" ';
 3339:                 if (defined($in{'mode'})) {
 3340:                     if ($in{'mode'} eq 'modifyuser') {
 3341:                         $loccheck = '';
 3342:                     }
 3343:                 }
 3344:                 if (defined($in{'curr_autharg'})) {
 3345:                     $locarg = $in{'curr_autharg'};
 3346:                 }
 3347:             } else {
 3348:                 $result = &mt('Currently using local (institutional) authentication.');
 3349:                 return $result;
 3350:             }
 3351:         }
 3352:     } else {
 3353:         if ($authnum == 1) {
 3354:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3355:         }
 3356:     }
 3357:     if (!$can_assign{'loc'}) {
 3358:         return;
 3359:     } elsif ($authtype eq '') {
 3360:         if (defined($in{'mode'})) {
 3361:             if ($in{'mode'} eq 'modifycourse') {
 3362:                 if ($authnum == 1) {
 3363:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3364:                 }
 3365:             }
 3366:         }
 3367:     }
 3368:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3369:     if ($authtype eq '') {
 3370:         $authtype = '<input type="radio" name="login" value="loc" '.
 3371:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3372:                     $jscall.'"'.$disabled.' />';
 3373:     }
 3374:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3375:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3376:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3377:                   '<label>'.$authtype,'</label>'.$autharg);
 3378:     return $result;
 3379: }
 3380: 
 3381: sub authform_filesystem {
 3382:     my %in = (
 3383:               formname => 'document.cu',
 3384:               kerb_def_dom => 'MSU.EDU',
 3385:               @_,
 3386:               );
 3387:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3388:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3389:     if ($in{'readonly'}) {
 3390:         $disabled = ' disabled="disabled"';
 3391:     }
 3392:     if (defined($in{'curr_authtype'})) {
 3393:         if ($in{'curr_authtype'} eq 'fsys') {
 3394:             if ($can_assign{'fsys'}) {
 3395:                 $fsyscheck = 'checked="checked" ';
 3396:                 if (defined($in{'mode'})) {
 3397:                     if ($in{'mode'} eq 'modifyuser') {
 3398:                         $fsyscheck = '';
 3399:                     }
 3400:                 }
 3401:             } else {
 3402:                 $result = &mt('Currently Filesystem Authenticated.');
 3403:                 return $result;
 3404:             }
 3405:         }
 3406:     } else {
 3407:         if ($authnum == 1) {
 3408:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3409:         }
 3410:     }
 3411:     if (!$can_assign{'fsys'}) {
 3412:         return;
 3413:     } elsif ($authtype eq '') {
 3414:         if (defined($in{'mode'})) {
 3415:             if ($in{'mode'} eq 'modifycourse') {
 3416:                 if ($authnum == 1) {
 3417:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3418:                 }
 3419:             }
 3420:         }
 3421:     }
 3422:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3423:     if ($authtype eq '') {
 3424:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3425:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3426:                     $jscall.'"'.$disabled.' />';
 3427:     }
 3428:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3429:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3430:     $result = &mt
 3431:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3432:          '<label><input type="radio" name="login" value="fsys" '.
 3433:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3434:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3435:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3436:     return $result;
 3437: }
 3438: 
 3439: sub get_assignable_auth {
 3440:     my ($dom) = @_;
 3441:     if ($dom eq '') {
 3442:         $dom = $env{'request.role.domain'};
 3443:     }
 3444:     my %can_assign = (
 3445:                           krb4 => 1,
 3446:                           krb5 => 1,
 3447:                           int  => 1,
 3448:                           loc  => 1,
 3449:                      );
 3450:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3451:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3452:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3453:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3454:             my $context;
 3455:             if ($env{'request.role'} =~ /^au/) {
 3456:                 $context = 'author';
 3457:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3458:                 $context = 'domain';
 3459:             } elsif ($env{'request.course.id'}) {
 3460:                 $context = 'course';
 3461:             }
 3462:             if ($context) {
 3463:                 if (ref($authhash->{$context}) eq 'HASH') {
 3464:                    %can_assign = %{$authhash->{$context}}; 
 3465:                 }
 3466:             }
 3467:         }
 3468:     }
 3469:     my $authnum = 0;
 3470:     foreach my $key (keys(%can_assign)) {
 3471:         if ($can_assign{$key}) {
 3472:             $authnum ++;
 3473:         }
 3474:     }
 3475:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3476:         $authnum --;
 3477:     }
 3478:     return ($authnum,%can_assign);
 3479: }
 3480: 
 3481: ###############################################################
 3482: ##    Get Kerberos Defaults for Domain                 ##
 3483: ###############################################################
 3484: ##
 3485: ## Returns default kerberos version and an associated argument
 3486: ## as listed in file domain.tab. If not listed, provides
 3487: ## appropriate default domain and kerberos version.
 3488: ##
 3489: #-------------------------------------------
 3490: 
 3491: =pod
 3492: 
 3493: =item * &get_kerberos_defaults()
 3494: 
 3495: get_kerberos_defaults($target_domain) returns the default kerberos
 3496: version and domain. If not found, it defaults to version 4 and the 
 3497: domain of the server.
 3498: 
 3499: =over 4
 3500: 
 3501: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3502: 
 3503: =back
 3504: 
 3505: =back
 3506: 
 3507: =cut
 3508: 
 3509: #-------------------------------------------
 3510: sub get_kerberos_defaults {
 3511:     my $domain=shift;
 3512:     my ($krbdef,$krbdefdom);
 3513:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3514:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3515:         $krbdef = $domdefaults{'auth_def'};
 3516:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3517:     } else {
 3518:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3519:         my $krbdefdom=$1;
 3520:         $krbdefdom=~tr/a-z/A-Z/;
 3521:         $krbdef = "krb4";
 3522:     }
 3523:     return ($krbdef,$krbdefdom);
 3524: }
 3525: 
 3526: 
 3527: ###############################################################
 3528: ##                Thesaurus Functions                        ##
 3529: ###############################################################
 3530: 
 3531: =pod
 3532: 
 3533: =head1 Thesaurus Functions
 3534: 
 3535: =over 4
 3536: 
 3537: =item * &initialize_keywords()
 3538: 
 3539: Initializes the package variable %Keywords if it is empty.  Uses the
 3540: package variable $thesaurus_db_file.
 3541: 
 3542: =cut
 3543: 
 3544: ###################################################
 3545: 
 3546: sub initialize_keywords {
 3547:     return 1 if (scalar keys(%Keywords));
 3548:     # If we are here, %Keywords is empty, so fill it up
 3549:     #   Make sure the file we need exists...
 3550:     if (! -e $thesaurus_db_file) {
 3551:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3552:                                  " failed because it does not exist");
 3553:         return 0;
 3554:     }
 3555:     #   Set up the hash as a database
 3556:     my %thesaurus_db;
 3557:     if (! tie(%thesaurus_db,'GDBM_File',
 3558:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3559:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3560:                                  $thesaurus_db_file);
 3561:         return 0;
 3562:     } 
 3563:     #  Get the average number of appearances of a word.
 3564:     my $avecount = $thesaurus_db{'average.count'};
 3565:     #  Put keywords (those that appear > average) into %Keywords
 3566:     while (my ($word,$data)=each (%thesaurus_db)) {
 3567:         my ($count,undef) = split /:/,$data;
 3568:         $Keywords{$word}++ if ($count > $avecount);
 3569:     }
 3570:     untie %thesaurus_db;
 3571:     # Remove special values from %Keywords.
 3572:     foreach my $value ('total.count','average.count') {
 3573:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3574:   }
 3575:     return 1;
 3576: }
 3577: 
 3578: ###################################################
 3579: 
 3580: =pod
 3581: 
 3582: =item * &keyword($word)
 3583: 
 3584: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3585: than the average number of times in the thesaurus database.  Calls 
 3586: &initialize_keywords
 3587: 
 3588: =cut
 3589: 
 3590: ###################################################
 3591: 
 3592: sub keyword {
 3593:     return if (!&initialize_keywords());
 3594:     my $word=lc(shift());
 3595:     $word=~s/\W//g;
 3596:     return exists($Keywords{$word});
 3597: }
 3598: 
 3599: ###############################################################
 3600: 
 3601: =pod 
 3602: 
 3603: =item * &get_related_words()
 3604: 
 3605: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3606: an array of words.  If the keyword is not in the thesaurus, an empty array
 3607: will be returned.  The order of the words returned is determined by the
 3608: database which holds them.
 3609: 
 3610: Uses global $thesaurus_db_file.
 3611: 
 3612: 
 3613: =cut
 3614: 
 3615: ###############################################################
 3616: sub get_related_words {
 3617:     my $keyword = shift;
 3618:     my %thesaurus_db;
 3619:     if (! -e $thesaurus_db_file) {
 3620:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3621:                                  "failed because the file does not exist");
 3622:         return ();
 3623:     }
 3624:     if (! tie(%thesaurus_db,'GDBM_File',
 3625:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3626:         return ();
 3627:     } 
 3628:     my @Words=();
 3629:     my $count=0;
 3630:     if (exists($thesaurus_db{$keyword})) {
 3631: 	# The first element is the number of times
 3632: 	# the word appears.  We do not need it now.
 3633: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3634: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3635: 	my $threshold=$mostfrequentcount/10;
 3636:         foreach my $possibleword (@RelatedWords) {
 3637:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3638:             if ($wordcount>$threshold) {
 3639: 		push(@Words,$word);
 3640:                 $count++;
 3641:                 if ($count>10) { last; }
 3642: 	    }
 3643:         }
 3644:     }
 3645:     untie %thesaurus_db;
 3646:     return @Words;
 3647: }
 3648: ###############################################################
 3649: #
 3650: #  Spell checking
 3651: #
 3652: 
 3653: =pod
 3654: 
 3655: =back
 3656: 
 3657: =head1 Spell checking
 3658: 
 3659: =over 4
 3660: 
 3661: =item * &check_spelling($wordlist $language)
 3662: 
 3663: Takes a string containing words and feeds it to an external
 3664: spellcheck program via a pipeline. Returns a string containing
 3665: them mis-spelled words.
 3666: 
 3667: Parameters:
 3668: 
 3669: =over 4
 3670: 
 3671: =item - $wordlist
 3672: 
 3673: String that will be fed into the spellcheck program.
 3674: 
 3675: =item - $language
 3676: 
 3677: Language string that specifies the language for which the spell
 3678: check will be performed.
 3679: 
 3680: =back
 3681: 
 3682: =back
 3683: 
 3684: Note: This sub assumes that aspell is installed.
 3685: 
 3686: 
 3687: =cut
 3688: 
 3689: 
 3690: sub check_spelling {
 3691:     my ($wordlist, $language) = @_;
 3692:     my @misspellings;
 3693:     
 3694:     # Generate the speller and set the langauge.
 3695:     # if explicitly selected:
 3696: 
 3697:     my $speller = Text::Aspell->new;
 3698:     if ($language) {
 3699: 	$speller->set_option('lang', $language);
 3700:     }
 3701: 
 3702:     # Turn the word list into an array of words by splittingon whitespace
 3703: 
 3704:     my @words = split(/\s+/, $wordlist);
 3705: 
 3706:     foreach my $word (@words) {
 3707: 	if(! $speller->check($word)) {
 3708: 	    push(@misspellings, $word);
 3709: 	}
 3710:     }
 3711:     return join(' ', @misspellings);
 3712:     
 3713: }
 3714: 
 3715: # -------------------------------------------------------------- Plaintext name
 3716: =pod
 3717: 
 3718: =head1 User Name Functions
 3719: 
 3720: =over 4
 3721: 
 3722: =item * &plainname($uname,$udom,$first)
 3723: 
 3724: Takes a users logon name and returns it as a string in
 3725: "first middle last generation" form 
 3726: if $first is set to 'lastname' then it returns it as
 3727: 'lastname generation, firstname middlename' if their is a lastname
 3728: 
 3729: =cut
 3730: 
 3731: 
 3732: ###############################################################
 3733: sub plainname {
 3734:     my ($uname,$udom,$first)=@_;
 3735:     return if (!defined($uname) || !defined($udom));
 3736:     my %names=&getnames($uname,$udom);
 3737:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3738: 					  $names{'middlename'},
 3739: 					  $names{'lastname'},
 3740: 					  $names{'generation'},$first);
 3741:     $name=~s/^\s+//;
 3742:     $name=~s/\s+$//;
 3743:     $name=~s/\s+/ /g;
 3744:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3745:     return $name;
 3746: }
 3747: 
 3748: # -------------------------------------------------------------------- Nickname
 3749: =pod
 3750: 
 3751: =item * &nickname($uname,$udom)
 3752: 
 3753: Gets a users name and returns it as a string as
 3754: 
 3755: "&quot;nickname&quot;"
 3756: 
 3757: if the user has a nickname or
 3758: 
 3759: "first middle last generation"
 3760: 
 3761: if the user does not
 3762: 
 3763: =cut
 3764: 
 3765: sub nickname {
 3766:     my ($uname,$udom)=@_;
 3767:     return if (!defined($uname) || !defined($udom));
 3768:     my %names=&getnames($uname,$udom);
 3769:     my $name=$names{'nickname'};
 3770:     if ($name) {
 3771:        $name='&quot;'.$name.'&quot;'; 
 3772:     } else {
 3773:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3774: 	     $names{'lastname'}.' '.$names{'generation'};
 3775:        $name=~s/\s+$//;
 3776:        $name=~s/\s+/ /g;
 3777:     }
 3778:     return $name;
 3779: }
 3780: 
 3781: sub getnames {
 3782:     my ($uname,$udom)=@_;
 3783:     return if (!defined($uname) || !defined($udom));
 3784:     if ($udom eq 'public' && $uname eq 'public') {
 3785: 	return ('lastname' => &mt('Public'));
 3786:     }
 3787:     my $id=$uname.':'.$udom;
 3788:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3789:     if ($cached) {
 3790: 	return %{$names};
 3791:     } else {
 3792: 	my %loadnames=&Apache::lonnet::get('environment',
 3793:                     ['firstname','middlename','lastname','generation','nickname'],
 3794: 					 $udom,$uname);
 3795: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3796: 	return %loadnames;
 3797:     }
 3798: }
 3799: 
 3800: # -------------------------------------------------------------------- getemails
 3801: 
 3802: =pod
 3803: 
 3804: =item * &getemails($uname,$udom)
 3805: 
 3806: Gets a user's email information and returns it as a hash with keys:
 3807: notification, critnotification, permanentemail
 3808: 
 3809: For notification and critnotification, values are comma-separated lists 
 3810: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3811:  
 3812: 
 3813: =cut
 3814: 
 3815: 
 3816: sub getemails {
 3817:     my ($uname,$udom)=@_;
 3818:     if ($udom eq 'public' && $uname eq 'public') {
 3819: 	return;
 3820:     }
 3821:     if (!$udom) { $udom=$env{'user.domain'}; }
 3822:     if (!$uname) { $uname=$env{'user.name'}; }
 3823:     my $id=$uname.':'.$udom;
 3824:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3825:     if ($cached) {
 3826: 	return %{$names};
 3827:     } else {
 3828: 	my %loadnames=&Apache::lonnet::get('environment',
 3829:                     			   ['notification','critnotification',
 3830: 					    'permanentemail'],
 3831: 					   $udom,$uname);
 3832: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3833: 	return %loadnames;
 3834:     }
 3835: }
 3836: 
 3837: sub flush_email_cache {
 3838:     my ($uname,$udom)=@_;
 3839:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3840:     if (!$uname) { $uname=$env{'user.name'};   }
 3841:     return if ($udom eq 'public' && $uname eq 'public');
 3842:     my $id=$uname.':'.$udom;
 3843:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3844: }
 3845: 
 3846: # -------------------------------------------------------------------- getlangs
 3847: 
 3848: =pod
 3849: 
 3850: =item * &getlangs($uname,$udom)
 3851: 
 3852: Gets a user's language preference and returns it as a hash with key:
 3853: language.
 3854: 
 3855: =cut
 3856: 
 3857: 
 3858: sub getlangs {
 3859:     my ($uname,$udom) = @_;
 3860:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3861:     if (!$uname) { $uname=$env{'user.name'};   }
 3862:     my $id=$uname.':'.$udom;
 3863:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3864:     if ($cached) {
 3865:         return %{$langs};
 3866:     } else {
 3867:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3868:                                            $udom,$uname);
 3869:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3870:         return %loadlangs;
 3871:     }
 3872: }
 3873: 
 3874: sub flush_langs_cache {
 3875:     my ($uname,$udom)=@_;
 3876:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3877:     if (!$uname) { $uname=$env{'user.name'};   }
 3878:     return if ($udom eq 'public' && $uname eq 'public');
 3879:     my $id=$uname.':'.$udom;
 3880:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3881: }
 3882: 
 3883: # ------------------------------------------------------------------ Screenname
 3884: 
 3885: =pod
 3886: 
 3887: =item * &screenname($uname,$udom)
 3888: 
 3889: Gets a users screenname and returns it as a string
 3890: 
 3891: =cut
 3892: 
 3893: sub screenname {
 3894:     my ($uname,$udom)=@_;
 3895:     if ($uname eq $env{'user.name'} &&
 3896: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3897:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3898:     return $names{'screenname'};
 3899: }
 3900: 
 3901: 
 3902: # ------------------------------------------------------------- Confirm Wrapper
 3903: =pod
 3904: 
 3905: =item * &confirmwrapper($message)
 3906: 
 3907: Wrap messages about completion of operation in box
 3908: 
 3909: =cut
 3910: 
 3911: sub confirmwrapper {
 3912:     my ($message)=@_;
 3913:     if ($message) {
 3914:         return "\n".'<div class="LC_confirm_box">'."\n"
 3915:                .$message."\n"
 3916:                .'</div>'."\n";
 3917:     } else {
 3918:         return $message;
 3919:     }
 3920: }
 3921: 
 3922: # ------------------------------------------------------------- Message Wrapper
 3923: 
 3924: sub messagewrapper {
 3925:     my ($link,$username,$domain,$subject,$text)=@_;
 3926:     return 
 3927:         '<a href="/adm/email?compose=individual&amp;'.
 3928:         'recname='.$username.'&amp;recdom='.$domain.
 3929: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3930:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3931: }
 3932: 
 3933: # --------------------------------------------------------------- Notes Wrapper
 3934: 
 3935: sub noteswrapper {
 3936:     my ($link,$un,$do)=@_;
 3937:     return 
 3938: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3939: }
 3940: 
 3941: # ------------------------------------------------------------- Aboutme Wrapper
 3942: 
 3943: sub aboutmewrapper {
 3944:     my ($link,$username,$domain,$target,$class)=@_;
 3945:     if (!defined($username)  && !defined($domain)) {
 3946:         return;
 3947:     }
 3948:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3949: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3950: }
 3951: 
 3952: # ------------------------------------------------------------ Syllabus Wrapper
 3953: 
 3954: sub syllabuswrapper {
 3955:     my ($linktext,$coursedir,$domain)=@_;
 3956:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3957: }
 3958: 
 3959: # -----------------------------------------------------------------------------
 3960: 
 3961: sub track_student_link {
 3962:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3963:     my $link ="/adm/trackstudent?";
 3964:     my $title = 'View recent activity';
 3965:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3966:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3967:         $link .= "selected_student=$sname:$sdom";
 3968:         $title .= ' of this student';
 3969:     } 
 3970:     if (defined($target) && $target !~ /^\s*$/) {
 3971:         $target = qq{target="$target"};
 3972:     } else {
 3973:         $target = '';
 3974:     }
 3975:     if ($start) { $link.='&amp;start='.$start; }
 3976:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3977:     $title = &mt($title);
 3978:     $linktext = &mt($linktext);
 3979:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3980: 	&help_open_topic('View_recent_activity');
 3981: }
 3982: 
 3983: sub slot_reservations_link {
 3984:     my ($linktext,$sname,$sdom,$target) = @_;
 3985:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3986:     my $title = 'View slot reservation history';
 3987:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3988:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3989:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3990:         $title .= ' of this student';
 3991:     }
 3992:     if (defined($target) && $target !~ /^\s*$/) {
 3993:         $target = qq{target="$target"};
 3994:     } else {
 3995:         $target = '';
 3996:     }
 3997:     $title = &mt($title);
 3998:     $linktext = &mt($linktext);
 3999:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 4000: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 4001: 
 4002: }
 4003: 
 4004: # ===================================================== Display a student photo
 4005: 
 4006: 
 4007: sub student_image_tag {
 4008:     my ($domain,$user)=@_;
 4009:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 4010:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 4011: 	return '<img src="'.$imgsrc.'" align="right" />';
 4012:     } else {
 4013: 	return '';
 4014:     }
 4015: }
 4016: 
 4017: =pod
 4018: 
 4019: =back
 4020: 
 4021: =head1 Access .tab File Data
 4022: 
 4023: =over 4
 4024: 
 4025: =item * &languageids() 
 4026: 
 4027: returns list of all language ids
 4028: 
 4029: =cut
 4030: 
 4031: sub languageids {
 4032:     return sort(keys(%language));
 4033: }
 4034: 
 4035: =pod
 4036: 
 4037: =item * &languagedescription() 
 4038: 
 4039: returns description of a specified language id
 4040: 
 4041: =cut
 4042: 
 4043: sub languagedescription {
 4044:     my $code=shift;
 4045:     return  ($supported_language{$code}?'* ':'').
 4046:             $language{$code}.
 4047: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4048: }
 4049: 
 4050: =pod
 4051: 
 4052: =item * &plainlanguagedescription
 4053: 
 4054: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4055: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4056: 
 4057: =cut
 4058: 
 4059: sub plainlanguagedescription {
 4060:     my $code=shift;
 4061:     return $language{$code};
 4062: }
 4063: 
 4064: =pod
 4065: 
 4066: =item * &supportedlanguagecode
 4067: 
 4068: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4069: code.
 4070: 
 4071: =cut
 4072: 
 4073: sub supportedlanguagecode {
 4074:     my $code=shift;
 4075:     return $supported_language{$code};
 4076: }
 4077: 
 4078: =pod
 4079: 
 4080: =item * &latexlanguage()
 4081: 
 4082: Given a language key code returns the correspondnig language to use
 4083: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4084: is no supported hyphenation for the language code.
 4085: 
 4086: =cut
 4087: 
 4088: sub latexlanguage {
 4089:     my $code = shift;
 4090:     return $latex_language{$code};
 4091: }
 4092: 
 4093: =pod
 4094: 
 4095: =item * &latexhyphenation()
 4096: 
 4097: Same as above but what's supplied is the language as it might be stored
 4098: in the metadata.
 4099: 
 4100: =cut
 4101: 
 4102: sub latexhyphenation {
 4103:     my $key = shift;
 4104:     return $latex_language_bykey{$key};
 4105: }
 4106: 
 4107: =pod
 4108: 
 4109: =item * &copyrightids() 
 4110: 
 4111: returns list of all copyrights
 4112: 
 4113: =cut
 4114: 
 4115: sub copyrightids {
 4116:     return sort(keys(%cprtag));
 4117: }
 4118: 
 4119: =pod
 4120: 
 4121: =item * &copyrightdescription() 
 4122: 
 4123: returns description of a specified copyright id
 4124: 
 4125: =cut
 4126: 
 4127: sub copyrightdescription {
 4128:     return &mt($cprtag{shift(@_)});
 4129: }
 4130: 
 4131: =pod
 4132: 
 4133: =item * &source_copyrightids() 
 4134: 
 4135: returns list of all source copyrights
 4136: 
 4137: =cut
 4138: 
 4139: sub source_copyrightids {
 4140:     return sort(keys(%scprtag));
 4141: }
 4142: 
 4143: =pod
 4144: 
 4145: =item * &source_copyrightdescription() 
 4146: 
 4147: returns description of a specified source copyright id
 4148: 
 4149: =cut
 4150: 
 4151: sub source_copyrightdescription {
 4152:     return &mt($scprtag{shift(@_)});
 4153: }
 4154: 
 4155: =pod
 4156: 
 4157: =item * &filecategories() 
 4158: 
 4159: returns list of all file categories
 4160: 
 4161: =cut
 4162: 
 4163: sub filecategories {
 4164:     return sort(keys(%category_extensions));
 4165: }
 4166: 
 4167: =pod
 4168: 
 4169: =item * &filecategorytypes() 
 4170: 
 4171: returns list of file types belonging to a given file
 4172: category
 4173: 
 4174: =cut
 4175: 
 4176: sub filecategorytypes {
 4177:     my ($cat) = @_;
 4178:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4179:         return @{$category_extensions{lc($cat)}};
 4180:     } else {
 4181:         return ();
 4182:     }
 4183: }
 4184: 
 4185: =pod
 4186: 
 4187: =item * &fileembstyle() 
 4188: 
 4189: returns embedding style for a specified file type
 4190: 
 4191: =cut
 4192: 
 4193: sub fileembstyle {
 4194:     return $fe{lc(shift(@_))};
 4195: }
 4196: 
 4197: sub filemimetype {
 4198:     return $fm{lc(shift(@_))};
 4199: }
 4200: 
 4201: 
 4202: sub filecategoryselect {
 4203:     my ($name,$value)=@_;
 4204:     return &select_form($value,$name,
 4205:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4206: }
 4207: 
 4208: =pod
 4209: 
 4210: =item * &filedescription() 
 4211: 
 4212: returns description for a specified file type
 4213: 
 4214: =cut
 4215: 
 4216: sub filedescription {
 4217:     my $file_description = $fd{lc(shift())};
 4218:     $file_description =~ s:([\[\]]):~$1:g;
 4219:     return &mt($file_description);
 4220: }
 4221: 
 4222: =pod
 4223: 
 4224: =item * &filedescriptionex() 
 4225: 
 4226: returns description for a specified file type with
 4227: extra formatting
 4228: 
 4229: =cut
 4230: 
 4231: sub filedescriptionex {
 4232:     my $ex=shift;
 4233:     my $file_description = $fd{lc($ex)};
 4234:     $file_description =~ s:([\[\]]):~$1:g;
 4235:     return '.'.$ex.' '.&mt($file_description);
 4236: }
 4237: 
 4238: # End of .tab access
 4239: =pod
 4240: 
 4241: =back
 4242: 
 4243: =cut
 4244: 
 4245: # ------------------------------------------------------------------ File Types
 4246: sub fileextensions {
 4247:     return sort(keys(%fe));
 4248: }
 4249: 
 4250: # ----------------------------------------------------------- Display Languages
 4251: # returns a hash with all desired display languages
 4252: #
 4253: 
 4254: sub display_languages {
 4255:     my %languages=();
 4256:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4257: 	$languages{$lang}=1;
 4258:     }
 4259:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4260:     if ($env{'form.displaylanguage'}) {
 4261: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4262: 	    $languages{$lang}=1;
 4263:         }
 4264:     }
 4265:     return %languages;
 4266: }
 4267: 
 4268: sub languages {
 4269:     my ($possible_langs) = @_;
 4270:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4271:     if (!ref($possible_langs)) {
 4272: 	if( wantarray ) {
 4273: 	    return @preferred_langs;
 4274: 	} else {
 4275: 	    return $preferred_langs[0];
 4276: 	}
 4277:     }
 4278:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4279:     my @preferred_possibilities;
 4280:     foreach my $preferred_lang (@preferred_langs) {
 4281: 	if (exists($possibilities{$preferred_lang})) {
 4282: 	    push(@preferred_possibilities, $preferred_lang);
 4283: 	}
 4284:     }
 4285:     if( wantarray ) {
 4286: 	return @preferred_possibilities;
 4287:     }
 4288:     return $preferred_possibilities[0];
 4289: }
 4290: 
 4291: sub user_lang {
 4292:     my ($touname,$toudom,$fromcid) = @_;
 4293:     my @userlangs;
 4294:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4295:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4296:                     $env{'course.'.$fromcid.'.languages'}));
 4297:     } else {
 4298:         my %langhash = &getlangs($touname,$toudom);
 4299:         if ($langhash{'languages'} ne '') {
 4300:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4301:         } else {
 4302:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4303:             if ($domdefs{'lang_def'} ne '') {
 4304:                 @userlangs = ($domdefs{'lang_def'});
 4305:             }
 4306:         }
 4307:     }
 4308:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4309:     my $user_lh = Apache::localize->get_handle(@languages);
 4310:     return $user_lh;
 4311: }
 4312: 
 4313: 
 4314: ###############################################################
 4315: ##               Student Answer Attempts                     ##
 4316: ###############################################################
 4317: 
 4318: =pod
 4319: 
 4320: =head1 Alternate Problem Views
 4321: 
 4322: =over 4
 4323: 
 4324: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4325:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4326: 
 4327: Return string with previous attempt on problem. Arguments:
 4328: 
 4329: =over 4
 4330: 
 4331: =item * $symb: Problem, including path
 4332: 
 4333: =item * $username: username of the desired student
 4334: 
 4335: =item * $domain: domain of the desired student
 4336: 
 4337: =item * $course: Course ID
 4338: 
 4339: =item * $getattempt: Leave blank for all attempts, otherwise put
 4340:     something
 4341: 
 4342: =item * $regexp: if string matches this regexp, the string will be
 4343:     sent to $gradesub
 4344: 
 4345: =item * $gradesub: routine that processes the string if it matches $regexp
 4346: 
 4347: =item * $usec: section of the desired student
 4348: 
 4349: =item * $identifier: counter for student (multiple students one problem) or 
 4350:     problem (one student; whole sequence).
 4351: 
 4352: =back
 4353: 
 4354: The output string is a table containing all desired attempts, if any.
 4355: 
 4356: =cut
 4357: 
 4358: sub get_previous_attempt {
 4359:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4360:   my $prevattempts='';
 4361:   no strict 'refs';
 4362:   if ($symb) {
 4363:     my (%returnhash)=
 4364:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4365:     if ($returnhash{'version'}) {
 4366:       my %lasthash=();
 4367:       my $version;
 4368:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4369:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4370:             if ($key =~ /\.rawrndseed$/) {
 4371:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4372:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4373:             } else {
 4374:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4375:             }
 4376:         }
 4377:       }
 4378:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4379:       $prevattempts.='<th>'.&mt('History').'</th>';
 4380:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4381:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4382:       foreach my $key (sort(keys(%lasthash))) {
 4383: 	my ($ign,@parts) = split(/\./,$key);
 4384: 	if ($#parts > 0) {
 4385: 	  my $data=$parts[-1];
 4386:           next if ($data eq 'foilorder');
 4387: 	  pop(@parts);
 4388:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4389:           if ($data eq 'type') {
 4390:               unless ($showsurv) {
 4391:                   my $id = join(',',@parts);
 4392:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4393:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4394:                       $lasthidden{$ign.'.'.$id} = 1;
 4395:                   }
 4396:               }
 4397:               if ($identifier ne '') {
 4398:                   my $id = join(',',@parts);
 4399:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4400:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4401:                       $hidestatus{$ign.'.'.$id} = 1;
 4402:                   }
 4403:               }
 4404:           } elsif ($data eq 'regrader') {
 4405:               if (($identifier ne '') && (@parts)) {
 4406:                   my $id = join(',',@parts);
 4407:                   $regraded{$ign.'.'.$id} = 1;
 4408:               }
 4409:           } 
 4410: 	} else {
 4411: 	  if ($#parts == 0) {
 4412: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4413: 	  } else {
 4414: 	    $prevattempts.='<th>'.$ign.'</th>';
 4415: 	  }
 4416: 	}
 4417:       }
 4418:       $prevattempts.=&end_data_table_header_row();
 4419:       if ($getattempt eq '') {
 4420:         my (%solved,%resets,%probstatus);
 4421:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4422:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4423:                 foreach my $id (keys(%regraded)) {
 4424:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4425:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4426:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4427:                         push(@{$resets{$id}},$version);
 4428:                     }
 4429:                 }
 4430:             }
 4431:         }
 4432: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4433:             my (@hidden,@unsolved);
 4434:             if (%typeparts) {
 4435:                 foreach my $id (keys(%typeparts)) {
 4436:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4437:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4438:                         push(@hidden,$id);
 4439:                     } elsif ($identifier ne '') {
 4440:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4441:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4442:                                 ($hidestatus{$id})) {
 4443:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4444:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4445:                                 push(@{$solved{$id}},$version);
 4446:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4447:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4448:                                 my $skip;
 4449:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4450:                                     foreach my $reset (@{$resets{$id}}) {
 4451:                                         if ($reset > $solved{$id}[-1]) {
 4452:                                             $skip=1;
 4453:                                             last;
 4454:                                         }
 4455:                                     }
 4456:                                 }
 4457:                                 unless ($skip) {
 4458:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4459:                                     push(@unsolved,$partslist);
 4460:                                 }
 4461:                             }
 4462:                         }
 4463:                     }
 4464:                 }
 4465:             }
 4466:             $prevattempts.=&start_data_table_row().
 4467:                            '<td>'.&mt('Transaction [_1]',$version);
 4468:             if (@unsolved) {
 4469:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4470:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4471:                                  &mt('Hide').'</label></span>';
 4472:             }
 4473:             $prevattempts .= '</td>';
 4474:             if (@hidden) {
 4475:                 foreach my $key (sort(keys(%lasthash))) {
 4476:                     next if ($key =~ /\.foilorder$/);
 4477:                     my $hide;
 4478:                     foreach my $id (@hidden) {
 4479:                         if ($key =~ /^\Q$id\E/) {
 4480:                             $hide = 1;
 4481:                             last;
 4482:                         }
 4483:                     }
 4484:                     if ($hide) {
 4485:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4486:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4487:                             my $value = &format_previous_attempt_value($key,
 4488:                                              $returnhash{$version.':'.$key});
 4489:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4490:                         } else {
 4491:                             $prevattempts.='<td>&nbsp;</td>';
 4492:                         }
 4493:                     } else {
 4494:                         if ($key =~ /\./) {
 4495:                             my $value = $returnhash{$version.':'.$key};
 4496:                             if ($key =~ /\.rndseed$/) {
 4497:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4498:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4499:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4500:                                 }
 4501:                             }
 4502:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4503:                                            '&nbsp;</td>';
 4504:                         } else {
 4505:                             $prevattempts.='<td>&nbsp;</td>';
 4506:                         }
 4507:                     }
 4508:                 }
 4509:             } else {
 4510: 	        foreach my $key (sort(keys(%lasthash))) {
 4511:                     next if ($key =~ /\.foilorder$/);
 4512:                     my $value = $returnhash{$version.':'.$key};
 4513:                     if ($key =~ /\.rndseed$/) {
 4514:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4515:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4516:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4517:                         }
 4518:                     }
 4519:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4520:                                    '&nbsp;</td>';
 4521: 	        }
 4522:             }
 4523: 	    $prevattempts.=&end_data_table_row();
 4524: 	 }
 4525:       }
 4526:       my @currhidden = keys(%lasthidden);
 4527:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4528:       foreach my $key (sort(keys(%lasthash))) {
 4529:           next if ($key =~ /\.foilorder$/);
 4530:           if (%typeparts) {
 4531:               my $hidden;
 4532:               foreach my $id (@currhidden) {
 4533:                   if ($key =~ /^\Q$id\E/) {
 4534:                       $hidden = 1;
 4535:                       last;
 4536:                   }
 4537:               }
 4538:               if ($hidden) {
 4539:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4540:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4541:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4542:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4543:                           $value = &$gradesub($value);
 4544:                       }
 4545:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4546:                   } else {
 4547:                       $prevattempts.='<td>&nbsp;</td>';
 4548:                   }
 4549:               } else {
 4550:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4551:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4552:                       $value = &$gradesub($value);
 4553:                   }
 4554:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4555:               }
 4556:           } else {
 4557: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4558: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4559:                   $value = &$gradesub($value);
 4560:               }
 4561: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4562:           }
 4563:       }
 4564:       $prevattempts.= &end_data_table_row().&end_data_table();
 4565:     } else {
 4566:       $prevattempts=
 4567: 	  &start_data_table().&start_data_table_row().
 4568: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4569: 	  &end_data_table_row().&end_data_table();
 4570:     }
 4571:   } else {
 4572:     $prevattempts=
 4573: 	  &start_data_table().&start_data_table_row().
 4574: 	  '<td>'.&mt('No data.').'</td>'.
 4575: 	  &end_data_table_row().&end_data_table();
 4576:   }
 4577: }
 4578: 
 4579: sub format_previous_attempt_value {
 4580:     my ($key,$value) = @_;
 4581:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4582:         $value = &Apache::lonlocal::locallocaltime($value);
 4583:     } elsif (ref($value) eq 'ARRAY') {
 4584:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4585:     } elsif ($key =~ /answerstring$/) {
 4586:         my %answers = &Apache::lonnet::str2hash($value);
 4587:         my @answer = %answers;
 4588:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4589:         my @anskeys = sort(keys(%answers));
 4590:         if (@anskeys == 1) {
 4591:             my $answer = $answers{$anskeys[0]};
 4592:             if ($answer =~ m{\0}) {
 4593:                 $answer =~ s{\0}{,}g;
 4594:             }
 4595:             my $tag_internal_answer_name = 'INTERNAL';
 4596:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4597:                 $value = $answer; 
 4598:             } else {
 4599:                 $value = $anskeys[0].'='.$answer;
 4600:             }
 4601:         } else {
 4602:             foreach my $ans (@anskeys) {
 4603:                 my $answer = $answers{$ans};
 4604:                 if ($answer =~ m{\0}) {
 4605:                     $answer =~ s{\0}{,}g;
 4606:                 }
 4607:                 $value .=  $ans.'='.$answer.'<br />';;
 4608:             } 
 4609:         }
 4610:     } else {
 4611:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4612:     }
 4613:     return $value;
 4614: }
 4615: 
 4616: 
 4617: sub relative_to_absolute {
 4618:     my ($url,$output)=@_;
 4619:     my $parser=HTML::TokeParser->new(\$output);
 4620:     my $token;
 4621:     my $thisdir=$url;
 4622:     my @rlinks=();
 4623:     while ($token=$parser->get_token) {
 4624: 	if ($token->[0] eq 'S') {
 4625: 	    if ($token->[1] eq 'a') {
 4626: 		if ($token->[2]->{'href'}) {
 4627: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4628: 		}
 4629: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4630: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4631: 	    } elsif ($token->[1] eq 'base') {
 4632: 		$thisdir=$token->[2]->{'href'};
 4633: 	    }
 4634: 	}
 4635:     }
 4636:     $thisdir=~s-/[^/]*$--;
 4637:     foreach my $link (@rlinks) {
 4638: 	unless (($link=~/^https?\:\/\//i) ||
 4639: 		($link=~/^\//) ||
 4640: 		($link=~/^javascript:/i) ||
 4641: 		($link=~/^mailto:/i) ||
 4642: 		($link=~/^\#/)) {
 4643: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4644: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4645: 	}
 4646:     }
 4647: # -------------------------------------------------- Deal with Applet codebases
 4648:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4649:     return $output;
 4650: }
 4651: 
 4652: =pod
 4653: 
 4654: =item * &get_student_view()
 4655: 
 4656: show a snapshot of what student was looking at
 4657: 
 4658: =cut
 4659: 
 4660: sub get_student_view {
 4661:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4662:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4663:   my (%form);
 4664:   my @elements=('symb','courseid','domain','username');
 4665:   foreach my $element (@elements) {
 4666:       $form{'grade_'.$element}=eval '$'.$element #'
 4667:   }
 4668:   if (defined($moreenv)) {
 4669:       %form=(%form,%{$moreenv});
 4670:   }
 4671:   if (defined($target)) { $form{'grade_target'} = $target; }
 4672:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4673:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4674:   $userview=~s/\<body[^\>]*\>//gi;
 4675:   $userview=~s/\<\/body\>//gi;
 4676:   $userview=~s/\<html\>//gi;
 4677:   $userview=~s/\<\/html\>//gi;
 4678:   $userview=~s/\<head\>//gi;
 4679:   $userview=~s/\<\/head\>//gi;
 4680:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4681:   $userview=&relative_to_absolute($feedurl,$userview);
 4682:   if (wantarray) {
 4683:      return ($userview,$response);
 4684:   } else {
 4685:      return $userview;
 4686:   }
 4687: }
 4688: 
 4689: sub get_student_view_with_retries {
 4690:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4691: 
 4692:     my $ok = 0;                 # True if we got a good response.
 4693:     my $content;
 4694:     my $response;
 4695: 
 4696:     # Try to get the student_view done. within the retries count:
 4697:     
 4698:     do {
 4699:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4700:          $ok      = $response->is_success;
 4701:          if (!$ok) {
 4702:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4703:          }
 4704:          $retries--;
 4705:     } while (!$ok && ($retries > 0));
 4706:     
 4707:     if (!$ok) {
 4708:        $content = '';          # On error return an empty content.
 4709:     }
 4710:     if (wantarray) {
 4711:        return ($content, $response);
 4712:     } else {
 4713:        return $content;
 4714:     }
 4715: }
 4716: 
 4717: =pod
 4718: 
 4719: =item * &get_student_answers() 
 4720: 
 4721: show a snapshot of how student was answering problem
 4722: 
 4723: =cut
 4724: 
 4725: sub get_student_answers {
 4726:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4727:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4728:   my (%moreenv);
 4729:   my @elements=('symb','courseid','domain','username');
 4730:   foreach my $element (@elements) {
 4731:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4732:   }
 4733:   $moreenv{'grade_target'}='answer';
 4734:   %moreenv=(%form,%moreenv);
 4735:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4736:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4737:   return $userview;
 4738: }
 4739: 
 4740: =pod
 4741: 
 4742: =item * &submlink()
 4743: 
 4744: Inputs: $text $uname $udom $symb $target
 4745: 
 4746: Returns: A link to grades.pm such as to see the SUBM view of a student
 4747: 
 4748: =cut
 4749: 
 4750: ###############################################
 4751: sub submlink {
 4752:     my ($text,$uname,$udom,$symb,$target)=@_;
 4753:     if (!($uname && $udom)) {
 4754: 	(my $cursymb, my $courseid,$udom,$uname)=
 4755: 	    &Apache::lonnet::whichuser($symb);
 4756: 	if (!$symb) { $symb=$cursymb; }
 4757:     }
 4758:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4759:     $symb=&escape($symb);
 4760:     if ($target) { $target=" target=\"$target\""; }
 4761:     return
 4762:         '<a href="/adm/grades?command=submission'.
 4763:         '&amp;symb='.$symb.
 4764:         '&amp;student='.$uname.
 4765:         '&amp;userdom='.$udom.'"'.
 4766:         $target.'>'.$text.'</a>';
 4767: }
 4768: ##############################################
 4769: 
 4770: =pod
 4771: 
 4772: =item * &pgrdlink()
 4773: 
 4774: Inputs: $text $uname $udom $symb $target
 4775: 
 4776: Returns: A link to grades.pm such as to see the PGRD view of a student
 4777: 
 4778: =cut
 4779: 
 4780: ###############################################
 4781: sub pgrdlink {
 4782:     my $link=&submlink(@_);
 4783:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4784:     return $link;
 4785: }
 4786: ##############################################
 4787: 
 4788: =pod
 4789: 
 4790: =item * &pprmlink()
 4791: 
 4792: Inputs: $text $uname $udom $symb $target
 4793: 
 4794: Returns: A link to parmset.pm such as to see the PPRM view of a
 4795: student and a specific resource
 4796: 
 4797: =cut
 4798: 
 4799: ###############################################
 4800: sub pprmlink {
 4801:     my ($text,$uname,$udom,$symb,$target)=@_;
 4802:     if (!($uname && $udom)) {
 4803: 	(my $cursymb, my $courseid,$udom,$uname)=
 4804: 	    &Apache::lonnet::whichuser($symb);
 4805: 	if (!$symb) { $symb=$cursymb; }
 4806:     }
 4807:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4808:     $symb=&escape($symb);
 4809:     if ($target) { $target="target=\"$target\""; }
 4810:     return '<a href="/adm/parmset?command=set&amp;'.
 4811: 	'symb='.$symb.'&amp;uname='.$uname.
 4812: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4813: }
 4814: ##############################################
 4815: 
 4816: =pod
 4817: 
 4818: =back
 4819: 
 4820: =cut
 4821: 
 4822: ###############################################
 4823: 
 4824: 
 4825: sub timehash {
 4826:     my ($thistime) = @_;
 4827:     my $timezone = &Apache::lonlocal::gettimezone();
 4828:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4829:                      ->set_time_zone($timezone);
 4830:     my $wday = $dt->day_of_week();
 4831:     if ($wday == 7) { $wday = 0; }
 4832:     return ( 'second' => $dt->second(),
 4833:              'minute' => $dt->minute(),
 4834:              'hour'   => $dt->hour(),
 4835:              'day'     => $dt->day_of_month(),
 4836:              'month'   => $dt->month(),
 4837:              'year'    => $dt->year(),
 4838:              'weekday' => $wday,
 4839:              'dayyear' => $dt->day_of_year(),
 4840:              'dlsav'   => $dt->is_dst() );
 4841: }
 4842: 
 4843: sub utc_string {
 4844:     my ($date)=@_;
 4845:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4846: }
 4847: 
 4848: sub maketime {
 4849:     my %th=@_;
 4850:     my ($epoch_time,$timezone,$dt);
 4851:     $timezone = &Apache::lonlocal::gettimezone();
 4852:     eval {
 4853:         $dt = DateTime->new( year   => $th{'year'},
 4854:                              month  => $th{'month'},
 4855:                              day    => $th{'day'},
 4856:                              hour   => $th{'hour'},
 4857:                              minute => $th{'minute'},
 4858:                              second => $th{'second'},
 4859:                              time_zone => $timezone,
 4860:                          );
 4861:     };
 4862:     if (!$@) {
 4863:         $epoch_time = $dt->epoch;
 4864:         if ($epoch_time) {
 4865:             return $epoch_time;
 4866:         }
 4867:     }
 4868:     return POSIX::mktime(
 4869:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4870:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4871: }
 4872: 
 4873: #########################################
 4874: 
 4875: sub findallcourses {
 4876:     my ($roles,$uname,$udom) = @_;
 4877:     my %roles;
 4878:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4879:     my %courses;
 4880:     my $now=time;
 4881:     if (!defined($uname)) {
 4882:         $uname = $env{'user.name'};
 4883:     }
 4884:     if (!defined($udom)) {
 4885:         $udom = $env{'user.domain'};
 4886:     }
 4887:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4888:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4889:         if (!%roles) {
 4890:             %roles = (
 4891:                        cc => 1,
 4892:                        co => 1,
 4893:                        in => 1,
 4894:                        ep => 1,
 4895:                        ta => 1,
 4896:                        cr => 1,
 4897:                        st => 1,
 4898:              );
 4899:         }
 4900:         foreach my $entry (keys(%roleshash)) {
 4901:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4902:             if ($trole =~ /^cr/) { 
 4903:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4904:             } else {
 4905:                 next if (!exists($roles{$trole}));
 4906:             }
 4907:             if ($tend) {
 4908:                 next if ($tend < $now);
 4909:             }
 4910:             if ($tstart) {
 4911:                 next if ($tstart > $now);
 4912:             }
 4913:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4914:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4915:             my $value = $trole.'/'.$cdom.'/';
 4916:             if ($secpart eq '') {
 4917:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4918:                 $sec = 'none';
 4919:                 $value .= $cnum.'/';
 4920:             } else {
 4921:                 $cnum = $cnumpart;
 4922:                 ($sec,$role) = split(/_/,$secpart);
 4923:                 $value .= $cnum.'/'.$sec;
 4924:             }
 4925:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4926:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4927:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4928:                 }
 4929:             } else {
 4930:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4931:             }
 4932:         }
 4933:     } else {
 4934:         foreach my $key (keys(%env)) {
 4935: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4936:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4937: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4938: 	        next if ($role eq 'ca' || $role eq 'aa');
 4939: 	        next if (%roles && !exists($roles{$role}));
 4940: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4941:                 my $active=1;
 4942:                 if ($starttime) {
 4943: 		    if ($now<$starttime) { $active=0; }
 4944:                 }
 4945:                 if ($endtime) {
 4946:                     if ($now>$endtime) { $active=0; }
 4947:                 }
 4948:                 if ($active) {
 4949:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4950:                     if ($sec eq '') {
 4951:                         $sec = 'none';
 4952:                     } else {
 4953:                         $value .= $sec;
 4954:                     }
 4955:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4956:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4957:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4958:                         }
 4959:                     } else {
 4960:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4961:                     }
 4962:                 }
 4963:             }
 4964:         }
 4965:     }
 4966:     return %courses;
 4967: }
 4968: 
 4969: ###############################################
 4970: 
 4971: sub blockcheck {
 4972:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4973: 
 4974:     if (defined($udom) && defined($uname)) {
 4975:         # If uname and udom are for a course, check for blocks in the course.
 4976:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4977:             my ($startblock,$endblock,$triggerblock) =
 4978:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4979:             return ($startblock,$endblock,$triggerblock);
 4980:         }
 4981:     } else {
 4982:         $udom = $env{'user.domain'};
 4983:         $uname = $env{'user.name'};
 4984:     }
 4985: 
 4986:     my $startblock = 0;
 4987:     my $endblock = 0;
 4988:     my $triggerblock = '';
 4989:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4990: 
 4991:     # If uname is for a user, and activity is course-specific, i.e.,
 4992:     # boards, chat or groups, check for blocking in current course only.
 4993: 
 4994:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4995:          $activity eq 'groups' || $activity eq 'printout' ||
 4996:          $activity eq 'reinit' || $activity eq 'alert') &&
 4997:         ($env{'request.course.id'})) {
 4998:         foreach my $key (keys(%live_courses)) {
 4999:             if ($key ne $env{'request.course.id'}) {
 5000:                 delete($live_courses{$key});
 5001:             }
 5002:         }
 5003:     }
 5004: 
 5005:     my $otheruser = 0;
 5006:     my %own_courses;
 5007:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5008:         # Resource belongs to user other than current user.
 5009:         $otheruser = 1;
 5010:         # Gather courses for current user
 5011:         %own_courses = 
 5012:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5013:     }
 5014: 
 5015:     # Gather active course roles - course coordinator, instructor, 
 5016:     # exam proctor, ta, student, or custom role.
 5017: 
 5018:     foreach my $course (keys(%live_courses)) {
 5019:         my ($cdom,$cnum);
 5020:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5021:             $cdom = $env{'course.'.$course.'.domain'};
 5022:             $cnum = $env{'course.'.$course.'.num'};
 5023:         } else {
 5024:             ($cdom,$cnum) = split(/_/,$course); 
 5025:         }
 5026:         my $no_ownblock = 0;
 5027:         my $no_userblock = 0;
 5028:         if ($otheruser && $activity ne 'com') {
 5029:             # Check if current user has 'evb' priv for this
 5030:             if (defined($own_courses{$course})) {
 5031:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5032:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5033:                     if ($sec ne 'none') {
 5034:                         $checkrole .= '/'.$sec;
 5035:                     }
 5036:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5037:                         $no_ownblock = 1;
 5038:                         last;
 5039:                     }
 5040:                 }
 5041:             }
 5042:             # if they have 'evb' priv and are currently not playing student
 5043:             next if (($no_ownblock) &&
 5044:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5045:         }
 5046:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5047:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5048:             if ($sec ne 'none') {
 5049:                 $checkrole .= '/'.$sec;
 5050:             }
 5051:             if ($otheruser) {
 5052:                 # Resource belongs to user other than current user.
 5053:                 # Assemble privs for that user, and check for 'evb' priv.
 5054:                 my (%allroles,%userroles);
 5055:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5056:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5057:                         my ($trole,$tdom,$tnum,$tsec);
 5058:                         if ($entry =~ /^cr/) {
 5059:                             ($trole,$tdom,$tnum,$tsec) = 
 5060:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5061:                         } else {
 5062:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5063:                         }
 5064:                         my ($spec,$area,$trest);
 5065:                         $area = '/'.$tdom.'/'.$tnum;
 5066:                         $trest = $tnum;
 5067:                         if ($tsec ne '') {
 5068:                             $area .= '/'.$tsec;
 5069:                             $trest .= '/'.$tsec;
 5070:                         }
 5071:                         $spec = $trole.'.'.$area;
 5072:                         if ($trole =~ /^cr/) {
 5073:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5074:                                                               $tdom,$spec,$trest,$area);
 5075:                         } else {
 5076:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5077:                                                                 $tdom,$spec,$trest,$area);
 5078:                         }
 5079:                     }
 5080:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5081:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5082:                         if ($1) {
 5083:                             $no_userblock = 1;
 5084:                             last;
 5085:                         }
 5086:                     }
 5087:                 }
 5088:             } else {
 5089:                 # Resource belongs to current user
 5090:                 # Check for 'evb' priv via lonnet::allowed().
 5091:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5092:                     $no_ownblock = 1;
 5093:                     last;
 5094:                 }
 5095:             }
 5096:         }
 5097:         # if they have the evb priv and are currently not playing student
 5098:         next if (($no_ownblock) &&
 5099:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5100:         next if ($no_userblock);
 5101: 
 5102:         # Retrieve blocking times and identity of locker for course
 5103:         # of specified user, unless user has 'evb' privilege.
 5104: 
 5105:         my ($start,$end,$trigger) = 
 5106:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5107:         if (($start != 0) && 
 5108:             (($startblock == 0) || ($startblock > $start))) {
 5109:             $startblock = $start;
 5110:             if ($trigger ne '') {
 5111:                 $triggerblock = $trigger;
 5112:             }
 5113:         }
 5114:         if (($end != 0)  &&
 5115:             (($endblock == 0) || ($endblock < $end))) {
 5116:             $endblock = $end;
 5117:             if ($trigger ne '') {
 5118:                 $triggerblock = $trigger;
 5119:             }
 5120:         }
 5121:     }
 5122:     return ($startblock,$endblock,$triggerblock);
 5123: }
 5124: 
 5125: sub get_blocks {
 5126:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5127:     my $startblock = 0;
 5128:     my $endblock = 0;
 5129:     my $triggerblock = '';
 5130:     my $course = $cdom.'_'.$cnum;
 5131:     $setters->{$course} = {};
 5132:     $setters->{$course}{'staff'} = [];
 5133:     $setters->{$course}{'times'} = [];
 5134:     $setters->{$course}{'triggers'} = [];
 5135:     my (@blockers,%triggered);
 5136:     my $now = time;
 5137:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5138:     if ($activity eq 'docs') {
 5139:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5140:         foreach my $block (@blockers) {
 5141:             if ($block =~ /^firstaccess____(.+)$/) {
 5142:                 my $item = $1;
 5143:                 my $type = 'map';
 5144:                 my $timersymb = $item;
 5145:                 if ($item eq 'course') {
 5146:                     $type = 'course';
 5147:                 } elsif ($item =~ /___\d+___/) {
 5148:                     $type = 'resource';
 5149:                 } else {
 5150:                     $timersymb = &Apache::lonnet::symbread($item);
 5151:                 }
 5152:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5153:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5154:                 $triggered{$block} = {
 5155:                                        start => $start,
 5156:                                        end   => $end,
 5157:                                        type  => $type,
 5158:                                      };
 5159:             }
 5160:         }
 5161:     } else {
 5162:         foreach my $block (keys(%commblocks)) {
 5163:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5164:                 my ($start,$end) = ($1,$2);
 5165:                 if ($start <= time && $end >= time) {
 5166:                     if (ref($commblocks{$block}) eq 'HASH') {
 5167:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5168:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5169:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5170:                                     push(@blockers,$block);
 5171:                                 }
 5172:                             }
 5173:                         }
 5174:                     }
 5175:                 }
 5176:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5177:                 my $item = $1;
 5178:                 my $timersymb = $item; 
 5179:                 my $type = 'map';
 5180:                 if ($item eq 'course') {
 5181:                     $type = 'course';
 5182:                 } elsif ($item =~ /___\d+___/) {
 5183:                     $type = 'resource';
 5184:                 } else {
 5185:                     $timersymb = &Apache::lonnet::symbread($item);
 5186:                 }
 5187:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5188:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5189:                 if ($start && $end) {
 5190:                     if (($start <= time) && ($end >= time)) {
 5191:                         if (ref($commblocks{$block}) eq 'HASH') {
 5192:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5193:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5194:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5195:                                         push(@blockers,$block);
 5196:                                         $triggered{$block} = {
 5197:                                                                start => $start,
 5198:                                                                end   => $end,
 5199:                                                                type  => $type,
 5200:                                                              };
 5201:                                     }
 5202:                                 }
 5203:                             }
 5204:                         }
 5205:                     }
 5206:                 }
 5207:             }
 5208:         }
 5209:     }
 5210:     foreach my $blocker (@blockers) {
 5211:         my ($staff_name,$staff_dom,$title,$blocks) =
 5212:             &parse_block_record($commblocks{$blocker});
 5213:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5214:         my ($start,$end,$triggertype);
 5215:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5216:             ($start,$end) = ($1,$2);
 5217:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5218:             $start = $triggered{$blocker}{'start'};
 5219:             $end = $triggered{$blocker}{'end'};
 5220:             $triggertype = $triggered{$blocker}{'type'};
 5221:         }
 5222:         if ($start) {
 5223:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5224:             if ($triggertype) {
 5225:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5226:             } else {
 5227:                 push(@{$$setters{$course}{'triggers'}},0);
 5228:             }
 5229:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5230:                 $startblock = $start;
 5231:                 if ($triggertype) {
 5232:                     $triggerblock = $blocker;
 5233:                 }
 5234:             }
 5235:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5236:                $endblock = $end;
 5237:                if ($triggertype) {
 5238:                    $triggerblock = $blocker;
 5239:                }
 5240:             }
 5241:         }
 5242:     }
 5243:     return ($startblock,$endblock,$triggerblock);
 5244: }
 5245: 
 5246: sub parse_block_record {
 5247:     my ($record) = @_;
 5248:     my ($setuname,$setudom,$title,$blocks);
 5249:     if (ref($record) eq 'HASH') {
 5250:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5251:         $title = &unescape($record->{'event'});
 5252:         $blocks = $record->{'blocks'};
 5253:     } else {
 5254:         my @data = split(/:/,$record,3);
 5255:         if (scalar(@data) eq 2) {
 5256:             $title = $data[1];
 5257:             ($setuname,$setudom) = split(/@/,$data[0]);
 5258:         } else {
 5259:             ($setuname,$setudom,$title) = @data;
 5260:         }
 5261:         $blocks = { 'com' => 'on' };
 5262:     }
 5263:     return ($setuname,$setudom,$title,$blocks);
 5264: }
 5265: 
 5266: sub blocking_status {
 5267:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5268:     my %setters;
 5269: 
 5270: # check for active blocking
 5271:     my ($startblock,$endblock,$triggerblock) = 
 5272:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5273:     my $blocked = 0;
 5274:     if ($startblock && $endblock) {
 5275:         $blocked = 1;
 5276:     }
 5277: 
 5278: # caller just wants to know whether a block is active
 5279:     if (!wantarray) { return $blocked; }
 5280: 
 5281: # build a link to a popup window containing the details
 5282:     my $querystring  = "?activity=$activity";
 5283: # $uname and $udom decide whose portfolio the user is trying to look at
 5284:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5285:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5286:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5287:     } elsif ($activity eq 'docs') {
 5288:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5289:     }
 5290: 
 5291:     my $output .= <<'END_MYBLOCK';
 5292: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5293:     var options = "width=" + w + ",height=" + h + ",";
 5294:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5295:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5296:     var newWin = window.open(url, wdwName, options);
 5297:     newWin.focus();
 5298: }
 5299: END_MYBLOCK
 5300: 
 5301:     $output = Apache::lonhtmlcommon::scripttag($output);
 5302:   
 5303:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5304:     my $text = &mt('Communication Blocked');
 5305:     my $class = 'LC_comblock';
 5306:     if ($activity eq 'docs') {
 5307:         $text = &mt('Content Access Blocked');
 5308:         $class = '';
 5309:     } elsif ($activity eq 'printout') {
 5310:         $text = &mt('Printing Blocked');
 5311:     } elsif ($activity eq 'passwd') {
 5312:         $text = &mt('Password Changing Blocked');
 5313:     } elsif ($activity eq 'alert') {
 5314:         $text = &mt('Checking Critical Messages Blocked');
 5315:     } elsif ($activity eq 'reinit') {
 5316:         $text = &mt('Checking Course Update Blocked');
 5317:     }
 5318:     $output .= <<"END_BLOCK";
 5319: <div class='$class'>
 5320:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5321:   title='$text'>
 5322:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5323:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5324:   title='$text'>$text</a>
 5325: </div>
 5326: 
 5327: END_BLOCK
 5328: 
 5329:     return ($blocked, $output);
 5330: }
 5331: 
 5332: ###############################################
 5333: 
 5334: sub check_ip_acc {
 5335:     my ($acc,$clientip)=@_;
 5336:     &Apache::lonxml::debug("acc is $acc");
 5337:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5338:         return 1;
 5339:     }
 5340:     my $allowed;
 5341:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5342: 
 5343:     my $name;
 5344:     my %access = (
 5345:                      allowfrom => 1,
 5346:                      denyfrom  => 0,
 5347:                  );
 5348:     my @allows;
 5349:     my @denies;
 5350:     foreach my $item (split(',',$acc)) {
 5351:         $item =~ s/^\s*//;
 5352:         $item =~ s/\s*$//;
 5353:         my $pattern;
 5354:         if ($item =~ /^\!(.+)$/) {
 5355:             push(@denies,$1);
 5356:         } else {
 5357:             push(@allows,$item);
 5358:         }
 5359:    }
 5360:    my $numdenies = scalar(@denies);
 5361:    my $numallows = scalar(@allows);
 5362:    my $count = 0;
 5363:    foreach my $pattern (@denies,@allows) {
 5364:         $count ++; 
 5365:         my $acctype = 'allowfrom';
 5366:         if ($count <= $numdenies) {
 5367:             $acctype = 'denyfrom';
 5368:         }
 5369:         if ($pattern =~ /\*$/) {
 5370:             #35.8.*
 5371:             $pattern=~s/\*//;
 5372:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5373:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5374:             #35.8.3.[34-56]
 5375:             my $low=$2;
 5376:             my $high=$3;
 5377:             $pattern=$1;
 5378:             if ($ip =~ /^\Q$pattern\E/) {
 5379:                 my $last=(split(/\./,$ip))[3];
 5380:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5381:             }
 5382:         } elsif ($pattern =~ /^\*/) {
 5383:             #*.msu.edu
 5384:             $pattern=~s/\*//;
 5385:             if (!defined($name)) {
 5386:                 use Socket;
 5387:                 my $netaddr=inet_aton($ip);
 5388:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5389:             }
 5390:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5391:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5392:             #127.0.0.1
 5393:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5394:         } else {
 5395:             #some.name.com
 5396:             if (!defined($name)) {
 5397:                 use Socket;
 5398:                 my $netaddr=inet_aton($ip);
 5399:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5400:             }
 5401:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5402:         }
 5403:         if ($allowed =~ /^(0|1)$/) { last; }
 5404:     }
 5405:     if ($allowed eq '') {
 5406:         if ($numdenies && !$numallows) {
 5407:             $allowed = 1;
 5408:         } else {
 5409:             $allowed = 0;
 5410:         }
 5411:     }
 5412:     return $allowed;
 5413: }
 5414: 
 5415: ###############################################
 5416: 
 5417: =pod
 5418: 
 5419: =head1 Domain Template Functions
 5420: 
 5421: =over 4
 5422: 
 5423: =item * &determinedomain()
 5424: 
 5425: Inputs: $domain (usually will be undef)
 5426: 
 5427: Returns: Determines which domain should be used for designs
 5428: 
 5429: =cut
 5430: 
 5431: ###############################################
 5432: sub determinedomain {
 5433:     my $domain=shift;
 5434:     if (! $domain) {
 5435:         # Determine domain if we have not been given one
 5436:         $domain = &Apache::lonnet::default_login_domain();
 5437:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5438:         if ($env{'request.role.domain'}) { 
 5439:             $domain=$env{'request.role.domain'}; 
 5440:         }
 5441:     }
 5442:     return $domain;
 5443: }
 5444: ###############################################
 5445: 
 5446: sub devalidate_domconfig_cache {
 5447:     my ($udom)=@_;
 5448:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5449: }
 5450: 
 5451: # ---------------------- Get domain configuration for a domain
 5452: sub get_domainconf {
 5453:     my ($udom) = @_;
 5454:     my $cachetime=1800;
 5455:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5456:     if (defined($cached)) { return %{$result}; }
 5457: 
 5458:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5459: 					     ['login','rolecolors','autoenroll'],$udom);
 5460:     my (%designhash,%legacy);
 5461:     if (keys(%domconfig) > 0) {
 5462:         if (ref($domconfig{'login'}) eq 'HASH') {
 5463:             if (keys(%{$domconfig{'login'}})) {
 5464:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5465:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5466:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5467:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5468:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5469:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5470:                                         if ($key eq 'loginvia') {
 5471:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5472:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5473:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5474:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5475: 
 5476:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5477:                                                 } else {
 5478:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5479:                                                 }
 5480:                                             }
 5481:                                         } elsif ($key eq 'headtag') {
 5482:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5483:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5484:                                             }
 5485:                                         }
 5486:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5487:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5488:                                         }
 5489:                                     }
 5490:                                 }
 5491:                             }
 5492:                         } else {
 5493:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5494:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5495:                                     $domconfig{'login'}{$key}{$img};
 5496:                             }
 5497:                         }
 5498:                     } else {
 5499:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5500:                     }
 5501:                 }
 5502:             } else {
 5503:                 $legacy{'login'} = 1;
 5504:             }
 5505:         } else {
 5506:             $legacy{'login'} = 1;
 5507:         }
 5508:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5509:             if (keys(%{$domconfig{'rolecolors'}})) {
 5510:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5511:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5512:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5513:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5514:                         }
 5515:                     }
 5516:                 }
 5517:             } else {
 5518:                 $legacy{'rolecolors'} = 1;
 5519:             }
 5520:         } else {
 5521:             $legacy{'rolecolors'} = 1;
 5522:         }
 5523:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5524:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5525:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5526:             }
 5527:         }
 5528:         if (keys(%legacy) > 0) {
 5529:             my %legacyhash = &get_legacy_domconf($udom);
 5530:             foreach my $item (keys(%legacyhash)) {
 5531:                 if ($item =~ /^\Q$udom\E\.login/) {
 5532:                     if ($legacy{'login'}) { 
 5533:                         $designhash{$item} = $legacyhash{$item};
 5534:                     }
 5535:                 } else {
 5536:                     if ($legacy{'rolecolors'}) {
 5537:                         $designhash{$item} = $legacyhash{$item};
 5538:                     }
 5539:                 }
 5540:             }
 5541:         }
 5542:     } else {
 5543:         %designhash = &get_legacy_domconf($udom); 
 5544:     }
 5545:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5546: 				  $cachetime);
 5547:     return %designhash;
 5548: }
 5549: 
 5550: sub get_legacy_domconf {
 5551:     my ($udom) = @_;
 5552:     my %legacyhash;
 5553:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5554:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5555:     if (-e $designfile) {
 5556:         if ( open (my $fh,"<$designfile") ) {
 5557:             while (my $line = <$fh>) {
 5558:                 next if ($line =~ /^\#/);
 5559:                 chomp($line);
 5560:                 my ($key,$val)=(split(/\=/,$line));
 5561:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5562:             }
 5563:             close($fh);
 5564:         }
 5565:     }
 5566:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5567:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5568:     }
 5569:     return %legacyhash;
 5570: }
 5571: 
 5572: =pod
 5573: 
 5574: =item * &domainlogo()
 5575: 
 5576: Inputs: $domain (usually will be undef)
 5577: 
 5578: Returns: A link to a domain logo, if the domain logo exists.
 5579: If the domain logo does not exist, a description of the domain.
 5580: 
 5581: =cut
 5582: 
 5583: ###############################################
 5584: sub domainlogo {
 5585:     my $domain = &determinedomain(shift);
 5586:     my %designhash = &get_domainconf($domain);    
 5587:     # See if there is a logo
 5588:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5589:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5590:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5591: 	    if ($imgsrc =~ m{^/res/}) {
 5592: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5593: 		&Apache::lonnet::repcopy($local_name);
 5594: 	    }
 5595: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5596:         } 
 5597:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5598:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5599:         return &Apache::lonnet::domain($domain,'description');
 5600:     } else {
 5601:         return '';
 5602:     }
 5603: }
 5604: ##############################################
 5605: 
 5606: =pod
 5607: 
 5608: =item * &designparm()
 5609: 
 5610: Inputs: $which parameter; $domain (usually will be undef)
 5611: 
 5612: Returns: value of designparamter $which
 5613: 
 5614: =cut
 5615: 
 5616: 
 5617: ##############################################
 5618: sub designparm {
 5619:     my ($which,$domain)=@_;
 5620:     if (exists($env{'environment.color.'.$which})) {
 5621:         return $env{'environment.color.'.$which};
 5622:     }
 5623:     $domain=&determinedomain($domain);
 5624:     my %domdesign;
 5625:     unless ($domain eq 'public') {
 5626:         %domdesign = &get_domainconf($domain);
 5627:     }
 5628:     my $output;
 5629:     if ($domdesign{$domain.'.'.$which} ne '') {
 5630:         $output = $domdesign{$domain.'.'.$which};
 5631:     } else {
 5632:         $output = $defaultdesign{$which};
 5633:     }
 5634:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5635:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5636:         if ($output =~ m{^/(adm|res)/}) {
 5637:             if ($output =~ m{^/res/}) {
 5638:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5639:                 &Apache::lonnet::repcopy($local_name);
 5640:             }
 5641:             $output = &lonhttpdurl($output);
 5642:         }
 5643:     }
 5644:     return $output;
 5645: }
 5646: 
 5647: ##############################################
 5648: =pod
 5649: 
 5650: =item * &authorspace()
 5651: 
 5652: Inputs: $url (usually will be undef).
 5653: 
 5654: Returns: Path to Authoring Space containing the resource or 
 5655:          directory being viewed (or for which action is being taken). 
 5656:          If $url is provided, and begins /priv/<domain>/<uname>
 5657:          the path will be that portion of the $context argument.
 5658:          Otherwise the path will be for the author space of the current
 5659:          user when the current role is author, or for that of the 
 5660:          co-author/assistant co-author space when the current role 
 5661:          is co-author or assistant co-author.
 5662: 
 5663: =cut
 5664: 
 5665: sub authorspace {
 5666:     my ($url) = @_;
 5667:     if ($url ne '') {
 5668:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5669:            return $1;
 5670:         }
 5671:     }
 5672:     my $caname = '';
 5673:     my $cadom = '';
 5674:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5675:         ($cadom,$caname) =
 5676:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5677:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5678:         $caname = $env{'user.name'};
 5679:         $cadom = $env{'user.domain'};
 5680:     }
 5681:     if (($caname ne '') && ($cadom ne '')) {
 5682:         return "/priv/$cadom/$caname/";
 5683:     }
 5684:     return;
 5685: }
 5686: 
 5687: ##############################################
 5688: =pod
 5689: 
 5690: =item * &head_subbox()
 5691: 
 5692: Inputs: $content (contains HTML code with page functions, etc.)
 5693: 
 5694: Returns: HTML div with $content
 5695:          To be included in page header
 5696: 
 5697: =cut
 5698: 
 5699: sub head_subbox {
 5700:     my ($content)=@_;
 5701:     my $output =
 5702:         '<div class="LC_head_subbox">'
 5703:        .$content
 5704:        .'</div>'
 5705: }
 5706: 
 5707: ##############################################
 5708: =pod
 5709: 
 5710: =item * &CSTR_pageheader()
 5711: 
 5712: Input: (optional) filename from which breadcrumb trail is built.
 5713:        In most cases no input as needed, as $env{'request.filename'}
 5714:        is appropriate for use in building the breadcrumb trail.
 5715: 
 5716: Returns: HTML div with CSTR path and recent box
 5717:          To be included on Authoring Space pages
 5718: 
 5719: =cut
 5720: 
 5721: sub CSTR_pageheader {
 5722:     my ($trailfile) = @_;
 5723:     if ($trailfile eq '') {
 5724:         $trailfile = $env{'request.filename'};
 5725:     }
 5726: 
 5727: # this is for resources; directories have customtitle, and crumbs
 5728: # and select recent are created in lonpubdir.pm
 5729: 
 5730:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5731:     my ($udom,$uname,$thisdisfn)=
 5732:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5733:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5734:     $formaction =~ s{/+}{/}g;
 5735: 
 5736:     my $parentpath = '';
 5737:     my $lastitem = '';
 5738:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5739:         $parentpath = $1;
 5740:         $lastitem = $2;
 5741:     } else {
 5742:         $lastitem = $thisdisfn;
 5743:     }
 5744: 
 5745:     my ($crsauthor,$title);
 5746:     if (($env{'request.course.id'}) &&
 5747:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5748:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5749:         $crsauthor = 1;
 5750:         $title = &mt('Course Authoring Space');
 5751:     } else {
 5752:         $title = &mt('Authoring Space');
 5753:     }
 5754: 
 5755:     my $output =
 5756:          '<div>'
 5757:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5758:         .'<b>'.$title.'</b> '
 5759:         .'<form name="dirs" method="post" action="'.$formaction
 5760:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5761:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5762: 
 5763:     if ($lastitem) {
 5764:         $output .=
 5765:              '<span class="LC_filename">'
 5766:             .$lastitem
 5767:             .'</span>';
 5768:     }
 5769: 
 5770:     if ($crsauthor) {
 5771:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5772:     } else {
 5773:         $output .=
 5774:              '<br />'
 5775:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5776:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5777:             .'</form>'
 5778:             .&Apache::lonmenu::constspaceform();
 5779:     }
 5780:     $output .= '</div>';
 5781: 
 5782:     return $output;
 5783: }
 5784: 
 5785: ###############################################
 5786: ###############################################
 5787: 
 5788: =pod
 5789: 
 5790: =back
 5791: 
 5792: =head1 HTML Helpers
 5793: 
 5794: =over 4
 5795: 
 5796: =item * &bodytag()
 5797: 
 5798: Returns a uniform header for LON-CAPA web pages.
 5799: 
 5800: Inputs: 
 5801: 
 5802: =over 4
 5803: 
 5804: =item * $title, A title to be displayed on the page.
 5805: 
 5806: =item * $function, the current role (can be undef).
 5807: 
 5808: =item * $addentries, extra parameters for the <body> tag.
 5809: 
 5810: =item * $bodyonly, if defined, only return the <body> tag.
 5811: 
 5812: =item * $domain, if defined, force a given domain.
 5813: 
 5814: =item * $forcereg, if page should register as content page (relevant for 
 5815:             text interface only)
 5816: 
 5817: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5818:                      navigational links
 5819: 
 5820: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5821: 
 5822: =item * $args, optional argument valid values are
 5823:             no_auto_mt_title -> prevents &mt()ing the title arg
 5824:             use_absolute     -> for external resource or syllabus, this will
 5825:                                 contain https://<hostname> if server uses
 5826:                                 https (as per hosts.tab), but request is for http
 5827:             hostname         -> hostname, from $r->hostname().
 5828: 
 5829: =item * $advtoolsref, optional argument, ref to an array containing
 5830:             inlineremote items to be added in "Functions" menu below
 5831:             breadcrumbs.
 5832: 
 5833: =back
 5834: 
 5835: Returns: A uniform header for LON-CAPA web pages.  
 5836: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5837: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5838: other decorations will be returned.
 5839: 
 5840: =cut
 5841: 
 5842: sub bodytag {
 5843:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5844:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5845: 
 5846:     my $public;
 5847:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5848:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5849:         $public = 1;
 5850:     }
 5851:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5852:     my $httphost = $args->{'use_absolute'};
 5853:     my $hostname = $args->{'hostname'};
 5854: 
 5855:     $function = &get_users_function() if (!$function);
 5856:     my $img =    &designparm($function.'.img',$domain);
 5857:     my $font =   &designparm($function.'.font',$domain);
 5858:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5859: 
 5860:     my %design = ( 'style'   => 'margin-top: 0',
 5861: 		   'bgcolor' => $pgbg,
 5862: 		   'text'    => $font,
 5863:                    'alink'   => &designparm($function.'.alink',$domain),
 5864: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5865: 		   'link'    => &designparm($function.'.link',$domain),);
 5866:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5867: 
 5868:  # role and realm
 5869:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5870:     if ($realm) {
 5871:         $realm = '/'.$realm;
 5872:     }
 5873:     if ($role  eq 'ca') {
 5874:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5875:         $realm = &plainname($rname,$rdom);
 5876:     } 
 5877: # realm
 5878:     if ($env{'request.course.id'}) {
 5879:         if ($env{'request.role'} !~ /^cr/) {
 5880:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5881:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5882:             if ($env{'request.role.desc'}) {
 5883:                 $role = $env{'request.role.desc'};
 5884:             } else {
 5885:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5886:             }
 5887:         } else {
 5888:             $role = (split(/\//,$role,4))[-1]; 
 5889:         }
 5890:         if ($env{'request.course.sec'}) {
 5891:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5892:         }   
 5893: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5894:     } else {
 5895:         $role = &Apache::lonnet::plaintext($role);
 5896:     }
 5897: 
 5898:     if (!$realm) { $realm='&nbsp;'; }
 5899: 
 5900:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5901: 
 5902: # construct main body tag
 5903:     my $bodytag = "<body $extra_body_attr>".
 5904: 	&Apache::lontexconvert::init_math_support();
 5905: 
 5906:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5907: 
 5908:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5909:         return $bodytag;
 5910:     }
 5911: 
 5912:     if ($public) {
 5913: 	undef($role);
 5914:     }
 5915:     
 5916:     my $titleinfo = '<h1>'.$title.'</h1>';
 5917:     #
 5918:     # Extra info if you are the DC
 5919:     my $dc_info = '';
 5920:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5921:                         $env{'course.'.$env{'request.course.id'}.
 5922:                                  '.domain'}.'/'})) {
 5923:         my $cid = $env{'request.course.id'};
 5924:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5925:         $dc_info =~ s/\s+$//;
 5926:     }
 5927: 
 5928:     my $crstype;
 5929:     if ($env{'request.course.id'}) {
 5930:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 5931:     } elsif ($args->{'crstype'}) {
 5932:         $crstype = $args->{'crstype'};
 5933:     }
 5934:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 5935:         undef($role);
 5936:     } else {
 5937:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5938:     }
 5939: 
 5940:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5941: 
 5942:         #    if ($env{'request.state'} eq 'construct') {
 5943:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5944:         #    }
 5945: 
 5946:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5947:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5948: 
 5949:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
 5950: 
 5951:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5952:              if ($dc_info) {
 5953:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5954:              }
 5955:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5956:                 <em>$realm</em> $dc_info</div>|;
 5957:             return $bodytag;
 5958:         }
 5959: 
 5960:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5961:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5962:         }
 5963: 
 5964:         $bodytag .= $right;
 5965: 
 5966:         if ($dc_info) {
 5967:             $dc_info = &dc_courseid_toggle($dc_info);
 5968:         }
 5969:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5970: 
 5971:         #if directed to not display the secondary menu, don't.  
 5972:         if ($args->{'no_secondary_menu'}) {
 5973:             return $bodytag;
 5974:         }
 5975:         #don't show menus for public users
 5976:         if (!$public){
 5977:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5978:             $bodytag .= Apache::lonmenu::serverform();
 5979:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5980:             if ($env{'request.state'} eq 'construct') {
 5981:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5982:                                 $args->{'bread_crumbs'},'','',$hostname);
 5983:             } elsif ($forcereg) {
 5984:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5985:                                                             $args->{'group'},
 5986:                                                             $args->{'hide_buttons'},
 5987:                                                             $hostname);
 5988:             } else {
 5989:                 $bodytag .= 
 5990:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5991:                                                         $forcereg,$args->{'group'},
 5992:                                                         $args->{'bread_crumbs'},
 5993:                                                         $advtoolsref,'',$hostname);
 5994:             }
 5995:         }else{
 5996:             # this is to seperate menu from content when there's no secondary
 5997:             # menu. Especially needed for public accessible ressources.
 5998:             $bodytag .= '<hr style="clear:both" />';
 5999:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6000:         }
 6001: 
 6002:         return $bodytag;
 6003: }
 6004: 
 6005: sub dc_courseid_toggle {
 6006:     my ($dc_info) = @_;
 6007:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6008:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6009:            &mt('(More ...)').'</a></span>'.
 6010:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6011: }
 6012: 
 6013: sub make_attr_string {
 6014:     my ($register,$attr_ref) = @_;
 6015: 
 6016:     if ($attr_ref && !ref($attr_ref)) {
 6017: 	die("addentries Must be a hash ref ".
 6018: 	    join(':',caller(1))." ".
 6019: 	    join(':',caller(0))." ");
 6020:     }
 6021: 
 6022:     if ($register) {
 6023: 	my ($on_load,$on_unload);
 6024: 	foreach my $key (keys(%{$attr_ref})) {
 6025: 	    if      (lc($key) eq 'onload') {
 6026: 		$on_load.=$attr_ref->{$key}.';';
 6027: 		delete($attr_ref->{$key});
 6028: 
 6029: 	    } elsif (lc($key) eq 'onunload') {
 6030: 		$on_unload.=$attr_ref->{$key}.';';
 6031: 		delete($attr_ref->{$key});
 6032: 	    }
 6033: 	}
 6034: 	$attr_ref->{'onload'}  = $on_load;
 6035: 	$attr_ref->{'onunload'}= $on_unload;
 6036:     }
 6037: 
 6038:     my $attr_string;
 6039:     foreach my $attr (sort(keys(%$attr_ref))) {
 6040: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6041:     }
 6042:     return $attr_string;
 6043: }
 6044: 
 6045: 
 6046: ###############################################
 6047: ###############################################
 6048: 
 6049: =pod
 6050: 
 6051: =item * &endbodytag()
 6052: 
 6053: Returns a uniform footer for LON-CAPA web pages.
 6054: 
 6055: Inputs: 1 - optional reference to an args hash
 6056: If in the hash, key for noredirectlink has a value which evaluates to true,
 6057: a 'Continue' link is not displayed if the page contains an
 6058: internal redirect in the <head></head> section,
 6059: i.e., $env{'internal.head.redirect'} exists   
 6060: 
 6061: =cut
 6062: 
 6063: sub endbodytag {
 6064:     my ($args) = @_;
 6065:     my $endbodytag;
 6066:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6067:         $endbodytag='</body>';
 6068:     }
 6069:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6070:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6071: 	    $endbodytag=
 6072: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6073: 	        &mt('Continue').'</a>'.
 6074: 	        $endbodytag;
 6075:         }
 6076:     }
 6077:     return $endbodytag;
 6078: }
 6079: 
 6080: =pod
 6081: 
 6082: =item * &standard_css()
 6083: 
 6084: Returns a style sheet
 6085: 
 6086: Inputs: (all optional)
 6087:             domain         -> force to color decorate a page for a specific
 6088:                                domain
 6089:             function       -> force usage of a specific rolish color scheme
 6090:             bgcolor        -> override the default page bgcolor
 6091: 
 6092: =cut
 6093: 
 6094: sub standard_css {
 6095:     my ($function,$domain,$bgcolor) = @_;
 6096:     $function  = &get_users_function() if (!$function);
 6097:     my $img    = &designparm($function.'.img',   $domain);
 6098:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6099:     my $font   = &designparm($function.'.font',  $domain);
 6100:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6101: #second colour for later usage
 6102:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6103:     my $pgbg_or_bgcolor =
 6104: 	         $bgcolor ||
 6105: 	         &designparm($function.'.pgbg',  $domain);
 6106:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6107:     my $alink  = &designparm($function.'.alink', $domain);
 6108:     my $vlink  = &designparm($function.'.vlink', $domain);
 6109:     my $link   = &designparm($function.'.link',  $domain);
 6110: 
 6111:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6112:     my $mono                 = 'monospace';
 6113:     my $data_table_head      = $sidebg;
 6114:     my $data_table_light     = '#FAFAFA';
 6115:     my $data_table_dark      = '#E0E0E0';
 6116:     my $data_table_darker    = '#CCCCCC';
 6117:     my $data_table_highlight = '#FFFF00';
 6118:     my $mail_new             = '#FFBB77';
 6119:     my $mail_new_hover       = '#DD9955';
 6120:     my $mail_read            = '#BBBB77';
 6121:     my $mail_read_hover      = '#999944';
 6122:     my $mail_replied         = '#AAAA88';
 6123:     my $mail_replied_hover   = '#888855';
 6124:     my $mail_other           = '#99BBBB';
 6125:     my $mail_other_hover     = '#669999';
 6126:     my $table_header         = '#DDDDDD';
 6127:     my $feedback_link_bg     = '#BBBBBB';
 6128:     my $lg_border_color      = '#C8C8C8';
 6129:     my $button_hover         = '#BF2317';
 6130: 
 6131:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6132:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6133:                                              : '0 3px 0 4px';
 6134: 
 6135: 
 6136:     return <<END;
 6137: 
 6138: /* needed for iframe to allow 100% height in FF */
 6139: body, html { 
 6140:     margin: 0;
 6141:     padding: 0 0.5%;
 6142:     height: 99%; /* to avoid scrollbars */
 6143: }
 6144: 
 6145: body {
 6146:   font-family: $sans;
 6147:   line-height:130%;
 6148:   font-size:0.83em;
 6149:   color:$font;
 6150: }
 6151: 
 6152: a:focus,
 6153: a:focus img {
 6154:   color: red;
 6155: }
 6156: 
 6157: form, .inline {
 6158:   display: inline;
 6159: }
 6160: 
 6161: .LC_right {
 6162:   text-align:right;
 6163: }
 6164: 
 6165: .LC_middle {
 6166:   vertical-align:middle;
 6167: }
 6168: 
 6169: .LC_floatleft {
 6170:   float: left;
 6171: }
 6172: 
 6173: .LC_floatright {
 6174:   float: right;
 6175: }
 6176: 
 6177: .LC_400Box {
 6178:   width:400px;
 6179: }
 6180: 
 6181: .LC_iframecontainer {
 6182:     width: 98%;
 6183:     margin: 0;
 6184:     position: fixed;
 6185:     top: 8.5em;
 6186:     bottom: 0;
 6187: }
 6188: 
 6189: .LC_iframecontainer iframe{
 6190:     border: none;
 6191:     width: 100%;
 6192:     height: 100%;
 6193: }
 6194: 
 6195: .LC_filename {
 6196:   font-family: $mono;
 6197:   white-space:pre;
 6198:   font-size: 120%;
 6199: }
 6200: 
 6201: .LC_fileicon {
 6202:   border: none;
 6203:   height: 1.3em;
 6204:   vertical-align: text-bottom;
 6205:   margin-right: 0.3em;
 6206:   text-decoration:none;
 6207: }
 6208: 
 6209: .LC_setting {
 6210:   text-decoration:underline;
 6211: }
 6212: 
 6213: .LC_error {
 6214:   color: red;
 6215: }
 6216: 
 6217: .LC_warning {
 6218:   color: darkorange;
 6219: }
 6220: 
 6221: .LC_diff_removed {
 6222:   color: red;
 6223: }
 6224: 
 6225: .LC_info,
 6226: .LC_success,
 6227: .LC_diff_added {
 6228:   color: green;
 6229: }
 6230: 
 6231: div.LC_confirm_box {
 6232:   background-color: #FAFAFA;
 6233:   border: 1px solid $lg_border_color;
 6234:   margin-right: 0;
 6235:   padding: 5px;
 6236: }
 6237: 
 6238: div.LC_confirm_box .LC_error img,
 6239: div.LC_confirm_box .LC_success img {
 6240:   vertical-align: middle;
 6241: }
 6242: 
 6243: .LC_maxwidth {
 6244:   max-width: 100%;
 6245:   height: auto;
 6246: }
 6247: 
 6248: .LC_textsize_mobile {
 6249:   \@media only screen and (max-device-width: 480px) {
 6250:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6251:   }
 6252: }
 6253: 
 6254: .LC_icon {
 6255:   border: none;
 6256:   vertical-align: middle;
 6257: }
 6258: 
 6259: .LC_docs_spacer {
 6260:   width: 25px;
 6261:   height: 1px;
 6262:   border: none;
 6263: }
 6264: 
 6265: .LC_internal_info {
 6266:   color: #999999;
 6267: }
 6268: 
 6269: .LC_discussion {
 6270:   background: $data_table_dark;
 6271:   border: 1px solid black;
 6272:   margin: 2px;
 6273: }
 6274: 
 6275: .LC_disc_action_left {
 6276:   background: $sidebg;
 6277:   text-align: left;
 6278:   padding: 4px;
 6279:   margin: 2px;
 6280: }
 6281: 
 6282: .LC_disc_action_right {
 6283:   background: $sidebg;
 6284:   text-align: right;
 6285:   padding: 4px;
 6286:   margin: 2px;
 6287: }
 6288: 
 6289: .LC_disc_new_item {
 6290:   background: white;
 6291:   border: 2px solid red;
 6292:   margin: 4px;
 6293:   padding: 4px;
 6294: }
 6295: 
 6296: .LC_disc_old_item {
 6297:   background: white;
 6298:   margin: 4px;
 6299:   padding: 4px;
 6300: }
 6301: 
 6302: table.LC_pastsubmission {
 6303:   border: 1px solid black;
 6304:   margin: 2px;
 6305: }
 6306: 
 6307: table#LC_menubuttons {
 6308:   width: 100%;
 6309:   background: $pgbg;
 6310:   border: 2px;
 6311:   border-collapse: separate;
 6312:   padding: 0;
 6313: }
 6314: 
 6315: table#LC_title_bar a {
 6316:   color: $fontmenu;
 6317: }
 6318: 
 6319: table#LC_title_bar {
 6320:   clear: both;
 6321:   display: none;
 6322: }
 6323: 
 6324: table#LC_title_bar,
 6325: table.LC_breadcrumbs, /* obsolete? */
 6326: table#LC_title_bar.LC_with_remote {
 6327:   width: 100%;
 6328:   border-color: $pgbg;
 6329:   border-style: solid;
 6330:   border-width: $border;
 6331:   background: $pgbg;
 6332:   color: $fontmenu;
 6333:   border-collapse: collapse;
 6334:   padding: 0;
 6335:   margin: 0;
 6336: }
 6337: 
 6338: ul.LC_breadcrumb_tools_outerlist {
 6339:     margin: 0;
 6340:     padding: 0;
 6341:     position: relative;
 6342:     list-style: none;
 6343: }
 6344: ul.LC_breadcrumb_tools_outerlist li {
 6345:     display: inline;
 6346: }
 6347: 
 6348: .LC_breadcrumb_tools_navigation {
 6349:     padding: 0;
 6350:     margin: 0;
 6351:     float: left;
 6352: }
 6353: .LC_breadcrumb_tools_tools {
 6354:     padding: 0;
 6355:     margin: 0;
 6356:     float: right;
 6357: }
 6358: 
 6359: .LC_placement_prog {
 6360:     padding-right: 20px;
 6361:     font-weight: bold;
 6362:     font-size: 90%;
 6363: }
 6364: 
 6365: table#LC_title_bar td {
 6366:   background: $tabbg;
 6367: }
 6368: 
 6369: table#LC_menubuttons img {
 6370:   border: none;
 6371: }
 6372: 
 6373: .LC_breadcrumbs_component {
 6374:   float: right;
 6375:   margin: 0 1em;
 6376: }
 6377: .LC_breadcrumbs_component img {
 6378:   vertical-align: middle;
 6379: }
 6380: 
 6381: .LC_breadcrumbs_hoverable {
 6382:   background: $sidebg;
 6383: }
 6384: 
 6385: td.LC_table_cell_checkbox {
 6386:   text-align: center;
 6387: }
 6388: 
 6389: .LC_fontsize_small {
 6390:   font-size: 70%;
 6391: }
 6392: 
 6393: #LC_breadcrumbs {
 6394:   clear:both;
 6395:   background: $sidebg;
 6396:   border-bottom: 1px solid $lg_border_color;
 6397:   line-height: 2.5em;
 6398:   overflow: hidden;
 6399:   margin: 0;
 6400:   padding: 0;
 6401:   text-align: left;
 6402: }
 6403: 
 6404: .LC_head_subbox, .LC_actionbox {
 6405:   clear:both;
 6406:   background: #F8F8F8; /* $sidebg; */
 6407:   border: 1px solid $sidebg;
 6408:   margin: 0 0 10px 0;
 6409:   padding: 3px;
 6410:   text-align: left;
 6411: }
 6412: 
 6413: .LC_fontsize_medium {
 6414:   font-size: 85%;
 6415: }
 6416: 
 6417: .LC_fontsize_large {
 6418:   font-size: 120%;
 6419: }
 6420: 
 6421: .LC_menubuttons_inline_text {
 6422:   color: $font;
 6423:   font-size: 90%;
 6424:   padding-left:3px;
 6425: }
 6426: 
 6427: .LC_menubuttons_inline_text img{
 6428:   vertical-align: middle;
 6429: }
 6430: 
 6431: li.LC_menubuttons_inline_text img {
 6432:   cursor:pointer;
 6433:   text-decoration: none;
 6434: }
 6435: 
 6436: .LC_menubuttons_link {
 6437:   text-decoration: none;
 6438: }
 6439: 
 6440: .LC_menubuttons_category {
 6441:   color: $font;
 6442:   background: $pgbg;
 6443:   font-size: larger;
 6444:   font-weight: bold;
 6445: }
 6446: 
 6447: td.LC_menubuttons_text {
 6448:   color: $font;
 6449: }
 6450: 
 6451: .LC_current_location {
 6452:   background: $tabbg;
 6453: }
 6454: 
 6455: td.LC_zero_height {
 6456:   line-height: 0; 
 6457:   cellpadding: 0;
 6458: }
 6459: 
 6460: table.LC_data_table {
 6461:   border: 1px solid #000000;
 6462:   border-collapse: separate;
 6463:   border-spacing: 1px;
 6464:   background: $pgbg;
 6465: }
 6466: 
 6467: .LC_data_table_dense {
 6468:   font-size: small;
 6469: }
 6470: 
 6471: table.LC_nested_outer {
 6472:   border: 1px solid #000000;
 6473:   border-collapse: collapse;
 6474:   border-spacing: 0;
 6475:   width: 100%;
 6476: }
 6477: 
 6478: table.LC_innerpickbox,
 6479: table.LC_nested {
 6480:   border: none;
 6481:   border-collapse: collapse;
 6482:   border-spacing: 0;
 6483:   width: 100%;
 6484: }
 6485: 
 6486: table.LC_data_table tr th,
 6487: table.LC_calendar tr th,
 6488: table.LC_prior_tries tr th,
 6489: table.LC_innerpickbox tr th {
 6490:   font-weight: bold;
 6491:   background-color: $data_table_head;
 6492:   color:$fontmenu;
 6493:   font-size:90%;
 6494: }
 6495: 
 6496: table.LC_innerpickbox tr th,
 6497: table.LC_innerpickbox tr td {
 6498:   vertical-align: top;
 6499: }
 6500: 
 6501: table.LC_data_table tr.LC_info_row > td {
 6502:   background-color: #CCCCCC;
 6503:   font-weight: bold;
 6504:   text-align: left;
 6505: }
 6506: 
 6507: table.LC_data_table tr.LC_odd_row > td {
 6508:   background-color: $data_table_light;
 6509:   padding: 2px;
 6510:   vertical-align: top;
 6511: }
 6512: 
 6513: table.LC_pick_box tr > td.LC_odd_row {
 6514:   background-color: $data_table_light;
 6515:   vertical-align: top;
 6516: }
 6517: 
 6518: table.LC_data_table tr.LC_even_row > td {
 6519:   background-color: $data_table_dark;
 6520:   padding: 2px;
 6521:   vertical-align: top;
 6522: }
 6523: 
 6524: table.LC_pick_box tr > td.LC_even_row {
 6525:   background-color: $data_table_dark;
 6526:   vertical-align: top;
 6527: }
 6528: 
 6529: table.LC_data_table tr.LC_data_table_highlight td {
 6530:   background-color: $data_table_darker;
 6531: }
 6532: 
 6533: table.LC_data_table tr td.LC_leftcol_header {
 6534:   background-color: $data_table_head;
 6535:   font-weight: bold;
 6536: }
 6537: 
 6538: table.LC_data_table tr.LC_empty_row td,
 6539: table.LC_nested tr.LC_empty_row td {
 6540:   font-weight: bold;
 6541:   font-style: italic;
 6542:   text-align: center;
 6543:   padding: 8px;
 6544: }
 6545: 
 6546: table.LC_data_table tr.LC_empty_row td,
 6547: table.LC_data_table tr.LC_footer_row td {
 6548:   background-color: $sidebg;
 6549: }
 6550: 
 6551: table.LC_nested tr.LC_empty_row td {
 6552:   background-color: #FFFFFF;
 6553: }
 6554: 
 6555: table.LC_caption {
 6556: }
 6557: 
 6558: table.LC_nested tr.LC_empty_row td {
 6559:   padding: 4ex
 6560: }
 6561: 
 6562: table.LC_nested_outer tr th {
 6563:   font-weight: bold;
 6564:   color:$fontmenu;
 6565:   background-color: $data_table_head;
 6566:   font-size: small;
 6567:   border-bottom: 1px solid #000000;
 6568: }
 6569: 
 6570: table.LC_nested_outer tr td.LC_subheader {
 6571:   background-color: $data_table_head;
 6572:   font-weight: bold;
 6573:   font-size: small;
 6574:   border-bottom: 1px solid #000000;
 6575:   text-align: right;
 6576: }
 6577: 
 6578: table.LC_nested tr.LC_info_row td {
 6579:   background-color: #CCCCCC;
 6580:   font-weight: bold;
 6581:   font-size: small;
 6582:   text-align: center;
 6583: }
 6584: 
 6585: table.LC_nested tr.LC_info_row td.LC_left_item,
 6586: table.LC_nested_outer tr th.LC_left_item {
 6587:   text-align: left;
 6588: }
 6589: 
 6590: table.LC_nested td {
 6591:   background-color: #FFFFFF;
 6592:   font-size: small;
 6593: }
 6594: 
 6595: table.LC_nested_outer tr th.LC_right_item,
 6596: table.LC_nested tr.LC_info_row td.LC_right_item,
 6597: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6598: table.LC_nested tr td.LC_right_item {
 6599:   text-align: right;
 6600: }
 6601: 
 6602: table.LC_nested tr.LC_odd_row td {
 6603:   background-color: #EEEEEE;
 6604: }
 6605: 
 6606: table.LC_createuser {
 6607: }
 6608: 
 6609: table.LC_createuser tr.LC_section_row td {
 6610:   font-size: small;
 6611: }
 6612: 
 6613: table.LC_createuser tr.LC_info_row td  {
 6614:   background-color: #CCCCCC;
 6615:   font-weight: bold;
 6616:   text-align: center;
 6617: }
 6618: 
 6619: table.LC_calendar {
 6620:   border: 1px solid #000000;
 6621:   border-collapse: collapse;
 6622:   width: 98%;
 6623: }
 6624: 
 6625: table.LC_calendar_pickdate {
 6626:   font-size: xx-small;
 6627: }
 6628: 
 6629: table.LC_calendar tr td {
 6630:   border: 1px solid #000000;
 6631:   vertical-align: top;
 6632:   width: 14%;
 6633: }
 6634: 
 6635: table.LC_calendar tr td.LC_calendar_day_empty {
 6636:   background-color: $data_table_dark;
 6637: }
 6638: 
 6639: table.LC_calendar tr td.LC_calendar_day_current {
 6640:   background-color: $data_table_highlight;
 6641: }
 6642: 
 6643: table.LC_data_table tr td.LC_mail_new {
 6644:   background-color: $mail_new;
 6645: }
 6646: 
 6647: table.LC_data_table tr.LC_mail_new:hover {
 6648:   background-color: $mail_new_hover;
 6649: }
 6650: 
 6651: table.LC_data_table tr td.LC_mail_read {
 6652:   background-color: $mail_read;
 6653: }
 6654: 
 6655: /*
 6656: table.LC_data_table tr.LC_mail_read:hover {
 6657:   background-color: $mail_read_hover;
 6658: }
 6659: */
 6660: 
 6661: table.LC_data_table tr td.LC_mail_replied {
 6662:   background-color: $mail_replied;
 6663: }
 6664: 
 6665: /*
 6666: table.LC_data_table tr.LC_mail_replied:hover {
 6667:   background-color: $mail_replied_hover;
 6668: }
 6669: */
 6670: 
 6671: table.LC_data_table tr td.LC_mail_other {
 6672:   background-color: $mail_other;
 6673: }
 6674: 
 6675: /*
 6676: table.LC_data_table tr.LC_mail_other:hover {
 6677:   background-color: $mail_other_hover;
 6678: }
 6679: */
 6680: 
 6681: table.LC_data_table tr > td.LC_browser_file,
 6682: table.LC_data_table tr > td.LC_browser_file_published {
 6683:   background: #AAEE77;
 6684: }
 6685: 
 6686: table.LC_data_table tr > td.LC_browser_file_locked,
 6687: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6688:   background: #FFAA99;
 6689: }
 6690: 
 6691: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6692:   background: #888888;
 6693: }
 6694: 
 6695: table.LC_data_table tr > td.LC_browser_file_modified,
 6696: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6697:   background: #F8F866;
 6698: }
 6699: 
 6700: table.LC_data_table tr.LC_browser_folder > td {
 6701:   background: #E0E8FF;
 6702: }
 6703: 
 6704: table.LC_data_table tr > td.LC_roles_is {
 6705:   /* background: #77FF77; */
 6706: }
 6707: 
 6708: table.LC_data_table tr > td.LC_roles_future {
 6709:   border-right: 8px solid #FFFF77;
 6710: }
 6711: 
 6712: table.LC_data_table tr > td.LC_roles_will {
 6713:   border-right: 8px solid #FFAA77;
 6714: }
 6715: 
 6716: table.LC_data_table tr > td.LC_roles_expired {
 6717:   border-right: 8px solid #FF7777;
 6718: }
 6719: 
 6720: table.LC_data_table tr > td.LC_roles_will_not {
 6721:   border-right: 8px solid #AAFF77;
 6722: }
 6723: 
 6724: table.LC_data_table tr > td.LC_roles_selected {
 6725:   border-right: 8px solid #11CC55;
 6726: }
 6727: 
 6728: span.LC_current_location {
 6729:   font-size:larger;
 6730:   background: $pgbg;
 6731: }
 6732: 
 6733: span.LC_current_nav_location {
 6734:   font-weight:bold;
 6735:   background: $sidebg;
 6736: }
 6737: 
 6738: span.LC_parm_menu_item {
 6739:   font-size: larger;
 6740: }
 6741: 
 6742: span.LC_parm_scope_all {
 6743:   color: red;
 6744: }
 6745: 
 6746: span.LC_parm_scope_folder {
 6747:   color: green;
 6748: }
 6749: 
 6750: span.LC_parm_scope_resource {
 6751:   color: orange;
 6752: }
 6753: 
 6754: span.LC_parm_part {
 6755:   color: blue;
 6756: }
 6757: 
 6758: span.LC_parm_folder,
 6759: span.LC_parm_symb {
 6760:   font-size: x-small;
 6761:   font-family: $mono;
 6762:   color: #AAAAAA;
 6763: }
 6764: 
 6765: ul.LC_parm_parmlist li {
 6766:   display: inline-block;
 6767:   padding: 0.3em 0.8em;
 6768:   vertical-align: top;
 6769:   width: 150px;
 6770:   border-top:1px solid $lg_border_color;
 6771: }
 6772: 
 6773: td.LC_parm_overview_level_menu,
 6774: td.LC_parm_overview_map_menu,
 6775: td.LC_parm_overview_parm_selectors,
 6776: td.LC_parm_overview_restrictions  {
 6777:   border: 1px solid black;
 6778:   border-collapse: collapse;
 6779: }
 6780: 
 6781: span.LC_parm_recursive,
 6782: td.LC_parm_recursive {
 6783:   font-weight: bold;
 6784:   font-size: smaller;
 6785: }
 6786: 
 6787: table.LC_parm_overview_restrictions td {
 6788:   border-width: 1px 4px 1px 4px;
 6789:   border-style: solid;
 6790:   border-color: $pgbg;
 6791:   text-align: center;
 6792: }
 6793: 
 6794: table.LC_parm_overview_restrictions th {
 6795:   background: $tabbg;
 6796:   border-width: 1px 4px 1px 4px;
 6797:   border-style: solid;
 6798:   border-color: $pgbg;
 6799: }
 6800: 
 6801: table#LC_helpmenu {
 6802:   border: none;
 6803:   height: 55px;
 6804:   border-spacing: 0;
 6805: }
 6806: 
 6807: table#LC_helpmenu fieldset legend {
 6808:   font-size: larger;
 6809: }
 6810: 
 6811: table#LC_helpmenu_links {
 6812:   width: 100%;
 6813:   border: 1px solid black;
 6814:   background: $pgbg;
 6815:   padding: 0;
 6816:   border-spacing: 1px;
 6817: }
 6818: 
 6819: table#LC_helpmenu_links tr td {
 6820:   padding: 1px;
 6821:   background: $tabbg;
 6822:   text-align: center;
 6823:   font-weight: bold;
 6824: }
 6825: 
 6826: table#LC_helpmenu_links a:link,
 6827: table#LC_helpmenu_links a:visited,
 6828: table#LC_helpmenu_links a:active {
 6829:   text-decoration: none;
 6830:   color: $font;
 6831: }
 6832: 
 6833: table#LC_helpmenu_links a:hover {
 6834:   text-decoration: underline;
 6835:   color: $vlink;
 6836: }
 6837: 
 6838: .LC_chrt_popup_exists {
 6839:   border: 1px solid #339933;
 6840:   margin: -1px;
 6841: }
 6842: 
 6843: .LC_chrt_popup_up {
 6844:   border: 1px solid yellow;
 6845:   margin: -1px;
 6846: }
 6847: 
 6848: .LC_chrt_popup {
 6849:   border: 1px solid #8888FF;
 6850:   background: #CCCCFF;
 6851: }
 6852: 
 6853: table.LC_pick_box {
 6854:   border-collapse: separate;
 6855:   background: white;
 6856:   border: 1px solid black;
 6857:   border-spacing: 1px;
 6858: }
 6859: 
 6860: table.LC_pick_box td.LC_pick_box_title {
 6861:   background: $sidebg;
 6862:   font-weight: bold;
 6863:   text-align: left;
 6864:   vertical-align: top;
 6865:   width: 184px;
 6866:   padding: 8px;
 6867: }
 6868: 
 6869: table.LC_pick_box td.LC_pick_box_value {
 6870:   text-align: left;
 6871:   padding: 8px;
 6872: }
 6873: 
 6874: table.LC_pick_box td.LC_pick_box_select {
 6875:   text-align: left;
 6876:   padding: 8px;
 6877: }
 6878: 
 6879: table.LC_pick_box td.LC_pick_box_separator {
 6880:   padding: 0;
 6881:   height: 1px;
 6882:   background: black;
 6883: }
 6884: 
 6885: table.LC_pick_box td.LC_pick_box_submit {
 6886:   text-align: right;
 6887: }
 6888: 
 6889: table.LC_pick_box td.LC_evenrow_value {
 6890:   text-align: left;
 6891:   padding: 8px;
 6892:   background-color: $data_table_light;
 6893: }
 6894: 
 6895: table.LC_pick_box td.LC_oddrow_value {
 6896:   text-align: left;
 6897:   padding: 8px;
 6898:   background-color: $data_table_light;
 6899: }
 6900: 
 6901: span.LC_helpform_receipt_cat {
 6902:   font-weight: bold;
 6903: }
 6904: 
 6905: table.LC_group_priv_box {
 6906:   background: white;
 6907:   border: 1px solid black;
 6908:   border-spacing: 1px;
 6909: }
 6910: 
 6911: table.LC_group_priv_box td.LC_pick_box_title {
 6912:   background: $tabbg;
 6913:   font-weight: bold;
 6914:   text-align: right;
 6915:   width: 184px;
 6916: }
 6917: 
 6918: table.LC_group_priv_box td.LC_groups_fixed {
 6919:   background: $data_table_light;
 6920:   text-align: center;
 6921: }
 6922: 
 6923: table.LC_group_priv_box td.LC_groups_optional {
 6924:   background: $data_table_dark;
 6925:   text-align: center;
 6926: }
 6927: 
 6928: table.LC_group_priv_box td.LC_groups_functionality {
 6929:   background: $data_table_darker;
 6930:   text-align: center;
 6931:   font-weight: bold;
 6932: }
 6933: 
 6934: table.LC_group_priv td {
 6935:   text-align: left;
 6936:   padding: 0;
 6937: }
 6938: 
 6939: .LC_navbuttons {
 6940:   margin: 2ex 0ex 2ex 0ex;
 6941: }
 6942: 
 6943: .LC_topic_bar {
 6944:   font-weight: bold;
 6945:   background: $tabbg;
 6946:   margin: 1em 0em 1em 2em;
 6947:   padding: 3px;
 6948:   font-size: 1.2em;
 6949: }
 6950: 
 6951: .LC_topic_bar span {
 6952:   left: 0.5em;
 6953:   position: absolute;
 6954:   vertical-align: middle;
 6955:   font-size: 1.2em;
 6956: }
 6957: 
 6958: table.LC_course_group_status {
 6959:   margin: 20px;
 6960: }
 6961: 
 6962: table.LC_status_selector td {
 6963:   vertical-align: top;
 6964:   text-align: center;
 6965:   padding: 4px;
 6966: }
 6967: 
 6968: div.LC_feedback_link {
 6969:   clear: both;
 6970:   background: $sidebg;
 6971:   width: 100%;
 6972:   padding-bottom: 10px;
 6973:   border: 1px $tabbg solid;
 6974:   height: 22px;
 6975:   line-height: 22px;
 6976:   padding-top: 5px;
 6977: }
 6978: 
 6979: div.LC_feedback_link img {
 6980:   height: 22px;
 6981:   vertical-align:middle;
 6982: }
 6983: 
 6984: div.LC_feedback_link a {
 6985:   text-decoration: none;
 6986: }
 6987: 
 6988: div.LC_comblock {
 6989:   display:inline;
 6990:   color:$font;
 6991:   font-size:90%;
 6992: }
 6993: 
 6994: div.LC_feedback_link div.LC_comblock {
 6995:   padding-left:5px;
 6996: }
 6997: 
 6998: div.LC_feedback_link div.LC_comblock a {
 6999:   color:$font;
 7000: }
 7001: 
 7002: span.LC_feedback_link {
 7003:   /* background: $feedback_link_bg; */
 7004:   font-size: larger;
 7005: }
 7006: 
 7007: span.LC_message_link {
 7008:   /* background: $feedback_link_bg; */
 7009:   font-size: larger;
 7010:   position: absolute;
 7011:   right: 1em;
 7012: }
 7013: 
 7014: table.LC_prior_tries {
 7015:   border: 1px solid #000000;
 7016:   border-collapse: separate;
 7017:   border-spacing: 1px;
 7018: }
 7019: 
 7020: table.LC_prior_tries td {
 7021:   padding: 2px;
 7022: }
 7023: 
 7024: .LC_answer_correct {
 7025:   background: lightgreen;
 7026:   color: darkgreen;
 7027:   padding: 6px;
 7028: }
 7029: 
 7030: .LC_answer_charged_try {
 7031:   background: #FFAAAA;
 7032:   color: darkred;
 7033:   padding: 6px;
 7034: }
 7035: 
 7036: .LC_answer_not_charged_try,
 7037: .LC_answer_no_grade,
 7038: .LC_answer_late {
 7039:   background: lightyellow;
 7040:   color: black;
 7041:   padding: 6px;
 7042: }
 7043: 
 7044: .LC_answer_previous {
 7045:   background: lightblue;
 7046:   color: darkblue;
 7047:   padding: 6px;
 7048: }
 7049: 
 7050: .LC_answer_no_message {
 7051:   background: #FFFFFF;
 7052:   color: black;
 7053:   padding: 6px;
 7054: }
 7055: 
 7056: .LC_answer_unknown {
 7057:   background: orange;
 7058:   color: black;
 7059:   padding: 6px;
 7060: }
 7061: 
 7062: span.LC_prior_numerical,
 7063: span.LC_prior_string,
 7064: span.LC_prior_custom,
 7065: span.LC_prior_reaction,
 7066: span.LC_prior_math {
 7067:   font-family: $mono;
 7068:   white-space: pre;
 7069: }
 7070: 
 7071: span.LC_prior_string {
 7072:   font-family: $mono;
 7073:   white-space: pre;
 7074: }
 7075: 
 7076: table.LC_prior_option {
 7077:   width: 100%;
 7078:   border-collapse: collapse;
 7079: }
 7080: 
 7081: table.LC_prior_rank,
 7082: table.LC_prior_match {
 7083:   border-collapse: collapse;
 7084: }
 7085: 
 7086: table.LC_prior_option tr td,
 7087: table.LC_prior_rank tr td,
 7088: table.LC_prior_match tr td {
 7089:   border: 1px solid #000000;
 7090: }
 7091: 
 7092: .LC_nobreak {
 7093:   white-space: nowrap;
 7094: }
 7095: 
 7096: span.LC_cusr_emph {
 7097:   font-style: italic;
 7098: }
 7099: 
 7100: span.LC_cusr_subheading {
 7101:   font-weight: normal;
 7102:   font-size: 85%;
 7103: }
 7104: 
 7105: div.LC_docs_entry_move {
 7106:   border: 1px solid #BBBBBB;
 7107:   background: #DDDDDD;
 7108:   width: 22px;
 7109:   padding: 1px;
 7110:   margin: 0;
 7111: }
 7112: 
 7113: table.LC_data_table tr > td.LC_docs_entry_commands,
 7114: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7115:   font-size: x-small;
 7116: }
 7117: 
 7118: .LC_docs_entry_parameter {
 7119:   white-space: nowrap;
 7120: }
 7121: 
 7122: .LC_docs_copy {
 7123:   color: #000099;
 7124: }
 7125: 
 7126: .LC_docs_cut {
 7127:   color: #550044;
 7128: }
 7129: 
 7130: .LC_docs_rename {
 7131:   color: #009900;
 7132: }
 7133: 
 7134: .LC_docs_remove {
 7135:   color: #990000;
 7136: }
 7137: 
 7138: .LC_docs_alias {
 7139:   color: #440055;  
 7140: }
 7141: 
 7142: .LC_domprefs_email,
 7143: .LC_docs_alias_name,
 7144: .LC_docs_reinit_warn,
 7145: .LC_docs_ext_edit {
 7146:   font-size: x-small;
 7147: }
 7148: 
 7149: table.LC_docs_adddocs td,
 7150: table.LC_docs_adddocs th {
 7151:   border: 1px solid #BBBBBB;
 7152:   padding: 4px;
 7153:   background: #DDDDDD;
 7154: }
 7155: 
 7156: table.LC_sty_begin {
 7157:   background: #BBFFBB;
 7158: }
 7159: 
 7160: table.LC_sty_end {
 7161:   background: #FFBBBB;
 7162: }
 7163: 
 7164: table.LC_double_column {
 7165:   border-width: 0;
 7166:   border-collapse: collapse;
 7167:   width: 100%;
 7168:   padding: 2px;
 7169: }
 7170: 
 7171: table.LC_double_column tr td.LC_left_col {
 7172:   top: 2px;
 7173:   left: 2px;
 7174:   width: 47%;
 7175:   vertical-align: top;
 7176: }
 7177: 
 7178: table.LC_double_column tr td.LC_right_col {
 7179:   top: 2px;
 7180:   right: 2px;
 7181:   width: 47%;
 7182:   vertical-align: top;
 7183: }
 7184: 
 7185: div.LC_left_float {
 7186:   float: left;
 7187:   padding-right: 5%;
 7188:   padding-bottom: 4px;
 7189: }
 7190: 
 7191: div.LC_clear_float_header {
 7192:   padding-bottom: 2px;
 7193: }
 7194: 
 7195: div.LC_clear_float_footer {
 7196:   padding-top: 10px;
 7197:   clear: both;
 7198: }
 7199: 
 7200: div.LC_grade_show_user {
 7201: /*  border-left: 5px solid $sidebg; */
 7202:   border-top: 5px solid #000000;
 7203:   margin: 50px 0 0 0;
 7204:   padding: 15px 0 5px 10px;
 7205: }
 7206: 
 7207: div.LC_grade_show_user_odd_row {
 7208: /*  border-left: 5px solid #000000; */
 7209: }
 7210: 
 7211: div.LC_grade_show_user div.LC_Box {
 7212:   margin-right: 50px;
 7213: }
 7214: 
 7215: div.LC_grade_submissions,
 7216: div.LC_grade_message_center,
 7217: div.LC_grade_info_links {
 7218:   margin: 5px;
 7219:   width: 99%;
 7220:   background: #FFFFFF;
 7221: }
 7222: 
 7223: div.LC_grade_submissions_header,
 7224: div.LC_grade_message_center_header {
 7225:   font-weight: bold;
 7226:   font-size: large;
 7227: }
 7228: 
 7229: div.LC_grade_submissions_body,
 7230: div.LC_grade_message_center_body {
 7231:   border: 1px solid black;
 7232:   width: 99%;
 7233:   background: #FFFFFF;
 7234: }
 7235: 
 7236: table.LC_scantron_action {
 7237:   width: 100%;
 7238: }
 7239: 
 7240: table.LC_scantron_action tr th {
 7241:   font-weight:bold;
 7242:   font-style:normal;
 7243: }
 7244: 
 7245: .LC_edit_problem_header,
 7246: div.LC_edit_problem_footer {
 7247:   font-weight: normal;
 7248:   font-size:  medium;
 7249:   margin: 2px;
 7250:   background-color: $sidebg;
 7251: }
 7252: 
 7253: div.LC_edit_problem_header,
 7254: div.LC_edit_problem_header div,
 7255: div.LC_edit_problem_footer,
 7256: div.LC_edit_problem_footer div,
 7257: div.LC_edit_problem_editxml_header,
 7258: div.LC_edit_problem_editxml_header div {
 7259:   z-index: 100;
 7260: }
 7261: 
 7262: div.LC_edit_problem_header_title {
 7263:   font-weight: bold;
 7264:   font-size: larger;
 7265:   background: $tabbg;
 7266:   padding: 3px;
 7267:   margin: 0 0 5px 0;
 7268: }
 7269: 
 7270: table.LC_edit_problem_header_title {
 7271:   width: 100%;
 7272:   background: $tabbg;
 7273: }
 7274: 
 7275: div.LC_edit_actionbar {
 7276:     background-color: $sidebg;
 7277:     margin: 0;
 7278:     padding: 0;
 7279:     line-height: 200%;
 7280: }
 7281: 
 7282: div.LC_edit_actionbar div{
 7283:     padding: 0;
 7284:     margin: 0;
 7285:     display: inline-block;
 7286: }
 7287: 
 7288: .LC_edit_opt {
 7289:   padding-left: 1em;
 7290:   white-space: nowrap;
 7291: }
 7292: 
 7293: .LC_edit_problem_latexhelper{
 7294:     text-align: right;
 7295: }
 7296: 
 7297: #LC_edit_problem_colorful div{
 7298:     margin-left: 40px;
 7299: }
 7300: 
 7301: #LC_edit_problem_codemirror div{
 7302:     margin-left: 0px;
 7303: }
 7304: 
 7305: img.stift {
 7306:   border-width: 0;
 7307:   vertical-align: middle;
 7308: }
 7309: 
 7310: table td.LC_mainmenu_col_fieldset {
 7311:   vertical-align: top;
 7312: }
 7313: 
 7314: div.LC_createcourse {
 7315:   margin: 10px 10px 10px 10px;
 7316: }
 7317: 
 7318: .LC_dccid {
 7319:   float: right;
 7320:   margin: 0.2em 0 0 0;
 7321:   padding: 0;
 7322:   font-size: 90%;
 7323:   display:none;
 7324: }
 7325: 
 7326: ol.LC_primary_menu a:hover,
 7327: ol#LC_MenuBreadcrumbs a:hover,
 7328: ol#LC_PathBreadcrumbs a:hover,
 7329: ul#LC_secondary_menu a:hover,
 7330: .LC_FormSectionClearButton input:hover
 7331: ul.LC_TabContent   li:hover a {
 7332:   color:$button_hover;
 7333:   text-decoration:none;
 7334: }
 7335: 
 7336: h1 {
 7337:   padding: 0;
 7338:   line-height:130%;
 7339: }
 7340: 
 7341: h2,
 7342: h3,
 7343: h4,
 7344: h5,
 7345: h6 {
 7346:   margin: 5px 0 5px 0;
 7347:   padding: 0;
 7348:   line-height:130%;
 7349: }
 7350: 
 7351: .LC_hcell {
 7352:   padding:3px 15px 3px 15px;
 7353:   margin: 0;
 7354:   background-color:$tabbg;
 7355:   color:$fontmenu;
 7356:   border-bottom:solid 1px $lg_border_color;
 7357: }
 7358: 
 7359: .LC_Box > .LC_hcell {
 7360:   margin: 0 -10px 10px -10px;
 7361: }
 7362: 
 7363: .LC_noBorder {
 7364:   border: 0;
 7365: }
 7366: 
 7367: .LC_FormSectionClearButton input {
 7368:   background-color:transparent;
 7369:   border: none;
 7370:   cursor:pointer;
 7371:   text-decoration:underline;
 7372: }
 7373: 
 7374: .LC_help_open_topic {
 7375:   color: #FFFFFF;
 7376:   background-color: #EEEEFF;
 7377:   margin: 1px;
 7378:   padding: 4px;
 7379:   border: 1px solid #000033;
 7380:   white-space: nowrap;
 7381:   /* vertical-align: middle; */
 7382: }
 7383: 
 7384: dl,
 7385: ul,
 7386: div,
 7387: fieldset {
 7388:   margin: 10px 10px 10px 0;
 7389:   /* overflow: hidden; */
 7390: }
 7391: 
 7392: article.geogebraweb div {
 7393:     margin: 0;
 7394: }
 7395: 
 7396: fieldset > legend {
 7397:   font-weight: bold;
 7398:   padding: 0 5px 0 5px;
 7399: }
 7400: 
 7401: #LC_nav_bar {
 7402:   float: left;
 7403:   background-color: $pgbg_or_bgcolor;
 7404:   margin: 0 0 2px 0;
 7405: }
 7406: 
 7407: #LC_realm {
 7408:   margin: 0.2em 0 0 0;
 7409:   padding: 0;
 7410:   font-weight: bold;
 7411:   text-align: center;
 7412:   background-color: $pgbg_or_bgcolor;
 7413: }
 7414: 
 7415: #LC_nav_bar em {
 7416:   font-weight: bold;
 7417:   font-style: normal;
 7418: }
 7419: 
 7420: ol.LC_primary_menu {
 7421:   margin: 0;
 7422:   padding: 0;
 7423: }
 7424: 
 7425: ol#LC_PathBreadcrumbs {
 7426:   margin: 0;
 7427: }
 7428: 
 7429: ol.LC_primary_menu li {
 7430:   color: RGB(80, 80, 80);
 7431:   vertical-align: middle;
 7432:   text-align: left;
 7433:   list-style: none;
 7434:   position: relative;
 7435:   float: left;
 7436:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7437:   line-height: 1.5em;
 7438: }
 7439: 
 7440: ol.LC_primary_menu li a,
 7441: ol.LC_primary_menu li p {
 7442:   display: block;
 7443:   margin: 0;
 7444:   padding: 0 5px 0 10px;
 7445:   text-decoration: none;
 7446: }
 7447: 
 7448: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7449:   display: inline-block;
 7450:   width: 95%;
 7451:   text-align: left;
 7452: }
 7453: 
 7454: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7455:   display: inline-block;	
 7456:   width: 5%;
 7457:   float: right;
 7458:   text-align: right;
 7459:   font-size: 70%;
 7460: }
 7461: 
 7462: ol.LC_primary_menu ul {
 7463:   display: none;
 7464:   width: 15em;
 7465:   background-color: $data_table_light;
 7466:   position: absolute;
 7467:   top: 100%;
 7468: }
 7469: 
 7470: ol.LC_primary_menu ul ul {
 7471:   left: 100%;
 7472:   top: 0;
 7473: }
 7474: 
 7475: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7476:   display: block;
 7477:   position: absolute;
 7478:   margin: 0;
 7479:   padding: 0;
 7480:   z-index: 2;
 7481: }
 7482: 
 7483: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7484: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7485:   font-size: 90%;
 7486:   vertical-align: top;
 7487:   float: none;
 7488:   border-left: 1px solid black;
 7489:   border-right: 1px solid black;
 7490: /* A dark bottom border to visualize different menu options; 
 7491: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7492:   border-bottom: 1px solid $data_table_dark; 
 7493: }
 7494: 
 7495: ol.LC_primary_menu li li p:hover {
 7496:   color:$button_hover;
 7497:   text-decoration:none;
 7498:   background-color:$data_table_dark;
 7499: }
 7500: 
 7501: ol.LC_primary_menu li li a:hover {
 7502:    color:$button_hover;
 7503:    background-color:$data_table_dark;
 7504: }
 7505: 
 7506: /* Font-size equal to the size of the predecessors*/
 7507: ol.LC_primary_menu li:hover li li {
 7508:   font-size: 100%;
 7509: }
 7510: 
 7511: ol.LC_primary_menu li img {
 7512:   vertical-align: bottom;
 7513:   height: 1.1em;
 7514:   margin: 0.2em 0 0 0;
 7515: }
 7516: 
 7517: ol.LC_primary_menu a {
 7518:   color: RGB(80, 80, 80);
 7519:   text-decoration: none;
 7520: }
 7521: 
 7522: ol.LC_primary_menu a.LC_new_message {
 7523:   font-weight:bold;
 7524:   color: darkred;
 7525: }
 7526: 
 7527: ol.LC_docs_parameters {
 7528:   margin-left: 0;
 7529:   padding: 0;
 7530:   list-style: none;
 7531: }
 7532: 
 7533: ol.LC_docs_parameters li {
 7534:   margin: 0;
 7535:   padding-right: 20px;
 7536:   display: inline;
 7537: }
 7538: 
 7539: ol.LC_docs_parameters li:before {
 7540:   content: "\\002022 \\0020";
 7541: }
 7542: 
 7543: li.LC_docs_parameters_title {
 7544:   font-weight: bold;
 7545: }
 7546: 
 7547: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7548:   content: "";
 7549: }
 7550: 
 7551: ul#LC_secondary_menu {
 7552:   clear: right;
 7553:   color: $fontmenu;
 7554:   background: $tabbg;
 7555:   list-style: none;
 7556:   padding: 0;
 7557:   margin: 0;
 7558:   width: 100%;
 7559:   text-align: left;
 7560:   float: left;
 7561: }
 7562: 
 7563: ul#LC_secondary_menu li {
 7564:   font-weight: bold;
 7565:   line-height: 1.8em;
 7566:   border-right: 1px solid black;
 7567:   float: left;
 7568: }
 7569: 
 7570: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7571:   background-color: $data_table_light;
 7572: }
 7573: 
 7574: ul#LC_secondary_menu li a {
 7575:   padding: 0 0.8em;
 7576: }
 7577: 
 7578: ul#LC_secondary_menu li ul {
 7579:   display: none;
 7580: }
 7581: 
 7582: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7583:   display: block;
 7584:   position: absolute;
 7585:   margin: 0;
 7586:   padding: 0;
 7587:   list-style:none;
 7588:   float: none;
 7589:   background-color: $data_table_light;
 7590:   z-index: 2;
 7591:   margin-left: -1px;
 7592: }
 7593: 
 7594: ul#LC_secondary_menu li ul li {
 7595:   font-size: 90%;
 7596:   vertical-align: top;
 7597:   border-left: 1px solid black;
 7598:   border-right: 1px solid black;
 7599:   background-color: $data_table_light;
 7600:   list-style:none;
 7601:   float: none;
 7602: }
 7603: 
 7604: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7605:   background-color: $data_table_dark;
 7606: }
 7607: 
 7608: ul.LC_TabContent {
 7609:   display:block;
 7610:   background: $sidebg;
 7611:   border-bottom: solid 1px $lg_border_color;
 7612:   list-style:none;
 7613:   margin: -1px -10px 0 -10px;
 7614:   padding: 0;
 7615: }
 7616: 
 7617: ul.LC_TabContent li,
 7618: ul.LC_TabContentBigger li {
 7619:   float:left;
 7620: }
 7621: 
 7622: ul#LC_secondary_menu li a {
 7623:   color: $fontmenu;
 7624:   text-decoration: none;
 7625: }
 7626: 
 7627: ul.LC_TabContent {
 7628:   min-height:20px;
 7629: }
 7630: 
 7631: ul.LC_TabContent li {
 7632:   vertical-align:middle;
 7633:   padding: 0 16px 0 10px;
 7634:   background-color:$tabbg;
 7635:   border-bottom:solid 1px $lg_border_color;
 7636:   border-left: solid 1px $font;
 7637: }
 7638: 
 7639: ul.LC_TabContent .right {
 7640:   float:right;
 7641: }
 7642: 
 7643: ul.LC_TabContent li a,
 7644: ul.LC_TabContent li {
 7645:   color:rgb(47,47,47);
 7646:   text-decoration:none;
 7647:   font-size:95%;
 7648:   font-weight:bold;
 7649:   min-height:20px;
 7650: }
 7651: 
 7652: ul.LC_TabContent li a:hover,
 7653: ul.LC_TabContent li a:focus {
 7654:   color: $button_hover;
 7655:   background:none;
 7656:   outline:none;
 7657: }
 7658: 
 7659: ul.LC_TabContent li:hover {
 7660:   color: $button_hover;
 7661:   cursor:pointer;
 7662: }
 7663: 
 7664: ul.LC_TabContent li.active {
 7665:   color: $font;
 7666:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7667:   border-bottom:solid 1px #FFFFFF;
 7668:   cursor: default;
 7669: }
 7670: 
 7671: ul.LC_TabContent li.active a {
 7672:   color:$font;
 7673:   background:#FFFFFF;
 7674:   outline: none;
 7675: }
 7676: 
 7677: ul.LC_TabContent li.goback {
 7678:   float: left;
 7679:   border-left: none;
 7680: }
 7681: 
 7682: #maincoursedoc {
 7683:   clear:both;
 7684: }
 7685: 
 7686: ul.LC_TabContentBigger {
 7687:   display:block;
 7688:   list-style:none;
 7689:   padding: 0;
 7690: }
 7691: 
 7692: ul.LC_TabContentBigger li {
 7693:   vertical-align:bottom;
 7694:   height: 30px;
 7695:   font-size:110%;
 7696:   font-weight:bold;
 7697:   color: #737373;
 7698: }
 7699: 
 7700: ul.LC_TabContentBigger li.active {
 7701:   position: relative;
 7702:   top: 1px;
 7703: }
 7704: 
 7705: ul.LC_TabContentBigger li a {
 7706:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7707:   height: 30px;
 7708:   line-height: 30px;
 7709:   text-align: center;
 7710:   display: block;
 7711:   text-decoration: none;
 7712:   outline: none;  
 7713: }
 7714: 
 7715: ul.LC_TabContentBigger li.active a {
 7716:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7717:   color:$font;
 7718: }
 7719: 
 7720: ul.LC_TabContentBigger li b {
 7721:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7722:   display: block;
 7723:   float: left;
 7724:   padding: 0 30px;
 7725:   border-bottom: 1px solid $lg_border_color;
 7726: }
 7727: 
 7728: ul.LC_TabContentBigger li:hover b {
 7729:   color:$button_hover;
 7730: }
 7731: 
 7732: ul.LC_TabContentBigger li.active b {
 7733:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7734:   color:$font;
 7735:   border: 0;
 7736: }
 7737: 
 7738: 
 7739: ul.LC_CourseBreadcrumbs {
 7740:   background: $sidebg;
 7741:   height: 2em;
 7742:   padding-left: 10px;
 7743:   margin: 0;
 7744:   list-style-position: inside;
 7745: }
 7746: 
 7747: ol#LC_MenuBreadcrumbs,
 7748: ol#LC_PathBreadcrumbs {
 7749:   padding-left: 10px;
 7750:   margin: 0;
 7751:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7752: }
 7753: 
 7754: ol#LC_MenuBreadcrumbs li,
 7755: ol#LC_PathBreadcrumbs li,
 7756: ul.LC_CourseBreadcrumbs li {
 7757:   display: inline;
 7758:   white-space: normal;  
 7759: }
 7760: 
 7761: ol#LC_MenuBreadcrumbs li a,
 7762: ul.LC_CourseBreadcrumbs li a {
 7763:   text-decoration: none;
 7764:   font-size:90%;
 7765: }
 7766: 
 7767: ol#LC_MenuBreadcrumbs h1 {
 7768:   display: inline;
 7769:   font-size: 90%;
 7770:   line-height: 2.5em;
 7771:   margin: 0;
 7772:   padding: 0;
 7773: }
 7774: 
 7775: ol#LC_PathBreadcrumbs li a {
 7776:   text-decoration:none;
 7777:   font-size:100%;
 7778:   font-weight:bold;
 7779: }
 7780: 
 7781: .LC_Box {
 7782:   border: solid 1px $lg_border_color;
 7783:   padding: 0 10px 10px 10px;
 7784: }
 7785: 
 7786: .LC_DocsBox {
 7787:   border: solid 1px $lg_border_color;
 7788:   padding: 0 0 10px 10px;
 7789: }
 7790: 
 7791: .LC_AboutMe_Image {
 7792:   float:left;
 7793:   margin-right:10px;
 7794: }
 7795: 
 7796: .LC_Clear_AboutMe_Image {
 7797:   clear:left;
 7798: }
 7799: 
 7800: dl.LC_ListStyleClean dt {
 7801:   padding-right: 5px;
 7802:   display: table-header-group;
 7803: }
 7804: 
 7805: dl.LC_ListStyleClean dd {
 7806:   display: table-row;
 7807: }
 7808: 
 7809: .LC_ListStyleClean,
 7810: .LC_ListStyleSimple,
 7811: .LC_ListStyleNormal,
 7812: .LC_ListStyleSpecial {
 7813:   /* display:block; */
 7814:   list-style-position: inside;
 7815:   list-style-type: none;
 7816:   overflow: hidden;
 7817:   padding: 0;
 7818: }
 7819: 
 7820: .LC_ListStyleSimple li,
 7821: .LC_ListStyleSimple dd,
 7822: .LC_ListStyleNormal li,
 7823: .LC_ListStyleNormal dd,
 7824: .LC_ListStyleSpecial li,
 7825: .LC_ListStyleSpecial dd {
 7826:   margin: 0;
 7827:   padding: 5px 5px 5px 10px;
 7828:   clear: both;
 7829: }
 7830: 
 7831: .LC_ListStyleClean li,
 7832: .LC_ListStyleClean dd {
 7833:   padding-top: 0;
 7834:   padding-bottom: 0;
 7835: }
 7836: 
 7837: .LC_ListStyleSimple dd,
 7838: .LC_ListStyleSimple li {
 7839:   border-bottom: solid 1px $lg_border_color;
 7840: }
 7841: 
 7842: .LC_ListStyleSpecial li,
 7843: .LC_ListStyleSpecial dd {
 7844:   list-style-type: none;
 7845:   background-color: RGB(220, 220, 220);
 7846:   margin-bottom: 4px;
 7847: }
 7848: 
 7849: table.LC_SimpleTable {
 7850:   margin:5px;
 7851:   border:solid 1px $lg_border_color;
 7852: }
 7853: 
 7854: table.LC_SimpleTable tr {
 7855:   padding: 0;
 7856:   border:solid 1px $lg_border_color;
 7857: }
 7858: 
 7859: table.LC_SimpleTable thead {
 7860:   background:rgb(220,220,220);
 7861: }
 7862: 
 7863: div.LC_columnSection {
 7864:   display: block;
 7865:   clear: both;
 7866:   overflow: hidden;
 7867:   margin: 0;
 7868: }
 7869: 
 7870: div.LC_columnSection>* {
 7871:   float: left;
 7872:   margin: 10px 20px 10px 0;
 7873:   overflow:hidden;
 7874: }
 7875: 
 7876: table em {
 7877:   font-weight: bold;
 7878:   font-style: normal;
 7879: }
 7880: 
 7881: table.LC_tableBrowseRes,
 7882: table.LC_tableOfContent {
 7883:   border:none;
 7884:   border-spacing: 1px;
 7885:   padding: 3px;
 7886:   background-color: #FFFFFF;
 7887:   font-size: 90%;
 7888: }
 7889: 
 7890: table.LC_tableOfContent {
 7891:   border-collapse: collapse;
 7892: }
 7893: 
 7894: table.LC_tableBrowseRes a,
 7895: table.LC_tableOfContent a {
 7896:   background-color: transparent;
 7897:   text-decoration: none;
 7898: }
 7899: 
 7900: table.LC_tableOfContent img {
 7901:   border: none;
 7902:   height: 1.3em;
 7903:   vertical-align: text-bottom;
 7904:   margin-right: 0.3em;
 7905: }
 7906: 
 7907: a#LC_content_toolbar_firsthomework {
 7908:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7909: }
 7910: 
 7911: a#LC_content_toolbar_everything {
 7912:   background-image:url(/res/adm/pages/show-all.gif);
 7913: }
 7914: 
 7915: a#LC_content_toolbar_uncompleted {
 7916:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7917: }
 7918: 
 7919: #LC_content_toolbar_clearbubbles {
 7920:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7921: }
 7922: 
 7923: a#LC_content_toolbar_changefolder {
 7924:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7925: }
 7926: 
 7927: a#LC_content_toolbar_changefolder_toggled {
 7928:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7929: }
 7930: 
 7931: a#LC_content_toolbar_edittoplevel {
 7932:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7933: }
 7934: 
 7935: ul#LC_toolbar li a:hover {
 7936:   background-position: bottom center;
 7937: }
 7938: 
 7939: ul#LC_toolbar {
 7940:   padding: 0;
 7941:   margin: 2px;
 7942:   list-style:none;
 7943:   position:relative;
 7944:   background-color:white;
 7945:   overflow: auto;
 7946: }
 7947: 
 7948: ul#LC_toolbar li {
 7949:   border:1px solid white;
 7950:   padding: 0;
 7951:   margin: 0;
 7952:   float: left;
 7953:   display:inline;
 7954:   vertical-align:middle;
 7955:   white-space: nowrap;
 7956: }
 7957: 
 7958: 
 7959: a.LC_toolbarItem {
 7960:   display:block;
 7961:   padding: 0;
 7962:   margin: 0;
 7963:   height: 32px;
 7964:   width: 32px;
 7965:   color:white;
 7966:   border: none;
 7967:   background-repeat:no-repeat;
 7968:   background-color:transparent;
 7969: }
 7970: 
 7971: ul.LC_funclist {
 7972:     margin: 0;
 7973:     padding: 0.5em 1em 0.5em 0;
 7974: }
 7975: 
 7976: ul.LC_funclist > li:first-child {
 7977:     font-weight:bold; 
 7978:     margin-left:0.8em;
 7979: }
 7980: 
 7981: ul.LC_funclist + ul.LC_funclist {
 7982:     /* 
 7983:        left border as a seperator if we have more than
 7984:        one list 
 7985:     */
 7986:     border-left: 1px solid $sidebg;
 7987:     /* 
 7988:        this hides the left border behind the border of the 
 7989:        outer box if element is wrapped to the next 'line' 
 7990:     */
 7991:     margin-left: -1px;
 7992: }
 7993: 
 7994: ul.LC_funclist li {
 7995:   display: inline;
 7996:   white-space: nowrap;
 7997:   margin: 0 0 0 25px;
 7998:   line-height: 150%;
 7999: }
 8000: 
 8001: .LC_hidden {
 8002:   display: none;
 8003: }
 8004: 
 8005: .LCmodal-overlay {
 8006: 		position:fixed;
 8007: 		top:0;
 8008: 		right:0;
 8009: 		bottom:0;
 8010: 		left:0;
 8011: 		height:100%;
 8012: 		width:100%;
 8013: 		margin:0;
 8014: 		padding:0;
 8015: 		background:#999;
 8016: 		opacity:.75;
 8017: 		filter: alpha(opacity=75);
 8018: 		-moz-opacity: 0.75;
 8019: 		z-index:101;
 8020: }
 8021: 
 8022: * html .LCmodal-overlay {   
 8023: 		position: absolute;
 8024: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8025: }
 8026: 
 8027: .LCmodal-window {
 8028: 		position:fixed;
 8029: 		top:50%;
 8030: 		left:50%;
 8031: 		margin:0;
 8032: 		padding:0;
 8033: 		z-index:102;
 8034: 	}
 8035: 
 8036: * html .LCmodal-window {
 8037: 		position:absolute;
 8038: }
 8039: 
 8040: .LCclose-window {
 8041: 		position:absolute;
 8042: 		width:32px;
 8043: 		height:32px;
 8044: 		right:8px;
 8045: 		top:8px;
 8046: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8047: 		text-indent:-99999px;
 8048: 		overflow:hidden;
 8049: 		cursor:pointer;
 8050: }
 8051: 
 8052: /*
 8053:   styles used for response display
 8054: */
 8055: div.LC_radiofoil, div.LC_rankfoil {
 8056:   margin: .5em 0em .5em 0em;
 8057: }
 8058: table.LC_itemgroup {
 8059:   margin-top: 1em;
 8060: }
 8061: 
 8062: /*
 8063:   styles used by TTH when "Default set of options to pass to tth/m
 8064:   when converting TeX" in course settings has been set
 8065: 
 8066:   option passed: -t
 8067: 
 8068: */
 8069: 
 8070: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8071: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8072: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8073: td div.norm {line-height:normal;}
 8074: 
 8075: /*
 8076:   option passed -y3
 8077: */
 8078: 
 8079: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8080: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8081: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8082: 
 8083: /*
 8084:   sections with roles, for content only
 8085: */
 8086: section[class^="role-"] {
 8087:   padding-left: 10px;
 8088:   padding-right: 5px;
 8089:   margin-top: 8px;
 8090:   margin-bottom: 8px;
 8091:   border: 1px solid #2A4;
 8092:   border-radius: 5px;
 8093:   box-shadow: 0px 1px 1px #BBB;
 8094: }
 8095: section[class^="role-"]>h1 {
 8096:   position: relative;
 8097:   margin: 0px;
 8098:   padding-top: 10px;
 8099:   padding-left: 40px;
 8100: }
 8101: section[class^="role-"]>h1:before {
 8102:   position: absolute;
 8103:   left: -5px;
 8104:   top: 5px;
 8105: }
 8106: section.role-activity>h1:before {
 8107:   content:url('/adm/daxe/images/section_icons/activity.png');
 8108: }
 8109: section.role-advice>h1:before {
 8110:   content:url('/adm/daxe/images/section_icons/advice.png');
 8111: }
 8112: section.role-bibliography>h1:before {
 8113:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8114: }
 8115: section.role-citation>h1:before {
 8116:   content:url('/adm/daxe/images/section_icons/citation.png');
 8117: }
 8118: section.role-conclusion>h1:before {
 8119:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8120: }
 8121: section.role-definition>h1:before {
 8122:   content:url('/adm/daxe/images/section_icons/definition.png');
 8123: }
 8124: section.role-demonstration>h1:before {
 8125:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8126: }
 8127: section.role-example>h1:before {
 8128:   content:url('/adm/daxe/images/section_icons/example.png');
 8129: }
 8130: section.role-explanation>h1:before {
 8131:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8132: }
 8133: section.role-introduction>h1:before {
 8134:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8135: }
 8136: section.role-method>h1:before {
 8137:   content:url('/adm/daxe/images/section_icons/method.png');
 8138: }
 8139: section.role-more_information>h1:before {
 8140:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8141: }
 8142: section.role-objectives>h1:before {
 8143:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8144: }
 8145: section.role-prerequisites>h1:before {
 8146:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8147: }
 8148: section.role-remark>h1:before {
 8149:   content:url('/adm/daxe/images/section_icons/remark.png');
 8150: }
 8151: section.role-reminder>h1:before {
 8152:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8153: }
 8154: section.role-summary>h1:before {
 8155:   content:url('/adm/daxe/images/section_icons/summary.png');
 8156: }
 8157: section.role-syntax>h1:before {
 8158:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8159: }
 8160: section.role-warning>h1:before {
 8161:   content:url('/adm/daxe/images/section_icons/warning.png');
 8162: }
 8163: 
 8164: #LC_minitab_header {
 8165:   float:left;
 8166:   width:100%;
 8167:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8168:   font-size:93%;
 8169:   line-height:normal;
 8170:   margin: 0.5em 0 0.5em 0;
 8171: }
 8172: #LC_minitab_header ul {
 8173:   margin:0;
 8174:   padding:10px 10px 0;
 8175:   list-style:none;
 8176: }
 8177: #LC_minitab_header li {
 8178:   float:left;
 8179:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8180:   margin:0;
 8181:   padding:0 0 0 9px;
 8182: }
 8183: #LC_minitab_header a {
 8184:   display:block;
 8185:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8186:   padding:5px 15px 4px 6px;
 8187: }
 8188: #LC_minitab_header #LC_current_minitab {
 8189:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8190: }
 8191: #LC_minitab_header #LC_current_minitab a {
 8192:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8193:   padding-bottom:5px;
 8194: }
 8195: 
 8196: 
 8197: END
 8198: }
 8199: 
 8200: =pod
 8201: 
 8202: =item * &headtag()
 8203: 
 8204: Returns a uniform footer for LON-CAPA web pages.
 8205: 
 8206: Inputs: $title - optional title for the head
 8207:         $head_extra - optional extra HTML to put inside the <head>
 8208:         $args - optional arguments
 8209:             force_register - if is true call registerurl so the remote is 
 8210:                              informed
 8211:             redirect       -> array ref of
 8212:                                    1- seconds before redirect occurs
 8213:                                    2- url to redirect to
 8214:                                    3- whether the side effect should occur
 8215:                            (side effect of setting 
 8216:                                $env{'internal.head.redirect'} to the url 
 8217:                                redirected too)
 8218:             domain         -> force to color decorate a page for a specific
 8219:                                domain
 8220:             function       -> force usage of a specific rolish color scheme
 8221:             bgcolor        -> override the default page bgcolor
 8222:             no_auto_mt_title
 8223:                            -> prevent &mt()ing the title arg
 8224: 
 8225: =cut
 8226: 
 8227: sub headtag {
 8228:     my ($title,$head_extra,$args) = @_;
 8229:     
 8230:     my $function = $args->{'function'} || &get_users_function();
 8231:     my $domain   = $args->{'domain'}   || &determinedomain();
 8232:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8233:     my $httphost = $args->{'use_absolute'};
 8234:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8235: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8236: 		   #time(),
 8237: 		   $env{'environment.color.timestamp'},
 8238: 		   $function,$domain,$bgcolor);
 8239: 
 8240:     $url = '/adm/css/'.&escape($url).'.css';
 8241: 
 8242:     my $result =
 8243: 	'<head>'.
 8244: 	&font_settings($args);
 8245: 
 8246:     my $inhibitprint;
 8247:     if ($args->{'print_suppress'}) {
 8248:         $inhibitprint = &print_suppression();
 8249:     }
 8250: 
 8251:     if (!$args->{'frameset'}) {
 8252: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8253:     }
 8254:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8255:         $result .= Apache::lonxml::display_title();
 8256:     }
 8257:     if (!$args->{'no_nav_bar'} 
 8258: 	&& !$args->{'only_body'}
 8259: 	&& !$args->{'frameset'}) {
 8260: 	$result .= &help_menu_js($httphost);
 8261:         $result.=&modal_window();
 8262:         $result.=&togglebox_script();
 8263:         $result.=&wishlist_window();
 8264:         $result.=&LCprogressbarUpdate_script();
 8265:     } else {
 8266:         if ($args->{'add_modal'}) {
 8267:            $result.=&modal_window();
 8268:         }
 8269:         if ($args->{'add_wishlist'}) {
 8270:            $result.=&wishlist_window();
 8271:         }
 8272:         if ($args->{'add_togglebox'}) {
 8273:            $result.=&togglebox_script();
 8274:         }
 8275:         if ($args->{'add_progressbar'}) {
 8276:            $result.=&LCprogressbarUpdate_script();
 8277:         }
 8278:     }
 8279:     if (ref($args->{'redirect'})) {
 8280: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8281: 	$url = &Apache::lonenc::check_encrypt($url);
 8282: 	if (!$inhibit_continue) {
 8283: 	    $env{'internal.head.redirect'} = $url;
 8284: 	}
 8285: 	$result.=<<ADDMETA
 8286: <meta http-equiv="pragma" content="no-cache" />
 8287: <meta http-equiv="Refresh" content="$time; url=$url" />
 8288: ADDMETA
 8289:     } else {
 8290:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8291:             my $requrl = $env{'request.uri'};
 8292:             if ($requrl eq '') {
 8293:                 $requrl = $ENV{'REQUEST_URI'};
 8294:                 $requrl =~ s/\?.+$//;
 8295:             }
 8296:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8297:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8298:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8299:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8300:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8301:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8302:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8303:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8304:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8305:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8306:                             if (($newserver) && ($newserver ne $lonhost)) {
 8307:                                 my $numsec = 5;
 8308:                                 my $timeout = $numsec * 1000;
 8309:                                 my ($newurl,$locknum,%locks,$msg);
 8310:                                 if ($env{'request.role.adv'}) {
 8311:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8312:                                 }
 8313:                                 my $disable_submit = 0;
 8314:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8315:                                     $disable_submit = 1;
 8316:                                 }
 8317:                                 if ($locknum) {
 8318:                                     my @lockinfo = sort(values(%locks));
 8319:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8320:                                            join(", ",sort(values(%locks)))."\\n".
 8321:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8322:                                 } else {
 8323:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8324:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8325:                                     }
 8326:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8327:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8328:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8329:                                         $newurl .= '&role='.$env{'request.role'};
 8330:                                     }
 8331:                                     if ($env{'request.symb'}) {
 8332:                                         $newurl .= '&symb='.$env{'request.symb'};
 8333:                                     } else {
 8334:                                         $newurl .= '&origurl='.$requrl;
 8335:                                     }
 8336:                                 }
 8337:                                 &js_escape(\$msg);
 8338:                                 $result.=<<OFFLOAD
 8339: <meta http-equiv="pragma" content="no-cache" />
 8340: <script type="text/javascript">
 8341: // <![CDATA[
 8342: function LC_Offload_Now() {
 8343:     var dest = "$newurl";
 8344:     if (dest != '') {
 8345:         window.location.href="$newurl";
 8346:     }
 8347: }
 8348: \$(document).ready(function () {
 8349:     window.alert('$msg');
 8350:     if ($disable_submit) {
 8351:         \$(".LC_hwk_submit").prop("disabled", true);
 8352:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8353:     }
 8354:     setTimeout('LC_Offload_Now()', $timeout);
 8355: });
 8356: // ]]>
 8357: </script>
 8358: OFFLOAD
 8359:                             }
 8360:                         }
 8361:                     }
 8362:                 }
 8363:             }
 8364:         }
 8365:     }
 8366:     if (!defined($title)) {
 8367: 	$title = 'The LearningOnline Network with CAPA';
 8368:     }
 8369:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8370:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8371: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8372:     if (!$args->{'frameset'}) {
 8373:         $result .= ' /';
 8374:     }
 8375:     $result .= '>' 
 8376:         .$inhibitprint
 8377: 	.$head_extra;
 8378:     my $clientmobile;
 8379:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8380:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8381:     } else {
 8382:         $clientmobile = $env{'browser.mobile'};
 8383:     }
 8384:     if ($clientmobile) {
 8385:         $result .= '
 8386: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8387: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8388:     }
 8389:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8390:     return $result.'</head>';
 8391: }
 8392: 
 8393: =pod
 8394: 
 8395: =item * &font_settings()
 8396: 
 8397: Returns neccessary <meta> to set the proper encoding
 8398: 
 8399: Inputs: optional reference to HASH -- $args passed to &headtag()
 8400: 
 8401: =cut
 8402: 
 8403: sub font_settings {
 8404:     my ($args) = @_;
 8405:     my $headerstring='';
 8406:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8407:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8408:         $headerstring.=
 8409:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8410:         if (!$args->{'frameset'}) {
 8411: 	    $headerstring.= ' /';
 8412:         }
 8413: 	$headerstring .= '>'."\n";
 8414:     }
 8415:     return $headerstring;
 8416: }
 8417: 
 8418: =pod
 8419: 
 8420: =item * &print_suppression()
 8421: 
 8422: In course context returns css which causes the body to be blank when media="print",
 8423: if printout generation is unavailable for the current resource.
 8424: 
 8425: This could be because:
 8426: 
 8427: (a) printstartdate is in the future
 8428: 
 8429: (b) printenddate is in the past
 8430: 
 8431: (c) there is an active exam block with "printout"
 8432: functionality blocked
 8433: 
 8434: Users with pav, pfo or evb privileges are exempt.
 8435: 
 8436: Inputs: none
 8437: 
 8438: =cut
 8439: 
 8440: 
 8441: sub print_suppression {
 8442:     my $noprint;
 8443:     if ($env{'request.course.id'}) {
 8444:         my $scope = $env{'request.course.id'};
 8445:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8446:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8447:             return;
 8448:         }
 8449:         if ($env{'request.course.sec'} ne '') {
 8450:             $scope .= "/$env{'request.course.sec'}";
 8451:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8452:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8453:                 return;
 8454:             }
 8455:         }
 8456:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8457:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8458:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8459:         if ($blocked) {
 8460:             my $checkrole = "cm./$cdom/$cnum";
 8461:             if ($env{'request.course.sec'} ne '') {
 8462:                 $checkrole .= "/$env{'request.course.sec'}";
 8463:             }
 8464:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8465:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8466:                 $noprint = 1;
 8467:             }
 8468:         }
 8469:         unless ($noprint) {
 8470:             my $symb = &Apache::lonnet::symbread();
 8471:             if ($symb ne '') {
 8472:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8473:                 if (ref($navmap)) {
 8474:                     my $res = $navmap->getBySymb($symb);
 8475:                     if (ref($res)) {
 8476:                         if (!$res->resprintable()) {
 8477:                             $noprint = 1;
 8478:                         }
 8479:                     }
 8480:                 }
 8481:             }
 8482:         }
 8483:         if ($noprint) {
 8484:             return <<"ENDSTYLE";
 8485: <style type="text/css" media="print">
 8486:     body { display:none }
 8487: </style>
 8488: ENDSTYLE
 8489:         }
 8490:     }
 8491:     return;
 8492: }
 8493: 
 8494: =pod
 8495: 
 8496: =item * &xml_begin()
 8497: 
 8498: Returns the needed doctype and <html>
 8499: 
 8500: Inputs: none
 8501: 
 8502: =cut
 8503: 
 8504: sub xml_begin {
 8505:     my ($is_frameset) = @_;
 8506:     my $output='';
 8507: 
 8508:     if ($env{'browser.mathml'}) {
 8509: 	$output='<?xml version="1.0"?>'
 8510:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8511: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8512:             
 8513: #	    .'<!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">] >'
 8514: 	    .'<!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">'
 8515:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8516: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8517:     } elsif ($is_frameset) {
 8518:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8519:                 '<html>'."\n";
 8520:     } else {
 8521: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8522:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8523:     }
 8524:     return $output;
 8525: }
 8526: 
 8527: =pod
 8528: 
 8529: =item * &start_page()
 8530: 
 8531: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8532: 
 8533: Inputs:
 8534: 
 8535: =over 4
 8536: 
 8537: $title - optional title for the page
 8538: 
 8539: $head_extra - optional extra HTML to incude inside the <head>
 8540: 
 8541: $args - additional optional args supported are:
 8542: 
 8543: =over 8
 8544: 
 8545:              only_body      -> is true will set &bodytag() onlybodytag
 8546:                                     arg on
 8547:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8548:              add_entries    -> additional attributes to add to the  <body>
 8549:              domain         -> force to color decorate a page for a 
 8550:                                     specific domain
 8551:              function       -> force usage of a specific rolish color
 8552:                                     scheme
 8553:              redirect       -> see &headtag()
 8554:              bgcolor        -> override the default page bg color
 8555:              js_ready       -> return a string ready for being used in 
 8556:                                     a javascript writeln
 8557:              html_encode    -> return a string ready for being used in 
 8558:                                     a html attribute
 8559:              force_register -> if is true will turn on the &bodytag()
 8560:                                     $forcereg arg
 8561:              frameset       -> if true will start with a <frameset>
 8562:                                     rather than <body>
 8563:              skip_phases    -> hash ref of 
 8564:                                     head -> skip the <html><head> generation
 8565:                                     body -> skip all <body> generation
 8566:              no_auto_mt_title -> prevent &mt()ing the title arg
 8567:              bread_crumbs ->             Array containing breadcrumbs
 8568:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8569:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8570:                                     to lonhtmlcommon::breadcrumbs
 8571:              group          -> includes the current group, if page is for a 
 8572:                                specific group
 8573:              use_absolute   -> for request for external resource or syllabus, this
 8574:                                will contain https://<hostname> if server uses
 8575:                                https (as per hosts.tab), but request is for http
 8576:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8577: 
 8578: =back
 8579: 
 8580: =back
 8581: 
 8582: =cut
 8583: 
 8584: sub start_page {
 8585:     my ($title,$head_extra,$args) = @_;
 8586:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8587: 
 8588:     $env{'internal.start_page'}++;
 8589:     my ($result,@advtools);
 8590: 
 8591:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8592:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8593:     }
 8594:     
 8595:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8596: 	if ($args->{'frameset'}) {
 8597: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8598: 						$args->{'add_entries'});
 8599: 	    $result .= "\n<frameset $attr_string>\n";
 8600:         } else {
 8601:             $result .=
 8602:                 &bodytag($title, 
 8603:                          $args->{'function'},       $args->{'add_entries'},
 8604:                          $args->{'only_body'},      $args->{'domain'},
 8605:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8606:                          $args->{'bgcolor'},        $args,
 8607:                          \@advtools);
 8608:         }
 8609:     }
 8610: 
 8611:     if ($args->{'js_ready'}) {
 8612: 		$result = &js_ready($result);
 8613:     }
 8614:     if ($args->{'html_encode'}) {
 8615: 		$result = &html_encode($result);
 8616:     }
 8617: 
 8618:     # Preparation for new and consistent functionlist at top of screen
 8619:     # if ($args->{'functionlist'}) {
 8620:     #            $result .= &build_functionlist();
 8621:     #}
 8622: 
 8623:     # Don't add anything more if only_body wanted or in const space
 8624:     return $result if    $args->{'only_body'} 
 8625:                       || $env{'request.state'} eq 'construct';
 8626: 
 8627:     #Breadcrumbs
 8628:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8629: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8630: 		#if any br links exists, add them to the breadcrumbs
 8631: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8632: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8633: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8634: 			}
 8635: 		}
 8636:                 # if @advtools array contains items add then to the breadcrumbs
 8637:                 if (@advtools > 0) {
 8638:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8639:                 }
 8640:                 my $menulink;
 8641:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8642:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8643:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
 8644:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
 8645:                      (!$env{'request.role.adv'}))) {
 8646:                     $menulink = 0;
 8647:                 } else {
 8648:                     undef($menulink);
 8649:                 }
 8650: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8651: 		if(exists($args->{'bread_crumbs_component'})){
 8652: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8653:                 } else {
 8654: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8655: 		}
 8656:     }
 8657:     return $result;
 8658: }
 8659: 
 8660: sub end_page {
 8661:     my ($args) = @_;
 8662:     $env{'internal.end_page'}++;
 8663:     my $result;
 8664:     if ($args->{'discussion'}) {
 8665: 	my ($target,$parser);
 8666: 	if (ref($args->{'discussion'})) {
 8667: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8668: 				$args->{'discussion'}{'parser'});
 8669: 	}
 8670: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8671:     }
 8672:     if ($args->{'frameset'}) {
 8673: 	$result .= '</frameset>';
 8674:     } else {
 8675: 	$result .= &endbodytag($args);
 8676:     }
 8677:     unless ($args->{'notbody'}) {
 8678:         $result .= "\n</html>";
 8679:     }
 8680: 
 8681:     if ($args->{'js_ready'}) {
 8682: 	$result = &js_ready($result);
 8683:     }
 8684: 
 8685:     if ($args->{'html_encode'}) {
 8686: 	$result = &html_encode($result);
 8687:     }
 8688: 
 8689:     return $result;
 8690: }
 8691: 
 8692: sub wishlist_window {
 8693:     return(<<'ENDWISHLIST');
 8694: <script type="text/javascript">
 8695: // <![CDATA[
 8696: // <!-- BEGIN LON-CAPA Internal
 8697: function set_wishlistlink(title, path) {
 8698:     if (!title) {
 8699:         title = document.title;
 8700:         title = title.replace(/^LON-CAPA /,'');
 8701:     }
 8702:     title = encodeURIComponent(title);
 8703:     title = title.replace("'","\\\'");
 8704:     if (!path) {
 8705:         path = location.pathname;
 8706:     }
 8707:     path = encodeURIComponent(path);
 8708:     path = path.replace("'","\\\'");
 8709:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8710:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8711: }
 8712: // END LON-CAPA Internal -->
 8713: // ]]>
 8714: </script>
 8715: ENDWISHLIST
 8716: }
 8717: 
 8718: sub modal_window {
 8719:     return(<<'ENDMODAL');
 8720: <script type="text/javascript">
 8721: // <![CDATA[
 8722: // <!-- BEGIN LON-CAPA Internal
 8723: var modalWindow = {
 8724: 	parent:"body",
 8725: 	windowId:null,
 8726: 	content:null,
 8727: 	width:null,
 8728: 	height:null,
 8729: 	close:function()
 8730: 	{
 8731: 	        $(".LCmodal-window").remove();
 8732: 	        $(".LCmodal-overlay").remove();
 8733: 	},
 8734: 	open:function()
 8735: 	{
 8736: 		var modal = "";
 8737: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8738: 		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;\">";
 8739: 		modal += this.content;
 8740: 		modal += "</div>";	
 8741: 
 8742: 		$(this.parent).append(modal);
 8743: 
 8744: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8745: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8746: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8747: 	}
 8748: };
 8749: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8750: 	{
 8751:                 source = source.replace(/'/g,"&#39;");
 8752: 		modalWindow.windowId = "myModal";
 8753: 		modalWindow.width = width;
 8754: 		modalWindow.height = height;
 8755: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8756: 		modalWindow.open();
 8757: 	};
 8758: // END LON-CAPA Internal -->
 8759: // ]]>
 8760: </script>
 8761: ENDMODAL
 8762: }
 8763: 
 8764: sub modal_link {
 8765:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8766:     unless ($width) { $width=480; }
 8767:     unless ($height) { $height=400; }
 8768:     unless ($scrolling) { $scrolling='yes'; }
 8769:     unless ($transparency) { $transparency='true'; }
 8770: 
 8771:     my $target_attr;
 8772:     if (defined($target)) {
 8773:         $target_attr = 'target="'.$target.'"';
 8774:     }
 8775:     return <<"ENDLINK";
 8776: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8777:            $linktext</a>
 8778: ENDLINK
 8779: }
 8780: 
 8781: sub modal_adhoc_script {
 8782:     my ($funcname,$width,$height,$content)=@_;
 8783:     return (<<ENDADHOC);
 8784: <script type="text/javascript">
 8785: // <![CDATA[
 8786:         var $funcname = function()
 8787:         {
 8788:                 modalWindow.windowId = "myModal";
 8789:                 modalWindow.width = $width;
 8790:                 modalWindow.height = $height;
 8791:                 modalWindow.content = '$content';
 8792:                 modalWindow.open();
 8793:         };  
 8794: // ]]>
 8795: </script>
 8796: ENDADHOC
 8797: }
 8798: 
 8799: sub modal_adhoc_inner {
 8800:     my ($funcname,$width,$height,$content)=@_;
 8801:     my $innerwidth=$width-20;
 8802:     $content=&js_ready(
 8803:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8804:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8805:                  $content.
 8806:                  &end_scrollbox().
 8807:                  &end_page()
 8808:              );
 8809:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8810: }
 8811: 
 8812: sub modal_adhoc_window {
 8813:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8814:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8815:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8816: }
 8817: 
 8818: sub modal_adhoc_launch {
 8819:     my ($funcname,$width,$height,$content)=@_;
 8820:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8821: <script type="text/javascript">
 8822: // <![CDATA[
 8823: $funcname();
 8824: // ]]>
 8825: </script>
 8826: ENDLAUNCH
 8827: }
 8828: 
 8829: sub modal_adhoc_close {
 8830:     return (<<ENDCLOSE);
 8831: <script type="text/javascript">
 8832: // <![CDATA[
 8833: modalWindow.close();
 8834: // ]]>
 8835: </script>
 8836: ENDCLOSE
 8837: }
 8838: 
 8839: sub togglebox_script {
 8840:    return(<<ENDTOGGLE);
 8841: <script type="text/javascript"> 
 8842: // <![CDATA[
 8843: function LCtoggleDisplay(id,hidetext,showtext) {
 8844:    link = document.getElementById(id + "link").childNodes[0];
 8845:    with (document.getElementById(id).style) {
 8846:       if (display == "none" ) {
 8847:           display = "inline";
 8848:           link.nodeValue = hidetext;
 8849:         } else {
 8850:           display = "none";
 8851:           link.nodeValue = showtext;
 8852:        }
 8853:    }
 8854: }
 8855: // ]]>
 8856: </script>
 8857: ENDTOGGLE
 8858: }
 8859: 
 8860: sub start_togglebox {
 8861:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8862:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8863:     unless ($showtext) { $showtext=&mt('show'); }
 8864:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8865:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8866:     return &start_data_table().
 8867:            &start_data_table_header_row().
 8868:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8869:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8870:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8871:            &end_data_table_header_row().
 8872:            '<tr id="'.$id.'" style="display:none""><td>';
 8873: }
 8874: 
 8875: sub end_togglebox {
 8876:     return '</td></tr>'.&end_data_table();
 8877: }
 8878: 
 8879: sub LCprogressbar_script {
 8880:    my ($id)=@_;
 8881:    return(<<ENDPROGRESS);
 8882: <script type="text/javascript">
 8883: // <![CDATA[
 8884: \$('#progressbar$id').progressbar({
 8885:   value: 0,
 8886:   change: function(event, ui) {
 8887:     var newVal = \$(this).progressbar('option', 'value');
 8888:     \$('.pblabel', this).text(LCprogressTxt);
 8889:   }
 8890: });
 8891: // ]]>
 8892: </script>
 8893: ENDPROGRESS
 8894: }
 8895: 
 8896: sub LCprogressbarUpdate_script {
 8897:    return(<<ENDPROGRESSUPDATE);
 8898: <style type="text/css">
 8899: .ui-progressbar { position:relative; }
 8900: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8901: </style>
 8902: <script type="text/javascript">
 8903: // <![CDATA[
 8904: var LCprogressTxt='---';
 8905: 
 8906: function LCupdateProgress(percent,progresstext,id) {
 8907:    LCprogressTxt=progresstext;
 8908:    \$('#progressbar'+id).progressbar('value',percent);
 8909: }
 8910: // ]]>
 8911: </script>
 8912: ENDPROGRESSUPDATE
 8913: }
 8914: 
 8915: my $LClastpercent;
 8916: my $LCidcnt;
 8917: my $LCcurrentid;
 8918: 
 8919: sub LCprogressbar {
 8920:     my ($r)=(@_);
 8921:     $LClastpercent=0;
 8922:     $LCidcnt++;
 8923:     $LCcurrentid=$$.'_'.$LCidcnt;
 8924:     my $starting=&mt('Starting');
 8925:     my $content=(<<ENDPROGBAR);
 8926:   <div id="progressbar$LCcurrentid">
 8927:     <span class="pblabel">$starting</span>
 8928:   </div>
 8929: ENDPROGBAR
 8930:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8931: }
 8932: 
 8933: sub LCprogressbarUpdate {
 8934:     my ($r,$val,$text)=@_;
 8935:     unless ($val) { 
 8936:        if ($LClastpercent) {
 8937:            $val=$LClastpercent;
 8938:        } else {
 8939:            $val=0;
 8940:        }
 8941:     }
 8942:     if ($val<0) { $val=0; }
 8943:     if ($val>100) { $val=0; }
 8944:     $LClastpercent=$val;
 8945:     unless ($text) { $text=$val.'%'; }
 8946:     $text=&js_ready($text);
 8947:     &r_print($r,<<ENDUPDATE);
 8948: <script type="text/javascript">
 8949: // <![CDATA[
 8950: LCupdateProgress($val,'$text','$LCcurrentid');
 8951: // ]]>
 8952: </script>
 8953: ENDUPDATE
 8954: }
 8955: 
 8956: sub LCprogressbarClose {
 8957:     my ($r)=@_;
 8958:     $LClastpercent=0;
 8959:     &r_print($r,<<ENDCLOSE);
 8960: <script type="text/javascript">
 8961: // <![CDATA[
 8962: \$("#progressbar$LCcurrentid").hide('slow'); 
 8963: // ]]>
 8964: </script>
 8965: ENDCLOSE
 8966: }
 8967: 
 8968: sub r_print {
 8969:     my ($r,$to_print)=@_;
 8970:     if ($r) {
 8971:       $r->print($to_print);
 8972:       $r->rflush();
 8973:     } else {
 8974:       print($to_print);
 8975:     }
 8976: }
 8977: 
 8978: sub html_encode {
 8979:     my ($result) = @_;
 8980: 
 8981:     $result = &HTML::Entities::encode($result,'<>&"');
 8982:     
 8983:     return $result;
 8984: }
 8985: 
 8986: sub js_ready {
 8987:     my ($result) = @_;
 8988: 
 8989:     $result =~ s/[\n\r]/ /xmsg;
 8990:     $result =~ s/\\/\\\\/xmsg;
 8991:     $result =~ s/'/\\'/xmsg;
 8992:     $result =~ s{</}{<\\/}xmsg;
 8993:     
 8994:     return $result;
 8995: }
 8996: 
 8997: sub validate_page {
 8998:     if (  exists($env{'internal.start_page'})
 8999: 	  &&     $env{'internal.start_page'} > 1) {
 9000: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9001: 				 $env{'internal.start_page'}.' '.
 9002: 				 $ENV{'request.filename'});
 9003:     }
 9004:     if (  exists($env{'internal.end_page'})
 9005: 	  &&     $env{'internal.end_page'} > 1) {
 9006: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9007: 				 $env{'internal.end_page'}.' '.
 9008: 				 $env{'request.filename'});
 9009:     }
 9010:     if (     exists($env{'internal.start_page'})
 9011: 	&& ! exists($env{'internal.end_page'})) {
 9012: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9013: 				 $env{'request.filename'});
 9014:     }
 9015:     if (   ! exists($env{'internal.start_page'})
 9016: 	&&   exists($env{'internal.end_page'})) {
 9017: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9018: 				 $env{'request.filename'});
 9019:     }
 9020: }
 9021: 
 9022: 
 9023: sub start_scrollbox {
 9024:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9025:     unless ($outerwidth) { $outerwidth='520px'; }
 9026:     unless ($width) { $width='500px'; }
 9027:     unless ($height) { $height='200px'; }
 9028:     my ($table_id,$div_id,$tdcol);
 9029:     if ($id ne '') {
 9030:         $table_id = ' id="table_'.$id.'"';
 9031:         $div_id = ' id="div_'.$id.'"';
 9032:     }
 9033:     if ($bgcolor ne '') {
 9034:         $tdcol = "background-color: $bgcolor;";
 9035:     }
 9036:     my $nicescroll_js;
 9037:     if ($env{'browser.mobile'}) {
 9038:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9039:     }
 9040:     return <<"END";
 9041: $nicescroll_js
 9042: 
 9043: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9044: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9045: END
 9046: }
 9047: 
 9048: sub end_scrollbox {
 9049:     return '</div></td></tr></table>';
 9050: }
 9051: 
 9052: sub nicescroll_javascript {
 9053:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9054:     my %options;
 9055:     if (ref($cursor) eq 'HASH') {
 9056:         %options = %{$cursor};
 9057:     }
 9058:     unless ($options{'railalign'} =~ /^left|right$/) {
 9059:         $options{'railalign'} = 'left';
 9060:     }
 9061:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9062:         my $function  = &get_users_function();
 9063:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9064:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9065:             $options{'cursorcolor'} = '#00F';
 9066:         }
 9067:     }
 9068:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9069:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9070:             $options{'cursoropacity'}='1.0';
 9071:         }
 9072:     } else {
 9073:         $options{'cursoropacity'}='1.0';
 9074:     }
 9075:     if ($options{'cursorfixedheight'} eq 'none') {
 9076:         delete($options{'cursorfixedheight'});
 9077:     } else {
 9078:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9079:     }
 9080:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9081:         delete($options{'railoffset'});
 9082:     }
 9083:     my @niceoptions;
 9084:     while (my($key,$value) = each(%options)) {
 9085:         if ($value =~ /^\{.+\}$/) {
 9086:             push(@niceoptions,$key.':'.$value);
 9087:         } else {
 9088:             push(@niceoptions,$key.':"'.$value.'"');
 9089:         }
 9090:     }
 9091:     my $nicescroll_js = '
 9092: $(document).ready(
 9093:       function() {
 9094:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9095:       }
 9096: );
 9097: ';
 9098:     if ($framecheck) {
 9099:         $nicescroll_js .= '
 9100: function expand_div(caller) {
 9101:     if (top === self) {
 9102:         document.getElementById("'.$id.'").style.width = "auto";
 9103:         document.getElementById("'.$id.'").style.height = "auto";
 9104:     } else {
 9105:         try {
 9106:             if (parent.frames) {
 9107:                 if (parent.frames.length > 1) {
 9108:                     var framesrc = parent.frames[1].location.href;
 9109:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9110:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9111:                         document.getElementById("'.$id.'").style.width = "auto";
 9112:                         document.getElementById("'.$id.'").style.height = "auto";
 9113:                     }
 9114:                 }
 9115:             }
 9116:         } catch (e) {
 9117:             return;
 9118:         }
 9119:     }
 9120:     return;
 9121: }
 9122: ';
 9123:     }
 9124:     if ($needjsready) {
 9125:         $nicescroll_js = '
 9126: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9127:     } else {
 9128:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9129:     }
 9130:     return $nicescroll_js;
 9131: }
 9132: 
 9133: sub simple_error_page {
 9134:     my ($r,$title,$msg,$args) = @_;
 9135:     if (ref($args) eq 'HASH') {
 9136:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9137:     } else {
 9138:         $msg = &mt($msg);
 9139:     }
 9140: 
 9141:     my $page =
 9142: 	&Apache::loncommon::start_page($title).
 9143: 	'<p class="LC_error">'.$msg.'</p>'.
 9144: 	&Apache::loncommon::end_page();
 9145:     if (ref($r)) {
 9146: 	$r->print($page);
 9147: 	return;
 9148:     }
 9149:     return $page;
 9150: }
 9151: 
 9152: {
 9153:     my @row_count;
 9154: 
 9155:     sub start_data_table_count {
 9156:         unshift(@row_count, 0);
 9157:         return;
 9158:     }
 9159: 
 9160:     sub end_data_table_count {
 9161:         shift(@row_count);
 9162:         return;
 9163:     }
 9164: 
 9165:     sub start_data_table {
 9166: 	my ($add_class,$id) = @_;
 9167: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9168:         my $table_id;
 9169:         if (defined($id)) {
 9170:             $table_id = ' id="'.$id.'"';
 9171:         }
 9172: 	&start_data_table_count();
 9173: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9174:     }
 9175: 
 9176:     sub end_data_table {
 9177: 	&end_data_table_count();
 9178: 	return '</table>'."\n";;
 9179:     }
 9180: 
 9181:     sub start_data_table_row {
 9182: 	my ($add_class, $id) = @_;
 9183: 	$row_count[0]++;
 9184: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9185: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9186:         $id = (' id="'.$id.'"') unless ($id eq '');
 9187:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9188:     }
 9189:     
 9190:     sub continue_data_table_row {
 9191: 	my ($add_class, $id) = @_;
 9192: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9193: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9194:         $id = (' id="'.$id.'"') unless ($id eq '');
 9195:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9196:     }
 9197: 
 9198:     sub end_data_table_row {
 9199: 	return '</tr>'."\n";;
 9200:     }
 9201: 
 9202:     sub start_data_table_empty_row {
 9203: #	$row_count[0]++;
 9204: 	return  '<tr class="LC_empty_row" >'."\n";;
 9205:     }
 9206: 
 9207:     sub end_data_table_empty_row {
 9208: 	return '</tr>'."\n";;
 9209:     }
 9210: 
 9211:     sub start_data_table_header_row {
 9212: 	return  '<tr class="LC_header_row">'."\n";;
 9213:     }
 9214: 
 9215:     sub end_data_table_header_row {
 9216: 	return '</tr>'."\n";;
 9217:     }
 9218: 
 9219:     sub data_table_caption {
 9220:         my $caption = shift;
 9221:         return "<caption class=\"LC_caption\">$caption</caption>";
 9222:     }
 9223: }
 9224: 
 9225: =pod
 9226: 
 9227: =item * &inhibit_menu_check($arg)
 9228: 
 9229: Checks for a inhibitmenu state and generates output to preserve it
 9230: 
 9231: Inputs:         $arg - can be any of
 9232:                      - undef - in which case the return value is a string 
 9233:                                to add  into arguments list of a uri
 9234:                      - 'input' - in which case the return value is a HTML
 9235:                                  <form> <input> field of type hidden to
 9236:                                  preserve the value
 9237:                      - a url - in which case the return value is the url with
 9238:                                the neccesary cgi args added to preserve the
 9239:                                inhibitmenu state
 9240:                      - a ref to a url - no return value, but the string is
 9241:                                         updated to include the neccessary cgi
 9242:                                         args to preserve the inhibitmenu state
 9243: 
 9244: =cut
 9245: 
 9246: sub inhibit_menu_check {
 9247:     my ($arg) = @_;
 9248:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9249:     if ($arg eq 'input') {
 9250: 	if ($env{'form.inhibitmenu'}) {
 9251: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9252: 	} else {
 9253: 	    return
 9254: 	}
 9255:     }
 9256:     if ($env{'form.inhibitmenu'}) {
 9257: 	if (ref($arg)) {
 9258: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9259: 	} elsif ($arg eq '') {
 9260: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9261: 	} else {
 9262: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9263: 	}
 9264:     }
 9265:     if (!ref($arg)) {
 9266: 	return $arg;
 9267:     }
 9268: }
 9269: 
 9270: ###############################################
 9271: 
 9272: =pod
 9273: 
 9274: =back
 9275: 
 9276: =head1 User Information Routines
 9277: 
 9278: =over 4
 9279: 
 9280: =item * &get_users_function()
 9281: 
 9282: Used by &bodytag to determine the current users primary role.
 9283: Returns either 'student','coordinator','admin', or 'author'.
 9284: 
 9285: =cut
 9286: 
 9287: ###############################################
 9288: sub get_users_function {
 9289:     my $function = 'norole';
 9290:     if ($env{'request.role'}=~/^(st)/) {
 9291:         $function='student';
 9292:     }
 9293:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9294:         $function='coordinator';
 9295:     }
 9296:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9297:         $function='admin';
 9298:     }
 9299:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9300:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9301:         $function='author';
 9302:     }
 9303:     return $function;
 9304: }
 9305: 
 9306: ###############################################
 9307: 
 9308: =pod
 9309: 
 9310: =item * &show_course()
 9311: 
 9312: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9313: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9314: 
 9315: Inputs:
 9316: None
 9317: 
 9318: Outputs:
 9319: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9320: 
 9321: =cut
 9322: 
 9323: ###############################################
 9324: sub show_course {
 9325:     my $course = !$env{'user.adv'};
 9326:     if (!$env{'user.adv'}) {
 9327:         foreach my $env (keys(%env)) {
 9328:             next if ($env !~ m/^user\.priv\./);
 9329:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9330:                 $course = 0;
 9331:                 last;
 9332:             }
 9333:         }
 9334:     }
 9335:     return $course;
 9336: }
 9337: 
 9338: ###############################################
 9339: 
 9340: =pod
 9341: 
 9342: =item * &check_user_status()
 9343: 
 9344: Determines current status of supplied role for a
 9345: specific user. Roles can be active, previous or future.
 9346: 
 9347: Inputs: 
 9348: user's domain, user's username, course's domain,
 9349: course's number, optional section ID.
 9350: 
 9351: Outputs:
 9352: role status: active, previous or future. 
 9353: 
 9354: =cut
 9355: 
 9356: sub check_user_status {
 9357:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9358:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9359:     my @uroles = keys(%userinfo);
 9360:     my $srchstr;
 9361:     my $active_chk = 'none';
 9362:     my $now = time;
 9363:     if (@uroles > 0) {
 9364:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9365:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9366:         } else {
 9367:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9368:         }
 9369:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9370:             my $role_end = 0;
 9371:             my $role_start = 0;
 9372:             $active_chk = 'active';
 9373:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9374:                 $role_end = $1;
 9375:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9376:                     $role_start = $1;
 9377:                 }
 9378:             }
 9379:             if ($role_start > 0) {
 9380:                 if ($now < $role_start) {
 9381:                     $active_chk = 'future';
 9382:                 }
 9383:             }
 9384:             if ($role_end > 0) {
 9385:                 if ($now > $role_end) {
 9386:                     $active_chk = 'previous';
 9387:                 }
 9388:             }
 9389:         }
 9390:     }
 9391:     return $active_chk;
 9392: }
 9393: 
 9394: ###############################################
 9395: 
 9396: =pod
 9397: 
 9398: =item * &get_sections()
 9399: 
 9400: Determines all the sections for a course including
 9401: sections with students and sections containing other roles.
 9402: Incoming parameters: 
 9403: 
 9404: 1. domain
 9405: 2. course number 
 9406: 3. reference to array containing roles for which sections should 
 9407: be gathered (optional).
 9408: 4. reference to array containing status types for which sections 
 9409: should be gathered (optional).
 9410: 
 9411: If the third argument is undefined, sections are gathered for any role. 
 9412: If the fourth argument is undefined, sections are gathered for any status.
 9413: Permissible values are 'active' or 'future' or 'previous'.
 9414:  
 9415: Returns section hash (keys are section IDs, values are
 9416: number of users in each section), subject to the
 9417: optional roles filter, optional status filter 
 9418: 
 9419: =cut
 9420: 
 9421: ###############################################
 9422: sub get_sections {
 9423:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9424:     if (!defined($cdom) || !defined($cnum)) {
 9425:         my $cid =  $env{'request.course.id'};
 9426: 
 9427: 	return if (!defined($cid));
 9428: 
 9429:         $cdom = $env{'course.'.$cid.'.domain'};
 9430:         $cnum = $env{'course.'.$cid.'.num'};
 9431:     }
 9432: 
 9433:     my %sectioncount;
 9434:     my $now = time;
 9435: 
 9436:     my $check_students = 1;
 9437:     my $only_students = 0;
 9438:     if (ref($possible_roles) eq 'ARRAY') {
 9439:         if (grep(/^st$/,@{$possible_roles})) {
 9440:             if (@{$possible_roles} == 1) {
 9441:                 $only_students = 1;
 9442:             }
 9443:         } else {
 9444:             $check_students = 0;
 9445:         }
 9446:     }
 9447: 
 9448:     if ($check_students) { 
 9449: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9450: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9451: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9452:         my $start_index = &Apache::loncoursedata::CL_START();
 9453:         my $end_index = &Apache::loncoursedata::CL_END();
 9454:         my $status;
 9455: 	while (my ($student,$data) = each(%$classlist)) {
 9456: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9457: 				                     $data->[$status_index],
 9458:                                                      $data->[$start_index],
 9459:                                                      $data->[$end_index]);
 9460:             if ($stu_status eq 'Active') {
 9461:                 $status = 'active';
 9462:             } elsif ($end < $now) {
 9463:                 $status = 'previous';
 9464:             } elsif ($start > $now) {
 9465:                 $status = 'future';
 9466:             } 
 9467: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9468:                 if ((!defined($possible_status)) || (($status ne '') && 
 9469:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9470: 		    $sectioncount{$section}++;
 9471:                 }
 9472: 	    }
 9473: 	}
 9474:     }
 9475:     if ($only_students) {
 9476:         return %sectioncount;
 9477:     }
 9478:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9479:     foreach my $user (sort(keys(%courseroles))) {
 9480: 	if ($user !~ /^(\w{2})/) { next; }
 9481: 	my ($role) = ($user =~ /^(\w{2})/);
 9482: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9483: 	my ($section,$status);
 9484: 	if ($role eq 'cr' &&
 9485: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9486: 	    $section=$1;
 9487: 	}
 9488: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9489: 	if (!defined($section) || $section eq '-1') { next; }
 9490:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9491:         if ($end == -1 && $start == -1) {
 9492:             next; #deleted role
 9493:         }
 9494:         if (!defined($possible_status)) { 
 9495:             $sectioncount{$section}++;
 9496:         } else {
 9497:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9498:                 $status = 'active';
 9499:             } elsif ($end < $now) {
 9500:                 $status = 'future';
 9501:             } elsif ($start > $now) {
 9502:                 $status = 'previous';
 9503:             }
 9504:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9505:                 $sectioncount{$section}++;
 9506:             }
 9507:         }
 9508:     }
 9509:     return %sectioncount;
 9510: }
 9511: 
 9512: ###############################################
 9513: 
 9514: =pod
 9515: 
 9516: =item * &get_course_users()
 9517: 
 9518: Retrieves usernames:domains for users in the specified course
 9519: with specific role(s), and access status. 
 9520: 
 9521: Incoming parameters:
 9522: 1. course domain
 9523: 2. course number
 9524: 3. access status: users must have - either active, 
 9525: previous, future, or all.
 9526: 4. reference to array of permissible roles
 9527: 5. reference to array of section restrictions (optional)
 9528: 6. reference to results object (hash of hashes).
 9529: 7. reference to optional userdata hash
 9530: 8. reference to optional statushash
 9531: 9. flag if privileged users (except those set to unhide in
 9532:    course settings) should be excluded    
 9533: Keys of top level results hash are roles.
 9534: Keys of inner hashes are username:domain, with 
 9535: values set to access type.
 9536: Optional userdata hash returns an array with arguments in the 
 9537: same order as loncoursedata::get_classlist() for student data.
 9538: 
 9539: Optional statushash returns
 9540: 
 9541: Entries for end, start, section and status are blank because
 9542: of the possibility of multiple values for non-student roles.
 9543: 
 9544: =cut
 9545: 
 9546: ###############################################
 9547: 
 9548: sub get_course_users {
 9549:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9550:     my %idx = ();
 9551:     my %seclists;
 9552: 
 9553:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9554:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9555:     $idx{end} = &Apache::loncoursedata::CL_END();
 9556:     $idx{start} = &Apache::loncoursedata::CL_START();
 9557:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9558:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9559:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9560:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9561: 
 9562:     if (grep(/^st$/,@{$roles})) {
 9563:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9564:         my $now = time;
 9565:         foreach my $student (keys(%{$classlist})) {
 9566:             my $match = 0;
 9567:             my $secmatch = 0;
 9568:             my $section = $$classlist{$student}[$idx{section}];
 9569:             my $status = $$classlist{$student}[$idx{status}];
 9570:             if ($section eq '') {
 9571:                 $section = 'none';
 9572:             }
 9573:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9574:                 if (grep(/^all$/,@{$sections})) {
 9575:                     $secmatch = 1;
 9576:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9577:                     if (grep(/^none$/,@{$sections})) {
 9578:                         $secmatch = 1;
 9579:                     }
 9580:                 } else {  
 9581: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9582: 		        $secmatch = 1;
 9583:                     }
 9584: 		}
 9585:                 if (!$secmatch) {
 9586:                     next;
 9587:                 }
 9588:             }
 9589:             if (defined($$types{'active'})) {
 9590:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9591:                     push(@{$$users{st}{$student}},'active');
 9592:                     $match = 1;
 9593:                 }
 9594:             }
 9595:             if (defined($$types{'previous'})) {
 9596:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9597:                     push(@{$$users{st}{$student}},'previous');
 9598:                     $match = 1;
 9599:                 }
 9600:             }
 9601:             if (defined($$types{'future'})) {
 9602:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9603:                     push(@{$$users{st}{$student}},'future');
 9604:                     $match = 1;
 9605:                 }
 9606:             }
 9607:             if ($match) {
 9608:                 push(@{$seclists{$student}},$section);
 9609:                 if (ref($userdata) eq 'HASH') {
 9610:                     $$userdata{$student} = $$classlist{$student};
 9611:                 }
 9612:                 if (ref($statushash) eq 'HASH') {
 9613:                     $statushash->{$student}{'st'}{$section} = $status;
 9614:                 }
 9615:             }
 9616:         }
 9617:     }
 9618:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9619:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9620:         my $now = time;
 9621:         my %displaystatus = ( previous => 'Expired',
 9622:                               active   => 'Active',
 9623:                               future   => 'Future',
 9624:                             );
 9625:         my (%nothide,@possdoms);
 9626:         if ($hidepriv) {
 9627:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9628:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9629:                 if ($user !~ /:/) {
 9630:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9631:                 } else {
 9632:                     $nothide{$user} = 1;
 9633:                 }
 9634:             }
 9635:             my @possdoms = ($cdom);
 9636:             if ($coursehash{'checkforpriv'}) {
 9637:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9638:             }
 9639:         }
 9640:         foreach my $person (sort(keys(%coursepersonnel))) {
 9641:             my $match = 0;
 9642:             my $secmatch = 0;
 9643:             my $status;
 9644:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9645:             $user =~ s/:$//;
 9646:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9647:             if ($end == -1 || $start == -1) {
 9648:                 next;
 9649:             }
 9650:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9651:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9652:                 my ($uname,$udom) = split(/:/,$user);
 9653:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9654:                     if (grep(/^all$/,@{$sections})) {
 9655:                         $secmatch = 1;
 9656:                     } elsif ($usec eq '') {
 9657:                         if (grep(/^none$/,@{$sections})) {
 9658:                             $secmatch = 1;
 9659:                         }
 9660:                     } else {
 9661:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9662:                             $secmatch = 1;
 9663:                         }
 9664:                     }
 9665:                     if (!$secmatch) {
 9666:                         next;
 9667:                     }
 9668:                 }
 9669:                 if ($usec eq '') {
 9670:                     $usec = 'none';
 9671:                 }
 9672:                 if ($uname ne '' && $udom ne '') {
 9673:                     if ($hidepriv) {
 9674:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9675:                             (!$nothide{$uname.':'.$udom})) {
 9676:                             next;
 9677:                         }
 9678:                     }
 9679:                     if ($end > 0 && $end < $now) {
 9680:                         $status = 'previous';
 9681:                     } elsif ($start > $now) {
 9682:                         $status = 'future';
 9683:                     } else {
 9684:                         $status = 'active';
 9685:                     }
 9686:                     foreach my $type (keys(%{$types})) { 
 9687:                         if ($status eq $type) {
 9688:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9689:                                 push(@{$$users{$role}{$user}},$type);
 9690:                             }
 9691:                             $match = 1;
 9692:                         }
 9693:                     }
 9694:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9695:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9696: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9697:                         }
 9698:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9699:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9700:                         }
 9701:                         if (ref($statushash) eq 'HASH') {
 9702:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9703:                         }
 9704:                     }
 9705:                 }
 9706:             }
 9707:         }
 9708:         if (grep(/^ow$/,@{$roles})) {
 9709:             if ((defined($cdom)) && (defined($cnum))) {
 9710:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9711:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9712:                     my $owner = $csettings{'internal.courseowner'};
 9713:                     next if ($owner eq '');
 9714:                     my ($ownername,$ownerdom);
 9715:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9716:                         $ownername = $1;
 9717:                         $ownerdom = $2;
 9718:                     } else {
 9719:                         $ownername = $owner;
 9720:                         $ownerdom = $cdom;
 9721:                         $owner = $ownername.':'.$ownerdom;
 9722:                     }
 9723:                     @{$$users{'ow'}{$owner}} = 'any';
 9724:                     if (defined($userdata) && 
 9725: 			!exists($$userdata{$owner})) {
 9726: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9727:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9728:                             push(@{$seclists{$owner}},'none');
 9729:                         }
 9730:                         if (ref($statushash) eq 'HASH') {
 9731:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9732:                         }
 9733: 		    }
 9734:                 }
 9735:             }
 9736:         }
 9737:         foreach my $user (keys(%seclists)) {
 9738:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9739:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9740:         }
 9741:     }
 9742:     return;
 9743: }
 9744: 
 9745: sub get_user_info {
 9746:     my ($udom,$uname,$idx,$userdata) = @_;
 9747:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9748: 	&plainname($uname,$udom,'lastname');
 9749:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9750:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9751:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9752:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9753:     return;
 9754: }
 9755: 
 9756: ###############################################
 9757: 
 9758: =pod
 9759: 
 9760: =item * &get_user_quota()
 9761: 
 9762: Retrieves quota assigned for storage of user files.
 9763: Default is to report quota for portfolio files.
 9764: 
 9765: Incoming parameters:
 9766: 1. user's username
 9767: 2. user's domain
 9768: 3. quota name - portfolio, author, or course
 9769:    (if no quota name provided, defaults to portfolio).
 9770: 4. crstype - official, unofficial, textbook, placement or community, 
 9771:    if quota name is course
 9772: 
 9773: Returns:
 9774: 1. Disk quota (in MB) assigned to student.
 9775: 2. (Optional) Type of setting: custom or default
 9776:    (individually assigned or default for user's 
 9777:    institutional status).
 9778: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9779:    or student - types as defined in localenroll::inst_usertypes 
 9780:    for user's domain, which determines default quota for user.
 9781: 4. (Optional) - Default quota which would apply to the user.
 9782: 
 9783: If a value has been stored in the user's environment, 
 9784: it will return that, otherwise it returns the maximal default
 9785: defined for the user's institutional status(es) in the domain.
 9786: 
 9787: =cut
 9788: 
 9789: ###############################################
 9790: 
 9791: 
 9792: sub get_user_quota {
 9793:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9794:     my ($quota,$quotatype,$settingstatus,$defquota);
 9795:     if (!defined($udom)) {
 9796:         $udom = $env{'user.domain'};
 9797:     }
 9798:     if (!defined($uname)) {
 9799:         $uname = $env{'user.name'};
 9800:     }
 9801:     if (($udom eq '' || $uname eq '') ||
 9802:         ($udom eq 'public') && ($uname eq 'public')) {
 9803:         $quota = 0;
 9804:         $quotatype = 'default';
 9805:         $defquota = 0; 
 9806:     } else {
 9807:         my $inststatus;
 9808:         if ($quotaname eq 'course') {
 9809:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9810:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9811:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9812:             } else {
 9813:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9814:                 $quota = $cenv{'internal.uploadquota'};
 9815:             }
 9816:         } else {
 9817:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9818:                 if ($quotaname eq 'author') {
 9819:                     $quota = $env{'environment.authorquota'};
 9820:                 } else {
 9821:                     $quota = $env{'environment.portfolioquota'};
 9822:                 }
 9823:                 $inststatus = $env{'environment.inststatus'};
 9824:             } else {
 9825:                 my %userenv = 
 9826:                     &Apache::lonnet::get('environment',['portfolioquota',
 9827:                                          'authorquota','inststatus'],$udom,$uname);
 9828:                 my ($tmp) = keys(%userenv);
 9829:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9830:                     if ($quotaname eq 'author') {
 9831:                         $quota = $userenv{'authorquota'};
 9832:                     } else {
 9833:                         $quota = $userenv{'portfolioquota'};
 9834:                     }
 9835:                     $inststatus = $userenv{'inststatus'};
 9836:                 } else {
 9837:                     undef(%userenv);
 9838:                 }
 9839:             }
 9840:         }
 9841:         if ($quota eq '' || wantarray) {
 9842:             if ($quotaname eq 'course') {
 9843:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9844:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9845:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
 9846:                     ($crstype eq 'placement')) { 
 9847:                     $defquota = $domdefs{$crstype.'quota'};
 9848:                 }
 9849:                 if ($defquota eq '') {
 9850:                     $defquota = 500;
 9851:                 }
 9852:             } else {
 9853:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9854:             }
 9855:             if ($quota eq '') {
 9856:                 $quota = $defquota;
 9857:                 $quotatype = 'default';
 9858:             } else {
 9859:                 $quotatype = 'custom';
 9860:             }
 9861:         }
 9862:     }
 9863:     if (wantarray) {
 9864:         return ($quota,$quotatype,$settingstatus,$defquota);
 9865:     } else {
 9866:         return $quota;
 9867:     }
 9868: }
 9869: 
 9870: ###############################################
 9871: 
 9872: =pod
 9873: 
 9874: =item * &default_quota()
 9875: 
 9876: Retrieves default quota assigned for storage of user portfolio files,
 9877: given an (optional) user's institutional status.
 9878: 
 9879: Incoming parameters:
 9880: 
 9881: 1. domain
 9882: 2. (Optional) institutional status(es).  This is a : separated list of 
 9883:    status types (e.g., faculty, staff, student etc.)
 9884:    which apply to the user for whom the default is being retrieved.
 9885:    If the institutional status string in undefined, the domain
 9886:    default quota will be returned.
 9887: 3.  quota name - portfolio, author, or course
 9888:    (if no quota name provided, defaults to portfolio).
 9889: 
 9890: Returns:
 9891: 
 9892: 1. Default disk quota (in MB) for user portfolios in the domain.
 9893: 2. (Optional) institutional type which determined the value of the
 9894:    default quota.
 9895: 
 9896: If a value has been stored in the domain's configuration db,
 9897: it will return that, otherwise it returns 20 (for backwards 
 9898: compatibility with domains which have not set up a configuration
 9899: db file; the original statically defined portfolio quota was 20 MB). 
 9900: 
 9901: If the user's status includes multiple types (e.g., staff and student),
 9902: the largest default quota which applies to the user determines the
 9903: default quota returned.
 9904: 
 9905: =cut
 9906: 
 9907: ###############################################
 9908: 
 9909: 
 9910: sub default_quota {
 9911:     my ($udom,$inststatus,$quotaname) = @_;
 9912:     my ($defquota,$settingstatus);
 9913:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9914:                                             ['quotas'],$udom);
 9915:     my $key = 'defaultquota';
 9916:     if ($quotaname eq 'author') {
 9917:         $key = 'authorquota';
 9918:     }
 9919:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9920:         if ($inststatus ne '') {
 9921:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9922:             foreach my $item (@statuses) {
 9923:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9924:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9925:                         if ($defquota eq '') {
 9926:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9927:                             $settingstatus = $item;
 9928:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9929:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9930:                             $settingstatus = $item;
 9931:                         }
 9932:                     }
 9933:                 } elsif ($key eq 'defaultquota') {
 9934:                     if ($quotahash{'quotas'}{$item} ne '') {
 9935:                         if ($defquota eq '') {
 9936:                             $defquota = $quotahash{'quotas'}{$item};
 9937:                             $settingstatus = $item;
 9938:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9939:                             $defquota = $quotahash{'quotas'}{$item};
 9940:                             $settingstatus = $item;
 9941:                         }
 9942:                     }
 9943:                 }
 9944:             }
 9945:         }
 9946:         if ($defquota eq '') {
 9947:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9948:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9949:             } elsif ($key eq 'defaultquota') {
 9950:                 $defquota = $quotahash{'quotas'}{'default'};
 9951:             }
 9952:             $settingstatus = 'default';
 9953:             if ($defquota eq '') {
 9954:                 if ($quotaname eq 'author') {
 9955:                     $defquota = 500;
 9956:                 }
 9957:             }
 9958:         }
 9959:     } else {
 9960:         $settingstatus = 'default';
 9961:         if ($quotaname eq 'author') {
 9962:             $defquota = 500;
 9963:         } else {
 9964:             $defquota = 20;
 9965:         }
 9966:     }
 9967:     if (wantarray) {
 9968:         return ($defquota,$settingstatus);
 9969:     } else {
 9970:         return $defquota;
 9971:     }
 9972: }
 9973: 
 9974: ###############################################
 9975: 
 9976: =pod
 9977: 
 9978: =item * &excess_filesize_warning()
 9979: 
 9980: Returns warning message if upload of file to authoring space, or copying
 9981: of existing file within authoring space will cause quota for the authoring
 9982: space to be exceeded.
 9983: 
 9984: Same, if upload of a file directly to a course/community via Course Editor
 9985: will cause quota for uploaded content for the course to be exceeded.
 9986: 
 9987: Inputs: 7 
 9988: 1. username or coursenum
 9989: 2. domain
 9990: 3. context ('author' or 'course')
 9991: 4. filename of file for which action is being requested
 9992: 5. filesize (kB) of file
 9993: 6. action being taken: copy or upload.
 9994: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
 9995: 
 9996: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9997:          otherwise return null.
 9998: 
 9999: =back
10000: 
10001: =cut
10002: 
10003: sub excess_filesize_warning {
10004:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10005:     my $current_disk_usage = 0;
10006:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10007:     if ($context eq 'author') {
10008:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10009:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10010:     } else {
10011:         foreach my $subdir ('docs','supplemental') {
10012:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10013:         }
10014:     }
10015:     $disk_quota = int($disk_quota * 1000);
10016:     if (($current_disk_usage + $filesize) > $disk_quota) {
10017:         return '<p class="LC_warning">'.
10018:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10019:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10020:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10021:                             $disk_quota,$current_disk_usage).
10022:                '</p>';
10023:     }
10024:     return;
10025: }
10026: 
10027: ###############################################
10028: 
10029: 
10030: 
10031: 
10032: sub get_secgrprole_info {
10033:     my ($cdom,$cnum,$needroles,$type)  = @_;
10034:     my %sections_count = &get_sections($cdom,$cnum);
10035:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10036:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10037:     my @groups = sort(keys(%curr_groups));
10038:     my $allroles = [];
10039:     my $rolehash;
10040:     my $accesshash = {
10041:                      active => 'Currently has access',
10042:                      future => 'Will have future access',
10043:                      previous => 'Previously had access',
10044:                   };
10045:     if ($needroles) {
10046:         $rolehash = {'all' => 'all'};
10047:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10048: 	if (&Apache::lonnet::error(%user_roles)) {
10049: 	    undef(%user_roles);
10050: 	}
10051:         foreach my $item (keys(%user_roles)) {
10052:             my ($role)=split(/\:/,$item,2);
10053:             if ($role eq 'cr') { next; }
10054:             if ($role =~ /^cr/) {
10055:                 $$rolehash{$role} = (split('/',$role))[3];
10056:             } else {
10057:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10058:             }
10059:         }
10060:         foreach my $key (sort(keys(%{$rolehash}))) {
10061:             push(@{$allroles},$key);
10062:         }
10063:         push (@{$allroles},'st');
10064:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10065:     }
10066:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10067: }
10068: 
10069: sub user_picker {
10070:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10071:     my $currdom = $dom;
10072:     my @alldoms = &Apache::lonnet::all_domains();
10073:     if (@alldoms == 1) {
10074:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10075:                                                ['directorysrch'],$alldoms[0]);
10076:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10077:         my $showdom = $domdesc;
10078:         if ($showdom eq '') {
10079:             $showdom = $dom;
10080:         }
10081:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10082:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10083:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10084:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10085:             }
10086:         }
10087:     }
10088:     my %curr_selected = (
10089:                         srchin => 'dom',
10090:                         srchby => 'lastname',
10091:                       );
10092:     my $srchterm;
10093:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10094:         if ($srch->{'srchby'} ne '') {
10095:             $curr_selected{'srchby'} = $srch->{'srchby'};
10096:         }
10097:         if ($srch->{'srchin'} ne '') {
10098:             $curr_selected{'srchin'} = $srch->{'srchin'};
10099:         }
10100:         if ($srch->{'srchtype'} ne '') {
10101:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10102:         }
10103:         if ($srch->{'srchdomain'} ne '') {
10104:             $currdom = $srch->{'srchdomain'};
10105:         }
10106:         $srchterm = $srch->{'srchterm'};
10107:     }
10108:     my %html_lt=&Apache::lonlocal::texthash(
10109:                     'usr'       => 'Search criteria',
10110:                     'doma'      => 'Domain/institution to search',
10111:                     'uname'     => 'username',
10112:                     'lastname'  => 'last name',
10113:                     'lastfirst' => 'last name, first name',
10114:                     'crs'       => 'in this course',
10115:                     'dom'       => 'in selected LON-CAPA domain', 
10116:                     'alc'       => 'all LON-CAPA',
10117:                     'instd'     => 'in institutional directory for selected domain',
10118:                     'exact'     => 'is',
10119:                     'contains'  => 'contains',
10120:                     'begins'    => 'begins with',
10121:                                        );
10122:     my %js_lt=&Apache::lonlocal::texthash(
10123:                     'youm'      => "You must include some text to search for.",
10124:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10125:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10126:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10127:                     'ymcd'      => "You must choose a domain when using a domain search.",
10128:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10129:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10130:                      'thfo'     => "The following need to be corrected before the search can be run:",
10131:                                        );
10132:     &html_escape(\%html_lt);
10133:     &js_escape(\%js_lt);
10134:     my $domform;
10135:     my $allow_blank = 1;
10136:     if ($fixeddom) {
10137:         $allow_blank = 0;
10138:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10139:     } else {
10140:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10141:     }
10142:     my $srchinsel = ' <select name="srchin">';
10143: 
10144:     my @srchins = ('crs','dom','alc','instd');
10145: 
10146:     foreach my $option (@srchins) {
10147:         # FIXME 'alc' option unavailable until 
10148:         #       loncreateuser::print_user_query_page()
10149:         #       has been completed.
10150:         next if ($option eq 'alc');
10151:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10152:         next if ($option eq 'crs' && !$env{'request.course.id'});
10153:         next if (($option eq 'instd') && ($noinstd));
10154:         if ($curr_selected{'srchin'} eq $option) {
10155:             $srchinsel .= ' 
10156:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10157:         } else {
10158:             $srchinsel .= '
10159:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10160:         }
10161:     }
10162:     $srchinsel .= "\n  </select>\n";
10163: 
10164:     my $srchbysel =  ' <select name="srchby">';
10165:     foreach my $option ('lastname','lastfirst','uname') {
10166:         if ($curr_selected{'srchby'} eq $option) {
10167:             $srchbysel .= '
10168:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10169:         } else {
10170:             $srchbysel .= '
10171:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10172:          }
10173:     }
10174:     $srchbysel .= "\n  </select>\n";
10175: 
10176:     my $srchtypesel = ' <select name="srchtype">';
10177:     foreach my $option ('begins','contains','exact') {
10178:         if ($curr_selected{'srchtype'} eq $option) {
10179:             $srchtypesel .= '
10180:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10181:         } else {
10182:             $srchtypesel .= '
10183:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10184:         }
10185:     }
10186:     $srchtypesel .= "\n  </select>\n";
10187: 
10188:     my ($newuserscript,$new_user_create);
10189:     my $context_dom = $env{'request.role.domain'};
10190:     if ($context eq 'requestcrs') {
10191:         if ($env{'form.coursedom'} ne '') { 
10192:             $context_dom = $env{'form.coursedom'};
10193:         }
10194:     }
10195:     if ($forcenewuser) {
10196:         if (ref($srch) eq 'HASH') {
10197:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10198:                 if ($cancreate) {
10199:                     $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>';
10200:                 } else {
10201:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10202:                     my %usertypetext = (
10203:                         official   => 'institutional',
10204:                         unofficial => 'non-institutional',
10205:                     );
10206:                     $new_user_create = '<p class="LC_warning">'
10207:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10208:                                       .' '
10209:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10210:                                           ,'<a href="'.$helplink.'">','</a>')
10211:                                       .'</p><br />';
10212:                 }
10213:             }
10214:         }
10215: 
10216:         $newuserscript = <<"ENDSCRIPT";
10217: 
10218: function setSearch(createnew,callingForm) {
10219:     if (createnew == 1) {
10220:         for (var i=0; i<callingForm.srchby.length; i++) {
10221:             if (callingForm.srchby.options[i].value == 'uname') {
10222:                 callingForm.srchby.selectedIndex = i;
10223:             }
10224:         }
10225:         for (var i=0; i<callingForm.srchin.length; i++) {
10226:             if ( callingForm.srchin.options[i].value == 'dom') {
10227: 		callingForm.srchin.selectedIndex = i;
10228:             }
10229:         }
10230:         for (var i=0; i<callingForm.srchtype.length; i++) {
10231:             if (callingForm.srchtype.options[i].value == 'exact') {
10232:                 callingForm.srchtype.selectedIndex = i;
10233:             }
10234:         }
10235:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10236:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10237:                 callingForm.srchdomain.selectedIndex = i;
10238:             }
10239:         }
10240:     }
10241: }
10242: ENDSCRIPT
10243: 
10244:     }
10245: 
10246:     my $output = <<"END_BLOCK";
10247: <script type="text/javascript">
10248: // <![CDATA[
10249: function validateEntry(callingForm) {
10250: 
10251:     var checkok = 1;
10252:     var srchin;
10253:     for (var i=0; i<callingForm.srchin.length; i++) {
10254: 	if ( callingForm.srchin[i].checked ) {
10255: 	    srchin = callingForm.srchin[i].value;
10256: 	}
10257:     }
10258: 
10259:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10260:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10261:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10262:     var srchterm =  callingForm.srchterm.value;
10263:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10264:     var msg = "";
10265: 
10266:     if (srchterm == "") {
10267:         checkok = 0;
10268:         msg += "$js_lt{'youm'}\\n";
10269:     }
10270: 
10271:     if (srchtype== 'begins') {
10272:         if (srchterm.length < 2) {
10273:             checkok = 0;
10274:             msg += "$js_lt{'thte'}\\n";
10275:         }
10276:     }
10277: 
10278:     if (srchtype== 'contains') {
10279:         if (srchterm.length < 3) {
10280:             checkok = 0;
10281:             msg += "$js_lt{'thet'}\\n";
10282:         }
10283:     }
10284:     if (srchin == 'instd') {
10285:         if (srchdomain == '') {
10286:             checkok = 0;
10287:             msg += "$js_lt{'yomc'}\\n";
10288:         }
10289:     }
10290:     if (srchin == 'dom') {
10291:         if (srchdomain == '') {
10292:             checkok = 0;
10293:             msg += "$js_lt{'ymcd'}\\n";
10294:         }
10295:     }
10296:     if (srchby == 'lastfirst') {
10297:         if (srchterm.indexOf(",") == -1) {
10298:             checkok = 0;
10299:             msg += "$js_lt{'whus'}\\n";
10300:         }
10301:         if (srchterm.indexOf(",") == srchterm.length -1) {
10302:             checkok = 0;
10303:             msg += "$js_lt{'whse'}\\n";
10304:         }
10305:     }
10306:     if (checkok == 0) {
10307:         alert("$js_lt{'thfo'}\\n"+msg);
10308:         return;
10309:     }
10310:     if (checkok == 1) {
10311:         callingForm.submit();
10312:     }
10313: }
10314: 
10315: $newuserscript
10316: 
10317: // ]]>
10318: </script>
10319: 
10320: $new_user_create
10321: 
10322: END_BLOCK
10323: 
10324:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10325:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10326:                $domform.
10327:                &Apache::lonhtmlcommon::row_closure().
10328:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10329:                $srchbysel.
10330:                $srchtypesel. 
10331:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10332:                $srchinsel.
10333:                &Apache::lonhtmlcommon::row_closure(1). 
10334:                &Apache::lonhtmlcommon::end_pick_box().
10335:                '<br />';
10336:     return ($output,1);
10337: }
10338: 
10339: sub user_rule_check {
10340:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10341:     my ($response,%inst_response);
10342:     if (ref($usershash) eq 'HASH') {
10343:         if (keys(%{$usershash}) > 1) {
10344:             my (%by_username,%by_id,%userdoms);
10345:             my $checkid; 
10346:             if (ref($checks) eq 'HASH') {
10347:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10348:                     $checkid = 1;
10349:                 }
10350:             }
10351:             foreach my $user (keys(%{$usershash})) {
10352:                 my ($uname,$udom) = split(/:/,$user);
10353:                 if ($checkid) {
10354:                     if (ref($usershash->{$user}) eq 'HASH') {
10355:                         if ($usershash->{$user}->{'id'} ne '') {
10356:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10357:                             $userdoms{$udom} = 1;
10358:                             if (ref($inst_results) eq 'HASH') {
10359:                                 $inst_results->{$uname.':'.$udom} = {};
10360:                             }
10361:                         }
10362:                     }
10363:                 } else {
10364:                     $by_username{$udom}{$uname} = 1;
10365:                     $userdoms{$udom} = 1;
10366:                     if (ref($inst_results) eq 'HASH') {
10367:                         $inst_results->{$uname.':'.$udom} = {};
10368:                     }
10369:                 }
10370:             }
10371:             foreach my $udom (keys(%userdoms)) {
10372:                 if (!$got_rules->{$udom}) {
10373:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10374:                                                              ['usercreation'],$udom);
10375:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10376:                         foreach my $item ('username','id') {
10377:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10378:                                 $$curr_rules{$udom}{$item} =
10379:                                     $domconfig{'usercreation'}{$item.'_rule'};
10380:                             }
10381:                         }
10382:                     }
10383:                     $got_rules->{$udom} = 1;
10384:                 }
10385:             }
10386:             if ($checkid) {
10387:                 foreach my $udom (keys(%by_id)) {
10388:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10389:                     if ($outcome eq 'ok') {
10390:                         foreach my $id (keys(%{$by_id{$udom}})) {
10391:                             my $uname = $by_id{$udom}{$id};
10392:                             $inst_response{$uname.':'.$udom} = $outcome;
10393:                         }
10394:                         if (ref($results) eq 'HASH') {
10395:                             foreach my $uname (keys(%{$results})) {
10396:                                 if (exists($inst_response{$uname.':'.$udom})) {
10397:                                     $inst_response{$uname.':'.$udom} = $outcome;
10398:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10399:                                 }
10400:                             }
10401:                         }
10402:                     }
10403:                 }
10404:             } else {
10405:                 foreach my $udom (keys(%by_username)) {
10406:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10407:                     if ($outcome eq 'ok') {
10408:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10409:                             $inst_response{$uname.':'.$udom} = $outcome;
10410:                         }
10411:                         if (ref($results) eq 'HASH') {
10412:                             foreach my $uname (keys(%{$results})) {
10413:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10414:                             }
10415:                         }
10416:                     }
10417:                 }
10418:             }
10419:         } elsif (keys(%{$usershash}) == 1) {
10420:             my $user = (keys(%{$usershash}))[0];
10421:             my ($uname,$udom) = split(/:/,$user);
10422:             if (($udom ne '') && ($uname ne '')) {
10423:                 if (ref($usershash->{$user}) eq 'HASH') {
10424:                     if (ref($checks) eq 'HASH') {
10425:                         if (defined($checks->{'username'})) {
10426:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10427:                                 &Apache::lonnet::get_instuser($udom,$uname);
10428:                         } elsif (defined($checks->{'id'})) {
10429:                             if ($usershash->{$user}->{'id'} ne '') {
10430:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10431:                                     &Apache::lonnet::get_instuser($udom,undef,
10432:                                                                   $usershash->{$user}->{'id'});
10433:                             } else {
10434:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10435:                                     &Apache::lonnet::get_instuser($udom,$uname);
10436:                             }
10437:                         }
10438:                     } else {
10439:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10440:                             &Apache::lonnet::get_instuser($udom,$uname);
10441:                        return;
10442:                     }
10443:                     if (!$got_rules->{$udom}) {
10444:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10445:                                                                  ['usercreation'],$udom);
10446:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10447:                             foreach my $item ('username','id') {
10448:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10449:                                    $$curr_rules{$udom}{$item} = 
10450:                                        $domconfig{'usercreation'}{$item.'_rule'};
10451:                                 }
10452:                             }
10453:                         }
10454:                         $got_rules->{$udom} = 1;
10455:                     }
10456:                 }
10457:             } else {
10458:                 return;
10459:             }
10460:         } else {
10461:             return;
10462:         }
10463:         foreach my $user (keys(%{$usershash})) {
10464:             my ($uname,$udom) = split(/:/,$user);
10465:             next if (($udom eq '') || ($uname eq ''));
10466:             my $id;
10467:             if (ref($inst_results) eq 'HASH') {
10468:                 if (ref($inst_results->{$user}) eq 'HASH') {
10469:                     $id = $inst_results->{$user}->{'id'};
10470:                 }
10471:             }
10472:             if ($id eq '') { 
10473:                 if (ref($usershash->{$user})) {
10474:                     $id = $usershash->{$user}->{'id'};
10475:                 }
10476:             }
10477:             foreach my $item (keys(%{$checks})) {
10478:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10479:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10480:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10481:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10482:                                                                              $$curr_rules{$udom}{$item});
10483:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10484:                                 if ($rule_check{$rule}) {
10485:                                     $$rulematch{$user}{$item} = $rule;
10486:                                     if ($inst_response{$user} eq 'ok') {
10487:                                         if (ref($inst_results) eq 'HASH') {
10488:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10489:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10490:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10491:                                                 } elsif ($item eq 'id') {
10492:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10493:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10494:                                                     }
10495:                                                 }
10496:                                             }
10497:                                         }
10498:                                     }
10499:                                     last;
10500:                                 }
10501:                             }
10502:                         }
10503:                     }
10504:                 }
10505:             }
10506:         }
10507:     }
10508:     return;
10509: }
10510: 
10511: sub user_rule_formats {
10512:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10513:     my %text = ( 
10514:                  'username' => 'Usernames',
10515:                  'id'       => 'IDs',
10516:                );
10517:     my $output;
10518:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10519:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10520:         if (@{$ruleorder} > 0) {
10521:             $output = '<br />'.
10522:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10523:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10524:                       ' <ul>';
10525:             foreach my $rule (@{$ruleorder}) {
10526:                 if (ref($curr_rules) eq 'ARRAY') {
10527:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10528:                         if (ref($rules->{$rule}) eq 'HASH') {
10529:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10530:                                         $rules->{$rule}{'desc'}.'</li>';
10531:                         }
10532:                     }
10533:                 }
10534:             }
10535:             $output .= '</ul>';
10536:         }
10537:     }
10538:     return $output;
10539: }
10540: 
10541: sub instrule_disallow_msg {
10542:     my ($checkitem,$domdesc,$count,$mode) = @_;
10543:     my $response;
10544:     my %text = (
10545:                   item   => 'username',
10546:                   items  => 'usernames',
10547:                   match  => 'matches',
10548:                   do     => 'does',
10549:                   action => 'a username',
10550:                   one    => 'one',
10551:                );
10552:     if ($count > 1) {
10553:         $text{'item'} = 'usernames';
10554:         $text{'match'} ='match';
10555:         $text{'do'} = 'do';
10556:         $text{'action'} = 'usernames',
10557:         $text{'one'} = 'ones';
10558:     }
10559:     if ($checkitem eq 'id') {
10560:         $text{'items'} = 'IDs';
10561:         $text{'item'} = 'ID';
10562:         $text{'action'} = 'an ID';
10563:         if ($count > 1) {
10564:             $text{'item'} = 'IDs';
10565:             $text{'action'} = 'IDs';
10566:         }
10567:     }
10568:     $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 />';
10569:     if ($mode eq 'upload') {
10570:         if ($checkitem eq 'username') {
10571:             $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'}.");
10572:         } elsif ($checkitem eq 'id') {
10573:             $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.");
10574:         }
10575:     } elsif ($mode eq 'selfcreate') {
10576:         if ($checkitem eq 'id') {
10577:             $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.");
10578:         }
10579:     } else {
10580:         if ($checkitem eq 'username') {
10581:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10582:         } elsif ($checkitem eq 'id') {
10583:             $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.");
10584:         }
10585:     }
10586:     return $response;
10587: }
10588: 
10589: sub personal_data_fieldtitles {
10590:     my %fieldtitles = &Apache::lonlocal::texthash (
10591:                         id => 'Student/Employee ID',
10592:                         permanentemail => 'E-mail address',
10593:                         lastname => 'Last Name',
10594:                         firstname => 'First Name',
10595:                         middlename => 'Middle Name',
10596:                         generation => 'Generation',
10597:                         gen => 'Generation',
10598:                         inststatus => 'Affiliation',
10599:                    );
10600:     return %fieldtitles;
10601: }
10602: 
10603: sub sorted_inst_types {
10604:     my ($dom) = @_;
10605:     my ($usertypes,$order);
10606:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10607:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10608:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10609:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10610:     } else {
10611:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10612:     }
10613:     my $othertitle = &mt('All users');
10614:     if ($env{'request.course.id'}) {
10615:         $othertitle  = &mt('Any users');
10616:     }
10617:     my @types;
10618:     if (ref($order) eq 'ARRAY') {
10619:         @types = @{$order};
10620:     }
10621:     if (@types == 0) {
10622:         if (ref($usertypes) eq 'HASH') {
10623:             @types = sort(keys(%{$usertypes}));
10624:         }
10625:     }
10626:     if (keys(%{$usertypes}) > 0) {
10627:         $othertitle = &mt('Other users');
10628:     }
10629:     return ($othertitle,$usertypes,\@types);
10630: }
10631: 
10632: sub get_institutional_codes {
10633:     my ($settings,$allcourses,$LC_code) = @_;
10634: # Get complete list of course sections to update
10635:     my @currsections = ();
10636:     my @currxlists = ();
10637:     my $coursecode = $$settings{'internal.coursecode'};
10638: 
10639:     if ($$settings{'internal.sectionnums'} ne '') {
10640:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10641:     }
10642: 
10643:     if ($$settings{'internal.crosslistings'} ne '') {
10644:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10645:     }
10646: 
10647:     if (@currxlists > 0) {
10648:         foreach (@currxlists) {
10649:             if (m/^([^:]+):(\w*)$/) {
10650:                 unless (grep/^$1$/,@{$allcourses}) {
10651:                     push(@{$allcourses},$1);
10652:                     $$LC_code{$1} = $2;
10653:                 }
10654:             }
10655:         }
10656:     }
10657:  
10658:     if (@currsections > 0) {
10659:         foreach (@currsections) {
10660:             if (m/^(\w+):(\w*)$/) {
10661:                 my $sec = $coursecode.$1;
10662:                 my $lc_sec = $2;
10663:                 unless (grep/^$sec$/,@{$allcourses}) {
10664:                     push(@{$allcourses},$sec);
10665:                     $$LC_code{$sec} = $lc_sec;
10666:                 }
10667:             }
10668:         }
10669:     }
10670:     return;
10671: }
10672: 
10673: sub get_standard_codeitems {
10674:     return ('Year','Semester','Department','Number','Section');
10675: }
10676: 
10677: =pod
10678: 
10679: =head1 Slot Helpers
10680: 
10681: =over 4
10682: 
10683: =item * sorted_slots()
10684: 
10685: Sorts an array of slot names in order of an optional sort key,
10686: default sort is by slot start time (earliest first). 
10687: 
10688: Inputs:
10689: 
10690: =over 4
10691: 
10692: slotsarr  - Reference to array of unsorted slot names.
10693: 
10694: slots     - Reference to hash of hash, where outer hash keys are slot names.
10695: 
10696: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10697: 
10698: =back
10699: 
10700: Returns:
10701: 
10702: =over 4
10703: 
10704: sorted   - An array of slot names sorted by a specified sort key 
10705:            (default sort key is start time of the slot).
10706: 
10707: =back
10708: 
10709: =cut
10710: 
10711: 
10712: sub sorted_slots {
10713:     my ($slotsarr,$slots,$sortkey) = @_;
10714:     if ($sortkey eq '') {
10715:         $sortkey = 'starttime';
10716:     }
10717:     my @sorted;
10718:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10719:         @sorted =
10720:             sort {
10721:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10722:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10723:                      }
10724:                      if (ref($slots->{$a})) { return -1;}
10725:                      if (ref($slots->{$b})) { return 1;}
10726:                      return 0;
10727:                  } @{$slotsarr};
10728:     }
10729:     return @sorted;
10730: }
10731: 
10732: =pod
10733: 
10734: =item * get_future_slots()
10735: 
10736: Inputs:
10737: 
10738: =over 4
10739: 
10740: cnum - course number
10741: 
10742: cdom - course domain
10743: 
10744: now - current UNIX time
10745: 
10746: symb - optional symb
10747: 
10748: =back
10749: 
10750: Returns:
10751: 
10752: =over 4
10753: 
10754: sorted_reservable - ref to array of student_schedulable slots currently 
10755:                     reservable, ordered by end date of reservation period.
10756: 
10757: reservable_now - ref to hash of student_schedulable slots currently
10758:                  reservable.
10759: 
10760:     Keys in inner hash are:
10761:     (a) symb: either blank or symb to which slot use is restricted.
10762:     (b) endreserve: end date of reservation period.
10763:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10764:         selected.
10765: 
10766: sorted_future - ref to array of student_schedulable slots reservable in
10767:                 the future, ordered by start date of reservation period.
10768: 
10769: future_reservable - ref to hash of student_schedulable slots reservable
10770:                     in the future.
10771: 
10772:     Keys in inner hash are:
10773:     (a) symb: either blank or symb to which slot use is restricted.
10774:     (b) startreserve: start date of reservation period.
10775:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10776:         selected.
10777: 
10778: =back
10779: 
10780: =cut
10781: 
10782: sub get_future_slots {
10783:     my ($cnum,$cdom,$now,$symb) = @_;
10784:     my $map;
10785:     if ($symb) {
10786:         ($map) = &Apache::lonnet::decode_symb($symb);
10787:     }
10788:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10789:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10790:     foreach my $slot (keys(%slots)) {
10791:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10792:         if ($symb) {
10793:             if ($slots{$slot}->{'symb'} ne '') {
10794:                 my $canuse;
10795:                 my %oksymbs;
10796:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10797:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10798:                 if ($oksymbs{$symb}) {
10799:                     $canuse = 1;
10800:                 } else {
10801:                     foreach my $item (@slotsymbs) {
10802:                         if ($item =~ /\.(page|sequence)$/) {
10803:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10804:                             if (($map ne '') && ($map eq $sloturl)) {
10805:                                 $canuse = 1;
10806:                                 last;
10807:                             }
10808:                         }
10809:                     }
10810:                 }
10811:                 next unless ($canuse);
10812:             }
10813:         }
10814:         if (($slots{$slot}->{'starttime'} > $now) &&
10815:             ($slots{$slot}->{'endtime'} > $now)) {
10816:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10817:                 my $userallowed = 0;
10818:                 if ($slots{$slot}->{'allowedsections'}) {
10819:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10820:                     if (!defined($env{'request.role.sec'})
10821:                         && grep(/^No section assigned$/,@allowed_sec)) {
10822:                         $userallowed=1;
10823:                     } else {
10824:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10825:                             $userallowed=1;
10826:                         }
10827:                     }
10828:                     unless ($userallowed) {
10829:                         if (defined($env{'request.course.groups'})) {
10830:                             my @groups = split(/:/,$env{'request.course.groups'});
10831:                             foreach my $group (@groups) {
10832:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10833:                                     $userallowed=1;
10834:                                     last;
10835:                                 }
10836:                             }
10837:                         }
10838:                     }
10839:                 }
10840:                 if ($slots{$slot}->{'allowedusers'}) {
10841:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10842:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10843:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10844:                         $userallowed = 1;
10845:                     }
10846:                 }
10847:                 next unless($userallowed);
10848:             }
10849:             my $startreserve = $slots{$slot}->{'startreserve'};
10850:             my $endreserve = $slots{$slot}->{'endreserve'};
10851:             my $symb = $slots{$slot}->{'symb'};
10852:             my $uniqueperiod;
10853:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10854:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10855:             }
10856:             if (($startreserve < $now) &&
10857:                 (!$endreserve || $endreserve > $now)) {
10858:                 my $lastres = $endreserve;
10859:                 if (!$lastres) {
10860:                     $lastres = $slots{$slot}->{'starttime'};
10861:                 }
10862:                 $reservable_now{$slot} = {
10863:                                            symb       => $symb,
10864:                                            endreserve => $lastres,
10865:                                            uniqueperiod => $uniqueperiod,
10866:                                          };
10867:             } elsif (($startreserve > $now) &&
10868:                      (!$endreserve || $endreserve > $startreserve)) {
10869:                 $future_reservable{$slot} = {
10870:                                               symb         => $symb,
10871:                                               startreserve => $startreserve,
10872:                                               uniqueperiod => $uniqueperiod,
10873:                                             };
10874:             }
10875:         }
10876:     }
10877:     my @unsorted_reservable = keys(%reservable_now);
10878:     if (@unsorted_reservable > 0) {
10879:         @sorted_reservable = 
10880:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10881:     }
10882:     my @unsorted_future = keys(%future_reservable);
10883:     if (@unsorted_future > 0) {
10884:         @sorted_future =
10885:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10886:     }
10887:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10888: }
10889: 
10890: =pod
10891: 
10892: =back
10893: 
10894: =head1 HTTP Helpers
10895: 
10896: =over 4
10897: 
10898: =item * &get_unprocessed_cgi($query,$possible_names)
10899: 
10900: Modify the %env hash to contain unprocessed CGI form parameters held in
10901: $query.  The parameters listed in $possible_names (an array reference),
10902: will be set in $env{'form.name'} if they do not already exist.
10903: 
10904: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10905: $possible_names is an ref to an array of form element names.  As an example:
10906: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10907: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10908: 
10909: =cut
10910: 
10911: sub get_unprocessed_cgi {
10912:   my ($query,$possible_names)= @_;
10913:   # $Apache::lonxml::debug=1;
10914:   foreach my $pair (split(/&/,$query)) {
10915:     my ($name, $value) = split(/=/,$pair);
10916:     $name = &unescape($name);
10917:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10918:       $value =~ tr/+/ /;
10919:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10920:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10921:     }
10922:   }
10923: }
10924: 
10925: =pod
10926: 
10927: =item * &cacheheader() 
10928: 
10929: returns cache-controlling header code
10930: 
10931: =cut
10932: 
10933: sub cacheheader {
10934:     unless ($env{'request.method'} eq 'GET') { return ''; }
10935:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10936:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10937:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10938:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10939:     return $output;
10940: }
10941: 
10942: =pod
10943: 
10944: =item * &no_cache($r) 
10945: 
10946: specifies header code to not have cache
10947: 
10948: =cut
10949: 
10950: sub no_cache {
10951:     my ($r) = @_;
10952:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10953: 	$env{'request.method'} ne 'GET') { return ''; }
10954:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10955:     $r->no_cache(1);
10956:     $r->header_out("Expires" => $date);
10957:     $r->header_out("Pragma" => "no-cache");
10958: }
10959: 
10960: sub content_type {
10961:     my ($r,$type,$charset) = @_;
10962:     if ($r) {
10963: 	#  Note that printout.pl calls this with undef for $r.
10964: 	&no_cache($r);
10965:     }
10966:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10967:     unless ($charset) {
10968: 	$charset=&Apache::lonlocal::current_encoding;
10969:     }
10970:     if ($charset) { $type.='; charset='.$charset; }
10971:     if ($r) {
10972: 	$r->content_type($type);
10973:     } else {
10974: 	print("Content-type: $type\n\n");
10975:     }
10976: }
10977: 
10978: =pod
10979: 
10980: =item * &add_to_env($name,$value) 
10981: 
10982: adds $name to the %env hash with value
10983: $value, if $name already exists, the entry is converted to an array
10984: reference and $value is added to the array.
10985: 
10986: =cut
10987: 
10988: sub add_to_env {
10989:   my ($name,$value)=@_;
10990:   if (defined($env{$name})) {
10991:     if (ref($env{$name})) {
10992:       #already have multiple values
10993:       push(@{ $env{$name} },$value);
10994:     } else {
10995:       #first time seeing multiple values, convert hash entry to an arrayref
10996:       my $first=$env{$name};
10997:       undef($env{$name});
10998:       push(@{ $env{$name} },$first,$value);
10999:     }
11000:   } else {
11001:     $env{$name}=$value;
11002:   }
11003: }
11004: 
11005: =pod
11006: 
11007: =item * &get_env_multiple($name) 
11008: 
11009: gets $name from the %env hash, it seemlessly handles the cases where multiple
11010: values may be defined and end up as an array ref.
11011: 
11012: returns an array of values
11013: 
11014: =cut
11015: 
11016: sub get_env_multiple {
11017:     my ($name) = @_;
11018:     my @values;
11019:     if (defined($env{$name})) {
11020:         # exists is it an array
11021:         if (ref($env{$name})) {
11022:             @values=@{ $env{$name} };
11023:         } else {
11024:             $values[0]=$env{$name};
11025:         }
11026:     }
11027:     return(@values);
11028: }
11029: 
11030: # Looks at given dependencies, and returns something depending on the context.
11031: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11032: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11033: # For all other contexts, returns ($output, $counter, $numpathchg).
11034: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11035: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11036: # $numpathchg: integer with the number of cleaned up dependency paths.
11037: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11038: # \%mapping: hash reference clean path -> original path for all dependencies.
11039: # @param {string} actionurl - The path to the handler, indicative of the context.
11040: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11041: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11042: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11043: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11044: # @return {Array} - array depending on the context (not a reference)
11045: sub ask_for_embedded_content {
11046:     # NOTE: documentation was added afterwards, it could be wrong
11047:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11048:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11049:         %currsubfile,%unused,$rem);
11050:     my $counter = 0;
11051:     my $numnew = 0;
11052:     my $numremref = 0;
11053:     my $numinvalid = 0;
11054:     my $numpathchg = 0;
11055:     my $numexisting = 0;
11056:     my $numunused = 0;
11057:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11058:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11059:     my $heading = &mt('Upload embedded files');
11060:     my $buttontext = &mt('Upload');
11061: 
11062:     # fills these variables based on the context:
11063:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11064:     # $path, $fileloc, $title, $rem, $filename
11065:     if ($env{'request.course.id'}) {
11066:         if ($actionurl eq '/adm/dependencies') {
11067:             $navmap = Apache::lonnavmaps::navmap->new();
11068:         }
11069:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11070:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11071:     }
11072:     if (($actionurl eq '/adm/portfolio') || 
11073:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11074:         my $current_path='/';
11075:         if ($env{'form.currentpath'}) {
11076:             $current_path = $env{'form.currentpath'};
11077:         }
11078:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11079:             $udom = $cdom;
11080:             $uname = $cnum;
11081:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11082:         } else {
11083:             $udom = $env{'user.domain'};
11084:             $uname = $env{'user.name'};
11085:             $url = '/userfiles/portfolio';
11086:         }
11087:         $toplevel = $url.'/';
11088:         $url .= $current_path;
11089:         $getpropath = 1;
11090:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11091:              ($actionurl eq '/adm/imsimport')) { 
11092:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11093:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11094:         $toplevel = $url;
11095:         if ($rest ne '') {
11096:             $url .= $rest;
11097:         }
11098:     } elsif ($actionurl eq '/adm/coursedocs') {
11099:         if (ref($args) eq 'HASH') {
11100:             $url = $args->{'docs_url'};
11101:             $toplevel = $url;
11102:             if ($args->{'context'} eq 'paste') {
11103:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11104:                 ($path) = 
11105:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11106:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11107:                 $fileloc =~ s{^/}{};
11108:             }
11109:         }
11110:     } elsif ($actionurl eq '/adm/dependencies')  {
11111:         if ($env{'request.course.id'} ne '') {
11112:             if (ref($args) eq 'HASH') {
11113:                 $url = $args->{'docs_url'};
11114:                 $title = $args->{'docs_title'};
11115:                 $toplevel = $url; 
11116:                 unless ($toplevel =~ m{^/}) {
11117:                     $toplevel = "/$url";
11118:                 }
11119:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11120:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11121:                     $path = $1;
11122:                 } else {
11123:                     ($path) =
11124:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11125:                 }
11126:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11127:                     $fileloc = $toplevel;
11128:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11129:                     my ($udom,$uname,$fname) =
11130:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11131:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11132:                 } else {
11133:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11134:                 }
11135:                 $fileloc =~ s{^/}{};
11136:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11137:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11138:             }
11139:         }
11140:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11141:         $udom = $cdom;
11142:         $uname = $cnum;
11143:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11144:         $toplevel = $url;
11145:         $path = $url;
11146:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11147:         $fileloc =~ s{^/}{};
11148:     }
11149:     
11150:     # parses the dependency paths to get some info
11151:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11152:     # $newfiles: hash URL -> 1 for new files or external URLs
11153:     # (will be completed later)
11154:     # $mapping:
11155:     #   for external URLs: external URL -> external URL
11156:     #   for relative paths: clean path -> original path
11157:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11158:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11159:     foreach my $file (keys(%{$allfiles})) {
11160:         my $embed_file;
11161:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11162:             $embed_file = $1;
11163:         } else {
11164:             $embed_file = $file;
11165:         }
11166:         my ($absolutepath,$cleaned_file);
11167:         if ($embed_file =~ m{^\w+://}) {
11168:             $cleaned_file = $embed_file;
11169:             $newfiles{$cleaned_file} = 1;
11170:             $mapping{$cleaned_file} = $embed_file;
11171:         } else {
11172:             $cleaned_file = &clean_path($embed_file);
11173:             if ($embed_file =~ m{^/}) {
11174:                 $absolutepath = $embed_file;
11175:             }
11176:             if ($cleaned_file =~ m{/}) {
11177:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11178:                 $path = &check_for_traversal($path,$url,$toplevel);
11179:                 my $item = $fname;
11180:                 if ($path ne '') {
11181:                     $item = $path.'/'.$fname;
11182:                     $subdependencies{$path}{$fname} = 1;
11183:                 } else {
11184:                     $dependencies{$item} = 1;
11185:                 }
11186:                 if ($absolutepath) {
11187:                     $mapping{$item} = $absolutepath;
11188:                 } else {
11189:                     $mapping{$item} = $embed_file;
11190:                 }
11191:             } else {
11192:                 $dependencies{$embed_file} = 1;
11193:                 if ($absolutepath) {
11194:                     $mapping{$cleaned_file} = $absolutepath;
11195:                 } else {
11196:                     $mapping{$cleaned_file} = $embed_file;
11197:                 }
11198:             }
11199:         }
11200:     }
11201:     
11202:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11203:     # and lists
11204:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11205:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11206:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11207:     #                                    the path had to be cleaned up
11208:     # $existing: hash clean path -> 1 if the file exists
11209:     # $numexisting: number of keys in $existing
11210:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11211:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11212:     #                                      dependency subdirectories that are
11213:     #                                      not listed as dependencies, with some exceptions using $rem
11214:     my $dirptr = 16384;
11215:     foreach my $path (keys(%subdependencies)) {
11216:         $currsubfile{$path} = {};
11217:         if (($actionurl eq '/adm/portfolio') || 
11218:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11219:             my ($sublistref,$listerror) =
11220:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11221:             if (ref($sublistref) eq 'ARRAY') {
11222:                 foreach my $line (@{$sublistref}) {
11223:                     my ($file_name,$rest) = split(/\&/,$line,2);
11224:                     $currsubfile{$path}{$file_name} = 1;
11225:                 }
11226:             }
11227:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11228:             if (opendir(my $dir,$url.'/'.$path)) {
11229:                 my @subdir_list = grep(!/^\./,readdir($dir));
11230:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11231:             }
11232:         } elsif (($actionurl eq '/adm/dependencies') ||
11233:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11234:                   ($args->{'context'} eq 'paste')) ||
11235:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11236:             if ($env{'request.course.id'} ne '') {
11237:                 my $dir;
11238:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11239:                     $dir = $fileloc;
11240:                 } else {
11241:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11242:                 }
11243:                 if ($dir ne '') {
11244:                     my ($sublistref,$listerror) =
11245:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11246:                     if (ref($sublistref) eq 'ARRAY') {
11247:                         foreach my $line (@{$sublistref}) {
11248:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11249:                                 undef,$mtime)=split(/\&/,$line,12);
11250:                             unless (($testdir&$dirptr) ||
11251:                                     ($file_name =~ /^\.\.?$/)) {
11252:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11253:                             }
11254:                         }
11255:                     }
11256:                 }
11257:             }
11258:         }
11259:         foreach my $file (keys(%{$subdependencies{$path}})) {
11260:             if (exists($currsubfile{$path}{$file})) {
11261:                 my $item = $path.'/'.$file;
11262:                 unless ($mapping{$item} eq $item) {
11263:                     $pathchanges{$item} = 1;
11264:                 }
11265:                 $existing{$item} = 1;
11266:                 $numexisting ++;
11267:             } else {
11268:                 $newfiles{$path.'/'.$file} = 1;
11269:             }
11270:         }
11271:         if ($actionurl eq '/adm/dependencies') {
11272:             foreach my $path (keys(%currsubfile)) {
11273:                 if (ref($currsubfile{$path}) eq 'HASH') {
11274:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11275:                          unless ($subdependencies{$path}{$file}) {
11276:                              next if (($rem ne '') &&
11277:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11278:                                        (ref($navmap) &&
11279:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11280:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11281:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11282:                              $unused{$path.'/'.$file} = 1; 
11283:                          }
11284:                     }
11285:                 }
11286:             }
11287:         }
11288:     }
11289:     
11290:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11291:     # for files in $url or $fileloc (target directory) in some contexts
11292:     my %currfile;
11293:     if (($actionurl eq '/adm/portfolio') ||
11294:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11295:         my ($dirlistref,$listerror) =
11296:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11297:         if (ref($dirlistref) eq 'ARRAY') {
11298:             foreach my $line (@{$dirlistref}) {
11299:                 my ($file_name,$rest) = split(/\&/,$line,2);
11300:                 $currfile{$file_name} = 1;
11301:             }
11302:         }
11303:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11304:         if (opendir(my $dir,$url)) {
11305:             my @dir_list = grep(!/^\./,readdir($dir));
11306:             map {$currfile{$_} = 1;} @dir_list;
11307:         }
11308:     } elsif (($actionurl eq '/adm/dependencies') ||
11309:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11310:               ($args->{'context'} eq 'paste')) ||
11311:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11312:         if ($env{'request.course.id'} ne '') {
11313:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11314:             if ($dir ne '') {
11315:                 my ($dirlistref,$listerror) =
11316:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11317:                 if (ref($dirlistref) eq 'ARRAY') {
11318:                     foreach my $line (@{$dirlistref}) {
11319:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11320:                             $size,undef,$mtime)=split(/\&/,$line,12);
11321:                         unless (($testdir&$dirptr) ||
11322:                                 ($file_name =~ /^\.\.?$/)) {
11323:                             $currfile{$file_name} = [$size,$mtime];
11324:                         }
11325:                     }
11326:                 }
11327:             }
11328:         }
11329:     }
11330:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11331:     # are not in subdirectories, using $currfile
11332:     foreach my $file (keys(%dependencies)) {
11333:         if (exists($currfile{$file})) {
11334:             unless ($mapping{$file} eq $file) {
11335:                 $pathchanges{$file} = 1;
11336:             }
11337:             $existing{$file} = 1;
11338:             $numexisting ++;
11339:         } else {
11340:             $newfiles{$file} = 1;
11341:         }
11342:     }
11343:     foreach my $file (keys(%currfile)) {
11344:         unless (($file eq $filename) ||
11345:                 ($file eq $filename.'.bak') ||
11346:                 ($dependencies{$file})) {
11347:             if ($actionurl eq '/adm/dependencies') {
11348:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11349:                     next if (($rem ne '') &&
11350:                              (($env{"httpref.$rem".$file} ne '') ||
11351:                               (ref($navmap) &&
11352:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11353:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11354:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11355:                 }
11356:             }
11357:             $unused{$file} = 1;
11358:         }
11359:     }
11360:     
11361:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11362:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11363:         ($args->{'context'} eq 'paste')) {
11364:         $counter = scalar(keys(%existing));
11365:         $numpathchg = scalar(keys(%pathchanges));
11366:         return ($output,$counter,$numpathchg,\%existing);
11367:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11368:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11369:         $counter = scalar(keys(%existing));
11370:         $numpathchg = scalar(keys(%pathchanges));
11371:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11372:     }
11373:     
11374:     # returns HTML otherwise, with dependency results and to ask for more uploads
11375:     
11376:     # $upload_output: missing dependencies (with upload form)
11377:     # $modify_output: uploaded dependencies (in use)
11378:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11379:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11380:         if ($actionurl eq '/adm/dependencies') {
11381:             next if ($embed_file =~ m{^\w+://});
11382:         }
11383:         $upload_output .= &start_data_table_row().
11384:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11385:                           '<span class="LC_filename">'.$embed_file.'</span>';
11386:         unless ($mapping{$embed_file} eq $embed_file) {
11387:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11388:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11389:         }
11390:         $upload_output .= '</td>';
11391:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11392:             $upload_output.='<td align="right">'.
11393:                             '<span class="LC_info LC_fontsize_medium">'.
11394:                             &mt("URL points to web address").'</span>';
11395:             $numremref++;
11396:         } elsif ($args->{'error_on_invalid_names'}
11397:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11398:             $upload_output.='<td align="right"><span class="LC_warning">'.
11399:                             &mt('Invalid characters').'</span>';
11400:             $numinvalid++;
11401:         } else {
11402:             $upload_output .= '<td>'.
11403:                               &embedded_file_element('upload_embedded',$counter,
11404:                                                      $embed_file,\%mapping,
11405:                                                      $allfiles,$codebase,'upload');
11406:             $counter ++;
11407:             $numnew ++;
11408:         }
11409:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11410:     }
11411:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11412:         if ($actionurl eq '/adm/dependencies') {
11413:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11414:             $modify_output .= &start_data_table_row().
11415:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11416:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11417:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11418:                               '<td>'.$size.'</td>'.
11419:                               '<td>'.$mtime.'</td>'.
11420:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11421:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11422:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11423:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11424:                               &embedded_file_element('upload_embedded',$counter,
11425:                                                      $embed_file,\%mapping,
11426:                                                      $allfiles,$codebase,'modify').
11427:                               '</div></td>'.
11428:                               &end_data_table_row()."\n";
11429:             $counter ++;
11430:         } else {
11431:             $upload_output .= &start_data_table_row().
11432:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11433:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11434:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11435:                               &Apache::loncommon::end_data_table_row()."\n";
11436:         }
11437:     }
11438:     my $delidx = $counter;
11439:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11440:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11441:         $delete_output .= &start_data_table_row().
11442:                           '<td><img src="'.&icon($oldfile).'" />'.
11443:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11444:                           '<td>'.$size.'</td>'.
11445:                           '<td>'.$mtime.'</td>'.
11446:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11447:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11448:                           &embedded_file_element('upload_embedded',$delidx,
11449:                                                  $oldfile,\%mapping,$allfiles,
11450:                                                  $codebase,'delete').'</td>'.
11451:                           &end_data_table_row()."\n"; 
11452:         $numunused ++;
11453:         $delidx ++;
11454:     }
11455:     if ($upload_output) {
11456:         $upload_output = &start_data_table().
11457:                          $upload_output.
11458:                          &end_data_table()."\n";
11459:     }
11460:     if ($modify_output) {
11461:         $modify_output = &start_data_table().
11462:                          &start_data_table_header_row().
11463:                          '<th>'.&mt('File').'</th>'.
11464:                          '<th>'.&mt('Size (KB)').'</th>'.
11465:                          '<th>'.&mt('Modified').'</th>'.
11466:                          '<th>'.&mt('Upload replacement?').'</th>'.
11467:                          &end_data_table_header_row().
11468:                          $modify_output.
11469:                          &end_data_table()."\n";
11470:     }
11471:     if ($delete_output) {
11472:         $delete_output = &start_data_table().
11473:                          &start_data_table_header_row().
11474:                          '<th>'.&mt('File').'</th>'.
11475:                          '<th>'.&mt('Size (KB)').'</th>'.
11476:                          '<th>'.&mt('Modified').'</th>'.
11477:                          '<th>'.&mt('Delete?').'</th>'.
11478:                          &end_data_table_header_row().
11479:                          $delete_output.
11480:                          &end_data_table()."\n";
11481:     }
11482:     my $applies = 0;
11483:     if ($numremref) {
11484:         $applies ++;
11485:     }
11486:     if ($numinvalid) {
11487:         $applies ++;
11488:     }
11489:     if ($numexisting) {
11490:         $applies ++;
11491:     }
11492:     if ($counter || $numunused) {
11493:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11494:                   ' method="post" enctype="multipart/form-data">'."\n".
11495:                   $state.'<h3>'.$heading.'</h3>'; 
11496:         if ($actionurl eq '/adm/dependencies') {
11497:             if ($numnew) {
11498:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11499:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11500:                            $upload_output.'<br />'."\n";
11501:             }
11502:             if ($numexisting) {
11503:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11504:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11505:                            $modify_output.'<br />'."\n";
11506:                            $buttontext = &mt('Save changes');
11507:             }
11508:             if ($numunused) {
11509:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11510:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11511:                            $delete_output.'<br />'."\n";
11512:                            $buttontext = &mt('Save changes');
11513:             }
11514:         } else {
11515:             $output .= $upload_output.'<br />'."\n";
11516:         }
11517:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11518:                    $counter.'" />'."\n";
11519:         if ($actionurl eq '/adm/dependencies') { 
11520:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11521:                        $numnew.'" />'."\n";
11522:         } elsif ($actionurl eq '') {
11523:             $output .=  '<input type="hidden" name="phase" value="three" />';
11524:         }
11525:     } elsif ($applies) {
11526:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11527:         if ($applies > 1) {
11528:             $output .=  
11529:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11530:             if ($numremref) {
11531:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11532:             }
11533:             if ($numinvalid) {
11534:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11535:             }
11536:             if ($numexisting) {
11537:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11538:             }
11539:             $output .= '</ul><br />';
11540:         } elsif ($numremref) {
11541:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11542:         } elsif ($numinvalid) {
11543:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11544:         } elsif ($numexisting) {
11545:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11546:         }
11547:         $output .= $upload_output.'<br />';
11548:     }
11549:     my ($pathchange_output,$chgcount);
11550:     $chgcount = $counter;
11551:     if (keys(%pathchanges) > 0) {
11552:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11553:             if ($counter) {
11554:                 $output .= &embedded_file_element('pathchange',$chgcount,
11555:                                                   $embed_file,\%mapping,
11556:                                                   $allfiles,$codebase,'change');
11557:             } else {
11558:                 $pathchange_output .= 
11559:                     &start_data_table_row().
11560:                     '<td><input type ="checkbox" name="namechange" value="'.
11561:                     $chgcount.'" checked="checked" /></td>'.
11562:                     '<td>'.$mapping{$embed_file}.'</td>'.
11563:                     '<td>'.$embed_file.
11564:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11565:                                            \%mapping,$allfiles,$codebase,'change').
11566:                     '</td>'.&end_data_table_row();
11567:             }
11568:             $numpathchg ++;
11569:             $chgcount ++;
11570:         }
11571:     }
11572:     if (($counter) || ($numunused)) {
11573:         if ($numpathchg) {
11574:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11575:                        $numpathchg.'" />'."\n";
11576:         }
11577:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11578:             ($actionurl eq '/adm/imsimport')) {
11579:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11580:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11581:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11582:         } elsif ($actionurl eq '/adm/dependencies') {
11583:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11584:         }
11585:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11586:     } elsif ($numpathchg) {
11587:         my %pathchange = ();
11588:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11589:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11590:             $output .= '<p>'.&mt('or').'</p>'; 
11591:         }
11592:     }
11593:     return ($output,$counter,$numpathchg);
11594: }
11595: 
11596: =pod
11597: 
11598: =item * clean_path($name)
11599: 
11600: Performs clean-up of directories, subdirectories and filename in an
11601: embedded object, referenced in an HTML file which is being uploaded
11602: to a course or portfolio, where 
11603: "Upload embedded images/multimedia files if HTML file" checkbox was
11604: checked.
11605: 
11606: Clean-up is similar to replacements in lonnet::clean_filename()
11607: except each / between sub-directory and next level is preserved.
11608: 
11609: =cut
11610: 
11611: sub clean_path {
11612:     my ($embed_file) = @_;
11613:     $embed_file =~s{^/+}{};
11614:     my @contents;
11615:     if ($embed_file =~ m{/}) {
11616:         @contents = split(/\//,$embed_file);
11617:     } else {
11618:         @contents = ($embed_file);
11619:     }
11620:     my $lastidx = scalar(@contents)-1;
11621:     for (my $i=0; $i<=$lastidx; $i++) { 
11622:         $contents[$i]=~s{\\}{/}g;
11623:         $contents[$i]=~s/\s+/\_/g;
11624:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11625:         if ($i == $lastidx) {
11626:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11627:         }
11628:     }
11629:     if ($lastidx > 0) {
11630:         return join('/',@contents);
11631:     } else {
11632:         return $contents[0];
11633:     }
11634: }
11635: 
11636: sub embedded_file_element {
11637:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11638:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11639:                    (ref($codebase) eq 'HASH'));
11640:     my $output;
11641:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11642:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11643:     }
11644:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11645:                &escape($embed_file).'" />';
11646:     unless (($context eq 'upload_embedded') && 
11647:             ($mapping->{$embed_file} eq $embed_file)) {
11648:         $output .='
11649:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11650:     }
11651:     my $attrib;
11652:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11653:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11654:     }
11655:     $output .=
11656:         "\n\t\t".
11657:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11658:         $attrib.'" />';
11659:     if (exists($codebase->{$mapping->{$embed_file}})) {
11660:         $output .=
11661:             "\n\t\t".
11662:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11663:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11664:     }
11665:     return $output;
11666: }
11667: 
11668: sub get_dependency_details {
11669:     my ($currfile,$currsubfile,$embed_file) = @_;
11670:     my ($size,$mtime,$showsize,$showmtime);
11671:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11672:         if ($embed_file =~ m{/}) {
11673:             my ($path,$fname) = split(/\//,$embed_file);
11674:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11675:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11676:             }
11677:         } else {
11678:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11679:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11680:             }
11681:         }
11682:         $showsize = $size/1024.0;
11683:         $showsize = sprintf("%.1f",$showsize);
11684:         if ($mtime > 0) {
11685:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11686:         }
11687:     }
11688:     return ($showsize,$showmtime);
11689: }
11690: 
11691: sub ask_embedded_js {
11692:     return <<"END";
11693: <script type="text/javascript"">
11694: // <![CDATA[
11695: function toggleBrowse(counter) {
11696:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11697:     var fileid = document.getElementById('embedded_item_'+counter);
11698:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11699:     if (chkboxid.checked == true) {
11700:         uploaddivid.style.display='block';
11701:     } else {
11702:         uploaddivid.style.display='none';
11703:         fileid.value = '';
11704:     }
11705: }
11706: // ]]>
11707: </script>
11708: 
11709: END
11710: }
11711: 
11712: sub upload_embedded {
11713:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11714:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11715:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11716:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11717:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11718:         my $orig_uploaded_filename =
11719:             $env{'form.embedded_item_'.$i.'.filename'};
11720:         foreach my $type ('orig','ref','attrib','codebase') {
11721:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11722:                 $env{'form.embedded_'.$type.'_'.$i} =
11723:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11724:             }
11725:         }
11726:         my ($path,$fname) =
11727:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11728:         # no path, whole string is fname
11729:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11730:         $fname = &Apache::lonnet::clean_filename($fname);
11731:         # See if there is anything left
11732:         next if ($fname eq '');
11733: 
11734:         # Check if file already exists as a file or directory.
11735:         my ($state,$msg);
11736:         if ($context eq 'portfolio') {
11737:             my $port_path = $dirpath;
11738:             if ($group ne '') {
11739:                 $port_path = "groups/$group/$port_path";
11740:             }
11741:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11742:                                               $fname,$group,'embedded_item_'.$i,
11743:                                               $dir_root,$port_path,$disk_quota,
11744:                                               $current_disk_usage,$uname,$udom);
11745:             if ($state eq 'will_exceed_quota'
11746:                 || $state eq 'file_locked') {
11747:                 $output .= $msg;
11748:                 next;
11749:             }
11750:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11751:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11752:             if ($state eq 'exists') {
11753:                 $output .= $msg;
11754:                 next;
11755:             }
11756:         }
11757:         # Check if extension is valid
11758:         if (($fname =~ /\.(\w+)$/) &&
11759:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11760:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11761:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11762:             next;
11763:         } elsif (($fname =~ /\.(\w+)$/) &&
11764:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11765:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11766:             next;
11767:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11768:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11769:             next;
11770:         }
11771:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11772:         my $subdir = $path;
11773:         $subdir =~ s{/+$}{};
11774:         if ($context eq 'portfolio') {
11775:             my $result;
11776:             if ($state eq 'existingfile') {
11777:                 $result=
11778:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11779:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11780:             } else {
11781:                 $result=
11782:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11783:                                                     $dirpath.
11784:                                                     $env{'form.currentpath'}.$subdir);
11785:                 if ($result !~ m|^/uploaded/|) {
11786:                     $output .= '<span class="LC_error">'
11787:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11788:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11789:                                .'</span><br />';
11790:                     next;
11791:                 } else {
11792:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11793:                                $path.$fname.'</span>').'<br />';     
11794:                 }
11795:             }
11796:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11797:             my $extendedsubdir = $dirpath.'/'.$subdir;
11798:             $extendedsubdir =~ s{/+$}{};
11799:             my $result =
11800:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11801:             if ($result !~ m|^/uploaded/|) {
11802:                 $output .= '<span class="LC_error">'
11803:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11804:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11805:                            .'</span><br />';
11806:                     next;
11807:             } else {
11808:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11809:                            $path.$fname.'</span>').'<br />';
11810:                 if ($context eq 'syllabus') {
11811:                     &Apache::lonnet::make_public_indefinitely($result);
11812:                 }
11813:             }
11814:         } else {
11815: # Save the file
11816:             my $target = $env{'form.embedded_item_'.$i};
11817:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11818:             my $dest = $fullpath.$fname;
11819:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11820:             my @parts=split(/\//,"$dirpath/$path");
11821:             my $count;
11822:             my $filepath = $dir_root;
11823:             foreach my $subdir (@parts) {
11824:                 $filepath .= "/$subdir";
11825:                 if (!-e $filepath) {
11826:                     mkdir($filepath,0770);
11827:                 }
11828:             }
11829:             my $fh;
11830:             if (!open($fh,'>'.$dest)) {
11831:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11832:                 $output .= '<span class="LC_error">'.
11833:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11834:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11835:                            '</span><br />';
11836:             } else {
11837:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11838:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11839:                     $output .= '<span class="LC_error">'.
11840:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11841:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11842:                               '</span><br />';
11843:                 } else {
11844:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11845:                                $url.'</span>').'<br />';
11846:                     unless ($context eq 'testbank') {
11847:                         $footer .= &mt('View embedded file: [_1]',
11848:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11849:                     }
11850:                 }
11851:                 close($fh);
11852:             }
11853:         }
11854:         if ($env{'form.embedded_ref_'.$i}) {
11855:             $pathchange{$i} = 1;
11856:         }
11857:     }
11858:     if ($output) {
11859:         $output = '<p>'.$output.'</p>';
11860:     }
11861:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11862:     $returnflag = 'ok';
11863:     my $numpathchgs = scalar(keys(%pathchange));
11864:     if ($numpathchgs > 0) {
11865:         if ($context eq 'portfolio') {
11866:             $output .= '<p>'.&mt('or').'</p>';
11867:         } elsif ($context eq 'testbank') {
11868:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11869:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11870:             $returnflag = 'modify_orightml';
11871:         }
11872:     }
11873:     return ($output.$footer,$returnflag,$numpathchgs);
11874: }
11875: 
11876: sub modify_html_form {
11877:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11878:     my $end = 0;
11879:     my $modifyform;
11880:     if ($context eq 'upload_embedded') {
11881:         return unless (ref($pathchange) eq 'HASH');
11882:         if ($env{'form.number_embedded_items'}) {
11883:             $end += $env{'form.number_embedded_items'};
11884:         }
11885:         if ($env{'form.number_pathchange_items'}) {
11886:             $end += $env{'form.number_pathchange_items'};
11887:         }
11888:         if ($end) {
11889:             for (my $i=0; $i<$end; $i++) {
11890:                 if ($i < $env{'form.number_embedded_items'}) {
11891:                     next unless($pathchange->{$i});
11892:                 }
11893:                 $modifyform .=
11894:                     &start_data_table_row().
11895:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11896:                     'checked="checked" /></td>'.
11897:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11898:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11899:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11900:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11901:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11902:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11903:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11904:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11905:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11906:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11907:                     &end_data_table_row();
11908:             }
11909:         }
11910:     } else {
11911:         $modifyform = $pathchgtable;
11912:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11913:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11914:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11915:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11916:         }
11917:     }
11918:     if ($modifyform) {
11919:         if ($actionurl eq '/adm/dependencies') {
11920:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11921:         }
11922:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11923:                '<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".
11924:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11925:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11926:                '</ol></p>'."\n".'<p>'.
11927:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11928:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11929:                &start_data_table()."\n".
11930:                &start_data_table_header_row().
11931:                '<th>'.&mt('Change?').'</th>'.
11932:                '<th>'.&mt('Current reference').'</th>'.
11933:                '<th>'.&mt('Required reference').'</th>'.
11934:                &end_data_table_header_row()."\n".
11935:                $modifyform.
11936:                &end_data_table().'<br />'."\n".$hiddenstate.
11937:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11938:                '</form>'."\n";
11939:     }
11940:     return;
11941: }
11942: 
11943: sub modify_html_refs {
11944:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11945:     my $container;
11946:     if ($context eq 'portfolio') {
11947:         $container = $env{'form.container'};
11948:     } elsif ($context eq 'coursedoc') {
11949:         $container = $env{'form.primaryurl'};
11950:     } elsif ($context eq 'manage_dependencies') {
11951:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11952:         $container = "/$container";
11953:     } elsif ($context eq 'syllabus') {
11954:         $container = $url;
11955:     } else {
11956:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11957:     }
11958:     my (%allfiles,%codebase,$output,$content);
11959:     my @changes = &get_env_multiple('form.namechange');
11960:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11961:         if (wantarray) {
11962:             return ('',0,0); 
11963:         } else {
11964:             return;
11965:         }
11966:     }
11967:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11968:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11969:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11970:             if (wantarray) {
11971:                 return ('',0,0);
11972:             } else {
11973:                 return;
11974:             }
11975:         } 
11976:         $content = &Apache::lonnet::getfile($container);
11977:         if ($content eq '-1') {
11978:             if (wantarray) {
11979:                 return ('',0,0);
11980:             } else {
11981:                 return;
11982:             }
11983:         }
11984:     } else {
11985:         unless ($container =~ /^\Q$dir_root\E/) {
11986:             if (wantarray) {
11987:                 return ('',0,0);
11988:             } else {
11989:                 return;
11990:             }
11991:         } 
11992:         if (open(my $fh,"<$container")) {
11993:             $content = join('', <$fh>);
11994:             close($fh);
11995:         } else {
11996:             if (wantarray) {
11997:                 return ('',0,0);
11998:             } else {
11999:                 return;
12000:             }
12001:         }
12002:     }
12003:     my ($count,$codebasecount) = (0,0);
12004:     my $mm = new File::MMagic;
12005:     my $mime_type = $mm->checktype_contents($content);
12006:     if ($mime_type eq 'text/html') {
12007:         my $parse_result = 
12008:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12009:                                                     \%codebase,\$content);
12010:         if ($parse_result eq 'ok') {
12011:             foreach my $i (@changes) {
12012:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12013:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12014:                 if ($allfiles{$ref}) {
12015:                     my $newname =  $orig;
12016:                     my ($attrib_regexp,$codebase);
12017:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12018:                     if ($attrib_regexp =~ /:/) {
12019:                         $attrib_regexp =~ s/\:/|/g;
12020:                     }
12021:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12022:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12023:                         $count += $numchg;
12024:                         $allfiles{$newname} = $allfiles{$ref};
12025:                         delete($allfiles{$ref});
12026:                     }
12027:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12028:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12029:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12030:                         $codebasecount ++;
12031:                     }
12032:                 }
12033:             }
12034:             my $skiprewrites;
12035:             if ($count || $codebasecount) {
12036:                 my $saveresult;
12037:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12038:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12039:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12040:                     if ($url eq $container) {
12041:                         my ($fname) = ($container =~ m{/([^/]+)$});
12042:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12043:                                             $count,'<span class="LC_filename">'.
12044:                                             $fname.'</span>').'</p>';
12045:                     } else {
12046:                          $output = '<p class="LC_error">'.
12047:                                    &mt('Error: update failed for: [_1].',
12048:                                    '<span class="LC_filename">'.
12049:                                    $container.'</span>').'</p>';
12050:                     }
12051:                     if ($context eq 'syllabus') {
12052:                         unless ($saveresult eq 'ok') {
12053:                             $skiprewrites = 1;
12054:                         }
12055:                     }
12056:                 } else {
12057:                     if (open(my $fh,">$container")) {
12058:                         print $fh $content;
12059:                         close($fh);
12060:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12061:                                   $count,'<span class="LC_filename">'.
12062:                                   $container.'</span>').'</p>';
12063:                     } else {
12064:                          $output = '<p class="LC_error">'.
12065:                                    &mt('Error: could not update [_1].',
12066:                                    '<span class="LC_filename">'.
12067:                                    $container.'</span>').'</p>';
12068:                     }
12069:                 }
12070:             }
12071:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12072:                 my ($actionurl,$state);
12073:                 $actionurl = "/public/$udom/$uname/syllabus";
12074:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12075:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12076:                                               \%codebase,
12077:                                               {'context' => 'rewrites',
12078:                                                'ignore_remote_references' => 1,});
12079:                 if (ref($mapping) eq 'HASH') {
12080:                     my $rewrites = 0;
12081:                     foreach my $key (keys(%{$mapping})) {
12082:                         next if ($key =~ m{^https?://});
12083:                         my $ref = $mapping->{$key};
12084:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12085:                         my $attrib;
12086:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12087:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12088:                         }
12089:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12090:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12091:                             $rewrites += $numchg;
12092:                         }
12093:                     }
12094:                     if ($rewrites) {
12095:                         my $saveresult; 
12096:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12097:                         if ($url eq $container) {
12098:                             my ($fname) = ($container =~ m{/([^/]+)$});
12099:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12100:                                             $count,'<span class="LC_filename">'.
12101:                                             $fname.'</span>').'</p>';
12102:                         } else {
12103:                             $output .= '<p class="LC_error">'.
12104:                                        &mt('Error: could not update links in [_1].',
12105:                                        '<span class="LC_filename">'.
12106:                                        $container.'</span>').'</p>';
12107: 
12108:                         }
12109:                     }
12110:                 }
12111:             }
12112:         } else {
12113:             &logthis('Failed to parse '.$container.
12114:                      ' to modify references: '.$parse_result);
12115:         }
12116:     }
12117:     if (wantarray) {
12118:         return ($output,$count,$codebasecount);
12119:     } else {
12120:         return $output;
12121:     }
12122: }
12123: 
12124: sub check_for_existing {
12125:     my ($path,$fname,$element) = @_;
12126:     my ($state,$msg);
12127:     if (-d $path.'/'.$fname) {
12128:         $state = 'exists';
12129:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12130:     } elsif (-e $path.'/'.$fname) {
12131:         $state = 'exists';
12132:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12133:     }
12134:     if ($state eq 'exists') {
12135:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12136:     }
12137:     return ($state,$msg);
12138: }
12139: 
12140: sub check_for_upload {
12141:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12142:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12143:     my $filesize = length($env{'form.'.$element});
12144:     if (!$filesize) {
12145:         my $msg = '<span class="LC_error">'.
12146:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12147:                       '<span class="LC_filename">'.$fname.'</span>',
12148:                       $filesize).'<br />'.
12149:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12150:                   '</span>';
12151:         return ('zero_bytes',$msg);
12152:     }
12153:     $filesize =  $filesize/1000; #express in k (1024?)
12154:     my $getpropath = 1;
12155:     my ($dirlistref,$listerror) =
12156:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12157:     my $found_file = 0;
12158:     my $locked_file = 0;
12159:     my @lockers;
12160:     my $navmap;
12161:     if ($env{'request.course.id'}) {
12162:         $navmap = Apache::lonnavmaps::navmap->new();
12163:     }
12164:     if (ref($dirlistref) eq 'ARRAY') {
12165:         foreach my $line (@{$dirlistref}) {
12166:             my ($file_name,$rest)=split(/\&/,$line,2);
12167:             if ($file_name eq $fname){
12168:                 $file_name = $path.$file_name;
12169:                 if ($group ne '') {
12170:                     $file_name = $group.$file_name;
12171:                 }
12172:                 $found_file = 1;
12173:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12174:                     foreach my $lock (@lockers) {
12175:                         if (ref($lock) eq 'ARRAY') {
12176:                             my ($symb,$crsid) = @{$lock};
12177:                             if ($crsid eq $env{'request.course.id'}) {
12178:                                 if (ref($navmap)) {
12179:                                     my $res = $navmap->getBySymb($symb);
12180:                                     foreach my $part (@{$res->parts()}) { 
12181:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12182:                                         unless (($slot_status == $res->RESERVED) ||
12183:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12184:                                             $locked_file = 1;
12185:                                         }
12186:                                     }
12187:                                 } else {
12188:                                     $locked_file = 1;
12189:                                 }
12190:                             } else {
12191:                                 $locked_file = 1;
12192:                             }
12193:                         }
12194:                    }
12195:                 } else {
12196:                     my @info = split(/\&/,$rest);
12197:                     my $currsize = $info[6]/1000;
12198:                     if ($currsize < $filesize) {
12199:                         my $extra = $filesize - $currsize;
12200:                         if (($current_disk_usage + $extra) > $disk_quota) {
12201:                             my $msg = '<p class="LC_warning">'.
12202:                                       &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.',
12203:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12204:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12205:                                                    $disk_quota,$current_disk_usage).'</p>';
12206:                             return ('will_exceed_quota',$msg);
12207:                         }
12208:                     }
12209:                 }
12210:             }
12211:         }
12212:     }
12213:     if (($current_disk_usage + $filesize) > $disk_quota){
12214:         my $msg = '<p class="LC_warning">'.
12215:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12216:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12217:         return ('will_exceed_quota',$msg);
12218:     } elsif ($found_file) {
12219:         if ($locked_file) {
12220:             my $msg = '<p class="LC_warning">';
12221:             $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>');
12222:             $msg .= '</p>';
12223:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12224:             return ('file_locked',$msg);
12225:         } else {
12226:             my $msg = '<p class="LC_error">';
12227:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12228:             $msg .= '</p>';
12229:             return ('existingfile',$msg);
12230:         }
12231:     }
12232: }
12233: 
12234: sub check_for_traversal {
12235:     my ($path,$url,$toplevel) = @_;
12236:     my @parts=split(/\//,$path);
12237:     my $cleanpath;
12238:     my $fullpath = $url;
12239:     for (my $i=0;$i<@parts;$i++) {
12240:         next if ($parts[$i] eq '.');
12241:         if ($parts[$i] eq '..') {
12242:             $fullpath =~ s{([^/]+/)$}{};
12243:         } else {
12244:             $fullpath .= $parts[$i].'/';
12245:         }
12246:     }
12247:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12248:         $cleanpath = $1;
12249:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12250:         my $curr_toprel = $1;
12251:         my @parts = split(/\//,$curr_toprel);
12252:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12253:         my @urlparts = split(/\//,$url_toprel);
12254:         my $doubledots;
12255:         my $startdiff = -1;
12256:         for (my $i=0; $i<@urlparts; $i++) {
12257:             if ($startdiff == -1) {
12258:                 unless ($urlparts[$i] eq $parts[$i]) {
12259:                     $startdiff = $i;
12260:                     $doubledots .= '../';
12261:                 }
12262:             } else {
12263:                 $doubledots .= '../';
12264:             }
12265:         }
12266:         if ($startdiff > -1) {
12267:             $cleanpath = $doubledots;
12268:             for (my $i=$startdiff; $i<@parts; $i++) {
12269:                 $cleanpath .= $parts[$i].'/';
12270:             }
12271:         }
12272:     }
12273:     $cleanpath =~ s{(/)$}{};
12274:     return $cleanpath;
12275: }
12276: 
12277: sub is_archive_file {
12278:     my ($mimetype) = @_;
12279:     if (($mimetype eq 'application/octet-stream') ||
12280:         ($mimetype eq 'application/x-stuffit') ||
12281:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12282:         return 1;
12283:     }
12284:     return;
12285: }
12286: 
12287: sub decompress_form {
12288:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12289:     my %lt = &Apache::lonlocal::texthash (
12290:         this => 'This file is an archive file.',
12291:         camt => 'This file is a Camtasia archive file.',
12292:         itsc => 'Its contents are as follows:',
12293:         youm => 'You may wish to extract its contents.',
12294:         extr => 'Extract contents',
12295:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12296:         proa => 'Process automatically?',
12297:         yes  => 'Yes',
12298:         no   => 'No',
12299:         fold => 'Title for folder containing movie',
12300:         movi => 'Title for page containing embedded movie', 
12301:     );
12302:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12303:     my ($is_camtasia,$topdir,%toplevel,@paths);
12304:     my $info = &list_archive_contents($fileloc,\@paths);
12305:     if (@paths) {
12306:         foreach my $path (@paths) {
12307:             $path =~ s{^/}{};
12308:             if ($path =~ m{^([^/]+)/$}) {
12309:                 $topdir = $1;
12310:             }
12311:             if ($path =~ m{^([^/]+)/}) {
12312:                 $toplevel{$1} = $path;
12313:             } else {
12314:                 $toplevel{$path} = $path;
12315:             }
12316:         }
12317:     }
12318:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12319:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12320:                         "$topdir/media/",
12321:                         "$topdir/media/$topdir.mp4",
12322:                         "$topdir/media/FirstFrame.png",
12323:                         "$topdir/media/player.swf",
12324:                         "$topdir/media/swfobject.js",
12325:                         "$topdir/media/expressInstall.swf");
12326:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12327:                          "$topdir/$topdir.mp4",
12328:                          "$topdir/$topdir\_config.xml",
12329:                          "$topdir/$topdir\_controller.swf",
12330:                          "$topdir/$topdir\_embed.css",
12331:                          "$topdir/$topdir\_First_Frame.png",
12332:                          "$topdir/$topdir\_player.html",
12333:                          "$topdir/$topdir\_Thumbnails.png",
12334:                          "$topdir/playerProductInstall.swf",
12335:                          "$topdir/scripts/",
12336:                          "$topdir/scripts/config_xml.js",
12337:                          "$topdir/scripts/handlebars.js",
12338:                          "$topdir/scripts/jquery-1.7.1.min.js",
12339:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12340:                          "$topdir/scripts/modernizr.js",
12341:                          "$topdir/scripts/player-min.js",
12342:                          "$topdir/scripts/swfobject.js",
12343:                          "$topdir/skins/",
12344:                          "$topdir/skins/configuration_express.xml",
12345:                          "$topdir/skins/express_show/",
12346:                          "$topdir/skins/express_show/player-min.css",
12347:                          "$topdir/skins/express_show/spritesheet.png");
12348:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12349:                          "$topdir/$topdir.mp4",
12350:                          "$topdir/$topdir\_config.xml",
12351:                          "$topdir/$topdir\_controller.swf",
12352:                          "$topdir/$topdir\_embed.css",
12353:                          "$topdir/$topdir\_First_Frame.png",
12354:                          "$topdir/$topdir\_player.html",
12355:                          "$topdir/$topdir\_Thumbnails.png",
12356:                          "$topdir/playerProductInstall.swf",
12357:                          "$topdir/scripts/",
12358:                          "$topdir/scripts/config_xml.js",
12359:                          "$topdir/scripts/techsmith-smart-player.min.js",
12360:                          "$topdir/skins/",
12361:                          "$topdir/skins/configuration_express.xml",
12362:                          "$topdir/skins/express_show/",
12363:                          "$topdir/skins/express_show/spritesheet.min.css",
12364:                          "$topdir/skins/express_show/spritesheet.png",
12365:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12366:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12367:         if (@diffs == 0) {
12368:             $is_camtasia = 6;
12369:         } else {
12370:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12371:             if (@diffs == 0) {
12372:                 $is_camtasia = 8;
12373:             } else {
12374:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12375:                 if (@diffs == 0) {
12376:                     $is_camtasia = 8;
12377:                 }
12378:             }
12379:         }
12380:     }
12381:     my $output;
12382:     if ($is_camtasia) {
12383:         $output = <<"ENDCAM";
12384: <script type="text/javascript" language="Javascript">
12385: // <![CDATA[
12386: 
12387: function camtasiaToggle() {
12388:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12389:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12390:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12391:                 document.getElementById('camtasia_titles').style.display='block';
12392:             } else {
12393:                 document.getElementById('camtasia_titles').style.display='none';
12394:             }
12395:         }
12396:     }
12397:     return;
12398: }
12399: 
12400: // ]]>
12401: </script>
12402: <p>$lt{'camt'}</p>
12403: ENDCAM
12404:     } else {
12405:         $output = '<p>'.$lt{'this'};
12406:         if ($info eq '') {
12407:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12408:         } else {
12409:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12410:                        '<div><pre>'.$info.'</pre></div>';
12411:         }
12412:     }
12413:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12414:     my $duplicates;
12415:     my $num = 0;
12416:     if (ref($dirlist) eq 'ARRAY') {
12417:         foreach my $item (@{$dirlist}) {
12418:             if (ref($item) eq 'ARRAY') {
12419:                 if (exists($toplevel{$item->[0]})) {
12420:                     $duplicates .= 
12421:                         &start_data_table_row().
12422:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12423:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12424:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12425:                         'value="1" />'.&mt('Yes').'</label>'.
12426:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12427:                         '<td>'.$item->[0].'</td>';
12428:                     if ($item->[2]) {
12429:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12430:                     } else {
12431:                         $duplicates .= '<td>'.&mt('File').'</td>';
12432:                     }
12433:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12434:                                    '<td>'.
12435:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12436:                                    '</td>'.
12437:                                    &end_data_table_row();
12438:                     $num ++;
12439:                 }
12440:             }
12441:         }
12442:     }
12443:     my $itemcount;
12444:     if (@paths > 0) {
12445:         $itemcount = scalar(@paths);
12446:     } else {
12447:         $itemcount = 1;
12448:     }
12449:     if ($is_camtasia) {
12450:         $output .= $lt{'auto'}.'<br />'.
12451:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12452:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12453:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12454:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12455:                    $lt{'no'}.'</label></span><br />'.
12456:                    '<div id="camtasia_titles" style="display:block">'.
12457:                    &Apache::lonhtmlcommon::start_pick_box().
12458:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12459:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12460:                    &Apache::lonhtmlcommon::row_closure().
12461:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12462:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12463:                    &Apache::lonhtmlcommon::row_closure(1).
12464:                    &Apache::lonhtmlcommon::end_pick_box().
12465:                    '</div>';
12466:     }
12467:     $output .= 
12468:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12469:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12470:         "\n";
12471:     if ($duplicates ne '') {
12472:         $output .= '<p><span class="LC_warning">'.
12473:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12474:                    &start_data_table().
12475:                    &start_data_table_header_row().
12476:                    '<th>'.&mt('Overwrite?').'</th>'.
12477:                    '<th>'.&mt('Name').'</th>'.
12478:                    '<th>'.&mt('Type').'</th>'.
12479:                    '<th>'.&mt('Size').'</th>'.
12480:                    '<th>'.&mt('Last modified').'</th>'.
12481:                    &end_data_table_header_row().
12482:                    $duplicates.
12483:                    &end_data_table().
12484:                    '</p>';
12485:     }
12486:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12487:     if (ref($hiddenelements) eq 'HASH') {
12488:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12489:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12490:         }
12491:     }
12492:     $output .= <<"END";
12493: <br />
12494: <input type="submit" name="decompress" value="$lt{'extr'}" />
12495: </form>
12496: $noextract
12497: END
12498:     return $output;
12499: }
12500: 
12501: sub decompression_utility {
12502:     my ($program) = @_;
12503:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12504:     my $location;
12505:     if (grep(/^\Q$program\E$/,@utilities)) { 
12506:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12507:                          '/usr/sbin/') {
12508:             if (-x $dir.$program) {
12509:                 $location = $dir.$program;
12510:                 last;
12511:             }
12512:         }
12513:     }
12514:     return $location;
12515: }
12516: 
12517: sub list_archive_contents {
12518:     my ($file,$pathsref) = @_;
12519:     my (@cmd,$output);
12520:     my $needsregexp;
12521:     if ($file =~ /\.zip$/) {
12522:         @cmd = (&decompression_utility('unzip'),"-l");
12523:         $needsregexp = 1;
12524:     } elsif (($file =~ m/\.tar\.gz$/) ||
12525:              ($file =~ /\.tgz$/)) {
12526:         @cmd = (&decompression_utility('tar'),"-ztf");
12527:     } elsif ($file =~ /\.tar\.bz2$/) {
12528:         @cmd = (&decompression_utility('tar'),"-jtf");
12529:     } elsif ($file =~ m|\.tar$|) {
12530:         @cmd = (&decompression_utility('tar'),"-tf");
12531:     }
12532:     if (@cmd) {
12533:         undef($!);
12534:         undef($@);
12535:         if (open(my $fh,"-|", @cmd, $file)) {
12536:             while (my $line = <$fh>) {
12537:                 $output .= $line;
12538:                 chomp($line);
12539:                 my $item;
12540:                 if ($needsregexp) {
12541:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12542:                 } else {
12543:                     $item = $line;
12544:                 }
12545:                 if ($item ne '') {
12546:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12547:                         push(@{$pathsref},$item);
12548:                     } 
12549:                 }
12550:             }
12551:             close($fh);
12552:         }
12553:     }
12554:     return $output;
12555: }
12556: 
12557: sub decompress_uploaded_file {
12558:     my ($file,$dir) = @_;
12559:     &Apache::lonnet::appenv({'cgi.file' => $file});
12560:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12561:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12562:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12563:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12564:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12565:     my $decompressed = $env{'cgi.decompressed'};
12566:     &Apache::lonnet::delenv('cgi.file');
12567:     &Apache::lonnet::delenv('cgi.dir');
12568:     &Apache::lonnet::delenv('cgi.decompressed');
12569:     return ($decompressed,$result);
12570: }
12571: 
12572: sub process_decompression {
12573:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12574:     my ($dir,$error,$warning,$output);
12575:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12576:         $error = &mt('Filename not a supported archive file type.').
12577:                  '<br />'.&mt('Filename should end with one of: [_1].',
12578:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12579:     } else {
12580:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12581:         if ($docuhome eq 'no_host') {
12582:             $error = &mt('Could not determine home server for course.');
12583:         } else {
12584:             my @ids=&Apache::lonnet::current_machine_ids();
12585:             my $currdir = "$dir_root/$destination";
12586:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12587:                 $dir = &LONCAPA::propath($docudom,$docuname).
12588:                        "$dir_root/$destination";
12589:             } else {
12590:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12591:                        "$dir_root/$docudom/$docuname/$destination";
12592:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12593:                     $error = &mt('Archive file not found.');
12594:                 }
12595:             }
12596:             my (@to_overwrite,@to_skip);
12597:             if ($env{'form.archive_overwrite_total'} > 0) {
12598:                 my $total = $env{'form.archive_overwrite_total'};
12599:                 for (my $i=0; $i<$total; $i++) {
12600:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12601:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12602:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12603:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12604:                     }
12605:                 }
12606:             }
12607:             my $numskip = scalar(@to_skip);
12608:             if (($numskip > 0) && 
12609:                 ($numskip == $env{'form.archive_itemcount'})) {
12610:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12611:             } elsif ($dir eq '') {
12612:                 $error = &mt('Directory containing archive file unavailable.');
12613:             } elsif (!$error) {
12614:                 my ($decompressed,$display);
12615:                 if ($numskip > 0) {
12616:                     my $tempdir = time.'_'.$$.int(rand(10000));
12617:                     mkdir("$dir/$tempdir",0755);
12618:                     system("mv $dir/$file $dir/$tempdir/$file");
12619:                     ($decompressed,$display) = 
12620:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12621:                     foreach my $item (@to_skip) {
12622:                         if (($item ne '') && ($item !~ /\.\./)) {
12623:                             if (-f "$dir/$tempdir/$item") { 
12624:                                 unlink("$dir/$tempdir/$item");
12625:                             } elsif (-d "$dir/$tempdir/$item") {
12626:                                 system("rm -rf $dir/$tempdir/$item");
12627:                             }
12628:                         }
12629:                     }
12630:                     system("mv $dir/$tempdir/* $dir");
12631:                     rmdir("$dir/$tempdir");   
12632:                 } else {
12633:                     ($decompressed,$display) = 
12634:                         &decompress_uploaded_file($file,$dir);
12635:                 }
12636:                 if ($decompressed eq 'ok') {
12637:                     $output = '<p class="LC_info">'.
12638:                               &mt('Files extracted successfully from archive.').
12639:                               '</p>'."\n";
12640:                     my ($warning,$result,@contents);
12641:                     my ($newdirlistref,$newlisterror) =
12642:                         &Apache::lonnet::dirlist($currdir,$docudom,
12643:                                                  $docuname,1);
12644:                     my (%is_dir,%changes,@newitems);
12645:                     my $dirptr = 16384;
12646:                     if (ref($newdirlistref) eq 'ARRAY') {
12647:                         foreach my $dir_line (@{$newdirlistref}) {
12648:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12649:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12650:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12651:                                 push(@newitems,$item);
12652:                                 if ($dirptr&$testdir) {
12653:                                     $is_dir{$item} = 1;
12654:                                 }
12655:                                 $changes{$item} = 1;
12656:                             }
12657:                         }
12658:                     }
12659:                     if (keys(%changes) > 0) {
12660:                         foreach my $item (sort(@newitems)) {
12661:                             if ($changes{$item}) {
12662:                                 push(@contents,$item);
12663:                             }
12664:                         }
12665:                     }
12666:                     if (@contents > 0) {
12667:                         my $wantform;
12668:                         unless ($env{'form.autoextract_camtasia'}) {
12669:                             $wantform = 1;
12670:                         }
12671:                         my (%children,%parent,%dirorder,%titles);
12672:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12673:                                                                 $currdir,\%is_dir,
12674:                                                                 \%children,\%parent,
12675:                                                                 \@contents,\%dirorder,
12676:                                                                 \%titles,$wantform);
12677:                         if ($datatable ne '') {
12678:                             $output .= &archive_options_form('decompressed',$datatable,
12679:                                                              $count,$hiddenelem);
12680:                             my $startcount = 6;
12681:                             $output .= &archive_javascript($startcount,$count,
12682:                                                            \%titles,\%children);
12683:                         }
12684:                         if ($env{'form.autoextract_camtasia'}) {
12685:                             my $version = $env{'form.autoextract_camtasia'};
12686:                             my %displayed;
12687:                             my $total = 1;
12688:                             $env{'form.archive_directory'} = [];
12689:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12690:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12691:                                 $path =~ s{/$}{};
12692:                                 my $item;
12693:                                 if ($path ne '') {
12694:                                     $item = "$path/$titles{$i}";
12695:                                 } else {
12696:                                     $item = $titles{$i};
12697:                                 }
12698:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12699:                                 if ($item eq $contents[0]) {
12700:                                     push(@{$env{'form.archive_directory'}},$i);
12701:                                     $env{'form.archive_'.$i} = 'display';
12702:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12703:                                     $displayed{'folder'} = $i;
12704:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12705:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12706:                                     $env{'form.archive_'.$i} = 'display';
12707:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12708:                                     $displayed{'web'} = $i;
12709:                                 } else {
12710:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12711:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12712:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12713:                                         push(@{$env{'form.archive_directory'}},$i);
12714:                                     }
12715:                                     $env{'form.archive_'.$i} = 'dependency';
12716:                                 }
12717:                                 $total ++;
12718:                             }
12719:                             for (my $i=1; $i<$total; $i++) {
12720:                                 next if ($i == $displayed{'web'});
12721:                                 next if ($i == $displayed{'folder'});
12722:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12723:                             }
12724:                             $env{'form.phase'} = 'decompress_cleanup';
12725:                             $env{'form.archivedelete'} = 1;
12726:                             $env{'form.archive_count'} = $total-1;
12727:                             $output .=
12728:                                 &process_extracted_files('coursedocs',$docudom,
12729:                                                          $docuname,$destination,
12730:                                                          $dir_root,$hiddenelem);
12731:                         }
12732:                     } else {
12733:                         $warning = &mt('No new items extracted from archive file.');
12734:                     }
12735:                 } else {
12736:                     $output = $display;
12737:                     $error = &mt('An error occurred during extraction from the archive file.');
12738:                 }
12739:             }
12740:         }
12741:     }
12742:     if ($error) {
12743:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12744:                    $error.'</p>'."\n";
12745:     }
12746:     if ($warning) {
12747:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12748:     }
12749:     return $output;
12750: }
12751: 
12752: sub get_extracted {
12753:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12754:         $titles,$wantform) = @_;
12755:     my $count = 0;
12756:     my $depth = 0;
12757:     my $datatable;
12758:     my @hierarchy;
12759:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12760:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12761:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12762:     foreach my $item (@{$contents}) {
12763:         $count ++;
12764:         @{$dirorder->{$count}} = @hierarchy;
12765:         $titles->{$count} = $item;
12766:         &archive_hierarchy($depth,$count,$parent,$children);
12767:         if ($wantform) {
12768:             $datatable .= &archive_row($is_dir->{$item},$item,
12769:                                        $currdir,$depth,$count);
12770:         }
12771:         if ($is_dir->{$item}) {
12772:             $depth ++;
12773:             push(@hierarchy,$count);
12774:             $parent->{$depth} = $count;
12775:             $datatable .=
12776:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12777:                                            \$depth,\$count,\@hierarchy,$dirorder,
12778:                                            $children,$parent,$titles,$wantform);
12779:             $depth --;
12780:             pop(@hierarchy);
12781:         }
12782:     }
12783:     return ($count,$datatable);
12784: }
12785: 
12786: sub recurse_extracted_archive {
12787:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12788:         $children,$parent,$titles,$wantform) = @_;
12789:     my $result='';
12790:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12791:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12792:             (ref($dirorder) eq 'HASH')) {
12793:         return $result;
12794:     }
12795:     my $dirptr = 16384;
12796:     my ($newdirlistref,$newlisterror) =
12797:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12798:     if (ref($newdirlistref) eq 'ARRAY') {
12799:         foreach my $dir_line (@{$newdirlistref}) {
12800:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12801:             unless ($item =~ /^\.+$/) {
12802:                 $$count ++;
12803:                 @{$dirorder->{$$count}} = @{$hierarchy};
12804:                 $titles->{$$count} = $item;
12805:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12806: 
12807:                 my $is_dir;
12808:                 if ($dirptr&$testdir) {
12809:                     $is_dir = 1;
12810:                 }
12811:                 if ($wantform) {
12812:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12813:                 }
12814:                 if ($is_dir) {
12815:                     $$depth ++;
12816:                     push(@{$hierarchy},$$count);
12817:                     $parent->{$$depth} = $$count;
12818:                     $result .=
12819:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12820:                                                    $docuname,$depth,$count,
12821:                                                    $hierarchy,$dirorder,$children,
12822:                                                    $parent,$titles,$wantform);
12823:                     $$depth --;
12824:                     pop(@{$hierarchy});
12825:                 }
12826:             }
12827:         }
12828:     }
12829:     return $result;
12830: }
12831: 
12832: sub archive_hierarchy {
12833:     my ($depth,$count,$parent,$children) =@_;
12834:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12835:         if (exists($parent->{$depth})) {
12836:              $children->{$parent->{$depth}} .= $count.':';
12837:         }
12838:     }
12839:     return;
12840: }
12841: 
12842: sub archive_row {
12843:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12844:     my ($name) = ($item =~ m{([^/]+)$});
12845:     my %choices = &Apache::lonlocal::texthash (
12846:                                        'display'    => 'Add as file',
12847:                                        'dependency' => 'Include as dependency',
12848:                                        'discard'    => 'Discard',
12849:                                       );
12850:     if ($is_dir) {
12851:         $choices{'display'} = &mt('Add as folder'); 
12852:     }
12853:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12854:     my $offset = 0;
12855:     foreach my $action ('display','dependency','discard') {
12856:         $offset ++;
12857:         if ($action ne 'display') {
12858:             $offset ++;
12859:         }  
12860:         $output .= '<td><span class="LC_nobreak">'.
12861:                    '<label><input type="radio" name="archive_'.$count.
12862:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12863:         my $text = $choices{$action};
12864:         if ($is_dir) {
12865:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12866:             if ($action eq 'display') {
12867:                 $text = &mt('Add as folder');
12868:             }
12869:         } else {
12870:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12871: 
12872:         }
12873:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12874:         if ($action eq 'dependency') {
12875:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12876:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12877:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12878:                        '<option value=""></option>'."\n".
12879:                        '</select>'."\n".
12880:                        '</div>';
12881:         } elsif ($action eq 'display') {
12882:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12883:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12884:                        '</div>';
12885:         }
12886:         $output .= '</td>';
12887:     }
12888:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12889:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12890:     for (my $i=0; $i<$depth; $i++) {
12891:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12892:     }
12893:     if ($is_dir) {
12894:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12895:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12896:     } else {
12897:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12898:     }
12899:     $output .= '&nbsp;'.$name.'</td>'."\n".
12900:                &end_data_table_row();
12901:     return $output;
12902: }
12903: 
12904: sub archive_options_form {
12905:     my ($form,$display,$count,$hiddenelem) = @_;
12906:     my %lt = &Apache::lonlocal::texthash(
12907:                perm => 'Permanently remove archive file?',
12908:                hows => 'How should each extracted item be incorporated in the course?',
12909:                cont => 'Content actions for all',
12910:                addf => 'Add as folder/file',
12911:                incd => 'Include as dependency for a displayed file',
12912:                disc => 'Discard',
12913:                no   => 'No',
12914:                yes  => 'Yes',
12915:                save => 'Save',
12916:     );
12917:     my $output = <<"END";
12918: <form name="$form" method="post" action="">
12919: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12920: <label>
12921:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12922: </label>
12923: &nbsp;
12924: <label>
12925:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12926: </span>
12927: </p>
12928: <input type="hidden" name="phase" value="decompress_cleanup" />
12929: <br />$lt{'hows'}
12930: <div class="LC_columnSection">
12931:   <fieldset>
12932:     <legend>$lt{'cont'}</legend>
12933:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12934:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12935:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12936:   </fieldset>
12937: </div>
12938: END
12939:     return $output.
12940:            &start_data_table()."\n".
12941:            $display."\n".
12942:            &end_data_table()."\n".
12943:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12944:            $hiddenelem.
12945:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12946:            '</form>';
12947: }
12948: 
12949: sub archive_javascript {
12950:     my ($startcount,$numitems,$titles,$children) = @_;
12951:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12952:     my $maintitle = $env{'form.comment'};
12953:     my $scripttag = <<START;
12954: <script type="text/javascript">
12955: // <![CDATA[
12956: 
12957: function checkAll(form,prefix) {
12958:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12959:     for (var i=0; i < form.elements.length; i++) {
12960:         var id = form.elements[i].id;
12961:         if ((id != '') && (id != undefined)) {
12962:             if (idstr.test(id)) {
12963:                 if (form.elements[i].type == 'radio') {
12964:                     form.elements[i].checked = true;
12965:                     var nostart = i-$startcount;
12966:                     var offset = nostart%7;
12967:                     var count = (nostart-offset)/7;    
12968:                     dependencyCheck(form,count,offset);
12969:                 }
12970:             }
12971:         }
12972:     }
12973: }
12974: 
12975: function propagateCheck(form,count) {
12976:     if (count > 0) {
12977:         var startelement = $startcount + ((count-1) * 7);
12978:         for (var j=1; j<6; j++) {
12979:             if ((j != 2) && (j != 4)) {
12980:                 var item = startelement + j; 
12981:                 if (form.elements[item].type == 'radio') {
12982:                     if (form.elements[item].checked) {
12983:                         containerCheck(form,count,j);
12984:                         break;
12985:                     }
12986:                 }
12987:             }
12988:         }
12989:     }
12990: }
12991: 
12992: numitems = $numitems
12993: var titles = new Array(numitems);
12994: var parents = new Array(numitems);
12995: for (var i=0; i<numitems; i++) {
12996:     parents[i] = new Array;
12997: }
12998: var maintitle = '$maintitle';
12999: 
13000: START
13001: 
13002:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13003:         my @contents = split(/:/,$children->{$container});
13004:         for (my $i=0; $i<@contents; $i ++) {
13005:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13006:         }
13007:     }
13008: 
13009:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13010:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13011:     }
13012: 
13013:     $scripttag .= <<END;
13014: 
13015: function containerCheck(form,count,offset) {
13016:     if (count > 0) {
13017:         dependencyCheck(form,count,offset);
13018:         var item = (offset+$startcount)+7*(count-1);
13019:         form.elements[item].checked = true;
13020:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13021:             if (parents[count].length > 0) {
13022:                 for (var j=0; j<parents[count].length; j++) {
13023:                     containerCheck(form,parents[count][j],offset);
13024:                 }
13025:             }
13026:         }
13027:     }
13028: }
13029: 
13030: function dependencyCheck(form,count,offset) {
13031:     if (count > 0) {
13032:         var chosen = (offset+$startcount)+7*(count-1);
13033:         var depitem = $startcount + ((count-1) * 7) + 4;
13034:         var currtype = form.elements[depitem].type;
13035:         if (form.elements[chosen].value == 'dependency') {
13036:             document.getElementById('arc_depon_'+count).style.display='block'; 
13037:             form.elements[depitem].options.length = 0;
13038:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13039:             for (var i=1; i<=numitems; i++) {
13040:                 if (i == count) {
13041:                     continue;
13042:                 }
13043:                 var startelement = $startcount + (i-1) * 7;
13044:                 for (var j=1; j<6; j++) {
13045:                     if ((j != 2) && (j!= 4)) {
13046:                         var item = startelement + j;
13047:                         if (form.elements[item].type == 'radio') {
13048:                             if (form.elements[item].checked) {
13049:                                 if (form.elements[item].value == 'display') {
13050:                                     var n = form.elements[depitem].options.length;
13051:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13052:                                 }
13053:                             }
13054:                         }
13055:                     }
13056:                 }
13057:             }
13058:         } else {
13059:             document.getElementById('arc_depon_'+count).style.display='none';
13060:             form.elements[depitem].options.length = 0;
13061:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13062:         }
13063:         titleCheck(form,count,offset);
13064:     }
13065: }
13066: 
13067: function propagateSelect(form,count,offset) {
13068:     if (count > 0) {
13069:         var item = (1+offset+$startcount)+7*(count-1);
13070:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13071:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13072:             if (parents[count].length > 0) {
13073:                 for (var j=0; j<parents[count].length; j++) {
13074:                     containerSelect(form,parents[count][j],offset,picked);
13075:                 }
13076:             }
13077:         }
13078:     }
13079: }
13080: 
13081: function containerSelect(form,count,offset,picked) {
13082:     if (count > 0) {
13083:         var item = (offset+$startcount)+7*(count-1);
13084:         if (form.elements[item].type == 'radio') {
13085:             if (form.elements[item].value == 'dependency') {
13086:                 if (form.elements[item+1].type == 'select-one') {
13087:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13088:                         if (form.elements[item+1].options[i].value == picked) {
13089:                             form.elements[item+1].selectedIndex = i;
13090:                             break;
13091:                         }
13092:                     }
13093:                 }
13094:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13095:                     if (parents[count].length > 0) {
13096:                         for (var j=0; j<parents[count].length; j++) {
13097:                             containerSelect(form,parents[count][j],offset,picked);
13098:                         }
13099:                     }
13100:                 }
13101:             }
13102:         }
13103:     }
13104: }
13105: 
13106: function titleCheck(form,count,offset) {
13107:     if (count > 0) {
13108:         var chosen = (offset+$startcount)+7*(count-1);
13109:         var depitem = $startcount + ((count-1) * 7) + 2;
13110:         var currtype = form.elements[depitem].type;
13111:         if (form.elements[chosen].value == 'display') {
13112:             document.getElementById('arc_title_'+count).style.display='block';
13113:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13114:                 document.getElementById('archive_title_'+count).value=maintitle;
13115:             }
13116:         } else {
13117:             document.getElementById('arc_title_'+count).style.display='none';
13118:             if (currtype == 'text') { 
13119:                 document.getElementById('archive_title_'+count).value='';
13120:             }
13121:         }
13122:     }
13123:     return;
13124: }
13125: 
13126: // ]]>
13127: </script>
13128: END
13129:     return $scripttag;
13130: }
13131: 
13132: sub process_extracted_files {
13133:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13134:     my $numitems = $env{'form.archive_count'};
13135:     return unless ($numitems);
13136:     my @ids=&Apache::lonnet::current_machine_ids();
13137:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13138:         %folders,%containers,%mapinner,%prompttofetch);
13139:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13140:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13141:         $prefix = &LONCAPA::propath($docudom,$docuname);
13142:         $pathtocheck = "$dir_root/$destination";
13143:         $dir = $dir_root;
13144:         $ishome = 1;
13145:     } else {
13146:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13147:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13148:         $dir = "$dir_root/$docudom/$docuname";    
13149:     }
13150:     my $currdir = "$dir_root/$destination";
13151:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13152:     if ($env{'form.folderpath'}) {
13153:         my @items = split('&',$env{'form.folderpath'});
13154:         $folders{'0'} = $items[-2];
13155:         if ($env{'form.folderpath'} =~ /\:1$/) {
13156:             $containers{'0'}='page';
13157:         } else {  
13158:             $containers{'0'}='sequence';
13159:         }
13160:     }
13161:     my @archdirs = &get_env_multiple('form.archive_directory');
13162:     if ($numitems) {
13163:         for (my $i=1; $i<=$numitems; $i++) {
13164:             my $path = $env{'form.archive_content_'.$i};
13165:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13166:                 my $item = $1;
13167:                 $toplevelitems{$item} = $i;
13168:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13169:                     $is_dir{$item} = 1;
13170:                 }
13171:             }
13172:         }
13173:     }
13174:     my ($output,%children,%parent,%titles,%dirorder,$result);
13175:     if (keys(%toplevelitems) > 0) {
13176:         my @contents = sort(keys(%toplevelitems));
13177:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13178:                                            \%parent,\@contents,\%dirorder,\%titles);
13179:     }
13180:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13181:     if ($numitems) {
13182:         for (my $i=1; $i<=$numitems; $i++) {
13183:             next if ($env{'form.archive_'.$i} eq 'dependency');
13184:             my $path = $env{'form.archive_content_'.$i};
13185:             if ($path =~ /^\Q$pathtocheck\E/) {
13186:                 if ($env{'form.archive_'.$i} eq 'discard') {
13187:                     if ($prefix ne '' && $path ne '') {
13188:                         if (-e $prefix.$path) {
13189:                             if ((@archdirs > 0) && 
13190:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13191:                                 $todeletedir{$prefix.$path} = 1;
13192:                             } else {
13193:                                 $todelete{$prefix.$path} = 1;
13194:                             }
13195:                         }
13196:                     }
13197:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13198:                     my ($docstitle,$title,$url,$outer);
13199:                     ($title) = ($path =~ m{/([^/]+)$});
13200:                     $docstitle = $env{'form.archive_title_'.$i};
13201:                     if ($docstitle eq '') {
13202:                         $docstitle = $title;
13203:                     }
13204:                     $outer = 0;
13205:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13206:                         if (@{$dirorder{$i}} > 0) {
13207:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13208:                                 if ($env{'form.archive_'.$item} eq 'display') {
13209:                                     $outer = $item;
13210:                                     last;
13211:                                 }
13212:                             }
13213:                         }
13214:                     }
13215:                     my ($errtext,$fatal) = 
13216:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13217:                                                '/'.$folders{$outer}.'.'.
13218:                                                $containers{$outer});
13219:                     next if ($fatal);
13220:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13221:                         if ($context eq 'coursedocs') {
13222:                             $mapinner{$i} = time;
13223:                             $folders{$i} = 'default_'.$mapinner{$i};
13224:                             $containers{$i} = 'sequence';
13225:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13226:                                       $folders{$i}.'.'.$containers{$i};
13227:                             my $newidx = &LONCAPA::map::getresidx();
13228:                             $LONCAPA::map::resources[$newidx]=
13229:                                 $docstitle.':'.$url.':false:normal:res';
13230:                             push(@LONCAPA::map::order,$newidx);
13231:                             my ($outtext,$errtext) =
13232:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13233:                                                         $docuname.'/'.$folders{$outer}.
13234:                                                         '.'.$containers{$outer},1,1);
13235:                             $newseqid{$i} = $newidx;
13236:                             unless ($errtext) {
13237:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
13238:                             }
13239:                         }
13240:                     } else {
13241:                         if ($context eq 'coursedocs') {
13242:                             my $newidx=&LONCAPA::map::getresidx();
13243:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13244:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13245:                                       $title;
13246:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13247:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13248:                             }
13249:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13250:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13251:                             }
13252:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13253:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
13254:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13255:                                 unless ($ishome) {
13256:                                     my $fetch = "$newdest{$i}/$title";
13257:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13258:                                     $prompttofetch{$fetch} = 1;
13259:                                 }
13260:                             }
13261:                             $LONCAPA::map::resources[$newidx]=
13262:                                 $docstitle.':'.$url.':false:normal:res';
13263:                             push(@LONCAPA::map::order, $newidx);
13264:                             my ($outtext,$errtext)=
13265:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13266:                                                         $docuname.'/'.$folders{$outer}.
13267:                                                         '.'.$containers{$outer},1,1);
13268:                             unless ($errtext) {
13269:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13270:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
13271:                                 }
13272:                             }
13273:                         }
13274:                     }
13275:                 }
13276:             } else {
13277:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13278:             }
13279:         }
13280:         for (my $i=1; $i<=$numitems; $i++) {
13281:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13282:             my $path = $env{'form.archive_content_'.$i};
13283:             if ($path =~ /^\Q$pathtocheck\E/) {
13284:                 my ($title) = ($path =~ m{/([^/]+)$});
13285:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13286:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13287:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13288:                         my ($itemidx,$fullpath,$relpath);
13289:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13290:                             my $container = $dirorder{$referrer{$i}}->[-1];
13291:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13292:                                 if ($dirorder{$i}->[$j] eq $container) {
13293:                                     $itemidx = $j;
13294:                                 }
13295:                             }
13296:                         }
13297:                         if ($itemidx eq '') {
13298:                             $itemidx =  0;
13299:                         } 
13300:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13301:                             if ($mapinner{$referrer{$i}}) {
13302:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13303:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13304:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13305:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13306:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13307:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13308:                                             if (!-e $fullpath) {
13309:                                                 mkdir($fullpath,0755);
13310:                                             }
13311:                                         }
13312:                                     } else {
13313:                                         last;
13314:                                     }
13315:                                 }
13316:                             }
13317:                         } elsif ($newdest{$referrer{$i}}) {
13318:                             $fullpath = $newdest{$referrer{$i}};
13319:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13320:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13321:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13322:                                     last;
13323:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13324:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13325:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13326:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13327:                                         if (!-e $fullpath) {
13328:                                             mkdir($fullpath,0755);
13329:                                         }
13330:                                     }
13331:                                 } else {
13332:                                     last;
13333:                                 }
13334:                             }
13335:                         }
13336:                         if ($fullpath ne '') {
13337:                             if (-e "$prefix$path") {
13338:                                 system("mv $prefix$path $fullpath/$title");
13339:                             }
13340:                             if (-e "$fullpath/$title") {
13341:                                 my $showpath;
13342:                                 if ($relpath ne '') {
13343:                                     $showpath = "$relpath/$title";
13344:                                 } else {
13345:                                     $showpath = "/$title";
13346:                                 } 
13347:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
13348:                             } 
13349:                             unless ($ishome) {
13350:                                 my $fetch = "$fullpath/$title";
13351:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
13352:                                 $prompttofetch{$fetch} = 1;
13353:                             }
13354:                         }
13355:                     }
13356:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13357:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13358:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
13359:                 }
13360:             } else {
13361:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13362:             }
13363:         }
13364:         if (keys(%todelete)) {
13365:             foreach my $key (keys(%todelete)) {
13366:                 unlink($key);
13367:             }
13368:         }
13369:         if (keys(%todeletedir)) {
13370:             foreach my $key (keys(%todeletedir)) {
13371:                 rmdir($key);
13372:             }
13373:         }
13374:         foreach my $dir (sort(keys(%is_dir))) {
13375:             if (($pathtocheck ne '') && ($dir ne ''))  {
13376:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13377:             }
13378:         }
13379:         if ($result ne '') {
13380:             $output .= '<ul>'."\n".
13381:                        $result."\n".
13382:                        '</ul>';
13383:         }
13384:         unless ($ishome) {
13385:             my $replicationfail;
13386:             foreach my $item (keys(%prompttofetch)) {
13387:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13388:                 unless ($fetchresult eq 'ok') {
13389:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13390:                 }
13391:             }
13392:             if ($replicationfail) {
13393:                 $output .= '<p class="LC_error">'.
13394:                            &mt('Course home server failed to retrieve:').'<ul>'.
13395:                            $replicationfail.
13396:                            '</ul></p>';
13397:             }
13398:         }
13399:     } else {
13400:         $warning = &mt('No items found in archive.');
13401:     }
13402:     if ($error) {
13403:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13404:                    $error.'</p>'."\n";
13405:     }
13406:     if ($warning) {
13407:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13408:     }
13409:     return $output;
13410: }
13411: 
13412: sub cleanup_empty_dirs {
13413:     my ($path) = @_;
13414:     if (($path ne '') && (-d $path)) {
13415:         if (opendir(my $dirh,$path)) {
13416:             my @dircontents = grep(!/^\./,readdir($dirh));
13417:             my $numitems = 0;
13418:             foreach my $item (@dircontents) {
13419:                 if (-d "$path/$item") {
13420:                     &cleanup_empty_dirs("$path/$item");
13421:                     if (-e "$path/$item") {
13422:                         $numitems ++;
13423:                     }
13424:                 } else {
13425:                     $numitems ++;
13426:                 }
13427:             }
13428:             if ($numitems == 0) {
13429:                 rmdir($path);
13430:             }
13431:             closedir($dirh);
13432:         }
13433:     }
13434:     return;
13435: }
13436: 
13437: =pod
13438: 
13439: =item * &get_folder_hierarchy()
13440: 
13441: Provides hierarchy of names of folders/sub-folders containing the current
13442: item,
13443: 
13444: Inputs: 3
13445:      - $navmap - navmaps object
13446: 
13447:      - $map - url for map (either the trigger itself, or map containing
13448:                            the resource, which is the trigger).
13449: 
13450:      - $showitem - 1 => show title for map itself; 0 => do not show.
13451: 
13452: Outputs: 1 @pathitems - array of folder/subfolder names.
13453: 
13454: =cut
13455: 
13456: sub get_folder_hierarchy {
13457:     my ($navmap,$map,$showitem) = @_;
13458:     my @pathitems;
13459:     if (ref($navmap)) {
13460:         my $mapres = $navmap->getResourceByUrl($map);
13461:         if (ref($mapres)) {
13462:             my $pcslist = $mapres->map_hierarchy();
13463:             if ($pcslist ne '') {
13464:                 my @pcs = split(/,/,$pcslist);
13465:                 foreach my $pc (@pcs) {
13466:                     if ($pc == 1) {
13467:                         push(@pathitems,&mt('Main Content'));
13468:                     } else {
13469:                         my $res = $navmap->getByMapPc($pc);
13470:                         if (ref($res)) {
13471:                             my $title = $res->compTitle();
13472:                             $title =~ s/\W+/_/g;
13473:                             if ($title ne '') {
13474:                                 push(@pathitems,$title);
13475:                             }
13476:                         }
13477:                     }
13478:                 }
13479:             }
13480:             if ($showitem) {
13481:                 if ($mapres->{ID} eq '0.0') {
13482:                     push(@pathitems,&mt('Main Content'));
13483:                 } else {
13484:                     my $maptitle = $mapres->compTitle();
13485:                     $maptitle =~ s/\W+/_/g;
13486:                     if ($maptitle ne '') {
13487:                         push(@pathitems,$maptitle);
13488:                     }
13489:                 }
13490:             }
13491:         }
13492:     }
13493:     return @pathitems;
13494: }
13495: 
13496: =pod
13497: 
13498: =item * &get_turnedin_filepath()
13499: 
13500: Determines path in a user's portfolio file for storage of files uploaded
13501: to a specific essayresponse or dropbox item.
13502: 
13503: Inputs: 3 required + 1 optional.
13504: $symb is symb for resource, $uname and $udom are for current user (required).
13505: $caller is optional (can be "submission", if routine is called when storing
13506: an upoaded file when "Submit Answer" button was pressed).
13507: 
13508: Returns array containing $path and $multiresp. 
13509: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13510: than one file upload item.  Callers of routine should append partid as a 
13511: subdirectory to $path in cases where $multiresp is 1.
13512: 
13513: Called by: homework/essayresponse.pm and homework/structuretags.pm
13514: 
13515: =cut
13516: 
13517: sub get_turnedin_filepath {
13518:     my ($symb,$uname,$udom,$caller) = @_;
13519:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13520:     my $turnindir;
13521:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13522:     $turnindir = $userhash{'turnindir'};
13523:     my ($path,$multiresp);
13524:     if ($turnindir eq '') {
13525:         if ($caller eq 'submission') {
13526:             $turnindir = &mt('turned in');
13527:             $turnindir =~ s/\W+/_/g;
13528:             my %newhash = (
13529:                             'turnindir' => $turnindir,
13530:                           );
13531:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13532:         }
13533:     }
13534:     if ($turnindir ne '') {
13535:         $path = '/'.$turnindir.'/';
13536:         my ($multipart,$turnin,@pathitems);
13537:         my $navmap = Apache::lonnavmaps::navmap->new();
13538:         if (defined($navmap)) {
13539:             my $mapres = $navmap->getResourceByUrl($map);
13540:             if (ref($mapres)) {
13541:                 my $pcslist = $mapres->map_hierarchy();
13542:                 if ($pcslist ne '') {
13543:                     foreach my $pc (split(/,/,$pcslist)) {
13544:                         my $res = $navmap->getByMapPc($pc);
13545:                         if (ref($res)) {
13546:                             my $title = $res->compTitle();
13547:                             $title =~ s/\W+/_/g;
13548:                             if ($title ne '') {
13549:                                 if (($pc > 1) && (length($title) > 12)) {
13550:                                     $title = substr($title,0,12);
13551:                                 }
13552:                                 push(@pathitems,$title);
13553:                             }
13554:                         }
13555:                     }
13556:                 }
13557:                 my $maptitle = $mapres->compTitle();
13558:                 $maptitle =~ s/\W+/_/g;
13559:                 if ($maptitle ne '') {
13560:                     if (length($maptitle) > 12) {
13561:                         $maptitle = substr($maptitle,0,12);
13562:                     }
13563:                     push(@pathitems,$maptitle);
13564:                 }
13565:                 unless ($env{'request.state'} eq 'construct') {
13566:                     my $res = $navmap->getBySymb($symb);
13567:                     if (ref($res)) {
13568:                         my $partlist = $res->parts();
13569:                         my $totaluploads = 0;
13570:                         if (ref($partlist) eq 'ARRAY') {
13571:                             foreach my $part (@{$partlist}) {
13572:                                 my @types = $res->responseType($part);
13573:                                 my @ids = $res->responseIds($part);
13574:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13575:                                     if ($types[$i] eq 'essay') {
13576:                                         my $partid = $part.'_'.$ids[$i];
13577:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13578:                                             $totaluploads ++;
13579:                                         }
13580:                                     }
13581:                                 }
13582:                             }
13583:                             if ($totaluploads > 1) {
13584:                                 $multiresp = 1;
13585:                             }
13586:                         }
13587:                     }
13588:                 }
13589:             } else {
13590:                 return;
13591:             }
13592:         } else {
13593:             return;
13594:         }
13595:         my $restitle=&Apache::lonnet::gettitle($symb);
13596:         $restitle =~ s/\W+/_/g;
13597:         if ($restitle eq '') {
13598:             $restitle = ($resurl =~ m{/[^/]+$});
13599:             if ($restitle eq '') {
13600:                 $restitle = time;
13601:             }
13602:         }
13603:         if (length($restitle) > 12) {
13604:             $restitle = substr($restitle,0,12);
13605:         }
13606:         push(@pathitems,$restitle);
13607:         $path .= join('/',@pathitems);
13608:     }
13609:     return ($path,$multiresp);
13610: }
13611: 
13612: =pod
13613: 
13614: =back
13615: 
13616: =head1 CSV Upload/Handling functions
13617: 
13618: =over 4
13619: 
13620: =item * &upfile_store($r)
13621: 
13622: Store uploaded file, $r should be the HTTP Request object,
13623: needs $env{'form.upfile'}
13624: returns $datatoken to be put into hidden field
13625: 
13626: =cut
13627: 
13628: sub upfile_store {
13629:     my $r=shift;
13630:     $env{'form.upfile'}=~s/\r/\n/gs;
13631:     $env{'form.upfile'}=~s/\f/\n/gs;
13632:     $env{'form.upfile'}=~s/\n+/\n/gs;
13633:     $env{'form.upfile'}=~s/\n+$//gs;
13634: 
13635:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13636: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13637:     {
13638:         my $datafile = $r->dir_config('lonDaemons').
13639:                            '/tmp/'.$datatoken.'.tmp';
13640:         if ( open(my $fh,">$datafile") ) {
13641:             print $fh $env{'form.upfile'};
13642:             close($fh);
13643:         }
13644:     }
13645:     return $datatoken;
13646: }
13647: 
13648: =pod
13649: 
13650: =item * &load_tmp_file($r)
13651: 
13652: Load uploaded file from tmp, $r should be the HTTP Request object,
13653: needs $env{'form.datatoken'},
13654: sets $env{'form.upfile'} to the contents of the file
13655: 
13656: =cut
13657: 
13658: sub load_tmp_file {
13659:     my $r=shift;
13660:     my @studentdata=();
13661:     {
13662:         my $studentfile = $r->dir_config('lonDaemons').
13663:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13664:         if ( open(my $fh,"<$studentfile") ) {
13665:             @studentdata=<$fh>;
13666:             close($fh);
13667:         }
13668:     }
13669:     $env{'form.upfile'}=join('',@studentdata);
13670: }
13671: 
13672: =pod
13673: 
13674: =item * &upfile_record_sep()
13675: 
13676: Separate uploaded file into records
13677: returns array of records,
13678: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13679: 
13680: =cut
13681: 
13682: sub upfile_record_sep {
13683:     if ($env{'form.upfiletype'} eq 'xml') {
13684:     } else {
13685: 	my @records;
13686: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13687: 	    if ($line=~/^\s*$/) { next; }
13688: 	    push(@records,$line);
13689: 	}
13690: 	return @records;
13691:     }
13692: }
13693: 
13694: =pod
13695: 
13696: =item * &record_sep($record)
13697: 
13698: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13699: 
13700: =cut
13701: 
13702: sub takeleft {
13703:     my $index=shift;
13704:     return substr('0000'.$index,-4,4);
13705: }
13706: 
13707: sub record_sep {
13708:     my $record=shift;
13709:     my %components=();
13710:     if ($env{'form.upfiletype'} eq 'xml') {
13711:     } elsif ($env{'form.upfiletype'} eq 'space') {
13712:         my $i=0;
13713:         foreach my $field (split(/\s+/,$record)) {
13714:             $field=~s/^(\"|\')//;
13715:             $field=~s/(\"|\')$//;
13716:             $components{&takeleft($i)}=$field;
13717:             $i++;
13718:         }
13719:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13720:         my $i=0;
13721:         foreach my $field (split(/\t/,$record)) {
13722:             $field=~s/^(\"|\')//;
13723:             $field=~s/(\"|\')$//;
13724:             $components{&takeleft($i)}=$field;
13725:             $i++;
13726:         }
13727:     } else {
13728:         my $separator=',';
13729:         if ($env{'form.upfiletype'} eq 'semisv') {
13730:             $separator=';';
13731:         }
13732:         my $i=0;
13733: # the character we are looking for to indicate the end of a quote or a record 
13734:         my $looking_for=$separator;
13735: # do not add the characters to the fields
13736:         my $ignore=0;
13737: # we just encountered a separator (or the beginning of the record)
13738:         my $just_found_separator=1;
13739: # store the field we are working on here
13740:         my $field='';
13741: # work our way through all characters in record
13742:         foreach my $character ($record=~/(.)/g) {
13743:             if ($character eq $looking_for) {
13744:                if ($character ne $separator) {
13745: # Found the end of a quote, again looking for separator
13746:                   $looking_for=$separator;
13747:                   $ignore=1;
13748:                } else {
13749: # Found a separator, store away what we got
13750:                   $components{&takeleft($i)}=$field;
13751: 	          $i++;
13752:                   $just_found_separator=1;
13753:                   $ignore=0;
13754:                   $field='';
13755:                }
13756:                next;
13757:             }
13758: # single or double quotation marks after a separator indicate beginning of a quote
13759: # we are now looking for the end of the quote and need to ignore separators
13760:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13761:                $looking_for=$character;
13762:                next;
13763:             }
13764: # ignore would be true after we reached the end of a quote
13765:             if ($ignore) { next; }
13766:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13767:             $field.=$character;
13768:             $just_found_separator=0; 
13769:         }
13770: # catch the very last entry, since we never encountered the separator
13771:         $components{&takeleft($i)}=$field;
13772:     }
13773:     return %components;
13774: }
13775: 
13776: ######################################################
13777: ######################################################
13778: 
13779: =pod
13780: 
13781: =item * &upfile_select_html()
13782: 
13783: Return HTML code to select a file from the users machine and specify 
13784: the file type.
13785: 
13786: =cut
13787: 
13788: ######################################################
13789: ######################################################
13790: sub upfile_select_html {
13791:     my %Types = (
13792:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13793:                  semisv => &mt('Semicolon separated values'),
13794:                  space => &mt('Space separated'),
13795:                  tab   => &mt('Tabulator separated'),
13796: #                 xml   => &mt('HTML/XML'),
13797:                  );
13798:     my $Str = '<input type="file" name="upfile" size="50" />'.
13799:         '<br />'.&mt('Type').': <select name="upfiletype">';
13800:     foreach my $type (sort(keys(%Types))) {
13801:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13802:     }
13803:     $Str .= "</select>\n";
13804:     return $Str;
13805: }
13806: 
13807: sub get_samples {
13808:     my ($records,$toget) = @_;
13809:     my @samples=({});
13810:     my $got=0;
13811:     foreach my $rec (@$records) {
13812: 	my %temp = &record_sep($rec);
13813: 	if (! grep(/\S/, values(%temp))) { next; }
13814: 	if (%temp) {
13815: 	    $samples[$got]=\%temp;
13816: 	    $got++;
13817: 	    if ($got == $toget) { last; }
13818: 	}
13819:     }
13820:     return \@samples;
13821: }
13822: 
13823: ######################################################
13824: ######################################################
13825: 
13826: =pod
13827: 
13828: =item * &csv_print_samples($r,$records)
13829: 
13830: Prints a table of sample values from each column uploaded $r is an
13831: Apache Request ref, $records is an arrayref from
13832: &Apache::loncommon::upfile_record_sep
13833: 
13834: =cut
13835: 
13836: ######################################################
13837: ######################################################
13838: sub csv_print_samples {
13839:     my ($r,$records) = @_;
13840:     my $samples = &get_samples($records,5);
13841: 
13842:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13843:               &start_data_table_header_row());
13844:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13845:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13846:     $r->print(&end_data_table_header_row());
13847:     foreach my $hash (@$samples) {
13848: 	$r->print(&start_data_table_row());
13849: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13850: 	    $r->print('<td>');
13851: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13852: 	    $r->print('</td>');
13853: 	}
13854: 	$r->print(&end_data_table_row());
13855:     }
13856:     $r->print(&end_data_table().'<br />'."\n");
13857: }
13858: 
13859: ######################################################
13860: ######################################################
13861: 
13862: =pod
13863: 
13864: =item * &csv_print_select_table($r,$records,$d)
13865: 
13866: Prints a table to create associations between values and table columns.
13867: 
13868: $r is an Apache Request ref,
13869: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13870: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13871: 
13872: =cut
13873: 
13874: ######################################################
13875: ######################################################
13876: sub csv_print_select_table {
13877:     my ($r,$records,$d) = @_;
13878:     my $i=0;
13879:     my $samples = &get_samples($records,1);
13880:     $r->print(&mt('Associate columns with student attributes.')."\n".
13881: 	      &start_data_table().&start_data_table_header_row().
13882:               '<th>'.&mt('Attribute').'</th>'.
13883:               '<th>'.&mt('Column').'</th>'.
13884:               &end_data_table_header_row()."\n");
13885:     foreach my $array_ref (@$d) {
13886: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13887: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13888: 
13889: 	$r->print('<td><select name="f'.$i.'"'.
13890: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13891: 	$r->print('<option value="none"></option>');
13892: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13893: 	    $r->print('<option value="'.$sample.'"'.
13894:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13895:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13896: 	}
13897: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13898: 	$i++;
13899:     }
13900:     $r->print(&end_data_table());
13901:     $i--;
13902:     return $i;
13903: }
13904: 
13905: ######################################################
13906: ######################################################
13907: 
13908: =pod
13909: 
13910: =item * &csv_samples_select_table($r,$records,$d)
13911: 
13912: Prints a table of sample values from the upload and can make associate samples to internal names.
13913: 
13914: $r is an Apache Request ref,
13915: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13916: $d is an array of 2 element arrays (internal name, displayed name)
13917: 
13918: =cut
13919: 
13920: ######################################################
13921: ######################################################
13922: sub csv_samples_select_table {
13923:     my ($r,$records,$d) = @_;
13924:     my $i=0;
13925:     #
13926:     my $max_samples = 5;
13927:     my $samples = &get_samples($records,$max_samples);
13928:     $r->print(&start_data_table().
13929:               &start_data_table_header_row().'<th>'.
13930:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13931:               &end_data_table_header_row());
13932: 
13933:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13934: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13935: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13936: 	foreach my $option (@$d) {
13937: 	    my ($value,$display,$defaultcol)=@{ $option };
13938: 	    $r->print('<option value="'.$value.'"'.
13939:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13940:                       $display.'</option>');
13941: 	}
13942: 	$r->print('</select></td><td>');
13943: 	foreach my $line (0..($max_samples-1)) {
13944: 	    if (defined($samples->[$line]{$key})) { 
13945: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13946: 	    }
13947: 	}
13948: 	$r->print('</td>'.&end_data_table_row());
13949: 	$i++;
13950:     }
13951:     $r->print(&end_data_table());
13952:     $i--;
13953:     return($i);
13954: }
13955: 
13956: ######################################################
13957: ######################################################
13958: 
13959: =pod
13960: 
13961: =item * &clean_excel_name($name)
13962: 
13963: Returns a replacement for $name which does not contain any illegal characters.
13964: 
13965: =cut
13966: 
13967: ######################################################
13968: ######################################################
13969: sub clean_excel_name {
13970:     my ($name) = @_;
13971:     $name =~ s/[:\*\?\/\\]//g;
13972:     if (length($name) > 31) {
13973:         $name = substr($name,0,31);
13974:     }
13975:     return $name;
13976: }
13977: 
13978: =pod
13979: 
13980: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13981: 
13982: Returns either 1 or undef
13983: 
13984: 1 if the part is to be hidden, undef if it is to be shown
13985: 
13986: Arguments are:
13987: 
13988: $id the id of the part to be checked
13989: $symb, optional the symb of the resource to check
13990: $udom, optional the domain of the user to check for
13991: $uname, optional the username of the user to check for
13992: 
13993: =cut
13994: 
13995: sub check_if_partid_hidden {
13996:     my ($id,$symb,$udom,$uname) = @_;
13997:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13998: 					 $symb,$udom,$uname);
13999:     my $truth=1;
14000:     #if the string starts with !, then the list is the list to show not hide
14001:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14002:     my @hiddenlist=split(/,/,$hiddenparts);
14003:     foreach my $checkid (@hiddenlist) {
14004: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14005:     }
14006:     return !$truth;
14007: }
14008: 
14009: 
14010: ############################################################
14011: ############################################################
14012: 
14013: =pod
14014: 
14015: =back 
14016: 
14017: =head1 cgi-bin script and graphing routines
14018: 
14019: =over 4
14020: 
14021: =item * &get_cgi_id()
14022: 
14023: Inputs: none
14024: 
14025: Returns an id which can be used to pass environment variables
14026: to various cgi-bin scripts.  These environment variables will
14027: be removed from the users environment after a given time by
14028: the routine &Apache::lonnet::transfer_profile_to_env.
14029: 
14030: =cut
14031: 
14032: ############################################################
14033: ############################################################
14034: my $uniq=0;
14035: sub get_cgi_id {
14036:     $uniq=($uniq+1)%100000;
14037:     return (time.'_'.$$.'_'.$uniq);
14038: }
14039: 
14040: ############################################################
14041: ############################################################
14042: 
14043: =pod
14044: 
14045: =item * &DrawBarGraph()
14046: 
14047: Facilitates the plotting of data in a (stacked) bar graph.
14048: Puts plot definition data into the users environment in order for 
14049: graph.png to plot it.  Returns an <img> tag for the plot.
14050: The bars on the plot are labeled '1','2',...,'n'.
14051: 
14052: Inputs:
14053: 
14054: =over 4
14055: 
14056: =item $Title: string, the title of the plot
14057: 
14058: =item $xlabel: string, text describing the X-axis of the plot
14059: 
14060: =item $ylabel: string, text describing the Y-axis of the plot
14061: 
14062: =item $Max: scalar, the maximum Y value to use in the plot
14063: If $Max is < any data point, the graph will not be rendered.
14064: 
14065: =item $colors: array ref holding the colors to be used for the data sets when
14066: they are plotted.  If undefined, default values will be used.
14067: 
14068: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14069: 
14070: =item @Values: An array of array references.  Each array reference holds data
14071: to be plotted in a stacked bar chart.
14072: 
14073: =item If the final element of @Values is a hash reference the key/value
14074: pairs will be added to the graph definition.
14075: 
14076: =back
14077: 
14078: Returns:
14079: 
14080: An <img> tag which references graph.png and the appropriate identifying
14081: information for the plot.
14082: 
14083: =cut
14084: 
14085: ############################################################
14086: ############################################################
14087: sub DrawBarGraph {
14088:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14089:     #
14090:     if (! defined($colors)) {
14091:         $colors = ['#33ff00', 
14092:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14093:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14094:                   ]; 
14095:     }
14096:     my $extra_settings = {};
14097:     if (ref($Values[-1]) eq 'HASH') {
14098:         $extra_settings = pop(@Values);
14099:     }
14100:     #
14101:     my $identifier = &get_cgi_id();
14102:     my $id = 'cgi.'.$identifier;        
14103:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14104:         return '';
14105:     }
14106:     #
14107:     my @Labels;
14108:     if (defined($labels)) {
14109:         @Labels = @$labels;
14110:     } else {
14111:         for (my $i=0;$i<@{$Values[0]};$i++) {
14112:             push(@Labels,$i+1);
14113:         }
14114:     }
14115:     #
14116:     my $NumBars = scalar(@{$Values[0]});
14117:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14118:     my %ValuesHash;
14119:     my $NumSets=1;
14120:     foreach my $array (@Values) {
14121:         next if (! ref($array));
14122:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14123:             join(',',@$array);
14124:     }
14125:     #
14126:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14127:     if ($NumBars < 3) {
14128:         $width = 120+$NumBars*32;
14129:         $xskip = 1;
14130:         $bar_width = 30;
14131:     } elsif ($NumBars < 5) {
14132:         $width = 120+$NumBars*20;
14133:         $xskip = 1;
14134:         $bar_width = 20;
14135:     } elsif ($NumBars < 10) {
14136:         $width = 120+$NumBars*15;
14137:         $xskip = 1;
14138:         $bar_width = 15;
14139:     } elsif ($NumBars <= 25) {
14140:         $width = 120+$NumBars*11;
14141:         $xskip = 5;
14142:         $bar_width = 8;
14143:     } elsif ($NumBars <= 50) {
14144:         $width = 120+$NumBars*8;
14145:         $xskip = 5;
14146:         $bar_width = 4;
14147:     } else {
14148:         $width = 120+$NumBars*8;
14149:         $xskip = 5;
14150:         $bar_width = 4;
14151:     }
14152:     #
14153:     $Max = 1 if ($Max < 1);
14154:     if ( int($Max) < $Max ) {
14155:         $Max++;
14156:         $Max = int($Max);
14157:     }
14158:     $Title  = '' if (! defined($Title));
14159:     $xlabel = '' if (! defined($xlabel));
14160:     $ylabel = '' if (! defined($ylabel));
14161:     $ValuesHash{$id.'.title'}    = &escape($Title);
14162:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14163:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14164:     $ValuesHash{$id.'.y_max_value'} = $Max;
14165:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14166:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14167:     $ValuesHash{$id.'.PlotType'} = 'bar';
14168:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14169:     $ValuesHash{$id.'.height'}   = $height;
14170:     $ValuesHash{$id.'.width'}    = $width;
14171:     $ValuesHash{$id.'.xskip'}    = $xskip;
14172:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14173:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14174:     #
14175:     # Deal with other parameters
14176:     while (my ($key,$value) = each(%$extra_settings)) {
14177:         $ValuesHash{$id.'.'.$key} = $value;
14178:     }
14179:     #
14180:     &Apache::lonnet::appenv(\%ValuesHash);
14181:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14182: }
14183: 
14184: ############################################################
14185: ############################################################
14186: 
14187: =pod
14188: 
14189: =item * &DrawXYGraph()
14190: 
14191: Facilitates the plotting of data in an XY graph.
14192: Puts plot definition data into the users environment in order for 
14193: graph.png to plot it.  Returns an <img> tag for the plot.
14194: 
14195: Inputs:
14196: 
14197: =over 4
14198: 
14199: =item $Title: string, the title of the plot
14200: 
14201: =item $xlabel: string, text describing the X-axis of the plot
14202: 
14203: =item $ylabel: string, text describing the Y-axis of the plot
14204: 
14205: =item $Max: scalar, the maximum Y value to use in the plot
14206: If $Max is < any data point, the graph will not be rendered.
14207: 
14208: =item $colors: Array ref containing the hex color codes for the data to be 
14209: plotted in.  If undefined, default values will be used.
14210: 
14211: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14212: 
14213: =item $Ydata: Array ref containing Array refs.  
14214: Each of the contained arrays will be plotted as a separate curve.
14215: 
14216: =item %Values: hash indicating or overriding any default values which are 
14217: passed to graph.png.  
14218: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14219: 
14220: =back
14221: 
14222: Returns:
14223: 
14224: An <img> tag which references graph.png and the appropriate identifying
14225: information for the plot.
14226: 
14227: =cut
14228: 
14229: ############################################################
14230: ############################################################
14231: sub DrawXYGraph {
14232:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14233:     #
14234:     # Create the identifier for the graph
14235:     my $identifier = &get_cgi_id();
14236:     my $id = 'cgi.'.$identifier;
14237:     #
14238:     $Title  = '' if (! defined($Title));
14239:     $xlabel = '' if (! defined($xlabel));
14240:     $ylabel = '' if (! defined($ylabel));
14241:     my %ValuesHash = 
14242:         (
14243:          $id.'.title'  => &escape($Title),
14244:          $id.'.xlabel' => &escape($xlabel),
14245:          $id.'.ylabel' => &escape($ylabel),
14246:          $id.'.y_max_value'=> $Max,
14247:          $id.'.labels'     => join(',',@$Xlabels),
14248:          $id.'.PlotType'   => 'XY',
14249:          );
14250:     #
14251:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14252:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14253:     }
14254:     #
14255:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14256:         return '';
14257:     }
14258:     my $NumSets=1;
14259:     foreach my $array (@{$Ydata}){
14260:         next if (! ref($array));
14261:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14262:     }
14263:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14264:     #
14265:     # Deal with other parameters
14266:     while (my ($key,$value) = each(%Values)) {
14267:         $ValuesHash{$id.'.'.$key} = $value;
14268:     }
14269:     #
14270:     &Apache::lonnet::appenv(\%ValuesHash);
14271:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14272: }
14273: 
14274: ############################################################
14275: ############################################################
14276: 
14277: =pod
14278: 
14279: =item * &DrawXYYGraph()
14280: 
14281: Facilitates the plotting of data in an XY graph with two Y axes.
14282: Puts plot definition data into the users environment in order for 
14283: graph.png to plot it.  Returns an <img> tag for the plot.
14284: 
14285: Inputs:
14286: 
14287: =over 4
14288: 
14289: =item $Title: string, the title of the plot
14290: 
14291: =item $xlabel: string, text describing the X-axis of the plot
14292: 
14293: =item $ylabel: string, text describing the Y-axis of the plot
14294: 
14295: =item $colors: Array ref containing the hex color codes for the data to be 
14296: plotted in.  If undefined, default values will be used.
14297: 
14298: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14299: 
14300: =item $Ydata1: The first data set
14301: 
14302: =item $Min1: The minimum value of the left Y-axis
14303: 
14304: =item $Max1: The maximum value of the left Y-axis
14305: 
14306: =item $Ydata2: The second data set
14307: 
14308: =item $Min2: The minimum value of the right Y-axis
14309: 
14310: =item $Max2: The maximum value of the left Y-axis
14311: 
14312: =item %Values: hash indicating or overriding any default values which are 
14313: passed to graph.png.  
14314: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14315: 
14316: =back
14317: 
14318: Returns:
14319: 
14320: An <img> tag which references graph.png and the appropriate identifying
14321: information for the plot.
14322: 
14323: =cut
14324: 
14325: ############################################################
14326: ############################################################
14327: sub DrawXYYGraph {
14328:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14329:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14330:     #
14331:     # Create the identifier for the graph
14332:     my $identifier = &get_cgi_id();
14333:     my $id = 'cgi.'.$identifier;
14334:     #
14335:     $Title  = '' if (! defined($Title));
14336:     $xlabel = '' if (! defined($xlabel));
14337:     $ylabel = '' if (! defined($ylabel));
14338:     my %ValuesHash = 
14339:         (
14340:          $id.'.title'  => &escape($Title),
14341:          $id.'.xlabel' => &escape($xlabel),
14342:          $id.'.ylabel' => &escape($ylabel),
14343:          $id.'.labels' => join(',',@$Xlabels),
14344:          $id.'.PlotType' => 'XY',
14345:          $id.'.NumSets' => 2,
14346:          $id.'.two_axes' => 1,
14347:          $id.'.y1_max_value' => $Max1,
14348:          $id.'.y1_min_value' => $Min1,
14349:          $id.'.y2_max_value' => $Max2,
14350:          $id.'.y2_min_value' => $Min2,
14351:          );
14352:     #
14353:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14354:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14355:     }
14356:     #
14357:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14358:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14359:         return '';
14360:     }
14361:     my $NumSets=1;
14362:     foreach my $array ($Ydata1,$Ydata2){
14363:         next if (! ref($array));
14364:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14365:     }
14366:     #
14367:     # Deal with other parameters
14368:     while (my ($key,$value) = each(%Values)) {
14369:         $ValuesHash{$id.'.'.$key} = $value;
14370:     }
14371:     #
14372:     &Apache::lonnet::appenv(\%ValuesHash);
14373:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14374: }
14375: 
14376: ############################################################
14377: ############################################################
14378: 
14379: =pod
14380: 
14381: =back 
14382: 
14383: =head1 Statistics helper routines?  
14384: 
14385: Bad place for them but what the hell.
14386: 
14387: =over 4
14388: 
14389: =item * &chartlink()
14390: 
14391: Returns a link to the chart for a specific student.  
14392: 
14393: Inputs:
14394: 
14395: =over 4
14396: 
14397: =item $linktext: The text of the link
14398: 
14399: =item $sname: The students username
14400: 
14401: =item $sdomain: The students domain
14402: 
14403: =back
14404: 
14405: =back
14406: 
14407: =cut
14408: 
14409: ############################################################
14410: ############################################################
14411: sub chartlink {
14412:     my ($linktext, $sname, $sdomain) = @_;
14413:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14414:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14415:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14416:        '">'.$linktext.'</a>';
14417: }
14418: 
14419: #######################################################
14420: #######################################################
14421: 
14422: =pod
14423: 
14424: =head1 Course Environment Routines
14425: 
14426: =over 4
14427: 
14428: =item * &restore_course_settings()
14429: 
14430: =item * &store_course_settings()
14431: 
14432: Restores/Store indicated form parameters from the course environment.
14433: Will not overwrite existing values of the form parameters.
14434: 
14435: Inputs: 
14436: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14437: 
14438: a hash ref describing the data to be stored.  For example:
14439:    
14440: %Save_Parameters = ('Status' => 'scalar',
14441:     'chartoutputmode' => 'scalar',
14442:     'chartoutputdata' => 'scalar',
14443:     'Section' => 'array',
14444:     'Group' => 'array',
14445:     'StudentData' => 'array',
14446:     'Maps' => 'array');
14447: 
14448: Returns: both routines return nothing
14449: 
14450: =back
14451: 
14452: =cut
14453: 
14454: #######################################################
14455: #######################################################
14456: sub store_course_settings {
14457:     return &store_settings($env{'request.course.id'},@_);
14458: }
14459: 
14460: sub store_settings {
14461:     # save to the environment
14462:     # appenv the same items, just to be safe
14463:     my $udom  = $env{'user.domain'};
14464:     my $uname = $env{'user.name'};
14465:     my ($context,$prefix,$Settings) = @_;
14466:     my %SaveHash;
14467:     my %AppHash;
14468:     while (my ($setting,$type) = each(%$Settings)) {
14469:         my $basename = join('.','internal',$context,$prefix,$setting);
14470:         my $envname = 'environment.'.$basename;
14471:         if (exists($env{'form.'.$setting})) {
14472:             # Save this value away
14473:             if ($type eq 'scalar' &&
14474:                 (! exists($env{$envname}) || 
14475:                  $env{$envname} ne $env{'form.'.$setting})) {
14476:                 $SaveHash{$basename} = $env{'form.'.$setting};
14477:                 $AppHash{$envname}   = $env{'form.'.$setting};
14478:             } elsif ($type eq 'array') {
14479:                 my $stored_form;
14480:                 if (ref($env{'form.'.$setting})) {
14481:                     $stored_form = join(',',
14482:                                         map {
14483:                                             &escape($_);
14484:                                         } sort(@{$env{'form.'.$setting}}));
14485:                 } else {
14486:                     $stored_form = 
14487:                         &escape($env{'form.'.$setting});
14488:                 }
14489:                 # Determine if the array contents are the same.
14490:                 if ($stored_form ne $env{$envname}) {
14491:                     $SaveHash{$basename} = $stored_form;
14492:                     $AppHash{$envname}   = $stored_form;
14493:                 }
14494:             }
14495:         }
14496:     }
14497:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14498:                                           $udom,$uname);
14499:     if ($put_result !~ /^(ok|delayed)/) {
14500:         &Apache::lonnet::logthis('unable to save form parameters, '.
14501:                                  'got error:'.$put_result);
14502:     }
14503:     # Make sure these settings stick around in this session, too
14504:     &Apache::lonnet::appenv(\%AppHash);
14505:     return;
14506: }
14507: 
14508: sub restore_course_settings {
14509:     return &restore_settings($env{'request.course.id'},@_);
14510: }
14511: 
14512: sub restore_settings {
14513:     my ($context,$prefix,$Settings) = @_;
14514:     while (my ($setting,$type) = each(%$Settings)) {
14515:         next if (exists($env{'form.'.$setting}));
14516:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14517:             '.'.$setting;
14518:         if (exists($env{$envname})) {
14519:             if ($type eq 'scalar') {
14520:                 $env{'form.'.$setting} = $env{$envname};
14521:             } elsif ($type eq 'array') {
14522:                 $env{'form.'.$setting} = [ 
14523:                                            map { 
14524:                                                &unescape($_); 
14525:                                            } split(',',$env{$envname})
14526:                                            ];
14527:             }
14528:         }
14529:     }
14530: }
14531: 
14532: #######################################################
14533: #######################################################
14534: 
14535: =pod
14536: 
14537: =head1 Domain E-mail Routines  
14538: 
14539: =over 4
14540: 
14541: =item * &build_recipient_list()
14542: 
14543: Build recipient lists for following types of e-mail:
14544: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14545: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14546: module change checking, student/employee ID conflict checks, as
14547: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14548: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14549: 
14550: Inputs:
14551: defmail (scalar - email address of default recipient), 
14552: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14553: requestsmail, updatesmail, or idconflictsmail).
14554: 
14555: defdom (domain for which to retrieve configuration settings),
14556: 
14557: origmail (scalar - email address of recipient from loncapa.conf, 
14558: i.e., predates configuration by DC via domainprefs.pm 
14559: 
14560: Returns: comma separated list of addresses to which to send e-mail.
14561: 
14562: =back
14563: 
14564: =cut
14565: 
14566: ############################################################
14567: ############################################################
14568: sub build_recipient_list {
14569:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14570:     my @recipients;
14571:     my ($otheremails,$lastresort,$allbcc,$addtext);
14572:     my %domconfig =
14573:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14574:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14575:         if (exists($domconfig{'contacts'}{$mailing})) {
14576:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14577:                 my @contacts = ('adminemail','supportemail');
14578:                 foreach my $item (@contacts) {
14579:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14580:                         my $addr = $domconfig{'contacts'}{$item}; 
14581:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14582:                             push(@recipients,$addr);
14583:                         }
14584:                     }
14585:                 }
14586:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14587:                 if ($mailing eq 'helpdeskmail') {
14588:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14589:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14590:                         my @ok_bccs;
14591:                         foreach my $bcc (@bccs) {
14592:                             $bcc =~ s/^\s+//g;
14593:                             $bcc =~ s/\s+$//g;
14594:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14595:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14596:                                     push(@ok_bccs,$bcc);
14597:                                 }
14598:                             }
14599:                         }
14600:                         if (@ok_bccs > 0) {
14601:                             $allbcc = join(', ',@ok_bccs);
14602:                         }
14603:                     }
14604:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14605:                 }
14606:             }
14607:         } elsif ($origmail ne '') {
14608:             $lastresort = $origmail;
14609:         }
14610:     } elsif ($origmail ne '') {
14611:         $lastresort = $origmail;
14612:     }
14613: 
14614:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
14615:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14616:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14617:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14618:             my %what = (
14619:                           perlvar => 1,
14620:                        );
14621:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14622:             if ($primary) {
14623:                 my $gotaddr;
14624:                 my ($result,$returnhash) =
14625:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14626:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14627:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14628:                         $lastresort = $returnhash->{'lonSupportEMail'};
14629:                         $gotaddr = 1;
14630:                     }
14631:                 }
14632:                 unless ($gotaddr) {
14633:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14634:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14635:                     unless ($uintdom eq $intdom) {
14636:                         my %domconfig =
14637:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14638:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14639:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14640:                                 my @contacts = ('adminemail','supportemail');
14641:                                 foreach my $item (@contacts) {
14642:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14643:                                         my $addr = $domconfig{'contacts'}{$item};
14644:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14645:                                             push(@recipients,$addr);
14646:                                         }
14647:                                     }
14648:                                 }
14649:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14650:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14651:                                 }
14652:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14653:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14654:                                     my @ok_bccs;
14655:                                     foreach my $bcc (@bccs) {
14656:                                         $bcc =~ s/^\s+//g;
14657:                                         $bcc =~ s/\s+$//g;
14658:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14659:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14660:                                                 push(@ok_bccs,$bcc);
14661:                                             }
14662:                                         }
14663:                                     }
14664:                                     if (@ok_bccs > 0) {
14665:                                         $allbcc = join(', ',@ok_bccs);
14666:                                     }
14667:                                 }
14668:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14669:                             }
14670:                         }
14671:                     }
14672:                 }
14673:             }
14674:         }
14675:     }
14676:     if (defined($defmail)) {
14677:         if ($defmail ne '') {
14678:             push(@recipients,$defmail);
14679:         }
14680:     }
14681:     if ($otheremails) {
14682:         my @others;
14683:         if ($otheremails =~ /,/) {
14684:             @others = split(/,/,$otheremails);
14685:         } else {
14686:             push(@others,$otheremails);
14687:         }
14688:         foreach my $addr (@others) {
14689:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14690:                 push(@recipients,$addr);
14691:             }
14692:         }
14693:     }
14694:     if ($mailing eq 'helpdesk') {
14695:         if ((!@recipients) && ($lastresort ne '')) {
14696:             push(@recipients,$lastresort);
14697:         }
14698:     } elsif ($lastresort ne '') {
14699:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14700:             push(@recipients,$lastresort);
14701:         }
14702:     }
14703:     my $recipientlist = join(',',@recipients);
14704:     if (wantarray) {
14705:         return ($recipientlist,$allbcc,$addtext);
14706:     } else {
14707:         return $recipientlist;
14708:     }
14709: }
14710: 
14711: ############################################################
14712: ############################################################
14713: 
14714: =pod
14715: 
14716: =over 4
14717: 
14718: =item * &mime_email()
14719: 
14720: Sends an email with a possible attachment
14721: 
14722: Inputs:
14723: 
14724: =over 4
14725: 
14726: from -              Sender's email address
14727: 
14728: to -                Email address of recipient
14729: 
14730: subject -           Subject of email
14731: 
14732: body -              Body of email
14733: 
14734: cc_string -         Carbon copy email address
14735: 
14736: bcc -               Blind carbon copy email address
14737: 
14738: type -              File type of attachment
14739: 
14740: attachment_path -   Path of file to be attached
14741: 
14742: file_name -         Name of file to be attached
14743: 
14744: attachment_text -   The body of an attachment of type "TEXT"
14745: 
14746: =back
14747: 
14748: =back
14749: 
14750: =cut
14751: 
14752: ############################################################
14753: ############################################################
14754: 
14755: sub mime_email {
14756:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14757:         $file_name, $attachment_text) = @_;
14758:     my $msg = MIME::Lite->new(
14759:              From    => $from,
14760:              To      => $to,
14761:              Subject => $subject,
14762:              Type    =>'TEXT',
14763:              Data    => $body,
14764:              );
14765:     if ($cc_string ne '') {
14766:         $msg->add("Cc" => $cc_string);
14767:     }
14768:     if ($bcc ne '') {
14769:         $msg->add("Bcc" => $bcc);
14770:     }
14771:     $msg->attr("content-type"         => "text/plain");
14772:     $msg->attr("content-type.charset" => "UTF-8");
14773:     # Attach file if given
14774:     if ($attachment_path) {
14775:         unless ($file_name) {
14776:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14777:         }
14778:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14779:         $msg->attach(Type     => $type,
14780:                      Path     => $attachment_path,
14781:                      Filename => $file_name
14782:                      );
14783:     # Otherwise attach text if given
14784:     } elsif ($attachment_text) {
14785:         $msg->attach(Type => 'TEXT',
14786:                      Data => $attachment_text);
14787:     }
14788:     # Send it
14789:     $msg->send('sendmail');
14790: }
14791: 
14792: ############################################################
14793: ############################################################
14794: 
14795: =pod
14796: 
14797: =head1 Course Catalog Routines
14798: 
14799: =over 4
14800: 
14801: =item * &gather_categories()
14802: 
14803: Converts category definitions - keys of categories hash stored in  
14804: coursecategories in configuration.db on the primary library server in a 
14805: domain - to an array.  Also generates javascript and idx hash used to 
14806: generate Domain Coordinator interface for editing Course Categories.
14807: 
14808: Inputs:
14809: 
14810: categories (reference to hash of category definitions).
14811: 
14812: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14813:       categories and subcategories).
14814: 
14815: idx (reference to hash of counters used in Domain Coordinator interface for 
14816:       editing Course Categories).
14817: 
14818: jsarray (reference to array of categories used to create Javascript arrays for
14819:          Domain Coordinator interface for editing Course Categories).
14820: 
14821: Returns: nothing
14822: 
14823: Side effects: populates cats, idx and jsarray. 
14824: 
14825: =cut
14826: 
14827: sub gather_categories {
14828:     my ($categories,$cats,$idx,$jsarray) = @_;
14829:     my %counters;
14830:     my $num = 0;
14831:     foreach my $item (keys(%{$categories})) {
14832:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14833:         if ($container eq '' && $depth == 0) {
14834:             $cats->[$depth][$categories->{$item}] = $cat;
14835:         } else {
14836:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14837:         }
14838:         my ($escitem,$tail) = split(/:/,$item,2);
14839:         if ($counters{$tail} eq '') {
14840:             $counters{$tail} = $num;
14841:             $num ++;
14842:         }
14843:         if (ref($idx) eq 'HASH') {
14844:             $idx->{$item} = $counters{$tail};
14845:         }
14846:         if (ref($jsarray) eq 'ARRAY') {
14847:             push(@{$jsarray->[$counters{$tail}]},$item);
14848:         }
14849:     }
14850:     return;
14851: }
14852: 
14853: =pod
14854: 
14855: =item * &extract_categories()
14856: 
14857: Used to generate breadcrumb trails for course categories.
14858: 
14859: Inputs:
14860: 
14861: categories (reference to hash of category definitions).
14862: 
14863: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14864:       categories and subcategories).
14865: 
14866: trails (reference to array of breacrumb trails for each category).
14867: 
14868: allitems (reference to hash - key is category key 
14869:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14870: 
14871: idx (reference to hash of counters used in Domain Coordinator interface for
14872:       editing Course Categories).
14873: 
14874: jsarray (reference to array of categories used to create Javascript arrays for
14875:          Domain Coordinator interface for editing Course Categories).
14876: 
14877: subcats (reference to hash of arrays containing all subcategories within each 
14878:          category, -recursive)
14879: 
14880: Returns: nothing
14881: 
14882: Side effects: populates trails and allitems hash references.
14883: 
14884: =cut
14885: 
14886: sub extract_categories {
14887:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14888:     if (ref($categories) eq 'HASH') {
14889:         &gather_categories($categories,$cats,$idx,$jsarray);
14890:         if (ref($cats->[0]) eq 'ARRAY') {
14891:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14892:                 my $name = $cats->[0][$i];
14893:                 my $item = &escape($name).'::0';
14894:                 my $trailstr;
14895:                 if ($name eq 'instcode') {
14896:                     $trailstr = &mt('Official courses (with institutional codes)');
14897:                 } elsif ($name eq 'communities') {
14898:                     $trailstr = &mt('Communities');
14899:                 } elsif ($name eq 'placement') {
14900:                     $trailstr = &mt('Placement Tests');
14901:                 } else {
14902:                     $trailstr = $name;
14903:                 }
14904:                 if ($allitems->{$item} eq '') {
14905:                     push(@{$trails},$trailstr);
14906:                     $allitems->{$item} = scalar(@{$trails})-1;
14907:                 }
14908:                 my @parents = ($name);
14909:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14910:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14911:                         my $category = $cats->[1]{$name}[$j];
14912:                         if (ref($subcats) eq 'HASH') {
14913:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14914:                         }
14915:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14916:                     }
14917:                 } else {
14918:                     if (ref($subcats) eq 'HASH') {
14919:                         $subcats->{$item} = [];
14920:                     }
14921:                 }
14922:             }
14923:         }
14924:     }
14925:     return;
14926: }
14927: 
14928: =pod
14929: 
14930: =item * &recurse_categories()
14931: 
14932: Recursively used to generate breadcrumb trails for course categories.
14933: 
14934: Inputs:
14935: 
14936: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14937:       categories and subcategories).
14938: 
14939: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14940: 
14941: category (current course category, for which breadcrumb trail is being generated).
14942: 
14943: trails (reference to array of breadcrumb trails for each category).
14944: 
14945: allitems (reference to hash - key is category key
14946:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14947: 
14948: parents (array containing containers directories for current category, 
14949:          back to top level). 
14950: 
14951: Returns: nothing
14952: 
14953: Side effects: populates trails and allitems hash references
14954: 
14955: =cut
14956: 
14957: sub recurse_categories {
14958:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14959:     my $shallower = $depth - 1;
14960:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14961:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14962:             my $name = $cats->[$depth]{$category}[$k];
14963:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14964:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14965:             if ($allitems->{$item} eq '') {
14966:                 push(@{$trails},$trailstr);
14967:                 $allitems->{$item} = scalar(@{$trails})-1;
14968:             }
14969:             my $deeper = $depth+1;
14970:             push(@{$parents},$category);
14971:             if (ref($subcats) eq 'HASH') {
14972:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14973:                 for (my $j=@{$parents}; $j>=0; $j--) {
14974:                     my $higher;
14975:                     if ($j > 0) {
14976:                         $higher = &escape($parents->[$j]).':'.
14977:                                   &escape($parents->[$j-1]).':'.$j;
14978:                     } else {
14979:                         $higher = &escape($parents->[$j]).'::'.$j;
14980:                     }
14981:                     push(@{$subcats->{$higher}},$subcat);
14982:                 }
14983:             }
14984:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14985:                                 $subcats);
14986:             pop(@{$parents});
14987:         }
14988:     } else {
14989:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14990:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14991:         if ($allitems->{$item} eq '') {
14992:             push(@{$trails},$trailstr);
14993:             $allitems->{$item} = scalar(@{$trails})-1;
14994:         }
14995:     }
14996:     return;
14997: }
14998: 
14999: =pod
15000: 
15001: =item * &assign_categories_table()
15002: 
15003: Create a datatable for display of hierarchical categories in a domain,
15004: with checkboxes to allow a course to be categorized. 
15005: 
15006: Inputs:
15007: 
15008: cathash - reference to hash of categories defined for the domain (from
15009:           configuration.db)
15010: 
15011: currcat - scalar with an & separated list of categories assigned to a course. 
15012: 
15013: type    - scalar contains course type (Course or Community).
15014: 
15015: disabled - scalar (optional) contains disabled="disabled" if input elements are
15016:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15017: 
15018: Returns: $output (markup to be displayed) 
15019: 
15020: =cut
15021: 
15022: sub assign_categories_table {
15023:     my ($cathash,$currcat,$type,$disabled) = @_;
15024:     my $output;
15025:     if (ref($cathash) eq 'HASH') {
15026:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
15027:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
15028:         $maxdepth = scalar(@cats);
15029:         if (@cats > 0) {
15030:             my $itemcount = 0;
15031:             if (ref($cats[0]) eq 'ARRAY') {
15032:                 my @currcategories;
15033:                 if ($currcat ne '') {
15034:                     @currcategories = split('&',$currcat);
15035:                 }
15036:                 my $table;
15037:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15038:                     my $parent = $cats[0][$i];
15039:                     next if ($parent eq 'instcode');
15040:                     if ($type eq 'Community') {
15041:                         next unless ($parent eq 'communities');
15042:                     } elsif ($type eq 'Placement') {
15043:                         next unless ($parent eq 'placement');
15044:                     } else {
15045:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
15046:                     }
15047:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15048:                     my $item = &escape($parent).'::0';
15049:                     my $checked = '';
15050:                     if (@currcategories > 0) {
15051:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15052:                             $checked = ' checked="checked"';
15053:                         }
15054:                     }
15055:                     my $parent_title = $parent;
15056:                     if ($parent eq 'communities') {
15057:                         $parent_title = &mt('Communities');
15058:                     } elsif ($parent eq 'placement') {
15059:                         $parent_title = &mt('Placement Tests');
15060:                     }
15061:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15062:                               '<input type="checkbox" name="usecategory" value="'.
15063:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15064:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15065:                     my $depth = 1;
15066:                     push(@path,$parent);
15067:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15068:                     pop(@path);
15069:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15070:                     $itemcount ++;
15071:                 }
15072:                 if ($itemcount) {
15073:                     $output = &Apache::loncommon::start_data_table().
15074:                               $table.
15075:                               &Apache::loncommon::end_data_table();
15076:                 }
15077:             }
15078:         }
15079:     }
15080:     return $output;
15081: }
15082: 
15083: =pod
15084: 
15085: =item * &assign_category_rows()
15086: 
15087: Create a datatable row for display of nested categories in a domain,
15088: with checkboxes to allow a course to be categorized,called recursively.
15089: 
15090: Inputs:
15091: 
15092: itemcount - track row number for alternating colors
15093: 
15094: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15095:       categories and subcategories.
15096: 
15097: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15098: 
15099: parent - parent of current category item
15100: 
15101: path - Array containing all categories back up through the hierarchy from the
15102:        current category to the top level.
15103: 
15104: currcategories - reference to array of current categories assigned to the course
15105: 
15106: disabled - scalar (optional) contains disabled="disabled" if input elements are
15107:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15108: 
15109: Returns: $output (markup to be displayed).
15110: 
15111: =cut
15112: 
15113: sub assign_category_rows {
15114:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15115:     my ($text,$name,$item,$chgstr);
15116:     if (ref($cats) eq 'ARRAY') {
15117:         my $maxdepth = scalar(@{$cats});
15118:         if (ref($cats->[$depth]) eq 'HASH') {
15119:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15120:                 my $numchildren = @{$cats->[$depth]{$parent}};
15121:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15122:                 $text .= '<td><table class="LC_data_table">';
15123:                 for (my $j=0; $j<$numchildren; $j++) {
15124:                     $name = $cats->[$depth]{$parent}[$j];
15125:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15126:                     my $deeper = $depth+1;
15127:                     my $checked = '';
15128:                     if (ref($currcategories) eq 'ARRAY') {
15129:                         if (@{$currcategories} > 0) {
15130:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15131:                                 $checked = ' checked="checked"';
15132:                             }
15133:                         }
15134:                     }
15135:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15136:                              '<input type="checkbox" name="usecategory" value="'.
15137:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15138:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15139:                              '</td><td>';
15140:                     if (ref($path) eq 'ARRAY') {
15141:                         push(@{$path},$name);
15142:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15143:                         pop(@{$path});
15144:                     }
15145:                     $text .= '</td></tr>';
15146:                 }
15147:                 $text .= '</table></td>';
15148:             }
15149:         }
15150:     }
15151:     return $text;
15152: }
15153: 
15154: =pod
15155: 
15156: =back
15157: 
15158: =cut
15159: 
15160: ############################################################
15161: ############################################################
15162: 
15163: 
15164: sub commit_customrole {
15165:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15166:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15167:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15168:                          ($end?', ending '.localtime($end):'').': <b>'.
15169:               &Apache::lonnet::assigncustomrole(
15170:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15171:                  '</b><br />';
15172:     return $output;
15173: }
15174: 
15175: sub commit_standardrole {
15176:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15177:     my ($output,$logmsg,$linefeed);
15178:     if ($context eq 'auto') {
15179:         $linefeed = "\n";
15180:     } else {
15181:         $linefeed = "<br />\n";
15182:     }  
15183:     if ($three eq 'st') {
15184:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15185:                                          $one,$two,$sec,$context,$credits);
15186:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15187:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15188:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15189:         } else {
15190:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15191:                ($start?', '.&mt('starting').' '.localtime($start):'').
15192:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15193:             if ($context eq 'auto') {
15194:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15195:             } else {
15196:                $output .= '<b>'.$result.'</b>'.$linefeed.
15197:                &mt('Add to classlist').': <b>ok</b>';
15198:             }
15199:             $output .= $linefeed;
15200:         }
15201:     } else {
15202:         $output = &mt('Assigning').' '.$three.' in '.$url.
15203:                ($start?', '.&mt('starting').' '.localtime($start):'').
15204:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15205:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15206:         if ($context eq 'auto') {
15207:             $output .= $result.$linefeed;
15208:         } else {
15209:             $output .= '<b>'.$result.'</b>'.$linefeed;
15210:         }
15211:     }
15212:     return $output;
15213: }
15214: 
15215: sub commit_studentrole {
15216:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15217:         $credits) = @_;
15218:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15219:     if ($context eq 'auto') {
15220:         $linefeed = "\n";
15221:     } else {
15222:         $linefeed = '<br />'."\n";
15223:     }
15224:     if (defined($one) && defined($two)) {
15225:         my $cid=$one.'_'.$two;
15226:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15227:         my $secchange = 0;
15228:         my $expire_role_result;
15229:         my $modify_section_result;
15230:         if ($oldsec ne '-1') { 
15231:             if ($oldsec ne $sec) {
15232:                 $secchange = 1;
15233:                 my $now = time;
15234:                 my $uurl='/'.$cid;
15235:                 $uurl=~s/\_/\//g;
15236:                 if ($oldsec) {
15237:                     $uurl.='/'.$oldsec;
15238:                 }
15239:                 $oldsecurl = $uurl;
15240:                 $expire_role_result = 
15241:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15242:                 if ($env{'request.course.sec'} ne '') { 
15243:                     if ($expire_role_result eq 'refused') {
15244:                         my @roles = ('st');
15245:                         my @statuses = ('previous');
15246:                         my @roledoms = ($one);
15247:                         my $withsec = 1;
15248:                         my %roleshash = 
15249:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15250:                                               \@statuses,\@roles,\@roledoms,$withsec);
15251:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15252:                             my ($oldstart,$oldend) = 
15253:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15254:                             if ($oldend > 0 && $oldend <= $now) {
15255:                                 $expire_role_result = 'ok';
15256:                             }
15257:                         }
15258:                     }
15259:                 }
15260:                 $result = $expire_role_result;
15261:             }
15262:         }
15263:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15264:             $modify_section_result = 
15265:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15266:                                                            undef,undef,undef,$sec,
15267:                                                            $end,$start,'','',$cid,
15268:                                                            '',$context,$credits);
15269:             if ($modify_section_result =~ /^ok/) {
15270:                 if ($secchange == 1) {
15271:                     if ($sec eq '') {
15272:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15273:                     } else {
15274:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15275:                     }
15276:                 } elsif ($oldsec eq '-1') {
15277:                     if ($sec eq '') {
15278:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15279:                     } else {
15280:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15281:                     }
15282:                 } else {
15283:                     if ($sec eq '') {
15284:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15285:                     } else {
15286:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15287:                     }
15288:                 }
15289:             } else {
15290:                 if ($secchange) { 
15291:                     $$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;
15292:                 } else {
15293:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15294:                 }
15295:             }
15296:             $result = $modify_section_result;
15297:         } elsif ($secchange == 1) {
15298:             if ($oldsec eq '') {
15299:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15300:             } else {
15301:                 $$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;
15302:             }
15303:             if ($expire_role_result eq 'refused') {
15304:                 my $newsecurl = '/'.$cid;
15305:                 $newsecurl =~ s/\_/\//g;
15306:                 if ($sec ne '') {
15307:                     $newsecurl.='/'.$sec;
15308:                 }
15309:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15310:                     if ($sec eq '') {
15311:                         $$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;
15312:                     } else {
15313:                         $$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;
15314:                     }
15315:                 }
15316:             }
15317:         }
15318:     } else {
15319:         $$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;
15320:         $result = "error: incomplete course id\n";
15321:     }
15322:     return $result;
15323: }
15324: 
15325: sub show_role_extent {
15326:     my ($scope,$context,$role) = @_;
15327:     $scope =~ s{^/}{};
15328:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15329:     push(@courseroles,'co');
15330:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15331:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15332:         $scope =~ s{/}{_};
15333:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15334:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15335:         my ($audom,$auname) = split(/\//,$scope);
15336:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15337:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15338:     } else {
15339:         $scope =~ s{/$}{};
15340:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15341:                    &Apache::lonnet::domain($scope,'description').'</span>');
15342:     }
15343: }
15344: 
15345: ############################################################
15346: ############################################################
15347: 
15348: sub check_clone {
15349:     my ($args,$linefeed) = @_;
15350:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15351:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15352:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15353:     my $clonemsg;
15354:     my $can_clone = 0;
15355:     my $lctype = lc($args->{'crstype'});
15356:     if ($lctype ne 'community') {
15357:         $lctype = 'course';
15358:     }
15359:     if ($clonehome eq 'no_host') {
15360:         if ($args->{'crstype'} eq 'Community') {
15361:             $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'});
15362:         } else {
15363:             $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'});
15364:         }     
15365:     } else {
15366: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15367:         if ($args->{'crstype'} eq 'Community') {
15368:             if ($clonedesc{'type'} ne 'Community') {
15369:                 $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'});
15370:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15371:             }
15372:         }
15373: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15374:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15375: 	    $can_clone = 1;
15376: 	} else {
15377: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15378: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15379:             if ($clonehash{'cloners'} eq '') {
15380:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15381:                 if ($domdefs{'canclone'}) {
15382:                     unless ($domdefs{'canclone'} eq 'none') {
15383:                         if ($domdefs{'canclone'} eq 'domain') {
15384:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15385:                                 $can_clone = 1;
15386:                             }
15387:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15388:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15389:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15390:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15391:                                 $can_clone = 1;
15392:                             }
15393:                         }
15394:                     }
15395:                 }
15396:             } else {
15397: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15398:                 if (grep(/^\*$/,@cloners)) {
15399:                     $can_clone = 1;
15400:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15401:                     $can_clone = 1;
15402:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15403:                     $can_clone = 1;
15404:                 }
15405:                 unless ($can_clone) {
15406:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15407:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15408:                         my (%gotdomdefaults,%gotcodedefaults);
15409:                         foreach my $cloner (@cloners) {
15410:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15411:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15412:                                 my (%codedefaults,@code_order);
15413:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15414:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15415:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15416:                                     }
15417:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15418:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15419:                                     }
15420:                                 } else {
15421:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15422:                                                                             \%codedefaults,
15423:                                                                             \@code_order);
15424:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15425:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15426:                                 }
15427:                                 if (@code_order > 0) {
15428:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15429:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15430:                                                                                 $args->{'crscode'})) {
15431:                                         $can_clone = 1;
15432:                                         last;
15433:                                     }
15434:                                 }
15435:                             }
15436:                         }
15437:                     }
15438:                 }
15439:             }
15440:             unless ($can_clone) {
15441:                 my $ccrole = 'cc';
15442:                 if ($args->{'crstype'} eq 'Community') {
15443:                     $ccrole = 'co';
15444:                 }
15445: 	        my %roleshash =
15446: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15447: 					          $args->{'ccdomain'},
15448:                                                   'userroles',['active'],[$ccrole],
15449: 					          [$args->{'clonedomain'}]);
15450: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15451:                     $can_clone = 1;
15452:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15453:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15454:                     $can_clone = 1;
15455:                 }
15456:             }
15457:             unless ($can_clone) {
15458:                 if ($args->{'crstype'} eq 'Community') {
15459:                     $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'});
15460:                 } else {
15461:                     $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'});
15462:                 }
15463: 	    }
15464:         }
15465:     }
15466:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15467: }
15468: 
15469: sub construct_course {
15470:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15471:         $cnum,$category,$coderef) = @_;
15472:     my $outcome;
15473:     my $linefeed =  '<br />'."\n";
15474:     if ($context eq 'auto') {
15475:         $linefeed = "\n";
15476:     }
15477: 
15478: #
15479: # Are we cloning?
15480: #
15481:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15482:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15483: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15484: 	if ($context ne 'auto') {
15485:             if ($clonemsg ne '') {
15486: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15487:             }
15488: 	}
15489: 	$outcome .= $clonemsg.$linefeed;
15490: 
15491:         if (!$can_clone) {
15492: 	    return (0,$outcome);
15493: 	}
15494:     }
15495: 
15496: #
15497: # Open course
15498: #
15499:     my $showncrstype;
15500:     if ($args->{'crstype'} eq 'Placement') {
15501:         $showncrstype = 'placement test'; 
15502:     } else {  
15503:         $showncrstype = lc($args->{'crstype'});
15504:     }
15505:     my %cenv=();
15506:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15507:                                              $args->{'cdescr'},
15508:                                              $args->{'curl'},
15509:                                              $args->{'course_home'},
15510:                                              $args->{'nonstandard'},
15511:                                              $args->{'crscode'},
15512:                                              $args->{'ccuname'}.':'.
15513:                                              $args->{'ccdomain'},
15514:                                              $args->{'crstype'},
15515:                                              $cnum,$context,$category);
15516: 
15517:     # Note: The testing routines depend on this being output; see 
15518:     # Utils::Course. This needs to at least be output as a comment
15519:     # if anyone ever decides to not show this, and Utils::Course::new
15520:     # will need to be suitably modified.
15521:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15522:     if ($$courseid =~ /^error:/) {
15523:         return (0,$outcome);
15524:     }
15525: 
15526: #
15527: # Check if created correctly
15528: #
15529:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15530:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15531:     if ($crsuhome eq 'no_host') {
15532:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15533:         return (0,$outcome);
15534:     }
15535:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15536: 
15537: #
15538: # Do the cloning
15539: #   
15540:     if ($can_clone && $cloneid) {
15541: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15542: 	if ($context ne 'auto') {
15543: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15544: 	}
15545: 	$outcome .= $clonemsg.$linefeed;
15546: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15547: # Copy all files
15548: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15549: # Restore URL
15550: 	$cenv{'url'}=$oldcenv{'url'};
15551: # Restore title
15552: 	$cenv{'description'}=$oldcenv{'description'};
15553: # Restore creation date, creator and creation context.
15554:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15555:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15556:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15557: # Mark as cloned
15558: 	$cenv{'clonedfrom'}=$cloneid;
15559: # Need to clone grading mode
15560:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15561:         $cenv{'grading'}=$newenv{'grading'};
15562: # Do not clone these environment entries
15563:         &Apache::lonnet::del('environment',
15564:                   ['default_enrollment_start_date',
15565:                    'default_enrollment_end_date',
15566:                    'question.email',
15567:                    'policy.email',
15568:                    'comment.email',
15569:                    'pch.users.denied',
15570:                    'plc.users.denied',
15571:                    'hidefromcat',
15572:                    'checkforpriv',
15573:                    'categories',
15574:                    'internal.uniquecode'],
15575:                    $$crsudom,$$crsunum);
15576:         if ($args->{'textbook'}) {
15577:             $cenv{'internal.textbook'} = $args->{'textbook'};
15578:         }
15579:     }
15580: 
15581: #
15582: # Set environment (will override cloned, if existing)
15583: #
15584:     my @sections = ();
15585:     my @xlists = ();
15586:     if ($args->{'crstype'}) {
15587:         $cenv{'type'}=$args->{'crstype'};
15588:     }
15589:     if ($args->{'crsid'}) {
15590:         $cenv{'courseid'}=$args->{'crsid'};
15591:     }
15592:     if ($args->{'crscode'}) {
15593:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15594:     }
15595:     if ($args->{'crsquota'} ne '') {
15596:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15597:     } else {
15598:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15599:     }
15600:     if ($args->{'ccuname'}) {
15601:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15602:                                         ':'.$args->{'ccdomain'};
15603:     } else {
15604:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15605:     }
15606:     if ($args->{'defaultcredits'}) {
15607:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15608:     }
15609:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15610:     if ($args->{'crssections'}) {
15611:         $cenv{'internal.sectionnums'} = '';
15612:         if ($args->{'crssections'} =~ m/,/) {
15613:             @sections = split/,/,$args->{'crssections'};
15614:         } else {
15615:             $sections[0] = $args->{'crssections'};
15616:         }
15617:         if (@sections > 0) {
15618:             foreach my $item (@sections) {
15619:                 my ($sec,$gp) = split/:/,$item;
15620:                 my $class = $args->{'crscode'}.$sec;
15621:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15622:                 $cenv{'internal.sectionnums'} .= $item.',';
15623:                 unless ($addcheck eq 'ok') {
15624:                     push(@badclasses,$class);
15625:                 }
15626:             }
15627:             $cenv{'internal.sectionnums'} =~ s/,$//;
15628:         }
15629:     }
15630: # do not hide course coordinator from staff listing, 
15631: # even if privileged
15632:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15633: # add course coordinator's domain to domains to check for privileged users
15634: # if different to course domain
15635:     if ($$crsudom ne $args->{'ccdomain'}) {
15636:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15637:     }
15638: # add crosslistings
15639:     if ($args->{'crsxlist'}) {
15640:         $cenv{'internal.crosslistings'}='';
15641:         if ($args->{'crsxlist'} =~ m/,/) {
15642:             @xlists = split/,/,$args->{'crsxlist'};
15643:         } else {
15644:             $xlists[0] = $args->{'crsxlist'};
15645:         }
15646:         if (@xlists > 0) {
15647:             foreach my $item (@xlists) {
15648:                 my ($xl,$gp) = split/:/,$item;
15649:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15650:                 $cenv{'internal.crosslistings'} .= $item.',';
15651:                 unless ($addcheck eq 'ok') {
15652:                     push(@badclasses,$xl);
15653:                 }
15654:             }
15655:             $cenv{'internal.crosslistings'} =~ s/,$//;
15656:         }
15657:     }
15658:     if ($args->{'autoadds'}) {
15659:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15660:     }
15661:     if ($args->{'autodrops'}) {
15662:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15663:     }
15664: # check for notification of enrollment changes
15665:     my @notified = ();
15666:     if ($args->{'notify_owner'}) {
15667:         if ($args->{'ccuname'} ne '') {
15668:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15669:         }
15670:     }
15671:     if ($args->{'notify_dc'}) {
15672:         if ($uname ne '') { 
15673:             push(@notified,$uname.':'.$udom);
15674:         }
15675:     }
15676:     if (@notified > 0) {
15677:         my $notifylist;
15678:         if (@notified > 1) {
15679:             $notifylist = join(',',@notified);
15680:         } else {
15681:             $notifylist = $notified[0];
15682:         }
15683:         $cenv{'internal.notifylist'} = $notifylist;
15684:     }
15685:     if (@badclasses > 0) {
15686:         my %lt=&Apache::lonlocal::texthash(
15687:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15688:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15689:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15690:         );
15691:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15692:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
15693:         if ($context eq 'auto') {
15694:             $outcome .= $badclass_msg.$linefeed;
15695:         } else {
15696:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15697:         }
15698:         foreach my $item (@badclasses) {
15699:             if ($context eq 'auto') {
15700:                 $outcome .= " - $item\n";
15701:             } else {
15702:                 $outcome .= "<li>$item</li>\n";
15703:             }
15704:         }
15705:         if ($context eq 'auto') {
15706:             $outcome .= $linefeed;
15707:         } else {
15708:             $outcome .= "</ul><br /><br /></div>\n";
15709:         } 
15710:     }
15711:     if ($args->{'no_end_date'}) {
15712:         $args->{'endaccess'} = 0;
15713:     }
15714:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15715:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15716:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15717:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15718:     if ($args->{'showphotos'}) {
15719:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15720:     }
15721:     $cenv{'internal.authtype'} = $args->{'authtype'};
15722:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15723:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15724:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15725:             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'); 
15726:             if ($context eq 'auto') {
15727:                 $outcome .= $krb_msg;
15728:             } else {
15729:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15730:             }
15731:             $outcome .= $linefeed;
15732:         }
15733:     }
15734:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15735:        if ($args->{'setpolicy'}) {
15736:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15737:        }
15738:        if ($args->{'setcontent'}) {
15739:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15740:        }
15741:        if ($args->{'setcomment'}) {
15742:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15743:        }
15744:     }
15745:     if ($args->{'reshome'}) {
15746: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15747: 	$cenv{'reshome'}=~s/\/+$/\//;
15748:     }
15749: #
15750: # course has keyed access
15751: #
15752:     if ($args->{'setkeys'}) {
15753:        $cenv{'keyaccess'}='yes';
15754:     }
15755: # if specified, key authority is not course, but user
15756: # only active if keyaccess is yes
15757:     if ($args->{'keyauth'}) {
15758: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15759: 	$user = &LONCAPA::clean_username($user);
15760: 	$domain = &LONCAPA::clean_username($domain);
15761: 	if ($user ne '' && $domain ne '') {
15762: 	    $cenv{'keyauth'}=$user.':'.$domain;
15763: 	}
15764:     }
15765: 
15766: #
15767: #  generate and store uniquecode (available to course requester), if course should have one.
15768: #
15769:     if ($args->{'uniquecode'}) {
15770:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15771:         if ($code) {
15772:             $cenv{'internal.uniquecode'} = $code;
15773:             my %crsinfo =
15774:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15775:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15776:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15777:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15778:             } 
15779:             if (ref($coderef)) {
15780:                 $$coderef = $code;
15781:             }
15782:         }
15783:     }
15784: 
15785:     if ($args->{'disresdis'}) {
15786:         $cenv{'pch.roles.denied'}='st';
15787:     }
15788:     if ($args->{'disablechat'}) {
15789:         $cenv{'plc.roles.denied'}='st';
15790:     }
15791: 
15792:     # Record we've not yet viewed the Course Initialization Helper for this 
15793:     # course
15794:     $cenv{'course.helper.not.run'} = 1;
15795:     #
15796:     # Use new Randomseed
15797:     #
15798:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15799:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15800:     #
15801:     # The encryption code and receipt prefix for this course
15802:     #
15803:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15804:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15805:     #
15806:     # By default, use standard grading
15807:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15808: 
15809:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15810:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15811: #
15812: # Open all assignments
15813: #
15814:     if ($args->{'openall'}) {
15815:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15816:        my %storecontent = ($storeunder         => time,
15817:                            $storeunder.'.type' => 'date_start');
15818:        
15819:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15820:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15821:    }
15822: #
15823: # Set first page
15824: #
15825:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15826: 	    || ($cloneid)) {
15827: 	use LONCAPA::map;
15828: 	$outcome .= &mt('Setting first resource').': ';
15829: 
15830: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15831:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15832: 
15833:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15834:         my $title; my $url;
15835:         if ($args->{'firstres'} eq 'syl') {
15836: 	    $title=&mt('Syllabus');
15837:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15838:         } else {
15839:             $title=&mt('Table of Contents');
15840:             $url='/adm/navmaps';
15841:         }
15842: 
15843:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15844: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15845: 
15846: 	if ($errtext) { $fatal=2; }
15847:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15848:     }
15849: 
15850: # 
15851: # Set params for Placement Tests
15852: #
15853:     if ($args->{'crstype'} eq 'Placement') {
15854:        my %storecontent; 
15855:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
15856:        my %defaults = (
15857:                         buttonshide   => { value => 'yes',
15858:                                            type => 'string_yesno',},
15859:                         type          => { value => 'randomizetry',
15860:                                            type  => 'string_questiontype',},
15861:                         maxtries      => { value => 1,
15862:                                            type => 'int_pos',},
15863:                         problemstatus => { value => 'no',
15864:                                            type  => 'string_problemstatus',},
15865:                       );
15866:        foreach my $key (keys(%defaults)) {
15867:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
15868:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
15869:        }
15870:        &Apache::lonnet::cput
15871:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
15872:     }
15873: 
15874:     return (1,$outcome);
15875: }
15876: 
15877: sub make_unique_code {
15878:     my ($cdom,$cnum) = @_;
15879:     # get lock on uniquecodes db
15880:     my $lockhash = {
15881:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15882:                                                   ':'.$env{'user.domain'},
15883:                    };
15884:     my $tries = 0;
15885:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15886:     my ($code,$error);
15887:   
15888:     while (($gotlock ne 'ok') && ($tries<3)) {
15889:         $tries ++;
15890:         sleep 1;
15891:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15892:     }
15893:     if ($gotlock eq 'ok') {
15894:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15895:         my $gotcode;
15896:         my $attempts = 0;
15897:         while ((!$gotcode) && ($attempts < 100)) {
15898:             $code = &generate_code();
15899:             if (!exists($currcodes{$code})) {
15900:                 $gotcode = 1;
15901:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15902:                     $error = 'nostore';
15903:                 }
15904:             }
15905:             $attempts ++;
15906:         }
15907:         my @del_lock = ($cnum."\0".'uniquecodes');
15908:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15909:     } else {
15910:         $error = 'nolock';
15911:     }
15912:     return ($code,$error);
15913: }
15914: 
15915: sub generate_code {
15916:     my $code;
15917:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15918:     for (my $i=0; $i<6; $i++) {
15919:         my $lettnum = int (rand 2);
15920:         my $item = '';
15921:         if ($lettnum) {
15922:             $item = $letts[int( rand(18) )];
15923:         } else {
15924:             $item = 1+int( rand(8) );
15925:         }
15926:         $code .= $item;
15927:     }
15928:     return $code;
15929: }
15930: 
15931: ############################################################
15932: ############################################################
15933: 
15934: # Community, Course and Placement Test
15935: sub course_type {
15936:     my ($cid) = @_;
15937:     if (!defined($cid)) {
15938:         $cid = $env{'request.course.id'};
15939:     }
15940:     if (defined($env{'course.'.$cid.'.type'})) {
15941:         return $env{'course.'.$cid.'.type'};
15942:     } else {
15943:         return 'Course';
15944:     }
15945: }
15946: 
15947: sub group_term {
15948:     my $crstype = &course_type();
15949:     my %names = (
15950:                   'Course' => 'group',
15951:                   'Community' => 'group',
15952:                   'Placement' => 'group',
15953:                 );
15954:     return $names{$crstype};
15955: }
15956: 
15957: sub course_types {
15958:     my @types = ('official','unofficial','community','textbook','placement');
15959:     my %typename = (
15960:                          official   => 'Official course',
15961:                          unofficial => 'Unofficial course',
15962:                          community  => 'Community',
15963:                          textbook   => 'Textbook course',
15964:                          placement  => 'Placement test',
15965:                    );
15966:     return (\@types,\%typename);
15967: }
15968: 
15969: sub icon {
15970:     my ($file)=@_;
15971:     my $curfext = lc((split(/\./,$file))[-1]);
15972:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15973:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15974:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15975: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15976: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15977: 	            $curfext.".gif") {
15978: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15979: 		$curfext.".gif";
15980: 	}
15981:     }
15982:     return &lonhttpdurl($iconname);
15983: } 
15984: 
15985: sub lonhttpdurl {
15986: #
15987: # Had been used for "small fry" static images on separate port 8080.
15988: # Modify here if lightweight http functionality desired again.
15989: # Currently eliminated due to increasing firewall issues.
15990: #
15991:     my ($url)=@_;
15992:     return $url;
15993: }
15994: 
15995: sub connection_aborted {
15996:     my ($r)=@_;
15997:     $r->print(" ");$r->rflush();
15998:     my $c = $r->connection;
15999:     return $c->aborted();
16000: }
16001: 
16002: #    Escapes strings that may have embedded 's that will be put into
16003: #    strings as 'strings'.
16004: sub escape_single {
16005:     my ($input) = @_;
16006:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16007:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16008:     return $input;
16009: }
16010: 
16011: #  Same as escape_single, but escape's "'s  This 
16012: #  can be used for  "strings"
16013: sub escape_double {
16014:     my ($input) = @_;
16015:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16016:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16017:     return $input;
16018: }
16019:  
16020: #   Escapes the last element of a full URL.
16021: sub escape_url {
16022:     my ($url)   = @_;
16023:     my @urlslices = split(/\//, $url,-1);
16024:     my $lastitem = &escape(pop(@urlslices));
16025:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16026: }
16027: 
16028: sub compare_arrays {
16029:     my ($arrayref1,$arrayref2) = @_;
16030:     my (@difference,%count);
16031:     @difference = ();
16032:     %count = ();
16033:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16034:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16035:         foreach my $element (keys(%count)) {
16036:             if ($count{$element} == 1) {
16037:                 push(@difference,$element);
16038:             }
16039:         }
16040:     }
16041:     return @difference;
16042: }
16043: 
16044: # -------------------------------------------------------- Initialize user login
16045: sub init_user_environment {
16046:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16047:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16048: 
16049:     my $public=($username eq 'public' && $domain eq 'public');
16050: 
16051:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16052:     my $now=time;
16053: 
16054:     if ($public) {
16055: 	my $max_public=100;
16056: 	my $oldest;
16057: 	my $oldest_time=0;
16058: 	for(my $next=1;$next<=$max_public;$next++) {
16059: 	    if (-e $lonids."/publicuser_$next.id") {
16060: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16061: 		if ($mtime<$oldest_time || !$oldest_time) {
16062: 		    $oldest_time=$mtime;
16063: 		    $oldest=$next;
16064: 		}
16065: 	    } else {
16066: 		$cookie="publicuser_$next";
16067: 		last;
16068: 	    }
16069: 	}
16070: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16071:     } else {
16072: 	# See if old ID present, if so, remove if this isn't a robot,
16073: 	# killing any existing non-robot sessions
16074: 	if (!$args->{'robot'}) {
16075: 	    opendir(DIR,$lonids);
16076: 	    while ($filename=readdir(DIR)) {
16077: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16078: 		    unlink($lonids.'/'.$filename);
16079: 		}
16080: 	    }
16081: 	    closedir(DIR);
16082: # If there is a undeleted lockfile for the user's paste buffer remove it.
16083:             my $namespace = 'nohist_courseeditor';
16084:             my $lockingkey = 'paste'."\0".'locked_num';
16085:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16086:                                                 $domain,$username);
16087:             if (exists($lockhash{$lockingkey})) {
16088:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16089:                 unless ($delresult eq 'ok') {
16090:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16091:                 }
16092:             }
16093: 	}
16094: # Give them a new cookie
16095: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16096: 		                   : $now.$$.int(rand(10000)));
16097: 	$cookie="$username\_$id\_$domain\_$authhost";
16098:     
16099: # Initialize roles
16100: 
16101: 	($userroles,$firstaccenv,$timerintenv) = 
16102:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16103:     }
16104: # ------------------------------------ Check browser type and MathML capability
16105: 
16106:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16107:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16108: 
16109: # ------------------------------------------------------------- Get environment
16110: 
16111:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16112:     my ($tmp) = keys(%userenv);
16113:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16114: 	undef(%userenv);
16115:     }
16116:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16117: 	$form->{'interface'}=$userenv{'interface'};
16118:     }
16119:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16120: 
16121: # --------------- Do not trust query string to be put directly into environment
16122:     foreach my $option ('interface','localpath','localres') {
16123:         $form->{$option}=~s/[\n\r\=]//gs;
16124:     }
16125: # --------------------------------------------------------- Write first profile
16126: 
16127:     {
16128: 	my %initial_env = 
16129: 	    ("user.name"          => $username,
16130: 	     "user.domain"        => $domain,
16131: 	     "user.home"          => $authhost,
16132: 	     "browser.type"       => $clientbrowser,
16133: 	     "browser.version"    => $clientversion,
16134: 	     "browser.mathml"     => $clientmathml,
16135: 	     "browser.unicode"    => $clientunicode,
16136: 	     "browser.os"         => $clientos,
16137:              "browser.mobile"     => $clientmobile,
16138:              "browser.info"       => $clientinfo,
16139:              "browser.osversion"  => $clientosversion,
16140: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16141: 	     "request.course.fn"  => '',
16142: 	     "request.course.uri" => '',
16143: 	     "request.course.sec" => '',
16144: 	     "request.role"       => 'cm',
16145: 	     "request.role.adv"   => $env{'user.adv'},
16146: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
16147: 
16148:         if ($form->{'localpath'}) {
16149: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16150: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16151:         }
16152: 	
16153: 	if ($form->{'interface'}) {
16154: 	    $form->{'interface'}=~s/\W//gs;
16155: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16156: 	    $env{'browser.interface'}=$form->{'interface'};
16157: 	}
16158: 
16159:         if ($form->{'iptoken'}) {
16160:             my $lonhost = $r->dir_config('lonHostID');
16161:             $initial_env{"user.noloadbalance"} = $lonhost;
16162:             $env{'user.noloadbalance'} = $lonhost;
16163:         }
16164: 
16165:         if ($form->{'noloadbalance'}) {
16166:             my @hosts = &Apache::lonnet::current_machine_ids();
16167:             my $hosthere = $form->{'noloadbalance'};
16168:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16169:                 $initial_env{"user.noloadbalance"} = $hosthere;
16170:                 $env{'user.noloadbalance'} = $hosthere;
16171:             }
16172:         }
16173: 
16174:         unless ($domain eq 'public') {
16175:             my %is_adv = ( is_adv => $env{'user.adv'} );
16176:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16177: 
16178:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
16179:                 $userenv{'availabletools.'.$tool} = 
16180:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16181:                                                       undef,\%userenv,\%domdef,\%is_adv);
16182:             }
16183: 
16184:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
16185:                 $userenv{'canrequest.'.$crstype} =
16186:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16187:                                                       'reload','requestcourses',
16188:                                                       \%userenv,\%domdef,\%is_adv);
16189:             }
16190: 
16191:             $userenv{'canrequest.author'} =
16192:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16193:                                                   'reload','requestauthor',
16194:                                                   \%userenv,\%domdef,\%is_adv);
16195:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16196:                                                  $domain,$username);
16197:             my $reqstatus = $reqauthor{'author_status'};
16198:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
16199:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16200:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16201:                                                       $reqauthor{'author'}{'timestamp'};
16202:                 }
16203:             }
16204:         }
16205: 
16206: 	$env{'user.environment'} = "$lonids/$cookie.id";
16207: 
16208: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16209: 		 &GDBM_WRCREAT(),0640)) {
16210: 	    &_add_to_env(\%disk_env,\%initial_env);
16211: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16212: 	    &_add_to_env(\%disk_env,$userroles);
16213:             if (ref($firstaccenv) eq 'HASH') {
16214:                 &_add_to_env(\%disk_env,$firstaccenv);
16215:             }
16216:             if (ref($timerintenv) eq 'HASH') {
16217:                 &_add_to_env(\%disk_env,$timerintenv);
16218:             }
16219: 	    if (ref($args->{'extra_env'})) {
16220: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16221: 	    }
16222: 	    untie(%disk_env);
16223: 	} else {
16224: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16225: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16226: 	    return 'error: '.$!;
16227: 	}
16228:     }
16229:     $env{'request.role'}='cm';
16230:     $env{'request.role.adv'}=$env{'user.adv'};
16231:     $env{'browser.type'}=$clientbrowser;
16232: 
16233:     return $cookie;
16234: 
16235: }
16236: 
16237: sub _add_to_env {
16238:     my ($idf,$env_data,$prefix) = @_;
16239:     if (ref($env_data) eq 'HASH') {
16240:         while (my ($key,$value) = each(%$env_data)) {
16241: 	    $idf->{$prefix.$key} = $value;
16242: 	    $env{$prefix.$key}   = $value;
16243:         }
16244:     }
16245: }
16246: 
16247: # --- Get the symbolic name of a problem and the url
16248: sub get_symb {
16249:     my ($request,$silent) = @_;
16250:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16251:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16252:     if ($symb eq '') {
16253:         if (!$silent) {
16254:             if (ref($request)) { 
16255:                 $request->print("Unable to handle ambiguous references:$url:.");
16256:             }
16257:             return ();
16258:         }
16259:     }
16260:     &Apache::lonenc::check_decrypt(\$symb);
16261:     return ($symb);
16262: }
16263: 
16264: # --------------------------------------------------------------Get annotation
16265: 
16266: sub get_annotation {
16267:     my ($symb,$enc) = @_;
16268: 
16269:     my $key = $symb;
16270:     if (!$enc) {
16271:         $key =
16272:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16273:     }
16274:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16275:     return $annotation{$key};
16276: }
16277: 
16278: sub clean_symb {
16279:     my ($symb,$delete_enc) = @_;
16280: 
16281:     &Apache::lonenc::check_decrypt(\$symb);
16282:     my $enc = $env{'request.enc'};
16283:     if ($delete_enc) {
16284:         delete($env{'request.enc'});
16285:     }
16286: 
16287:     return ($symb,$enc);
16288: }
16289: 
16290: ############################################################
16291: ############################################################
16292: 
16293: =pod
16294: 
16295: =head1 Routines for building display used to search for courses
16296: 
16297: 
16298: =over 4
16299: 
16300: =item * &build_filters()
16301: 
16302: Create markup for a table used to set filters to use when selecting
16303: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16304: and quotacheck.pl
16305: 
16306: 
16307: Inputs:
16308: 
16309: filterlist - anonymous array of fields to include as potential filters 
16310: 
16311: crstype - course type
16312: 
16313: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16314:               to pop-open a course selector (will contain "extra element"). 
16315: 
16316: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16317: 
16318: filter - anonymous hash of criteria and their values
16319: 
16320: action - form action
16321: 
16322: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16323: 
16324: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16325: 
16326: cloneruname - username of owner of new course who wants to clone
16327: 
16328: clonerudom - domain of owner of new course who wants to clone
16329: 
16330: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16331: 
16332: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16333: 
16334: codedom - domain
16335: 
16336: formname - value of form element named "form". 
16337: 
16338: fixeddom - domain, if fixed.
16339: 
16340: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16341: 
16342: cnameelement - name of form element in form on opener page which will receive title of selected course 
16343: 
16344: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16345: 
16346: cdomelement - name of form element in form on opener page which will receive domain of selected course
16347: 
16348: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16349: 
16350: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16351: 
16352: clonewarning - warning message about missing information for intended course owner when DC creates a course
16353: 
16354: 
16355: Returns: $output - HTML for display of search criteria, and hidden form elements.
16356: 
16357: 
16358: Side Effects: None
16359: 
16360: =cut
16361: 
16362: # ---------------------------------------------- search for courses based on last activity etc.
16363: 
16364: sub build_filters {
16365:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16366:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16367:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16368:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16369:         $clonetext,$clonewarning) = @_;
16370:     my ($list,$jscript);
16371:     my $onchange = 'javascript:updateFilters(this)';
16372:     my ($domainselectform,$sincefilterform,$createdfilterform,
16373:         $ownerdomselectform,$persondomselectform,$instcodeform,
16374:         $typeselectform,$instcodetitle);
16375:     if ($formname eq '') {
16376:         $formname = $caller;
16377:     }
16378:     foreach my $item (@{$filterlist}) {
16379:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16380:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16381:             if ($item eq 'domainfilter') {
16382:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16383:             } elsif ($item eq 'coursefilter') {
16384:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16385:             } elsif ($item eq 'ownerfilter') {
16386:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16387:             } elsif ($item eq 'ownerdomfilter') {
16388:                 $filter->{'ownerdomfilter'} =
16389:                     &LONCAPA::clean_domain($filter->{$item});
16390:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16391:                                                        'ownerdomfilter',1);
16392:             } elsif ($item eq 'personfilter') {
16393:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16394:             } elsif ($item eq 'persondomfilter') {
16395:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16396:                                                         'persondomfilter',1);
16397:             } else {
16398:                 $filter->{$item} =~ s/\W//g;
16399:             }
16400:             if (!$filter->{$item}) {
16401:                 $filter->{$item} = '';
16402:             }
16403:         }
16404:         if ($item eq 'domainfilter') {
16405:             my $allow_blank = 1;
16406:             if ($formname eq 'portform') {
16407:                 $allow_blank=0;
16408:             } elsif ($formname eq 'studentform') {
16409:                 $allow_blank=0;
16410:             }
16411:             if ($fixeddom) {
16412:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16413:                                     ' value="'.$codedom.'" />'.
16414:                                     &Apache::lonnet::domain($codedom,'description');
16415:             } else {
16416:                 $domainselectform = &select_dom_form($filter->{$item},
16417:                                                      'domainfilter',
16418:                                                       $allow_blank,'',$onchange);
16419:             }
16420:         } else {
16421:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16422:         }
16423:     }
16424: 
16425:     # last course activity filter and selection
16426:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16427: 
16428:     # course created filter and selection
16429:     if (exists($filter->{'createdfilter'})) {
16430:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16431:     }
16432: 
16433:     my $prefix = $crstype;
16434:     if ($crstype eq 'Placement') {
16435:         $prefix = 'Placement Test'
16436:     }
16437:     my %lt = &Apache::lonlocal::texthash(
16438:                 'cac' => "$prefix Activity",
16439:                 'ccr' => "$prefix Created",
16440:                 'cde' => "$prefix Title",
16441:                 'cdo' => "$prefix Domain",
16442:                 'ins' => 'Institutional Code',
16443:                 'inc' => 'Institutional Categorization',
16444:                 'cow' => "$prefix Owner/Co-owner",
16445:                 'cop' => "$prefix Personnel Includes",
16446:                 'cog' => 'Type',
16447:              );
16448: 
16449:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16450:         my $typeval = 'Course';
16451:         if ($crstype eq 'Community') {
16452:             $typeval = 'Community';
16453:         } elsif ($crstype eq 'Placement') {
16454:             $typeval = 'Placement';
16455:         }
16456:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16457:     } else {
16458:         $typeselectform =  '<select name="type" size="1"';
16459:         if ($onchange) {
16460:             $typeselectform .= ' onchange="'.$onchange.'"';
16461:         }
16462:         $typeselectform .= '>'."\n";
16463:         foreach my $posstype ('Course','Community','Placement') {
16464:             my $shown;
16465:             if ($posstype eq 'Placement') {
16466:                 $shown = &mt('Placement Test');
16467:             } else {
16468:                 $shown = &mt($posstype);
16469:             }
16470:             $typeselectform.='<option value="'.$posstype.'"'.
16471:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16472:         }
16473:         $typeselectform.="</select>";
16474:     }
16475: 
16476:     my ($cloneableonlyform,$cloneabletitle);
16477:     if (exists($filter->{'cloneableonly'})) {
16478:         my $cloneableon = '';
16479:         my $cloneableoff = ' checked="checked"';
16480:         if ($filter->{'cloneableonly'}) {
16481:             $cloneableon = $cloneableoff;
16482:             $cloneableoff = '';
16483:         }
16484:         $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>';
16485:         if ($formname eq 'ccrs') {
16486:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16487:         } else {
16488:             $cloneabletitle = &mt('Cloneable by you');
16489:         }
16490:     }
16491:     my $officialjs;
16492:     if ($crstype eq 'Course') {
16493:         if (exists($filter->{'instcodefilter'})) {
16494: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16495: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16496:             if ($codedom) { 
16497:                 $officialjs = 1;
16498:                 ($instcodeform,$jscript,$$numtitlesref) =
16499:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16500:                                                                   $officialjs,$codetitlesref);
16501:                 if ($jscript) {
16502:                     $jscript = '<script type="text/javascript">'."\n".
16503:                                '// <![CDATA['."\n".
16504:                                $jscript."\n".
16505:                                '// ]]>'."\n".
16506:                                '</script>'."\n";
16507:                 }
16508:             }
16509:             if ($instcodeform eq '') {
16510:                 $instcodeform =
16511:                     '<input type="text" name="instcodefilter" size="10" value="'.
16512:                     $list->{'instcodefilter'}.'" />';
16513:                 $instcodetitle = $lt{'ins'};
16514:             } else {
16515:                 $instcodetitle = $lt{'inc'};
16516:             }
16517:             if ($fixeddom) {
16518:                 $instcodetitle .= '<br />('.$codedom.')';
16519:             }
16520:         }
16521:     }
16522:     my $output = qq|
16523: <form method="post" name="filterpicker" action="$action">
16524: <input type="hidden" name="form" value="$formname" />
16525: |;
16526:     if ($formname eq 'modifycourse') {
16527:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16528:                    '<input type="hidden" name="prevphase" value="'.
16529:                    $prevphase.'" />'."\n";
16530:     } elsif ($formname eq 'quotacheck') {
16531:         $output .= qq|
16532: <input type="hidden" name="sortby" value="" />
16533: <input type="hidden" name="sortorder" value="" />
16534: |;
16535:     } else {
16536:         my $name_input;
16537:         if ($cnameelement ne '') {
16538:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16539:                           $cnameelement.'" />';
16540:         }
16541:         $output .= qq|
16542: <input type="hidden" name="cnumelement" value="$cnumelement" />
16543: <input type="hidden" name="cdomelement" value="$cdomelement" />
16544: $name_input
16545: $roleelement
16546: $multelement
16547: $typeelement
16548: |;
16549:         if ($formname eq 'portform') {
16550:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16551:         }
16552:     }
16553:     if ($fixeddom) {
16554:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16555:     }
16556:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16557:     if ($sincefilterform) {
16558:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16559:                   .$sincefilterform
16560:                   .&Apache::lonhtmlcommon::row_closure();
16561:     }
16562:     if ($createdfilterform) {
16563:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16564:                   .$createdfilterform
16565:                   .&Apache::lonhtmlcommon::row_closure();
16566:     }
16567:     if ($domainselectform) {
16568:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16569:                   .$domainselectform
16570:                   .&Apache::lonhtmlcommon::row_closure();
16571:     }
16572:     if ($typeselectform) {
16573:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16574:             $output .= $typeselectform;
16575:         } else {
16576:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16577:                       .$typeselectform
16578:                       .&Apache::lonhtmlcommon::row_closure();
16579:         }
16580:     }
16581:     if ($instcodeform) {
16582:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16583:                   .$instcodeform
16584:                   .&Apache::lonhtmlcommon::row_closure();
16585:     }
16586:     if (exists($filter->{'ownerfilter'})) {
16587:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16588:                    '<table><tr><td>'.&mt('Username').'<br />'.
16589:                    '<input type="text" name="ownerfilter" size="20" value="'.
16590:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16591:                    $ownerdomselectform.'</td></tr></table>'.
16592:                    &Apache::lonhtmlcommon::row_closure();
16593:     }
16594:     if (exists($filter->{'personfilter'})) {
16595:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16596:                    '<table><tr><td>'.&mt('Username').'<br />'.
16597:                    '<input type="text" name="personfilter" size="20" value="'.
16598:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16599:                    $persondomselectform.'</td></tr></table>'.
16600:                    &Apache::lonhtmlcommon::row_closure();
16601:     }
16602:     if (exists($filter->{'coursefilter'})) {
16603:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16604:                   .'<input type="text" name="coursefilter" size="25" value="'
16605:                   .$list->{'coursefilter'}.'" />'
16606:                   .&Apache::lonhtmlcommon::row_closure();
16607:     }
16608:     if ($cloneableonlyform) {
16609:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16610:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16611:     }
16612:     if (exists($filter->{'descriptfilter'})) {
16613:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16614:                   .'<input type="text" name="descriptfilter" size="40" value="'
16615:                   .$list->{'descriptfilter'}.'" />'
16616:                   .&Apache::lonhtmlcommon::row_closure(1);
16617:     }
16618:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16619:                '<input type="hidden" name="updater" value="" />'."\n".
16620:                '<input type="submit" name="gosearch" value="'.
16621:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16622:     return $jscript.$clonewarning.$output;
16623: }
16624: 
16625: =pod 
16626: 
16627: =item * &timebased_select_form()
16628: 
16629: Create markup for a dropdown list used to select a time-based
16630: filter e.g., Course Activity, Course Created, when searching for courses
16631: or communities
16632: 
16633: Inputs:
16634: 
16635: item - name of form element (sincefilter or createdfilter)
16636: 
16637: filter - anonymous hash of criteria and their values
16638: 
16639: Returns: HTML for a select box contained a blank, then six time selections,
16640:          with value set in incoming form variables currently selected. 
16641: 
16642: Side Effects: None
16643: 
16644: =cut
16645: 
16646: sub timebased_select_form {
16647:     my ($item,$filter) = @_;
16648:     if (ref($filter) eq 'HASH') {
16649:         $filter->{$item} =~ s/[^\d-]//g;
16650:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16651:         return &select_form(
16652:                             $filter->{$item},
16653:                             $item,
16654:                             {      '-1' => '',
16655:                                 '86400' => &mt('today'),
16656:                                '604800' => &mt('last week'),
16657:                               '2592000' => &mt('last month'),
16658:                               '7776000' => &mt('last three months'),
16659:                              '15552000' => &mt('last six months'),
16660:                              '31104000' => &mt('last year'),
16661:                     'select_form_order' =>
16662:                            ['-1','86400','604800','2592000','7776000',
16663:                             '15552000','31104000']});
16664:     }
16665: }
16666: 
16667: =pod
16668: 
16669: =item * &js_changer()
16670: 
16671: Create script tag containing Javascript used to submit course search form
16672: when course type or domain is changed, and also to hide 'Searching ...' on
16673: page load completion for page showing search result.
16674: 
16675: Inputs: None
16676: 
16677: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
16678: 
16679: Side Effects: None
16680: 
16681: =cut
16682: 
16683: sub js_changer {
16684:     return <<ENDJS;
16685: <script type="text/javascript">
16686: // <![CDATA[
16687: function updateFilters(caller) {
16688:     if (typeof(caller) != "undefined") {
16689:         document.filterpicker.updater.value = caller.name;
16690:     }
16691:     document.filterpicker.submit();
16692: }
16693: 
16694: function hideSearching() {
16695:     if (document.getElementById('searching')) {
16696:         document.getElementById('searching').style.display = 'none';
16697:     }
16698:     return;
16699: }
16700: 
16701: // ]]>
16702: </script>
16703: 
16704: ENDJS
16705: }
16706: 
16707: =pod
16708: 
16709: =item * &search_courses()
16710: 
16711: Process selected filters form course search form and pass to lonnet::courseiddump
16712: to retrieve a hash for which keys are courseIDs which match the selected filters.
16713: 
16714: Inputs:
16715: 
16716: dom - domain being searched 
16717: 
16718: type - course type ('Course' or 'Community' or '.' if any).
16719: 
16720: filter - anonymous hash of criteria and their values
16721: 
16722: numtitles - for institutional codes - number of categories
16723: 
16724: cloneruname - optional username of new course owner
16725: 
16726: clonerudom - optional domain of new course owner
16727: 
16728: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16729:             (used when DC is using course creation form)
16730: 
16731: codetitles - reference to array of titles of components in institutional codes (official courses).
16732: 
16733: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16734:            (and so can clone automatically)
16735: 
16736: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16737: 
16738: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16739:               courses to clone 
16740: 
16741: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16742: 
16743: 
16744: Side Effects: None
16745: 
16746: =cut
16747: 
16748: 
16749: sub search_courses {
16750:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16751:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16752:     my (%courses,%showcourses,$cloner);
16753:     if (($filter->{'ownerfilter'} ne '') ||
16754:         ($filter->{'ownerdomfilter'} ne '')) {
16755:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16756:                                        $filter->{'ownerdomfilter'};
16757:     }
16758:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16759:         if (!$filter->{$item}) {
16760:             $filter->{$item}='.';
16761:         }
16762:     }
16763:     my $now = time;
16764:     my $timefilter =
16765:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16766:     my ($createdbefore,$createdafter);
16767:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16768:         $createdbefore = $now;
16769:         $createdafter = $now-$filter->{'createdfilter'};
16770:     }
16771:     my ($instcodefilter,$regexpok);
16772:     if ($numtitles) {
16773:         if ($env{'form.official'} eq 'on') {
16774:             $instcodefilter =
16775:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16776:             $regexpok = 1;
16777:         } elsif ($env{'form.official'} eq 'off') {
16778:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16779:             unless ($instcodefilter eq '') {
16780:                 $regexpok = -1;
16781:             }
16782:         }
16783:     } else {
16784:         $instcodefilter = $filter->{'instcodefilter'};
16785:     }
16786:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16787:     if ($type eq '') { $type = '.'; }
16788: 
16789:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16790:         $cloner = $cloneruname.':'.$clonerudom;
16791:     }
16792:     %courses = &Apache::lonnet::courseiddump($dom,
16793:                                              $filter->{'descriptfilter'},
16794:                                              $timefilter,
16795:                                              $instcodefilter,
16796:                                              $filter->{'combownerfilter'},
16797:                                              $filter->{'coursefilter'},
16798:                                              undef,undef,$type,$regexpok,undef,undef,
16799:                                              undef,undef,$cloner,$cc_clone,
16800:                                              $filter->{'cloneableonly'},
16801:                                              $createdbefore,$createdafter,undef,
16802:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16803:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16804:         my $ccrole;
16805:         if ($type eq 'Community') {
16806:             $ccrole = 'co';
16807:         } else {
16808:             $ccrole = 'cc';
16809:         }
16810:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16811:                                                      $filter->{'persondomfilter'},
16812:                                                      'userroles',undef,
16813:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16814:                                                      $dom);
16815:         foreach my $role (keys(%rolehash)) {
16816:             my ($cnum,$cdom,$courserole) = split(':',$role);
16817:             my $cid = $cdom.'_'.$cnum;
16818:             if (exists($courses{$cid})) {
16819:                 if (ref($courses{$cid}) eq 'HASH') {
16820:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16821:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16822:                             push(@{$courses{$cid}{roles}},$courserole);
16823:                         }
16824:                     } else {
16825:                         $courses{$cid}{roles} = [$courserole];
16826:                     }
16827:                     $showcourses{$cid} = $courses{$cid};
16828:                 }
16829:             }
16830:         }
16831:         %courses = %showcourses;
16832:     }
16833:     return %courses;
16834: }
16835: 
16836: =pod
16837: 
16838: =back
16839: 
16840: =head1 Routines for version requirements for current course.
16841: 
16842: =over 4
16843: 
16844: =item * &check_release_required()
16845: 
16846: Compares required LON-CAPA version with version on server, and
16847: if required version is newer looks for a server with the required version.
16848: 
16849: Looks first at servers in user's owen domain; if none suitable, looks at
16850: servers in course's domain are permitted to host sessions for user's domain.
16851: 
16852: Inputs:
16853: 
16854: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16855: 
16856: $courseid - Course ID of current course
16857: 
16858: $rolecode - User's current role in course (for switchserver query string).
16859: 
16860: $required - LON-CAPA version needed by course (format: Major.Minor).
16861: 
16862: 
16863: Returns:
16864: 
16865: $switchserver - query string tp append to /adm/switchserver call (if 
16866:                 current server's LON-CAPA version is too old. 
16867: 
16868: $warning - Message is displayed if no suitable server could be found.
16869: 
16870: =cut
16871: 
16872: sub check_release_required {
16873:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16874:     my ($switchserver,$warning);
16875:     if ($required ne '') {
16876:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16877:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16878:         if ($reqdmajor ne '' && $reqdminor ne '') {
16879:             my $otherserver;
16880:             if (($major eq '' && $minor eq '') ||
16881:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16882:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16883:                 my $switchlcrev =
16884:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16885:                                                            $userdomserver);
16886:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16887:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16888:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16889:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16890:                     if ($cdom ne $env{'user.domain'}) {
16891:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16892:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16893:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16894:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16895:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16896:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16897:                         my $canhost =
16898:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16899:                                                               $coursedomserver,
16900:                                                               $remoterev,
16901:                                                               $udomdefaults{'remotesessions'},
16902:                                                               $defdomdefaults{'hostedsessions'});
16903: 
16904:                         if ($canhost) {
16905:                             $otherserver = $coursedomserver;
16906:                         } else {
16907:                             $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.");
16908:                         }
16909:                     } else {
16910:                         $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).");
16911:                     }
16912:                 } else {
16913:                     $otherserver = $userdomserver;
16914:                 }
16915:             }
16916:             if ($otherserver ne '') {
16917:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16918:             }
16919:         }
16920:     }
16921:     return ($switchserver,$warning);
16922: }
16923: 
16924: =pod
16925: 
16926: =item * &check_release_result()
16927: 
16928: Inputs:
16929: 
16930: $switchwarning - Warning message if no suitable server found to host session.
16931: 
16932: $switchserver - query string to append to /adm/switchserver containing lonHostID
16933:                 and current role.
16934: 
16935: Returns: HTML to display with information about requirement to switch server.
16936:          Either displaying warning with link to Roles/Courses screen or
16937:          display link to switchserver.
16938: 
16939: =cut
16940: 
16941: sub check_release_result {
16942:     my ($switchwarning,$switchserver) = @_;
16943:     my $output = &start_page('Selected course unavailable on this server').
16944:                  '<p class="LC_warning">';
16945:     if ($switchwarning) {
16946:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16947:         if (&show_course()) {
16948:             $output .= &mt('Display courses');
16949:         } else {
16950:             $output .= &mt('Display roles');
16951:         }
16952:         $output .= '</a>';
16953:     } elsif ($switchserver) {
16954:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16955:                    '<br />'.
16956:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16957:                    &mt('Switch Server').
16958:                    '</a>';
16959:     }
16960:     $output .= '</p>'.&end_page();
16961:     return $output;
16962: }
16963: 
16964: =pod
16965: 
16966: =item * &needs_coursereinit()
16967: 
16968: Determine if course contents stored for user's session needs to be
16969: refreshed, because content has changed since "Big Hash" last tied.
16970: 
16971: Check for change is made if time last checked is more than 10 minutes ago
16972: (by default).
16973: 
16974: Inputs:
16975: 
16976: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16977: 
16978: $interval (optional) - Time which may elapse (in s) between last check for content
16979:                        change in current course. (default: 600 s).  
16980: 
16981: Returns: an array; first element is:
16982: 
16983: =over 4
16984: 
16985: 'switch' - if content updates mean user's session
16986:            needs to be switched to a server running a newer LON-CAPA version
16987:  
16988: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16989:            on current server hosting user's session                
16990: 
16991: ''       - if no action required.
16992: 
16993: =back
16994: 
16995: If first item element is 'switch':
16996: 
16997: second item is $switchwarning - Warning message if no suitable server found to host session. 
16998: 
16999: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17000:                               and current role. 
17001: 
17002: otherwise: no other elements returned.
17003: 
17004: =back
17005: 
17006: =cut
17007: 
17008: sub needs_coursereinit {
17009:     my ($loncaparev,$interval) = @_;
17010:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17011:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17012:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17013:     my $now = time;
17014:     if ($interval eq '') {
17015:         $interval = 600;
17016:     }
17017:     if (($now-$env{'request.course.timechecked'})>$interval) {
17018:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17019:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17020:         if ($blocked) {
17021:             return ();
17022:         }
17023:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17024:         if ($lastchange > $env{'request.course.tied'}) {
17025:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17026:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17027:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17028:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17029:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17030:                                              $curr_reqd_hash{'internal.releaserequired'}});
17031:                     my ($switchserver,$switchwarning) =
17032:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17033:                                                 $curr_reqd_hash{'internal.releaserequired'});
17034:                     if ($switchwarning ne '' || $switchserver ne '') {
17035:                         return ('switch',$switchwarning,$switchserver);
17036:                     }
17037:                 }
17038:             }
17039:             return ('update');
17040:         }
17041:     }
17042:     return ();
17043: }
17044: 
17045: sub update_content_constraints {
17046:     my ($cdom,$cnum,$chome,$cid) = @_;
17047:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17048:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17049:     my %checkresponsetypes;
17050:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17051:         my ($item,$name,$value) = split(/:/,$key);
17052:         if ($item eq 'resourcetag') {
17053:             if ($name eq 'responsetype') {
17054:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17055:             }
17056:         }
17057:     }
17058:     my $navmap = Apache::lonnavmaps::navmap->new();
17059:     if (defined($navmap)) {
17060:         my %allresponses;
17061:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17062:             my %responses = $res->responseTypes();
17063:             foreach my $key (keys(%responses)) {
17064:                 next unless(exists($checkresponsetypes{$key}));
17065:                 $allresponses{$key} += $responses{$key};
17066:             }
17067:         }
17068:         foreach my $key (keys(%allresponses)) {
17069:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17070:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17071:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17072:             }
17073:         }
17074:         undef($navmap);
17075:     }
17076:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17077:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17078:     }
17079:     return;
17080: }
17081: 
17082: sub allmaps_incourse {
17083:     my ($cdom,$cnum,$chome,$cid) = @_;
17084:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17085:         $cid = $env{'request.course.id'};
17086:         $cdom = $env{'course.'.$cid.'.domain'};
17087:         $cnum = $env{'course.'.$cid.'.num'};
17088:         $chome = $env{'course.'.$cid.'.home'};
17089:     }
17090:     my %allmaps = ();
17091:     my $lastchange =
17092:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17093:     if ($lastchange > $env{'request.course.tied'}) {
17094:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17095:         unless ($ferr) {
17096:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17097:         }
17098:     }
17099:     my $navmap = Apache::lonnavmaps::navmap->new();
17100:     if (defined($navmap)) {
17101:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17102:             $allmaps{$res->src()} = 1;
17103:         }
17104:     }
17105:     return \%allmaps;
17106: }
17107: 
17108: sub parse_supplemental_title {
17109:     my ($title) = @_;
17110: 
17111:     my ($foldertitle,$renametitle);
17112:     if ($title =~ /&amp;&amp;&amp;/) {
17113:         $title = &HTML::Entites::decode($title);
17114:     }
17115:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17116:         $renametitle=$4;
17117:         my ($time,$uname,$udom) = ($1,$2,$3);
17118:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17119:         my $name =  &plainname($uname,$udom);
17120:         $name = &HTML::Entities::encode($name,'"<>&\'');
17121:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17122:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17123:             $name.': <br />'.$foldertitle;
17124:     }
17125:     if (wantarray) {
17126:         return ($title,$foldertitle,$renametitle);
17127:     }
17128:     return $title;
17129: }
17130: 
17131: sub recurse_supplemental {
17132:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17133:     if ($suppmap) {
17134:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17135:         if ($fatal) {
17136:             $errors ++;
17137:         } else {
17138:             if ($#LONCAPA::map::resources > 0) {
17139:                 foreach my $res (@LONCAPA::map::resources) {
17140:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17141:                     if (($src ne '') && ($status eq 'res')) {
17142:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17143:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17144:                         } else {
17145:                             $numfiles ++;
17146:                         }
17147:                     }
17148:                 }
17149:             }
17150:         }
17151:     }
17152:     return ($numfiles,$errors);
17153: }
17154: 
17155: sub symb_to_docspath {
17156:     my ($symb,$navmapref) = @_;
17157:     return unless ($symb && ref($navmapref));
17158:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17159:     if ($resurl=~/\.(sequence|page)$/) {
17160:         $mapurl=$resurl;
17161:     } elsif ($resurl eq 'adm/navmaps') {
17162:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17163:     }
17164:     my $mapresobj;
17165:     unless (ref($$navmapref)) {
17166:         $$navmapref = Apache::lonnavmaps::navmap->new();
17167:     }
17168:     if (ref($$navmapref)) {
17169:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17170:     }
17171:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17172:     my $type=$2;
17173:     my $path;
17174:     if (ref($mapresobj)) {
17175:         my $pcslist = $mapresobj->map_hierarchy();
17176:         if ($pcslist ne '') {
17177:             foreach my $pc (split(/,/,$pcslist)) {
17178:                 next if ($pc <= 1);
17179:                 my $res = $$navmapref->getByMapPc($pc);
17180:                 if (ref($res)) {
17181:                     my $thisurl = $res->src();
17182:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17183:                     my $thistitle = $res->title();
17184:                     $path .= '&'.
17185:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17186:                              &escape($thistitle).
17187:                              ':'.$res->randompick().
17188:                              ':'.$res->randomout().
17189:                              ':'.$res->encrypted().
17190:                              ':'.$res->randomorder().
17191:                              ':'.$res->is_page();
17192:                 }
17193:             }
17194:         }
17195:         $path =~ s/^\&//;
17196:         my $maptitle = $mapresobj->title();
17197:         if ($mapurl eq 'default') {
17198:             $maptitle = 'Main Content';
17199:         }
17200:         $path .= (($path ne '')? '&' : '').
17201:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17202:                  &escape($maptitle).
17203:                  ':'.$mapresobj->randompick().
17204:                  ':'.$mapresobj->randomout().
17205:                  ':'.$mapresobj->encrypted().
17206:                  ':'.$mapresobj->randomorder().
17207:                  ':'.$mapresobj->is_page();
17208:     } else {
17209:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17210:         my $ispage = (($type eq 'page')? 1 : '');
17211:         if ($mapurl eq 'default') {
17212:             $maptitle = 'Main Content';
17213:         }
17214:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17215:                 &escape($maptitle).':::::'.$ispage;
17216:     }
17217:     unless ($mapurl eq 'default') {
17218:         $path = 'default&'.
17219:                 &escape('Main Content').
17220:                 ':::::&'.$path;
17221:     }
17222:     return $path;
17223: }
17224: 
17225: sub captcha_display {
17226:     my ($context,$lonhost) = @_;
17227:     my ($output,$error);
17228:     my ($captcha,$pubkey,$privkey,$version) = 
17229:         &get_captcha_config($context,$lonhost);
17230:     if ($captcha eq 'original') {
17231:         $output = &create_captcha();
17232:         unless ($output) {
17233:             $error = 'captcha';
17234:         }
17235:     } elsif ($captcha eq 'recaptcha') {
17236:         $output = &create_recaptcha($pubkey,$version);
17237:         unless ($output) {
17238:             $error = 'recaptcha';
17239:         }
17240:     }
17241:     return ($output,$error,$captcha,$version);
17242: }
17243: 
17244: sub captcha_response {
17245:     my ($context,$lonhost) = @_;
17246:     my ($captcha_chk,$captcha_error);
17247:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
17248:     if ($captcha eq 'original') {
17249:         ($captcha_chk,$captcha_error) = &check_captcha();
17250:     } elsif ($captcha eq 'recaptcha') {
17251:         $captcha_chk = &check_recaptcha($privkey,$version);
17252:     } else {
17253:         $captcha_chk = 1;
17254:     }
17255:     return ($captcha_chk,$captcha_error);
17256: }
17257: 
17258: sub get_captcha_config {
17259:     my ($context,$lonhost) = @_;
17260:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17261:     my $hostname = &Apache::lonnet::hostname($lonhost);
17262:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17263:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17264:     if ($context eq 'usercreation') {
17265:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17266:         if (ref($domconfig{$context}) eq 'HASH') {
17267:             $hashtocheck = $domconfig{$context}{'cancreate'};
17268:             if (ref($hashtocheck) eq 'HASH') {
17269:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17270:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17271:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17272:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17273:                     }
17274:                     if ($privkey && $pubkey) {
17275:                         $captcha = 'recaptcha';
17276:                         $version = $hashtocheck->{'recaptchaversion'};
17277:                         if ($version ne '2') {
17278:                             $version = 1;
17279:                         }
17280:                     } else {
17281:                         $captcha = 'original';
17282:                     }
17283:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17284:                     $captcha = 'original';
17285:                 }
17286:             }
17287:         } else {
17288:             $captcha = 'captcha';
17289:         }
17290:     } elsif ($context eq 'login') {
17291:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17292:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17293:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17294:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17295:             if ($privkey && $pubkey) {
17296:                 $captcha = 'recaptcha';
17297:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17298:                 if ($version ne '2') {
17299:                     $version = 1; 
17300:                 }
17301:             } else {
17302:                 $captcha = 'original';
17303:             }
17304:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17305:             $captcha = 'original';
17306:         }
17307:     }
17308:     return ($captcha,$pubkey,$privkey,$version);
17309: }
17310: 
17311: sub create_captcha {
17312:     my %captcha_params = &captcha_settings();
17313:     my ($output,$maxtries,$tries) = ('',10,0);
17314:     while ($tries < $maxtries) {
17315:         $tries ++;
17316:         my $captcha = Authen::Captcha->new (
17317:                                            output_folder => $captcha_params{'output_dir'},
17318:                                            data_folder   => $captcha_params{'db_dir'},
17319:                                           );
17320:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17321: 
17322:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17323:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17324:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17325:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17326:                       '<br />'.
17327:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17328:             last;
17329:         }
17330:     }
17331:     return $output;
17332: }
17333: 
17334: sub captcha_settings {
17335:     my %captcha_params = (
17336:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17337:                            www_output_dir => "/captchaspool",
17338:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17339:                            numchars       => '5',
17340:                          );
17341:     return %captcha_params;
17342: }
17343: 
17344: sub check_captcha {
17345:     my ($captcha_chk,$captcha_error);
17346:     my $code = $env{'form.code'};
17347:     my $md5sum = $env{'form.crypt'};
17348:     my %captcha_params = &captcha_settings();
17349:     my $captcha = Authen::Captcha->new(
17350:                       output_folder => $captcha_params{'output_dir'},
17351:                       data_folder   => $captcha_params{'db_dir'},
17352:                   );
17353:     $captcha_chk = $captcha->check_code($code,$md5sum);
17354:     my %captcha_hash = (
17355:                         0       => 'Code not checked (file error)',
17356:                        -1      => 'Failed: code expired',
17357:                        -2      => 'Failed: invalid code (not in database)',
17358:                        -3      => 'Failed: invalid code (code does not match crypt)',
17359:     );
17360:     if ($captcha_chk != 1) {
17361:         $captcha_error = $captcha_hash{$captcha_chk}
17362:     }
17363:     return ($captcha_chk,$captcha_error);
17364: }
17365: 
17366: sub create_recaptcha {
17367:     my ($pubkey,$version) = @_;
17368:     if ($version >= 2) {
17369:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17370:     } else {
17371:         my $use_ssl;
17372:         if ($ENV{'SERVER_PORT'} == 443) {
17373:             $use_ssl = 1;
17374:         }
17375:         my $captcha = Captcha::reCAPTCHA->new;
17376:         return $captcha->get_options_setter({theme => 'white'})."\n".
17377:                $captcha->get_html($pubkey,undef,$use_ssl).
17378:                &mt('If the text is hard to read, [_1] will replace them.',
17379:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17380:                '<br /><br />';
17381:     }
17382: }
17383: 
17384: sub check_recaptcha {
17385:     my ($privkey,$version) = @_;
17386:     my $captcha_chk;
17387:     if ($version >= 2) {
17388:         my %info = (
17389:                      secret   => $privkey, 
17390:                      response => $env{'form.g-recaptcha-response'},
17391:                      remoteip => $ENV{'REMOTE_ADDR'},
17392:                    );
17393:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
17394:         $request->content(join('&',map {
17395:                          my $name = escape($_);
17396:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
17397:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
17398:                          : &escape($info{$_}) );
17399:         } keys(%info)));
17400:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
17401:         if ($response->is_success)  {
17402:             my $data = JSON::DWIW->from_json($response->decoded_content);
17403:             if (ref($data) eq 'HASH') {
17404:                 if ($data->{'success'}) {
17405:                     $captcha_chk = 1;
17406:                 }
17407:             }
17408:         }
17409:     } else {
17410:         my $captcha = Captcha::reCAPTCHA->new;
17411:         my $captcha_result =
17412:             $captcha->check_answer(
17413:                                     $privkey,
17414:                                     $ENV{'REMOTE_ADDR'},
17415:                                     $env{'form.recaptcha_challenge_field'},
17416:                                     $env{'form.recaptcha_response_field'},
17417:                                   );
17418:         if ($captcha_result->{is_valid}) {
17419:             $captcha_chk = 1;
17420:         }
17421:     }
17422:     return $captcha_chk;
17423: }
17424: 
17425: sub emailusername_info {
17426:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17427:     my %titles = &Apache::lonlocal::texthash (
17428:                      lastname      => 'Last Name',
17429:                      firstname     => 'First Name',
17430:                      institution   => 'School/college/university',
17431:                      location      => "School's city, state/province, country",
17432:                      web           => "School's web address",
17433:                      officialemail => 'E-mail address at institution (if different)',
17434:                      id            => 'Student/Employee ID',
17435:                  );
17436:     return (\@fields,\%titles);
17437: }
17438: 
17439: sub cleanup_html {
17440:     my ($incoming) = @_;
17441:     my $outgoing;
17442:     if ($incoming ne '') {
17443:         $outgoing = $incoming;
17444:         $outgoing =~ s/;/&#059;/g;
17445:         $outgoing =~ s/\#/&#035;/g;
17446:         $outgoing =~ s/\&/&#038;/g;
17447:         $outgoing =~ s/</&#060;/g;
17448:         $outgoing =~ s/>/&#062;/g;
17449:         $outgoing =~ s/\(/&#040/g;
17450:         $outgoing =~ s/\)/&#041;/g;
17451:         $outgoing =~ s/"/&#034;/g;
17452:         $outgoing =~ s/'/&#039;/g;
17453:         $outgoing =~ s/\$/&#036;/g;
17454:         $outgoing =~ s{/}{&#047;}g;
17455:         $outgoing =~ s/=/&#061;/g;
17456:         $outgoing =~ s/\\/&#092;/g
17457:     }
17458:     return $outgoing;
17459: }
17460: 
17461: # Checks for critical messages and returns a redirect url if one exists.
17462: # $interval indicates how often to check for messages.
17463: # $context is the calling context -- roles, grades, contents, menu or flip. 
17464: sub critical_redirect {
17465:     my ($interval,$context) = @_;
17466:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17467:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17468:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17469:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17470:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
17471:             if ($blocked) {
17472:                 my $checkrole = "cm./$cdom/$cnum";
17473:                 if ($env{'request.course.sec'} ne '') {
17474:                     $checkrole .= "/$env{'request.course.sec'}";
17475:                 }
17476:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17477:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17478:                     return;
17479:                 }
17480:             }
17481:         }
17482:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
17483:                                         $env{'user.name'});
17484:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17485:         my $redirecturl;
17486:         if ($what[0]) {
17487: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17488: 	        $redirecturl='/adm/email?critical=display';
17489: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
17490:                 return (1, $url);
17491:             }
17492:         }
17493:     } 
17494:     return ();
17495: }
17496: 
17497: # Use:
17498: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17499: #
17500: ##################################################
17501: #          password associated functions         #
17502: ##################################################
17503: sub des_keys {
17504:     # Make a new key for DES encryption.
17505:     # Each key has two parts which are returned separately.
17506:     # Please note:  Each key must be passed through the &hex function
17507:     # before it is output to the web browser.  The hex versions cannot
17508:     # be used to decrypt.
17509:     my @hexstr=('0','1','2','3','4','5','6','7',
17510:                 '8','9','a','b','c','d','e','f');
17511:     my $lkey='';
17512:     for (0..7) {
17513:         $lkey.=$hexstr[rand(15)];
17514:     }
17515:     my $ukey='';
17516:     for (0..7) {
17517:         $ukey.=$hexstr[rand(15)];
17518:     }
17519:     return ($lkey,$ukey);
17520: }
17521: 
17522: sub des_decrypt {
17523:     my ($key,$cyphertext) = @_;
17524:     my $keybin=pack("H16",$key);
17525:     my $cypher;
17526:     if ($Crypt::DES::VERSION>=2.03) {
17527:         $cypher=new Crypt::DES $keybin;
17528:     } else {
17529:         $cypher=new DES $keybin;
17530:     }
17531:     my $plaintext='';
17532:     my $cypherlength = length($cyphertext);
17533:     my $numchunks = int($cypherlength/32);
17534:     for (my $j=0; $j<$numchunks; $j++) {
17535:         my $start = $j*32;
17536:         my $cypherblock = substr($cyphertext,$start,32);
17537:         my $chunk =
17538:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17539:         $chunk .=
17540:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17541:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17542:         $plaintext .= $chunk;
17543:     }
17544:     return $plaintext;
17545: }
17546: 
17547: 1;
17548: __END__;
17549: 

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