Annotation of loncom/interface/loncommon.pm, revision 1.1316

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1316  ! raeburn     4: # $Id: loncommon.pm,v 1.1315 2018/04/24 14:05:22 raeburn Exp $
1.10      albertel    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: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.657     raeburn    75: use DateTime::TimeZone;
1.1241    raeburn    76: use DateTime::Locale;
1.1220    raeburn    77: use Encode();
1.1091    foxr       78: use Text::Aspell;
1.1094    raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1234    raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
                    206:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
                    228:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
                    242:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
                    256:     if ( open (my $fh,"<$designfile") ) {
                    257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
                    270:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
                    285:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.999     www       438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   453:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       454:         var title = 'Student_Browser';
1.74      www       455:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    456:         options += ',width=700,height=600';
                    457:         stdeditbrowser = open(url,title,options,'1');
                    458:         stdeditbrowser.focus();
                    459:     }
1.824     bisitz    460: // ]]>
1.74      www       461: </script>
                    462: ENDSTDBRW
                    463: }
1.42      matthew   464: 
1.1003    www       465: sub resourcebrowser_javascript {
                    466:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       467:    return (<<'ENDRESBRW');
1.1003    www       468: <script type="text/javascript" language="Javascript">
                    469: // <![CDATA[
                    470:     var reseditbrowser;
1.1004    www       471:     function openresbrowser(formname,reslink) {
1.1005    www       472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       473:         var title = 'Resource_Browser';
                    474:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       475:         options += ',width=700,height=500';
1.1004    www       476:         reseditbrowser = open(url,title,options,'1');
                    477:         reseditbrowser.focus();
1.1003    www       478:     }
                    479: // ]]>
                    480: </script>
1.1004    www       481: ENDRESBRW
1.1003    www       482: }
                    483: 
1.74      www       484: sub selectstudent_link {
1.999     www       485:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  489:    if ($env{'request.course.id'}) {  
1.302     albertel  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    492: 					'/'.$env{'request.course.sec'})) {
1.111     www       493: 	   return '';
                    494:        }
1.999     www       495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   496:        if ($courseadvonly)  {
                    497:            $callargs .= ",'',1,1";
                    498:        }
                    499:        return '<span class="LC_nobreak">'.
                    500:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    501:               &mt('Select User').'</a></span>';
1.74      www       502:    }
1.258     albertel  503:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       504:        $callargs .= ",'',1"; 
1.793     raeburn   505:        return '<span class="LC_nobreak">'.
                    506:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    507:               &mt('Select User').'</a></span>';
1.111     www       508:    }
                    509:    return '';
1.91      www       510: }
                    511: 
1.1004    www       512: sub selectresource_link {
                    513:    my ($form,$reslink,$arg)=@_;
                    514:    
                    515:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    516:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    517:    unless ($env{'request.course.id'}) { return $arg; }
                    518:    return '<span class="LC_nobreak">'.
                    519:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    520:               $arg.'</a></span>';
                    521: }
                    522: 
                    523: 
                    524: 
1.653     raeburn   525: sub authorbrowser_javascript {
                    526:     return <<"ENDAUTHORBRW";
1.776     bisitz    527: <script type="text/javascript" language="JavaScript">
1.824     bisitz    528: // <![CDATA[
1.653     raeburn   529: var stdeditbrowser;
                    530: 
                    531: function openauthorbrowser(formname,udom) {
                    532:     var url = '/adm/pickauthor?';
                    533:     url += 'form='+formname+'&roledom='+udom;
                    534:     var title = 'Author_Browser';
                    535:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    536:     options += ',width=700,height=600';
                    537:     stdeditbrowser = open(url,title,options,'1');
                    538:     stdeditbrowser.focus();
                    539: }
                    540: 
1.824     bisitz    541: // ]]>
1.653     raeburn   542: </script>
                    543: ENDAUTHORBRW
                    544: }
                    545: 
1.91      www       546: sub coursebrowser_javascript {
1.1116    raeburn   547:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   548:         $credits_element,$instcode) = @_;
1.932     raeburn   549:     my $wintitle = 'Course_Browser';
1.931     raeburn   550:     if ($crstype eq 'Community') {
1.932     raeburn   551:         $wintitle = 'Community_Browser';
1.909     raeburn   552:     }
1.876     raeburn   553:     my $id_functions = &javascript_index_functions();
                    554:     my $output = '
1.776     bisitz    555: <script type="text/javascript" language="JavaScript">
1.824     bisitz    556: // <![CDATA[
1.468     raeburn   557:     var stdeditbrowser;'."\n";
1.876     raeburn   558: 
                    559:     $output .= <<"ENDSTDBRW";
1.909     raeburn   560:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       561:         var url = '/adm/pickcourse?';
1.895     raeburn   562:         var formid = getFormIdByName(formname);
1.876     raeburn   563:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  564:         if (domainfilter != null) {
                    565:            if (domainfilter != '') {
                    566:                url += 'domainfilter='+domainfilter+'&';
                    567: 	   }
                    568:         }
1.91      www       569:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  570: 	                            '&cdomelement='+udom+
                    571:                                     '&cnameelement='+desc;
1.468     raeburn   572:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   573:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   574:                 url += '&roleelement='+extra_element;
                    575:                 if (domainfilter == null || domainfilter == '') {
                    576:                     url += '&domainfilter='+extra_element;
                    577:                 }
1.234     raeburn   578:             }
1.468     raeburn   579:             else {
                    580:                 if (formname == 'portform') {
                    581:                     url += '&setroles='+extra_element;
1.800     raeburn   582:                 } else {
                    583:                     if (formname == 'rules') {
                    584:                         url += '&fixeddom='+extra_element; 
                    585:                     }
1.468     raeburn   586:                 }
                    587:             }     
1.230     raeburn   588:         }
1.909     raeburn   589:         if (type != null && type != '') {
                    590:             url += '&type='+type;
                    591:         }
                    592:         if (type_elem != null && type_elem != '') {
                    593:             url += '&typeelement='+type_elem;
                    594:         }
1.872     raeburn   595:         if (formname == 'ccrs') {
                    596:             var ownername = document.forms[formid].ccuname.value;
                    597:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   598:             url += '&cloner='+ownername+':'+ownerdom;
                    599:             if (type == 'Course') {
                    600:                 url += '&crscode='+document.forms[formid].crscode.value;
                    601:             }
1.1221    raeburn   602:         }
                    603:         if (formname == 'requestcrs') {
                    604:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   605:         }
1.293     raeburn   606:         if (multflag !=null && multflag != '') {
                    607:             url += '&multiple='+multflag;
                    608:         }
1.909     raeburn   609:         var title = '$wintitle';
1.91      www       610:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    611:         options += ',width=700,height=600';
                    612:         stdeditbrowser = open(url,title,options,'1');
                    613:         stdeditbrowser.focus();
                    614:     }
1.876     raeburn   615: $id_functions
                    616: ENDSTDBRW
1.1116    raeburn   617:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    618:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    619:                                       $credits_element);
1.876     raeburn   620:     }
                    621:     $output .= '
                    622: // ]]>
                    623: </script>';
                    624:     return $output;
                    625: }
                    626: 
                    627: sub javascript_index_functions {
                    628:     return <<"ENDJS";
                    629: 
                    630: function getFormIdByName(formname) {
                    631:     for (var i=0;i<document.forms.length;i++) {
                    632:         if (document.forms[i].name == formname) {
                    633:             return i;
                    634:         }
                    635:     }
                    636:     return -1;
                    637: }
                    638: 
                    639: function getIndexByName(formid,item) {
                    640:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    641:         if (document.forms[formid].elements[i].name == item) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
1.468     raeburn   647: 
1.876     raeburn   648: function getDomainFromSelectbox(formname,udom) {
                    649:     var userdom;
                    650:     var formid = getFormIdByName(formname);
                    651:     if (formid > -1) {
                    652:         var domid = getIndexByName(formid,udom);
                    653:         if (domid > -1) {
                    654:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    655:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    656:             }
                    657:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    658:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   659:             }
                    660:         }
                    661:     }
1.876     raeburn   662:     return userdom;
                    663: }
                    664: 
                    665: ENDJS
1.468     raeburn   666: 
1.876     raeburn   667: }
                    668: 
1.1017    raeburn   669: sub javascript_array_indexof {
1.1018    raeburn   670:     return <<ENDJS;
1.1017    raeburn   671: <script type="text/javascript" language="JavaScript">
                    672: // <![CDATA[
                    673: 
                    674: if (!Array.prototype.indexOf) {
                    675:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    676:         "use strict";
                    677:         if (this === void 0 || this === null) {
                    678:             throw new TypeError();
                    679:         }
                    680:         var t = Object(this);
                    681:         var len = t.length >>> 0;
                    682:         if (len === 0) {
                    683:             return -1;
                    684:         }
                    685:         var n = 0;
                    686:         if (arguments.length > 0) {
                    687:             n = Number(arguments[1]);
1.1088    foxr      688:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   689:                 n = 0;
                    690:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    691:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    692:             }
                    693:         }
                    694:         if (n >= len) {
                    695:             return -1;
                    696:         }
                    697:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    698:         for (; k < len; k++) {
                    699:             if (k in t && t[k] === searchElement) {
                    700:                 return k;
                    701:             }
                    702:         }
                    703:         return -1;
                    704:     }
                    705: }
                    706: 
                    707: // ]]>
                    708: </script>
                    709: 
                    710: ENDJS
                    711: 
                    712: }
                    713: 
1.876     raeburn   714: sub userbrowser_javascript {
                    715:     my $id_functions = &javascript_index_functions();
                    716:     return <<"ENDUSERBRW";
                    717: 
1.888     raeburn   718: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   719:     var url = '/adm/pickuser?';
                    720:     var userdom = getDomainFromSelectbox(formname,udom);
                    721:     if (userdom != null) {
                    722:        if (userdom != '') {
                    723:            url += 'srchdom='+userdom+'&';
                    724:        }
                    725:     }
                    726:     url += 'form=' + formname + '&unameelement='+uname+
                    727:                                 '&udomelement='+udom+
                    728:                                 '&ulastelement='+ulast+
                    729:                                 '&ufirstelement='+ufirst+
                    730:                                 '&uemailelement='+uemail+
1.881     raeburn   731:                                 '&hideudomelement='+hideudom+
                    732:                                 '&coursedom='+crsdom;
1.888     raeburn   733:     if ((caller != null) && (caller != undefined)) {
                    734:         url += '&caller='+caller;
                    735:     }
1.876     raeburn   736:     var title = 'User_Browser';
                    737:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    738:     options += ',width=700,height=600';
                    739:     var stdeditbrowser = open(url,title,options,'1');
                    740:     stdeditbrowser.focus();
                    741: }
                    742: 
1.888     raeburn   743: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   744:     var formid = getFormIdByName(formname);
                    745:     if (formid > -1) {
1.888     raeburn   746:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   747:         var domid = getIndexByName(formid,udom);
                    748:         var hidedomid = getIndexByName(formid,origdom);
                    749:         if (hidedomid > -1) {
                    750:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   751:             var unameval = document.forms[formid].elements[unameid].value;
                    752:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    753:                 if (domid > -1) {
                    754:                     var slct = document.forms[formid].elements[domid];
                    755:                     if (slct.type == 'select-one') {
                    756:                         var i;
                    757:                         for (i=0;i<slct.length;i++) {
                    758:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    759:                         }
                    760:                     }
                    761:                     if (slct.type == 'hidden') {
                    762:                         slct.value = fixeddom;
1.876     raeburn   763:                     }
                    764:                 }
1.468     raeburn   765:             }
                    766:         }
                    767:     }
1.876     raeburn   768:     return;
                    769: }
                    770: 
                    771: $id_functions
                    772: ENDUSERBRW
1.468     raeburn   773: }
                    774: 
                    775: sub setsec_javascript {
1.1116    raeburn   776:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   777:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    778:         $communityrolestr);
                    779:     if ($role_element ne '') {
                    780:         my @allroles = ('st','ta','ep','in','ad');
                    781:         foreach my $crstype ('Course','Community') {
                    782:             if ($crstype eq 'Community') {
                    783:                 foreach my $role (@allroles) {
                    784:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    785:                 }
                    786:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    787:             } else {
                    788:                 foreach my $role (@allroles) {
                    789:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    790:                 }
                    791:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    792:             }
                    793:         }
                    794:         $rolestr = '"'.join('","',@allroles).'"';
                    795:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    796:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    797:     }
1.468     raeburn   798:     my $setsections = qq|
                    799: function setSect(sectionlist) {
1.629     raeburn   800:     var sectionsArray = new Array();
                    801:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    802:         sectionsArray = sectionlist.split(",");
                    803:     }
1.468     raeburn   804:     var numSections = sectionsArray.length;
                    805:     document.$formname.$sec_element.length = 0;
                    806:     if (numSections == 0) {
                    807:         document.$formname.$sec_element.multiple=false;
                    808:         document.$formname.$sec_element.size=1;
                    809:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    810:     } else {
                    811:         if (numSections == 1) {
                    812:             document.$formname.$sec_element.multiple=false;
                    813:             document.$formname.$sec_element.size=1;
                    814:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    815:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    816:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    817:         } else {
                    818:             for (var i=0; i<numSections; i++) {
                    819:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    820:             }
                    821:             document.$formname.$sec_element.multiple=true
                    822:             if (numSections < 3) {
                    823:                 document.$formname.$sec_element.size=numSections;
                    824:             } else {
                    825:                 document.$formname.$sec_element.size=3;
                    826:             }
                    827:             document.$formname.$sec_element.options[0].selected = false
                    828:         }
                    829:     }
1.91      www       830: }
1.905     raeburn   831: 
                    832: function setRole(crstype) {
1.468     raeburn   833: |;
1.905     raeburn   834:     if ($role_element eq '') {
                    835:         $setsections .= '    return;
                    836: }
                    837: ';
                    838:     } else {
                    839:         $setsections .= qq|
                    840:     var elementLength = document.$formname.$role_element.length;
                    841:     var allroles = Array($rolestr);
                    842:     var courserolenames = Array($courserolestr);
                    843:     var communityrolenames = Array($communityrolestr);
                    844:     if (elementLength != undefined) {
                    845:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    846:             if (crstype == 'Course') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'co';
                    850:                 for (var i=0; i<6; i++) {
                    851:                     document.$formname.$role_element.options[i].value = allroles[i];
                    852:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    853:                 }
                    854:             }
                    855:         } else {
                    856:             if (crstype == 'Community') {
                    857:                 return;
                    858:             } else {
                    859:                 allroles[5] = 'cc';
                    860:                 for (var i=0; i<6; i++) {
                    861:                     document.$formname.$role_element.options[i].value = allroles[i];
                    862:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    863:                 }
                    864:             }
                    865:         }
                    866:     }
                    867:     return;
                    868: }
                    869: |;
                    870:     }
1.1116    raeburn   871:     if ($credits_element) {
                    872:         $setsections .= qq|
                    873: function setCredits(defaultcredits) {
                    874:     document.$formname.$credits_element.value = defaultcredits;
                    875:     return;
                    876: }
                    877: |;
                    878:     }
1.468     raeburn   879:     return $setsections;
                    880: }
                    881: 
1.91      www       882: sub selectcourse_link {
1.909     raeburn   883:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    884:        $typeelement) = @_;
                    885:    my $type = $selecttype;
1.871     raeburn   886:    my $linktext = &mt('Select Course');
                    887:    if ($selecttype eq 'Community') {
1.909     raeburn   888:        $linktext = &mt('Select Community');
1.1239    raeburn   889:    } elsif ($selecttype eq 'Placement') {
                    890:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   891:    } elsif ($selecttype eq 'Course/Community') {
                    892:        $linktext = &mt('Select Course/Community');
1.909     raeburn   893:        $type = '';
1.1019    raeburn   894:    } elsif ($selecttype eq 'Select') {
                    895:        $linktext = &mt('Select');
                    896:        $type = '';
1.871     raeburn   897:    }
1.787     bisitz    898:    return '<span class="LC_nobreak">'
                    899:          ."<a href='"
                    900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   903:          ."'>".$linktext.'</a>'
1.787     bisitz    904:          .'</span>';
1.74      www       905: }
1.42      matthew   906: 
1.653     raeburn   907: sub selectauthor_link {
                    908:    my ($form,$udom)=@_;
                    909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    910:           &mt('Select Author').'</a>';
                    911: }
                    912: 
1.876     raeburn   913: sub selectuser_link {
1.881     raeburn   914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   915:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   918:            ');">'.$linktext.'</a>';
1.876     raeburn   919: }
                    920: 
1.273     raeburn   921: sub check_uncheck_jscript {
                    922:     my $jscript = <<"ENDSCRT";
                    923: function checkAll(field) {
                    924:     if (field.length > 0) {
                    925:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   926:             if (!field[i].disabled) { 
                    927:                 field[i].checked = true;
                    928:             }
1.273     raeburn   929:         }
                    930:     } else {
1.1093    raeburn   931:         if (!field.disabled) { 
                    932:             field.checked = true;
                    933:         }
1.273     raeburn   934:     }
                    935: }
                    936:  
                    937: function uncheckAll(field) {
                    938:     if (field.length > 0) {
                    939:         for (i = 0; i < field.length; i++) {
                    940:             field[i].checked = false ;
1.543     albertel  941:         }
                    942:     } else {
1.273     raeburn   943:         field.checked = false ;
                    944:     }
                    945: }
                    946: ENDSCRT
                    947:     return $jscript;
                    948: }
                    949: 
1.656     www       950: sub select_timezone {
1.1256    raeburn   951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   953:    if ($includeempty) {
                    954:        $output .= '<option value=""';
                    955:        if (($selected eq '') || ($selected eq 'local')) {
                    956:            $output .= ' selected="selected" ';
                    957:        }
                    958:        $output .= '> </option>';
                    959:    }
1.657     raeburn   960:    my @timezones = DateTime::TimeZone->all_names;
                    961:    foreach my $tzone (@timezones) {
                    962:        $output.= '<option value="'.$tzone.'"';
                    963:        if ($tzone eq $selected) {
                    964:            $output.=' selected="selected"';
                    965:        }
                    966:        $output.=">$tzone</option>\n";
1.656     www       967:    }
                    968:    $output.="</select>";
                    969:    return $output;
                    970: }
1.273     raeburn   971: 
1.687     raeburn   972: sub select_datelocale {
1.1256    raeburn   973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   975:     if ($includeempty) {
                    976:         $output .= '<option value=""';
                    977:         if ($selected eq '') {
                    978:             $output .= ' selected="selected" ';
                    979:         }
                    980:         $output .= '> </option>';
                    981:     }
1.1241    raeburn   982:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   983:     my (@possibles,%locale_names);
1.1241    raeburn   984:     my @locales = DateTime::Locale->ids();
                    985:     foreach my $id (@locales) {
                    986:         if ($id ne '') {
                    987:             my ($en_terr,$native_terr);
                    988:             my $loc = DateTime::Locale->load($id);
                    989:             if (ref($loc)) {
                    990:                 $en_terr = $loc->name();
                    991:                 $native_terr = $loc->native_name();
1.687     raeburn   992:                 if (grep(/^en$/,@languages) || !@languages) {
                    993:                     if ($en_terr ne '') {
                    994:                         $locale_names{$id} = '('.$en_terr.')';
                    995:                     } elsif ($native_terr ne '') {
                    996:                         $locale_names{$id} = $native_terr;
                    997:                     }
                    998:                 } else {
                    999:                     if ($native_terr ne '') {
                   1000:                         $locale_names{$id} = $native_terr.' ';
                   1001:                     } elsif ($en_terr ne '') {
                   1002:                         $locale_names{$id} = '('.$en_terr.')';
                   1003:                     }
                   1004:                 }
1.1220    raeburn  1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1006:                 push(@possibles,$id);
                   1007:             } 
1.687     raeburn  1008:         }
                   1009:     }
                   1010:     foreach my $item (sort(@possibles)) {
                   1011:         $output.= '<option value="'.$item.'"';
                   1012:         if ($item eq $selected) {
                   1013:             $output.=' selected="selected"';
                   1014:         }
                   1015:         $output.=">$item";
                   1016:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1017:             $output.='  '.$locale_names{$item};
1.687     raeburn  1018:         }
                   1019:         $output.="</option>\n";
                   1020:     }
                   1021:     $output.="</select>";
                   1022:     return $output;
                   1023: }
                   1024: 
1.792     raeburn  1025: sub select_language {
1.1256    raeburn  1026:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1027:     my %langchoices;
                   1028:     if ($includeempty) {
1.1117    raeburn  1029:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1030:     }
                   1031:     foreach my $id (&languageids()) {
                   1032:         my $code = &supportedlanguagecode($id);
                   1033:         if ($code) {
                   1034:             $langchoices{$code} = &plainlanguagedescription($id);
                   1035:         }
                   1036:     }
1.1117    raeburn  1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1039: }
                   1040: 
1.42      matthew  1041: =pod
1.36      matthew  1042: 
1.1088    foxr     1043: 
                   1044: =item * &list_languages()
                   1045: 
                   1046: Returns an array reference that is suitable for use in language prompters.
                   1047: Each array element is itself a two element array.  The first element
                   1048: is the language code.  The second element a descsriptiuon of the 
                   1049: language itself.  This is suitable for use in e.g.
                   1050: &Apache::edit::select_arg (once dereferenced that is).
                   1051: 
                   1052: =cut 
                   1053: 
                   1054: sub list_languages {
                   1055:     my @lang_choices;
                   1056: 
                   1057:     foreach my $id (&languageids()) {
                   1058: 	my $code = &supportedlanguagecode($id);
                   1059: 	if ($code) {
                   1060: 	    my $selector    = $supported_codes{$id};
                   1061: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1062: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1063: 	}
                   1064:     }
                   1065:     return \@lang_choices;
                   1066: }
                   1067: 
                   1068: =pod
                   1069: 
1.648     raeburn  1070: =item * &linked_select_forms(...)
1.36      matthew  1071: 
                   1072: linked_select_forms returns a string containing a <script></script> block
                   1073: and html for two <select> menus.  The select menus will be linked in that
                   1074: changing the value of the first menu will result in new values being placed
                   1075: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1076: order unless a defined order is provided.
1.36      matthew  1077: 
                   1078: linked_select_forms takes the following ordered inputs:
                   1079: 
                   1080: =over 4
                   1081: 
1.112     bowersj2 1082: =item * $formname, the name of the <form> tag
1.36      matthew  1083: 
1.112     bowersj2 1084: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1085: 
1.112     bowersj2 1086: =item * $firstdefault, the default value for the first menu
1.36      matthew  1087: 
1.112     bowersj2 1088: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1089: 
1.112     bowersj2 1090: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1091: 
1.112     bowersj2 1092: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1093: 
1.609     raeburn  1094: =item * $menuorder, the order of values in the first menu
                   1095: 
1.1115    raeburn  1096: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1097:         event for the first <select> tag
                   1098: 
                   1099: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1100:         event for the second <select> tag
                   1101: 
1.1245    raeburn  1102: =item * $suffix, to differentiate separate uses of select2data javascript
                   1103:         objects in a page.
                   1104: 
1.41      ng       1105: =back 
                   1106: 
1.36      matthew  1107: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1108: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1109: values for the first select menu.  The text that coincides with the 
1.41      ng       1110: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1111: and text for the second menu are given in the hash pointed to by 
                   1112: $menu{$choice1}->{'select2'}.  
                   1113: 
1.112     bowersj2 1114:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1115:                        default => "B3",
                   1116:                        select2 => { 
                   1117:                            B1 => "Choice B1",
                   1118:                            B2 => "Choice B2",
                   1119:                            B3 => "Choice B3",
                   1120:                            B4 => "Choice B4"
1.609     raeburn  1121:                            },
                   1122:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1123:                    },
                   1124:                A2 => { text =>"Choice A2" ,
                   1125:                        default => "C2",
                   1126:                        select2 => { 
                   1127:                            C1 => "Choice C1",
                   1128:                            C2 => "Choice C2",
                   1129:                            C3 => "Choice C3"
1.609     raeburn  1130:                            },
                   1131:                        order => ['C2','C1','C3'],
1.112     bowersj2 1132:                    },
                   1133:                A3 => { text =>"Choice A3" ,
                   1134:                        default => "D6",
                   1135:                        select2 => { 
                   1136:                            D1 => "Choice D1",
                   1137:                            D2 => "Choice D2",
                   1138:                            D3 => "Choice D3",
                   1139:                            D4 => "Choice D4",
                   1140:                            D5 => "Choice D5",
                   1141:                            D6 => "Choice D6",
                   1142:                            D7 => "Choice D7"
1.609     raeburn  1143:                            },
                   1144:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1145:                    }
                   1146:                );
1.36      matthew  1147: 
                   1148: =cut
                   1149: 
                   1150: sub linked_select_forms {
                   1151:     my ($formname,
                   1152:         $middletext,
                   1153:         $firstdefault,
                   1154:         $firstselectname,
                   1155:         $secondselectname, 
1.609     raeburn  1156:         $hashref,
                   1157:         $menuorder,
1.1115    raeburn  1158:         $onchangefirst,
1.1245    raeburn  1159:         $onchangesecond,
                   1160:         $suffix
1.36      matthew  1161:         ) = @_;
                   1162:     my $second = "document.$formname.$secondselectname";
                   1163:     my $first = "document.$formname.$firstselectname";
                   1164:     # output the javascript to do the changing
                   1165:     my $result = '';
1.776     bisitz   1166:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1167:     $result.="// <![CDATA[\n";
1.1245    raeburn  1168:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1169:     $" = '","';
                   1170:     my $debug = '';
                   1171:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1172:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1173:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1174:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1175:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1176:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1177:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1178:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1179:         }
1.36      matthew  1180:         $result.="\"@s2values\");\n";
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1182:         my @s2texts;
                   1183:         foreach my $value (@s2values) {
1.1263    raeburn  1184:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1185:         }
                   1186:         $result.="\"@s2texts\");\n";
                   1187:     }
                   1188:     $"=' ';
                   1189:     $result.= <<"END";
                   1190: 
1.1245    raeburn  1191: function select1${suffix}_changed() {
1.36      matthew  1192:     // Determine new choice
1.1245    raeburn  1193:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1194:     // update select2
1.1245    raeburn  1195:     var values     = select2data${suffix}[newvalue].values;
                   1196:     var texts      = select2data${suffix}[newvalue].texts;
                   1197:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1198:     var i;
                   1199:     // out with the old
1.1245    raeburn  1200:     $second.options.length = 0;
                   1201:     // in with the new
1.36      matthew  1202:     for (i=0;i<values.length; i++) {
                   1203:         $second.options[i] = new Option(values[i]);
1.143     matthew  1204:         $second.options[i].value = values[i];
1.36      matthew  1205:         $second.options[i].text = texts[i];
                   1206:         if (values[i] == select2def) {
                   1207:             $second.options[i].selected = true;
                   1208:         }
                   1209:     }
                   1210: }
1.824     bisitz   1211: // ]]>
1.36      matthew  1212: </script>
                   1213: END
                   1214:     # output the initial values for the selection lists
1.1245    raeburn  1215:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1216:     my @order = sort(keys(%{$hashref}));
                   1217:     if (ref($menuorder) eq 'ARRAY') {
                   1218:         @order = @{$menuorder};
                   1219:     }
                   1220:     foreach my $value (@order) {
1.36      matthew  1221:         $result.="    <option value=\"$value\" ";
1.253     albertel 1222:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1223:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1224:     }
                   1225:     $result .= "</select>\n";
                   1226:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1227:     $result .= $middletext;
1.1115    raeburn  1228:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1229:     if ($onchangesecond) {
                   1230:         $result .= ' onchange="'.$onchangesecond.'"';
                   1231:     }
                   1232:     $result .= ">\n";
1.36      matthew  1233:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1234:     
                   1235:     my @secondorder = sort(keys(%select2));
                   1236:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1237:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1238:     }
                   1239:     foreach my $value (@secondorder) {
1.36      matthew  1240:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1241:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1242:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1243:     }
                   1244:     $result .= "</select>\n";
                   1245:     #    return $debug;
                   1246:     return $result;
                   1247: }   #  end of sub linked_select_forms {
                   1248: 
1.45      matthew  1249: =pod
1.44      bowersj2 1250: 
1.973     raeburn  1251: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1252: 
1.112     bowersj2 1253: Returns a string corresponding to an HTML link to the given help
                   1254: $topic, where $topic corresponds to the name of a .tex file in
                   1255: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1256: spaces. 
                   1257: 
                   1258: $text will optionally be linked to the same topic, allowing you to
                   1259: link text in addition to the graphic. If you do not want to link
                   1260: text, but wish to specify one of the later parameters, pass an
                   1261: empty string. 
                   1262: 
                   1263: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1264: the link will not open a new window. If false, the link will open
                   1265: a new window using Javascript. (Default is false.) 
                   1266: 
                   1267: $width and $height are optional numerical parameters that will
                   1268: override the width and height of the popped up window, which may
1.973     raeburn  1269: be useful for certain help topics with big pictures included.
                   1270: 
                   1271: $imgid is the id of the img tag used for the help icon. This may be
                   1272: used in a javascript call to switch the image src.  See 
                   1273: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1274: 
                   1275: =cut
                   1276: 
                   1277: sub help_open_topic {
1.973     raeburn  1278:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1279:     $text = "" if (not defined $text);
1.44      bowersj2 1280:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1281:     $width = 500 if (not defined $width);
1.44      bowersj2 1282:     $height = 400 if (not defined $height);
                   1283:     my $filename = $topic;
                   1284:     $filename =~ s/ /_/g;
                   1285: 
1.48      bowersj2 1286:     my $template = "";
                   1287:     my $link;
1.572     banghart 1288:     
1.159     www      1289:     $topic=~s/\W/\_/g;
1.44      bowersj2 1290: 
1.572     banghart 1291:     if (!$stayOnPage) {
1.1033    www      1292: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1293:     } elsif ($stayOnPage eq 'popup') {
                   1294:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1295:     } else {
1.48      bowersj2 1296: 	$link = "/adm/help/${filename}.hlp";
                   1297:     }
                   1298: 
                   1299:     # Add the text
1.1314    raeburn  1300:     my $target = ' target="_top"';
                   1301:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1302:         $target = '';
                   1303:     }
1.755     neumanie 1304:     if ($text ne "") {	
1.763     bisitz   1305: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1306:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1307:                   .$text.'</a>';
1.48      bowersj2 1308:     }
                   1309: 
1.763     bisitz   1310:     # (Always) Add the graphic
1.179     matthew  1311:     my $title = &mt('Online Help');
1.667     raeburn  1312:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1313:     if ($imgid ne '') {
                   1314:         $imgid = ' id="'.$imgid.'"';
                   1315:     }
1.1314    raeburn  1316:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1317:               .'<img src="'.$helpicon.'" border="0"'
                   1318:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1319:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1320:               .' /></a>';
                   1321:     if ($text ne "") {	
                   1322:         $template.='</span>';
                   1323:     }
1.44      bowersj2 1324:     return $template;
                   1325: 
1.106     bowersj2 1326: }
                   1327: 
                   1328: # This is a quicky function for Latex cheatsheet editing, since it 
                   1329: # appears in at least four places
                   1330: sub helpLatexCheatsheet {
1.1037    www      1331:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1332:     my $out;
1.106     bowersj2 1333:     my $addOther = '';
1.732     raeburn  1334:     if ($topic) {
1.1037    www      1335: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1336:     }
                   1337:     $out = '<span>' # Start cheatsheet
                   1338: 	  .$addOther
                   1339:           .'<span>'
1.1037    www      1340: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1341: 	  .'</span> <span>'
1.1037    www      1342: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1343: 	  .'</span>';
1.732     raeburn  1344:     unless ($not_author) {
1.1186    kruse    1345:         $out .= '<span>'
                   1346:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1347:                .'</span> <span>'
                   1348:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1349: 	       .'</span>';
1.732     raeburn  1350:     }
1.763     bisitz   1351:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1352:     return $out;
1.172     www      1353: }
                   1354: 
1.430     albertel 1355: sub general_help {
                   1356:     my $helptopic='Student_Intro';
                   1357:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1358: 	$helptopic='Authoring_Intro';
1.907     raeburn  1359:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1360: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1361:     } elsif ($env{'request.role'}=~/^dc/) {
                   1362:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1363:     }
                   1364:     return $helptopic;
                   1365: }
                   1366: 
                   1367: sub update_help_link {
                   1368:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1369:     my $origurl = $ENV{'REQUEST_URI'};
                   1370:     $origurl=~s|^/~|/priv/|;
                   1371:     my $timestamp = time;
                   1372:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1373:         $$datum = &escape($$datum);
                   1374:     }
                   1375: 
                   1376:     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";
                   1377:     my $output .= <<"ENDOUTPUT";
                   1378: <script type="text/javascript">
1.824     bisitz   1379: // <![CDATA[
1.430     albertel 1380: banner_link = '$banner_link';
1.824     bisitz   1381: // ]]>
1.430     albertel 1382: </script>
                   1383: ENDOUTPUT
                   1384:     return $output;
                   1385: }
                   1386: 
                   1387: # now just updates the help link and generates a blue icon
1.193     raeburn  1388: sub help_open_menu {
1.430     albertel 1389:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1390: 	= @_;    
1.949     droeschl 1391:     $stayOnPage = 1;
1.430     albertel 1392:     my $output;
                   1393:     if ($component_help) {
                   1394: 	if (!$text) {
                   1395: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1396: 				       $width,$height);
                   1397: 	} else {
                   1398: 	    my $help_text;
                   1399: 	    $help_text=&unescape($topic);
                   1400: 	    $output='<table><tr><td>'.
                   1401: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1402: 				 $width,$height).'</td></tr></table>';
                   1403: 	}
                   1404:     }
                   1405:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1406:     return $output.$banner_link;
                   1407: }
                   1408: 
                   1409: sub top_nav_help {
                   1410:     my ($text) = @_;
1.436     albertel 1411:     $text = &mt($text);
1.949     droeschl 1412:     my $stay_on_page = 1;
                   1413: 
1.1168    raeburn  1414:     my ($link,$banner_link);
                   1415:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1416:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1417: 	                         : "javascript:helpMenu('open')";
                   1418:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1419:     }
1.201     raeburn  1420:     my $title = &mt('Get help');
1.1168    raeburn  1421:     if ($link) {
                   1422:         return <<"END";
1.436     albertel 1423: $banner_link
1.1159    raeburn  1424: <a href="$link" title="$title">$text</a>
1.436     albertel 1425: END
1.1168    raeburn  1426:     } else {
                   1427:         return '&nbsp;'.$text.'&nbsp;';
                   1428:     }
1.436     albertel 1429: }
                   1430: 
                   1431: sub help_menu_js {
1.1154    raeburn  1432:     my ($httphost) = @_;
1.949     droeschl 1433:     my $stayOnPage = 1;
1.436     albertel 1434:     my $width = 620;
                   1435:     my $height = 600;
1.430     albertel 1436:     my $helptopic=&general_help();
1.1154    raeburn  1437:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1438:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1439:     my $start_page =
                   1440:         &Apache::loncommon::start_page('Help Menu', undef,
                   1441: 				       {'frameset'    => 1,
                   1442: 					'js_ready'    => 1,
1.1154    raeburn  1443:                                         'use_absolute' => $httphost,
1.331     albertel 1444: 					'add_entries' => {
1.1168    raeburn  1445: 					    'border' => '0', 
1.579     raeburn  1446: 					    'rows'   => "110,*",},});
1.331     albertel 1447:     my $end_page =
                   1448:         &Apache::loncommon::end_page({'frameset' => 1,
                   1449: 				      'js_ready' => 1,});
                   1450: 
1.436     albertel 1451:     my $template .= <<"ENDTEMPLATE";
                   1452: <script type="text/javascript">
1.877     bisitz   1453: // <![CDATA[
1.253     albertel 1454: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1455: var banner_link = '';
1.243     raeburn  1456: function helpMenu(target) {
                   1457:     var caller = this;
                   1458:     if (target == 'open') {
                   1459:         var newWindow = null;
                   1460:         try {
1.262     albertel 1461:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1462:         }
                   1463:         catch(error) {
                   1464:             writeHelp(caller);
                   1465:             return;
                   1466:         }
                   1467:         if (newWindow) {
                   1468:             caller = newWindow;
                   1469:         }
1.193     raeburn  1470:     }
1.243     raeburn  1471:     writeHelp(caller);
                   1472:     return;
                   1473: }
                   1474: function writeHelp(caller) {
1.1168    raeburn  1475:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1476:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1477:     caller.document.close();
                   1478:     caller.focus();
1.193     raeburn  1479: }
1.877     bisitz   1480: // END LON-CAPA Internal -->
1.253     albertel 1481: // ]]>
1.436     albertel 1482: </script>
1.193     raeburn  1483: ENDTEMPLATE
                   1484:     return $template;
                   1485: }
                   1486: 
1.172     www      1487: sub help_open_bug {
                   1488:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1489:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1490:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1491:     $text = "" if (not defined $text);
                   1492: 	$stayOnPage=1;
1.184     albertel 1493:     $width = 600 if (not defined $width);
                   1494:     $height = 600 if (not defined $height);
1.172     www      1495: 
                   1496:     $topic=~s/\W+/\+/g;
                   1497:     my $link='';
                   1498:     my $template='';
1.379     albertel 1499:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1500: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1501:     if (!$stayOnPage)
                   1502:     {
                   1503: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1504:     }
                   1505:     else
                   1506:     {
                   1507: 	$link = $url;
                   1508:     }
1.1314    raeburn  1509: 
                   1510:     my $target = ' target="_top"';
                   1511:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1512:         $target = '';
                   1513:     }
1.172     www      1514:     # Add the text
                   1515:     if ($text ne "")
                   1516:     {
                   1517: 	$template .= 
                   1518:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1519:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1520:     }
                   1521: 
                   1522:     # Add the graphic
1.179     matthew  1523:     my $title = &mt('Report a Bug');
1.215     albertel 1524:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1525:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1526:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1527: ENDTEMPLATE
                   1528:     if ($text ne '') { $template.='</td></tr></table>' };
                   1529:     return $template;
                   1530: 
                   1531: }
                   1532: 
                   1533: sub help_open_faq {
                   1534:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1535:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1536:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1537:     $text = "" if (not defined $text);
                   1538: 	$stayOnPage=1;
                   1539:     $width = 350 if (not defined $width);
                   1540:     $height = 400 if (not defined $height);
                   1541: 
                   1542:     $topic=~s/\W+/\+/g;
                   1543:     my $link='';
                   1544:     my $template='';
                   1545:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1546:     if (!$stayOnPage)
                   1547:     {
                   1548: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1549:     }
                   1550:     else
                   1551:     {
                   1552: 	$link = $url;
                   1553:     }
                   1554: 
                   1555:     # Add the text
                   1556:     if ($text ne "")
                   1557:     {
                   1558: 	$template .= 
1.173     www      1559:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1560:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1561:     }
                   1562: 
                   1563:     # Add the graphic
1.179     matthew  1564:     my $title = &mt('View the FAQ');
1.215     albertel 1565:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1566:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1567:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1568: ENDTEMPLATE
                   1569:     if ($text ne '') { $template.='</td></tr></table>' };
                   1570:     return $template;
                   1571: 
1.44      bowersj2 1572: }
1.37      matthew  1573: 
1.180     matthew  1574: ###############################################################
                   1575: ###############################################################
                   1576: 
1.45      matthew  1577: =pod
                   1578: 
1.648     raeburn  1579: =item * &change_content_javascript():
1.256     matthew  1580: 
                   1581: This and the next function allow you to create small sections of an
                   1582: otherwise static HTML page that you can update on the fly with
                   1583: Javascript, even in Netscape 4.
                   1584: 
                   1585: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1586: must be written to the HTML page once. It will prove the Javascript
                   1587: function "change(name, content)". Calling the change function with the
                   1588: name of the section 
                   1589: you want to update, matching the name passed to C<changable_area>, and
                   1590: the new content you want to put in there, will put the content into
                   1591: that area.
                   1592: 
                   1593: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1594: to contain room for the original contents. You need to "make space"
                   1595: for whatever changes you wish to make, and be B<sure> to check your
                   1596: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1597: it's adequate for updating a one-line status display, but little more.
                   1598: This script will set the space to 100% width, so you only need to
                   1599: worry about height in Netscape 4.
                   1600: 
                   1601: Modern browsers are much less limiting, and if you can commit to the
                   1602: user not using Netscape 4, this feature may be used freely with
                   1603: pretty much any HTML.
                   1604: 
                   1605: =cut
                   1606: 
                   1607: sub change_content_javascript {
                   1608:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1609:     if ($env{'browser.type'} eq 'netscape' &&
                   1610: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1611: 	return (<<NETSCAPE4);
                   1612: 	function change(name, content) {
                   1613: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1614: 	    doc.open();
                   1615: 	    doc.write(content);
                   1616: 	    doc.close();
                   1617: 	}
                   1618: NETSCAPE4
                   1619:     } else {
                   1620: 	# Otherwise, we need to use semi-standards-compliant code
                   1621: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1622: 	# is really scary, and every useful browser supports it
                   1623: 	return (<<DOMBASED);
                   1624: 	function change(name, content) {
                   1625: 	    element = document.getElementById(name);
                   1626: 	    element.innerHTML = content;
                   1627: 	}
                   1628: DOMBASED
                   1629:     }
                   1630: }
                   1631: 
                   1632: =pod
                   1633: 
1.648     raeburn  1634: =item * &changable_area($name,$origContent):
1.256     matthew  1635: 
                   1636: This provides a "changable area" that can be modified on the fly via
                   1637: the Javascript code provided in C<change_content_javascript>. $name is
                   1638: the name you will use to reference the area later; do not repeat the
                   1639: same name on a given HTML page more then once. $origContent is what
                   1640: the area will originally contain, which can be left blank.
                   1641: 
                   1642: =cut
                   1643: 
                   1644: sub changable_area {
                   1645:     my ($name, $origContent) = @_;
                   1646: 
1.258     albertel 1647:     if ($env{'browser.type'} eq 'netscape' &&
                   1648: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1649: 	# If this is netscape 4, we need to use the Layer tag
                   1650: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1651:     } else {
                   1652: 	return "<span id='$name'>$origContent</span>";
                   1653:     }
                   1654: }
                   1655: 
                   1656: =pod
                   1657: 
1.648     raeburn  1658: =item * &viewport_geometry_js 
1.590     raeburn  1659: 
                   1660: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1661: 
                   1662: =cut
                   1663: 
                   1664: 
                   1665: sub viewport_geometry_js { 
                   1666:     return <<"GEOMETRY";
                   1667: var Geometry = {};
                   1668: function init_geometry() {
                   1669:     if (Geometry.init) { return };
                   1670:     Geometry.init=1;
                   1671:     if (window.innerHeight) {
                   1672:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1673:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1674:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1675:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1676:     }
                   1677:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1678:         Geometry.getViewportHeight =
                   1679:             function() { return document.documentElement.clientHeight; };
                   1680:         Geometry.getViewportWidth =
                   1681:             function() { return document.documentElement.clientWidth; };
                   1682: 
                   1683:         Geometry.getHorizontalScroll =
                   1684:             function() { return document.documentElement.scrollLeft; };
                   1685:         Geometry.getVerticalScroll =
                   1686:             function() { return document.documentElement.scrollTop; };
                   1687:     }
                   1688:     else if (document.body.clientHeight) {
                   1689:         Geometry.getViewportHeight =
                   1690:             function() { return document.body.clientHeight; };
                   1691:         Geometry.getViewportWidth =
                   1692:             function() { return document.body.clientWidth; };
                   1693:         Geometry.getHorizontalScroll =
                   1694:             function() { return document.body.scrollLeft; };
                   1695:         Geometry.getVerticalScroll =
                   1696:             function() { return document.body.scrollTop; };
                   1697:     }
                   1698: }
                   1699: 
                   1700: GEOMETRY
                   1701: }
                   1702: 
                   1703: =pod
                   1704: 
1.648     raeburn  1705: =item * &viewport_size_js()
1.590     raeburn  1706: 
                   1707: 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. 
                   1708: 
                   1709: =cut
                   1710: 
                   1711: sub viewport_size_js {
                   1712:     my $geometry = &viewport_geometry_js();
                   1713:     return <<"DIMS";
                   1714: 
                   1715: $geometry
                   1716: 
                   1717: function getViewportDims(width,height) {
                   1718:     init_geometry();
                   1719:     width.value = Geometry.getViewportWidth();
                   1720:     height.value = Geometry.getViewportHeight();
                   1721:     return;
                   1722: }
                   1723: 
                   1724: DIMS
                   1725: }
                   1726: 
                   1727: =pod
                   1728: 
1.648     raeburn  1729: =item * &resize_textarea_js()
1.565     albertel 1730: 
                   1731: emits the needed javascript to resize a textarea to be as big as possible
                   1732: 
                   1733: creates a function resize_textrea that takes two IDs first should be
                   1734: the id of the element to resize, second should be the id of a div that
                   1735: surrounds everything that comes after the textarea, this routine needs
                   1736: to be attached to the <body> for the onload and onresize events.
                   1737: 
1.648     raeburn  1738: =back
1.565     albertel 1739: 
                   1740: =cut
                   1741: 
                   1742: sub resize_textarea_js {
1.590     raeburn  1743:     my $geometry = &viewport_geometry_js();
1.565     albertel 1744:     return <<"RESIZE";
                   1745:     <script type="text/javascript">
1.824     bisitz   1746: // <![CDATA[
1.590     raeburn  1747: $geometry
1.565     albertel 1748: 
1.588     albertel 1749: function getX(element) {
                   1750:     var x = 0;
                   1751:     while (element) {
                   1752: 	x += element.offsetLeft;
                   1753: 	element = element.offsetParent;
                   1754:     }
                   1755:     return x;
                   1756: }
                   1757: function getY(element) {
                   1758:     var y = 0;
                   1759:     while (element) {
                   1760: 	y += element.offsetTop;
                   1761: 	element = element.offsetParent;
                   1762:     }
                   1763:     return y;
                   1764: }
                   1765: 
                   1766: 
1.565     albertel 1767: function resize_textarea(textarea_id,bottom_id) {
                   1768:     init_geometry();
                   1769:     var textarea        = document.getElementById(textarea_id);
                   1770:     //alert(textarea);
                   1771: 
1.588     albertel 1772:     var textarea_top    = getY(textarea);
1.565     albertel 1773:     var textarea_height = textarea.offsetHeight;
                   1774:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1775:     var bottom_top      = getY(bottom);
1.565     albertel 1776:     var bottom_height   = bottom.offsetHeight;
                   1777:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1778:     var fudge           = 23;
1.565     albertel 1779:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1780:     if (new_height < 300) {
                   1781: 	new_height = 300;
                   1782:     }
                   1783:     textarea.style.height=new_height+'px';
                   1784: }
1.824     bisitz   1785: // ]]>
1.565     albertel 1786: </script>
                   1787: RESIZE
                   1788: 
                   1789: }
                   1790: 
1.1205    golterma 1791: sub colorfuleditor_js {
1.1248    raeburn  1792:     my $browse_or_search;
                   1793:     my $respath;
                   1794:     my ($cnum,$cdom) = &crsauthor_url();
                   1795:     if ($cnum) {
                   1796:         $respath = "/res/$cdom/$cnum/";
                   1797:         my %js_lt = &Apache::lonlocal::texthash(
                   1798:             sunm => 'Sub-directory name',
                   1799:             save => 'Save page to make this permanent',
                   1800:         );
                   1801:         &js_escape(\%js_lt);
                   1802:         $browse_or_search = <<"END";
                   1803: 
                   1804:     function toggleChooser(form,element,titleid,only,search) {
                   1805:         var disp = 'none';
                   1806:         if (document.getElementById('chooser_'+element)) {
                   1807:             var curr = document.getElementById('chooser_'+element).style.display;
                   1808:             if (curr == 'none') {
                   1809:                 disp='inline';
                   1810:                 if (form.elements['chooser_'+element].length) {
                   1811:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1812:                         form.elements['chooser_'+element][i].checked = false;
                   1813:                     }
                   1814:                 }
                   1815:                 toggleResImport(form,element);
                   1816:             }
                   1817:             document.getElementById('chooser_'+element).style.display = disp;
                   1818:         }
                   1819:     }
                   1820: 
                   1821:     function toggleCrsFile(form,element,numdirs) {
                   1822:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1823:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1824:             if (curr == 'none') {
                   1825:                 if (numdirs) {
                   1826:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1827:                     if (numdirs > 1) {
                   1828:                         window['select1'+element+'_changed']();
                   1829:                     }
                   1830:                 }
                   1831:             } 
                   1832:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1833:             
                   1834:         }
                   1835:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1836:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1837:             if (document.getElementById('uploadcrsres_'+element)) {
                   1838:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1839:             }
                   1840:         }
                   1841:         return;
                   1842:     }
                   1843: 
                   1844:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1845:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1846:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1847:         }
                   1848:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1849:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1850:             if (curr == 'none') {
                   1851:                 if (numcrsdirs) {
                   1852:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1853:                    form.elements['newsubdir_'+element][0].checked = true;
                   1854:                    toggleNewsubdir(form,element);
                   1855:                 }
                   1856:             }
                   1857:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1858:         }
                   1859:         return;
                   1860:     }
                   1861: 
                   1862:     function toggleResImport(form,element) {
                   1863:         var choices = new Array('crsres','upload');
                   1864:         for (var i=0; i<choices.length; i++) {
                   1865:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1866:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1867:             }
                   1868:         }
                   1869:     }
                   1870: 
                   1871:     function toggleNewsubdir(form,element) {
                   1872:         var newsub = form.elements['newsubdir_'+element];
                   1873:         if (newsub) {
                   1874:             if (newsub.length) {
                   1875:                 for (var j=0; j<newsub.length; j++) {
                   1876:                     if (newsub[j].checked) {
                   1877:                         if (document.getElementById('newsubdirname_'+element)) {
                   1878:                             if (newsub[j].value == '1') {
                   1879:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1880:                                 if (document.getElementById('newsubdir_'+element)) {
                   1881:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1882:                                 }
                   1883:                             } else {
                   1884:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1885:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1886:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1887:                             }
                   1888:                         }
                   1889:                         break; 
                   1890:                     }
                   1891:                 }
                   1892:             }
                   1893:         }
                   1894:     }
                   1895: 
                   1896:     function updateCrsFile(form,element) {
                   1897:         var directory = form.elements['coursepath_'+element];
                   1898:         var filename = form.elements['coursefile_'+element];
                   1899:         var path = directory.options[directory.selectedIndex].value;
                   1900:         var file = filename.options[filename.selectedIndex].value;
                   1901:         form.elements[element].value = '$respath';
                   1902:         if (path == '/') {
                   1903:             form.elements[element].value += file;
                   1904:         } else {
                   1905:             form.elements[element].value += path+'/'+file;
                   1906:         }
                   1907:         unClean();
                   1908:         if (document.getElementById('previewimg_'+element)) {
                   1909:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1910:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1911:         }
                   1912:         if (document.getElementById('showimg_'+element)) {
                   1913:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1914:         }
                   1915:         toggleChooser(form,element);
                   1916:         return;
                   1917:     }
                   1918: 
                   1919:     function uploadDone(suffix,name) {
                   1920:         if (name) {
                   1921: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1922:             unClean();
                   1923:             toggleChooser(document.forms["lonhomework"],suffix);
                   1924:         }
                   1925:     }
                   1926: 
                   1927: \$(document).ready(function(){
                   1928: 
                   1929:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1930:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1931:             var buttonId = this.id;
                   1932:             var suffix = buttonId.toString();
                   1933:             suffix = suffix.replace(/^crsupload_/,'');
                   1934:             event.preventDefault();
                   1935:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1936:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1937:             \$(this.form).submit();
                   1938:             document.lonhomework.target = '';
                   1939:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1940:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1941:             }
                   1942:             return false;
                   1943:         }
                   1944:     });
                   1945: });
                   1946: END
                   1947:     }
1.1205    golterma 1948:     return <<"COLORFULEDIT"
                   1949: <script type="text/javascript">
                   1950: // <![CDATA[>
                   1951:     function fold_box(curDepth, lastresource){
                   1952: 
                   1953:     // we need a list because there can be several blocks you need to fold in one tag
                   1954:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1955:     // but there is only one folding button per tag
                   1956:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1957: 
                   1958:         if(block.item(0).style.display == 'none'){
                   1959: 
                   1960:             foldbutton.value = '@{[&mt("Hide")]}';
                   1961:             for (i = 0; i < block.length; i++){
                   1962:                 block.item(i).style.display = '';
                   1963:             }
                   1964:         }else{
                   1965: 
                   1966:             foldbutton.value = '@{[&mt("Show")]}';
                   1967:             for (i = 0; i < block.length; i++){
                   1968:                 // block.item(i).style.visibility = 'collapse';
                   1969:                 block.item(i).style.display = 'none';
                   1970:             }
                   1971:         };
                   1972:         saveState(lastresource);
                   1973:     }
                   1974: 
                   1975:     function saveState (lastresource) {
                   1976: 
                   1977:         var tag_list = getTagList();
                   1978:         if(tag_list != null){
                   1979:             var timestamp = new Date().getTime();
                   1980:             var key = lastresource;
                   1981: 
                   1982:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1983:             // starting with timestamp
                   1984:             var value = timestamp+';';
                   1985: 
                   1986:             // building the list of key-value pairs
                   1987:             for(var i = 0; i < tag_list.length; i++){
                   1988:                 value += tag_list[i]+',';
                   1989:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1990:             }
                   1991: 
                   1992:             // only iterate whole storage if nothing to override
                   1993:             if(localStorage.getItem(key) == null){        
                   1994: 
                   1995:                 // prevent storage from growing large
                   1996:                 if(localStorage.length > 50){
                   1997:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1998:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1999:                     var oldest_key;
                   2000:                     
                   2001:                     for(var i = 1; i < localStorage.length; i++){
                   2002:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2003:                             oldest_key = localStorage.key(i);
                   2004:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2005:                         }
                   2006:                     }
                   2007:                     localStorage.removeItem(oldest_key);
                   2008:                 }
                   2009:             }
                   2010:             localStorage.setItem(key,value);
                   2011:         }
                   2012:     }
                   2013: 
                   2014:     // restore folding status of blocks (on page load)
                   2015:     function restoreState (lastresource) {
                   2016:         if(localStorage.getItem(lastresource) != null){
                   2017:             var key = lastresource;
                   2018:             var value = localStorage.getItem(key);
                   2019:             var regex_delTimestamp = /^\d+;/;
                   2020: 
                   2021:             value.replace(regex_delTimestamp, '');
                   2022: 
                   2023:             var valueArr = value.split(';');
                   2024:             var pairs;
                   2025:             var elements;
                   2026:             for (var i = 0; i < valueArr.length; i++){
                   2027:                 pairs = valueArr[i].split(',');
                   2028:                 elements = document.getElementsByName(pairs[0]);
                   2029: 
                   2030:                 for (var j = 0; j < elements.length; j++){  
                   2031:                     elements[j].style.display = pairs[1];
                   2032:                     if (pairs[1] == "none"){
                   2033:                         var regex_id = /([_\\d]+)\$/;
                   2034:                         regex_id.exec(pairs[0]);
                   2035:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2036:                     }
                   2037:                 }
                   2038:             }
                   2039:         }
                   2040:     }
                   2041: 
                   2042:     function getTagList () {
                   2043:         
                   2044:         var stringToSearch = document.lonhomework.innerHTML;
                   2045: 
                   2046:         var ret = new Array();
                   2047:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2048:         var tag_list = stringToSearch.match(regex_findBlock);
                   2049: 
                   2050:         if(tag_list != null){
                   2051:             for(var i = 0; i < tag_list.length; i++){            
                   2052:                 ret.push(tag_list[i].replace(/"/, ''));
                   2053:             }
                   2054:         }
                   2055:         return ret;
                   2056:     }
                   2057: 
                   2058:     function saveScrollPosition (resource) {
                   2059:         var tag_list = getTagList();
                   2060: 
                   2061:         // we dont always want to jump to the first block
                   2062:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2063:         if(\$(window).scrollTop() > 170){
                   2064:             if(tag_list != null){
                   2065:                 var result;
                   2066:                 for(var i = 0; i < tag_list.length; i++){
                   2067:                     if(isElementInViewport(tag_list[i])){
                   2068:                         result += tag_list[i]+';';
                   2069:                     }
                   2070:                 }
                   2071:                 sessionStorage.setItem('anchor_'+resource, result);
                   2072:             }
                   2073:         } else {
                   2074:             // we dont need to save zero, just delete the item to leave everything tidy
                   2075:             sessionStorage.removeItem('anchor_'+resource);
                   2076:         }
                   2077:     }
                   2078: 
                   2079:     function restoreScrollPosition(resource){
                   2080: 
                   2081:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2082:         if(elem != null){
                   2083:             var tag_list = elem.split(';');
                   2084:             var elem_list;
                   2085: 
                   2086:             for(var i = 0; i < tag_list.length; i++){
                   2087:                 elem_list = document.getElementsByName(tag_list[i]);
                   2088:                 
                   2089:                 if(elem_list.length > 0){
                   2090:                     elem = elem_list[0];
                   2091:                     break;
                   2092:                 }
                   2093:             }
                   2094:             elem.scrollIntoView();
                   2095:         }
                   2096:     }
                   2097: 
                   2098:     function isElementInViewport(el) {
                   2099: 
                   2100:         // change to last element instead of first
                   2101:         var elem = document.getElementsByName(el);
                   2102:         var rect = elem[0].getBoundingClientRect();
                   2103: 
                   2104:         return (
                   2105:             rect.top >= 0 &&
                   2106:             rect.left >= 0 &&
                   2107:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2108:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2109:         );
                   2110:     }
                   2111:     
                   2112:     function autosize(depth){
                   2113:         var cmInst = window['cm'+depth];
                   2114:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2115: 
                   2116:         // is fixed size, switching to dynamic
                   2117:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2118:             cmInst.setSize("","auto");
                   2119:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2120:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2121: 
                   2122:         // is dynamic size, switching to fixed
                   2123:         } else {
                   2124:             cmInst.setSize("","300px");
                   2125:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2126:             sessionStorage.removeItem("autosized_"+depth);
                   2127:         }
                   2128:     }
                   2129: 
1.1248    raeburn  2130: $browse_or_search
1.1205    golterma 2131: 
                   2132: // ]]>
                   2133: </script>
                   2134: COLORFULEDIT
                   2135: }
                   2136: 
                   2137: sub xmleditor_js {
                   2138:     return <<XMLEDIT
                   2139: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2140: <script type="text/javascript">
                   2141: // <![CDATA[>
                   2142: 
                   2143:     function saveScrollPosition (resource) {
                   2144: 
                   2145:         var scrollPos = \$(window).scrollTop();
                   2146:         sessionStorage.setItem(resource,scrollPos);
                   2147:     }
                   2148: 
                   2149:     function restoreScrollPosition(resource){
                   2150: 
                   2151:         var scrollPos = sessionStorage.getItem(resource);
                   2152:         \$(window).scrollTop(scrollPos);
                   2153:     }
                   2154: 
                   2155:     // unless internet explorer
                   2156:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2157: 
                   2158:         \$(document).ready(function() {
                   2159:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2160:         });
                   2161:     }
                   2162: 
                   2163:     // inserts text at cursor position into codemirror (xml editor only)
                   2164:     function insertText(text){
                   2165:         cm.focus();
                   2166:         var curPos = cm.getCursor();
                   2167:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2168:     }
                   2169: // ]]>
                   2170: </script>
                   2171: XMLEDIT
                   2172: }
                   2173: 
                   2174: sub insert_folding_button {
                   2175:     my $curDepth = $Apache::lonxml::curdepth;
                   2176:     my $lastresource = $env{'request.ambiguous'};
                   2177: 
                   2178:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2179:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2180: }
                   2181: 
1.1248    raeburn  2182: sub crsauthor_url {
                   2183:     my ($url) = @_;
                   2184:     if ($url eq '') {
                   2185:         $url = $ENV{'REQUEST_URI'};
                   2186:     }
                   2187:     my ($cnum,$cdom);
                   2188:     if ($env{'request.course.id'}) {
                   2189:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2190:         if ($audom ne '' && $auname ne '') {
                   2191:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2192:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2193:                 $cnum = $auname;
                   2194:                 $cdom = $audom;
                   2195:             }
                   2196:         }
                   2197:     }
                   2198:     return ($cnum,$cdom);
                   2199: }
                   2200: 
                   2201: sub import_crsauthor_form {
1.1265    raeburn  2202:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2203:     return (0) unless ($env{'request.course.id'});
                   2204:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2205:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2206:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2207:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2208:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2209:     my @ids=&Apache::lonnet::current_machine_ids();
                   2210:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2211:     
                   2212:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2213:         $is_home = 1;
                   2214:     }
                   2215:     $relpath = "/priv/$cdom/$cnum";
                   2216:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2217:     my %lt = &Apache::lonlocal::texthash (
                   2218:         fnam => 'Filename',
                   2219:         dire => 'Directory',
                   2220:     );
                   2221:     my $numdirs = scalar(keys(%files));
                   2222:     my (%possexts,$singledir,@singledirfiles);
                   2223:     if ($only) {
                   2224:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2225:     }
                   2226:     my (%nonemptydirs,$possdirs);
                   2227:     if ($numdirs > 1) {
                   2228:         my @order;
                   2229:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2230:             if (ref($files{$key}) eq 'HASH') {
                   2231:                 my $shown = $key;
                   2232:                 if ($key eq '') {
                   2233:                     $shown = '/';
                   2234:                 }
                   2235:                 my @ordered = ();
                   2236:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2237:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2238:                     if ($only) {
                   2239:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2240:                         unless ($possexts{lc($ext)}) {
                   2241:                             next;
                   2242:                         }
                   2243:                     }
                   2244:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2245:                     push(@ordered,$file);
                   2246:                 }
                   2247:                 if (@ordered) {
                   2248:                     push(@order,$key);
                   2249:                     $nonemptydirs{$key} = 1;
                   2250:                     $selimport_menus{$key}->{'text'} = $shown;
                   2251:                     $selimport_menus{$key}->{'default'} = '';
                   2252:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2253:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2254:                 }
                   2255:             }
                   2256:         }
                   2257:         $possdirs = scalar(keys(%nonemptydirs));
                   2258:         if ($possdirs > 1) {
                   2259:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2260:             $output = $lt{'dire'}.
                   2261:                       &linked_select_forms($form,'<br />'.
                   2262:                                            $lt{'fnam'},'',
                   2263:                                            $firstselectname,$secondselectname,
                   2264:                                            \%selimport_menus,\@order,
                   2265:                                            $onchangefirst,'',$suffix).'<br />';
                   2266:         } elsif ($possdirs == 1) {
                   2267:             $singledir = (keys(%nonemptydirs))[0];
                   2268:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2269:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2270:             }
                   2271:             delete($selimport_menus{$singledir});
                   2272:         }
                   2273:     } elsif ($numdirs == 1) {
                   2274:         $singledir = (keys(%files))[0];
                   2275:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2276:             if ($only) {
                   2277:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2278:                 unless ($possexts{lc($ext)}) {
                   2279:                     next;
                   2280:                 }
1.1315    raeburn  2281:             } else {
                   2282:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2283:             }
                   2284:             push(@singledirfiles,$file);
                   2285:         }
                   2286:         if (@singledirfiles) {
1.1315    raeburn  2287:             $possdirs = 1;
1.1248    raeburn  2288:         }
                   2289:     }
                   2290:     if (($possdirs == 1) && (@singledirfiles)) {
                   2291:         my $showdir = $singledir;
                   2292:         if ($singledir eq '') {
                   2293:             $showdir = '/';
                   2294:         }
                   2295:         $output = $lt{'dire'}.
                   2296:                   '<select name="'.$firstselectname.'">'.
                   2297:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2298:                   '</select><br />'.
                   2299:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2300:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2301:         foreach my $file (@singledirfiles) {
                   2302:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2303:         }
                   2304:         $output .= '</select><br />'."\n";
                   2305:     }
                   2306:     return ($possdirs,$output);
                   2307: }
                   2308: 
1.565     albertel 2309: =pod
                   2310: 
1.256     matthew  2311: =head1 Excel and CSV file utility routines
                   2312: 
                   2313: =cut
                   2314: 
                   2315: ###############################################################
                   2316: ###############################################################
                   2317: 
                   2318: =pod
                   2319: 
1.1162    raeburn  2320: =over 4
                   2321: 
1.648     raeburn  2322: =item * &csv_translate($text) 
1.37      matthew  2323: 
1.185     www      2324: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2325: format.
                   2326: 
                   2327: =cut
                   2328: 
1.180     matthew  2329: ###############################################################
                   2330: ###############################################################
1.37      matthew  2331: sub csv_translate {
                   2332:     my $text = shift;
                   2333:     $text =~ s/\"/\"\"/g;
1.209     albertel 2334:     $text =~ s/\n/ /g;
1.37      matthew  2335:     return $text;
                   2336: }
1.180     matthew  2337: 
                   2338: ###############################################################
                   2339: ###############################################################
                   2340: 
                   2341: =pod
                   2342: 
1.648     raeburn  2343: =item * &define_excel_formats()
1.180     matthew  2344: 
                   2345: Define some commonly used Excel cell formats.
                   2346: 
                   2347: Currently supported formats:
                   2348: 
                   2349: =over 4
                   2350: 
                   2351: =item header
                   2352: 
                   2353: =item bold
                   2354: 
                   2355: =item h1
                   2356: 
                   2357: =item h2
                   2358: 
                   2359: =item h3
                   2360: 
1.256     matthew  2361: =item h4
                   2362: 
                   2363: =item i
                   2364: 
1.180     matthew  2365: =item date
                   2366: 
                   2367: =back
                   2368: 
                   2369: Inputs: $workbook
                   2370: 
                   2371: Returns: $format, a hash reference.
                   2372: 
1.1057    foxr     2373: 
1.180     matthew  2374: =cut
                   2375: 
                   2376: ###############################################################
                   2377: ###############################################################
                   2378: sub define_excel_formats {
                   2379:     my ($workbook) = @_;
                   2380:     my $format;
                   2381:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2382:                                                 bottom    => 1,
                   2383:                                                 align     => 'center');
                   2384:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2385:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2386:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2387:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2388:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2389:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2390:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2391:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2392:     return $format;
                   2393: }
                   2394: 
                   2395: ###############################################################
                   2396: ###############################################################
1.113     bowersj2 2397: 
                   2398: =pod
                   2399: 
1.648     raeburn  2400: =item * &create_workbook()
1.255     matthew  2401: 
                   2402: Create an Excel worksheet.  If it fails, output message on the
                   2403: request object and return undefs.
                   2404: 
                   2405: Inputs: Apache request object
                   2406: 
                   2407: Returns (undef) on failure, 
                   2408:     Excel worksheet object, scalar with filename, and formats 
                   2409:     from &Apache::loncommon::define_excel_formats on success
                   2410: 
                   2411: =cut
                   2412: 
                   2413: ###############################################################
                   2414: ###############################################################
                   2415: sub create_workbook {
                   2416:     my ($r) = @_;
                   2417:         #
                   2418:     # Create the excel spreadsheet
                   2419:     my $filename = '/prtspool/'.
1.258     albertel 2420:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2421:         time.'_'.rand(1000000000).'.xls';
                   2422:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2423:     if (! defined($workbook)) {
                   2424:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2425:         $r->print(
                   2426:             '<p class="LC_error">'
                   2427:            .&mt('Problems occurred in creating the new Excel file.')
                   2428:            .' '.&mt('This error has been logged.')
                   2429:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2430:            .'</p>'
                   2431:         );
1.255     matthew  2432:         return (undef);
                   2433:     }
                   2434:     #
1.1014    foxr     2435:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2436:     #
                   2437:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2438:     return ($workbook,$filename,$format);
                   2439: }
                   2440: 
                   2441: ###############################################################
                   2442: ###############################################################
                   2443: 
                   2444: =pod
                   2445: 
1.648     raeburn  2446: =item * &create_text_file()
1.113     bowersj2 2447: 
1.542     raeburn  2448: Create a file to write to and eventually make available to the user.
1.256     matthew  2449: If file creation fails, outputs an error message on the request object and 
                   2450: return undefs.
1.113     bowersj2 2451: 
1.256     matthew  2452: Inputs: Apache request object, and file suffix
1.113     bowersj2 2453: 
1.256     matthew  2454: Returns (undef) on failure, 
                   2455:     Filehandle and filename on success.
1.113     bowersj2 2456: 
                   2457: =cut
                   2458: 
1.256     matthew  2459: ###############################################################
                   2460: ###############################################################
                   2461: sub create_text_file {
                   2462:     my ($r,$suffix) = @_;
                   2463:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2464:     my $fh;
                   2465:     my $filename = '/prtspool/'.
1.258     albertel 2466:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2467:         time.'_'.rand(1000000000).'.'.$suffix;
                   2468:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2469:     if (! defined($fh)) {
                   2470:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2471:         $r->print(
                   2472:             '<p class="LC_error">'
                   2473:            .&mt('Problems occurred in creating the output file.')
                   2474:            .' '.&mt('This error has been logged.')
                   2475:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2476:            .'</p>'
                   2477:         );
1.113     bowersj2 2478:     }
1.256     matthew  2479:     return ($fh,$filename)
1.113     bowersj2 2480: }
                   2481: 
                   2482: 
1.256     matthew  2483: =pod 
1.113     bowersj2 2484: 
                   2485: =back
                   2486: 
                   2487: =cut
1.37      matthew  2488: 
                   2489: ###############################################################
1.33      matthew  2490: ##        Home server <option> list generating code          ##
                   2491: ###############################################################
1.35      matthew  2492: 
1.169     www      2493: # ------------------------------------------
                   2494: 
                   2495: sub domain_select {
1.1289    raeburn  2496:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2497:     my @possdoms;
                   2498:     if (ref($incdoms) eq 'ARRAY') {
                   2499:         @possdoms = @{$incdoms};
                   2500:     } else {
                   2501:         @possdoms = &Apache::lonnet::all_domains();
                   2502:     }
                   2503: 
1.169     www      2504:     my %domains=map { 
1.514     albertel 2505: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2506:     } @possdoms;
                   2507: 
                   2508:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2509:         foreach my $dom (@{$excdoms}) {
                   2510:             delete($domains{$dom});
                   2511:         }
                   2512:     }
                   2513: 
1.169     www      2514:     if ($multiple) {
                   2515: 	$domains{''}=&mt('Any domain');
1.550     albertel 2516: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2517: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2518:     } else {
1.550     albertel 2519: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2520: 	return &select_form($name,$value,\%domains);
1.169     www      2521:     }
                   2522: }
                   2523: 
1.282     albertel 2524: #-------------------------------------------
                   2525: 
                   2526: =pod
                   2527: 
1.519     raeburn  2528: =head1 Routines for form select boxes
                   2529: 
                   2530: =over 4
                   2531: 
1.648     raeburn  2532: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2533: 
                   2534: Returns a string containing a <select> element int multiple mode
                   2535: 
                   2536: 
                   2537: Args:
                   2538:   $name - name of the <select> element
1.506     raeburn  2539:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2540:   $size - number of rows long the select element is
1.283     albertel 2541:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2542:           (shown text should already have been &mt())
1.506     raeburn  2543:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2544: 
1.282     albertel 2545: =cut
                   2546: 
                   2547: #-------------------------------------------
1.169     www      2548: sub multiple_select_form {
1.284     albertel 2549:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2550:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2551:     my $output='';
1.191     matthew  2552:     if (! defined($size)) {
                   2553:         $size = 4;
1.283     albertel 2554:         if (scalar(keys(%$hash))<4) {
                   2555:             $size = scalar(keys(%$hash));
1.191     matthew  2556:         }
                   2557:     }
1.734     bisitz   2558:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2559:     my @order;
1.506     raeburn  2560:     if (ref($order) eq 'ARRAY')  {
                   2561:         @order = @{$order};
                   2562:     } else {
                   2563:         @order = sort(keys(%$hash));
1.501     banghart 2564:     }
                   2565:     if (exists($$hash{'select_form_order'})) {
                   2566:         @order = @{$$hash{'select_form_order'}};
                   2567:     }
                   2568:         
1.284     albertel 2569:     foreach my $key (@order) {
1.356     albertel 2570:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2571:         $output.='selected="selected" ' if ($selected{$key});
                   2572:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2573:     }
                   2574:     $output.="</select>\n";
                   2575:     return $output;
                   2576: }
                   2577: 
1.88      www      2578: #-------------------------------------------
                   2579: 
                   2580: =pod
                   2581: 
1.1254    raeburn  2582: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2583: 
                   2584: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2585: allow a user to select options from a ref to a hash containing:
                   2586: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2587: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2588: An optional arg -- $readonly -- if true will cause the select form
                   2589: to be disabled, e.g., for the case where an instructor has a section-
                   2590: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2591: 
1.88      www      2592: See lonrights.pm for an example invocation and use.
                   2593: 
                   2594: =cut
                   2595: 
                   2596: #-------------------------------------------
                   2597: sub select_form {
1.1228    raeburn  2598:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2599:     return unless (ref($hashref) eq 'HASH');
                   2600:     if ($onchange) {
                   2601:         $onchange = ' onchange="'.$onchange.'"';
                   2602:     }
1.1228    raeburn  2603:     my $disabled;
                   2604:     if ($readonly) {
                   2605:         $disabled = ' disabled="disabled"';
                   2606:     }
                   2607:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2608:     my @keys;
1.970     raeburn  2609:     if (exists($hashref->{'select_form_order'})) {
                   2610: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2611:     } else {
1.970     raeburn  2612: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2613:     }
1.356     albertel 2614:     foreach my $key (@keys) {
                   2615:         $selectform.=
                   2616: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2617:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2618:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2619:     }
                   2620:     $selectform.="</select>";
                   2621:     return $selectform;
                   2622: }
                   2623: 
1.475     www      2624: # For display filters
                   2625: 
                   2626: sub display_filter {
1.1074    raeburn  2627:     my ($context) = @_;
1.475     www      2628:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2629:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2630:     my $phraseinput = 'hidden';
                   2631:     my $includeinput = 'hidden';
                   2632:     my ($checked,$includetypestext);
                   2633:     if ($env{'form.displayfilter'} eq 'containing') {
                   2634:         $phraseinput = 'text'; 
                   2635:         if ($context eq 'parmslog') {
                   2636:             $includeinput = 'checkbox';
                   2637:             if ($env{'form.includetypes'}) {
                   2638:                 $checked = ' checked="checked"';
                   2639:             }
                   2640:             $includetypestext = &mt('Include parameter types');
                   2641:         }
                   2642:     } else {
                   2643:         $includetypestext = '&nbsp;';
                   2644:     }
                   2645:     my ($additional,$secondid,$thirdid);
                   2646:     if ($context eq 'parmslog') {
                   2647:         $additional = 
                   2648:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2649:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2650:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2651:             '</label>';
                   2652:         $secondid = 'includetypes';
                   2653:         $thirdid = 'includetypestext';
                   2654:     }
                   2655:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2656:                                                     '$secondid','$thirdid')";
                   2657:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2658: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2659: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2660: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2661:            &mt('Filter: [_1]',
1.477     www      2662: 	   &select_form($env{'form.displayfilter'},
                   2663: 			'displayfilter',
1.970     raeburn  2664: 			{'currentfolder' => 'Current folder/page',
1.477     www      2665: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2666: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2667: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2668:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2669:                          '" />'.$additional;
                   2670: }
                   2671: 
                   2672: sub display_filter_js {
                   2673:     my $includetext = &mt('Include parameter types');
                   2674:     return <<"ENDJS";
                   2675:   
                   2676: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2677:     var firstType = 'hidden';
                   2678:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2679:         firstType = 'text';
                   2680:     }
                   2681:     firstObject = document.getElementById(firstid);
                   2682:     if (typeof(firstObject) == 'object') {
                   2683:         if (firstObject.type != firstType) {
                   2684:             changeInputType(firstObject,firstType);
                   2685:         }
                   2686:     }
                   2687:     if (context == 'parmslog') {
                   2688:         var secondType = 'hidden';
                   2689:         if (firstType == 'text') {
                   2690:             secondType = 'checkbox';
                   2691:         }
                   2692:         secondObject = document.getElementById(secondid);  
                   2693:         if (typeof(secondObject) == 'object') {
                   2694:             if (secondObject.type != secondType) {
                   2695:                 changeInputType(secondObject,secondType);
                   2696:             }
                   2697:         }
                   2698:         var textItem = document.getElementById(thirdid);
                   2699:         var currtext = textItem.innerHTML;
                   2700:         var newtext;
                   2701:         if (firstType == 'text') {
                   2702:             newtext = '$includetext';
                   2703:         } else {
                   2704:             newtext = '&nbsp;';
                   2705:         }
                   2706:         if (currtext != newtext) {
                   2707:             textItem.innerHTML = newtext;
                   2708:         }
                   2709:     }
                   2710:     return;
                   2711: }
                   2712: 
                   2713: function changeInputType(oldObject,newType) {
                   2714:     var newObject = document.createElement('input');
                   2715:     newObject.type = newType;
                   2716:     if (oldObject.size) {
                   2717:         newObject.size = oldObject.size;
                   2718:     }
                   2719:     if (oldObject.value) {
                   2720:         newObject.value = oldObject.value;
                   2721:     }
                   2722:     if (oldObject.name) {
                   2723:         newObject.name = oldObject.name;
                   2724:     }
                   2725:     if (oldObject.id) {
                   2726:         newObject.id = oldObject.id;
                   2727:     }
                   2728:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2729:     return;
                   2730: }
                   2731: 
                   2732: ENDJS
1.475     www      2733: }
                   2734: 
1.167     www      2735: sub gradeleveldescription {
                   2736:     my $gradelevel=shift;
                   2737:     my %gradelevels=(0 => 'Not specified',
                   2738: 		     1 => 'Grade 1',
                   2739: 		     2 => 'Grade 2',
                   2740: 		     3 => 'Grade 3',
                   2741: 		     4 => 'Grade 4',
                   2742: 		     5 => 'Grade 5',
                   2743: 		     6 => 'Grade 6',
                   2744: 		     7 => 'Grade 7',
                   2745: 		     8 => 'Grade 8',
                   2746: 		     9 => 'Grade 9',
                   2747: 		     10 => 'Grade 10',
                   2748: 		     11 => 'Grade 11',
                   2749: 		     12 => 'Grade 12',
                   2750: 		     13 => 'Grade 13',
                   2751: 		     14 => '100 Level',
                   2752: 		     15 => '200 Level',
                   2753: 		     16 => '300 Level',
                   2754: 		     17 => '400 Level',
                   2755: 		     18 => 'Graduate Level');
                   2756:     return &mt($gradelevels{$gradelevel});
                   2757: }
                   2758: 
1.163     www      2759: sub select_level_form {
                   2760:     my ($deflevel,$name)=@_;
                   2761:     unless ($deflevel) { $deflevel=0; }
1.167     www      2762:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2763:     for (my $i=0; $i<=18; $i++) {
                   2764:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2765:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2766:                 ">".&gradeleveldescription($i)."</option>\n";
                   2767:     }
                   2768:     $selectform.="</select>";
                   2769:     return $selectform;
1.163     www      2770: }
1.167     www      2771: 
1.35      matthew  2772: #-------------------------------------------
                   2773: 
1.45      matthew  2774: =pod
                   2775: 
1.1256    raeburn  2776: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2777: 
                   2778: Returns a string containing a <select name='$name' size='1'> form to 
                   2779: allow a user to select the domain to preform an operation in.  
                   2780: See loncreateuser.pm for an example invocation and use.
                   2781: 
1.90      www      2782: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2783: selected");
                   2784: 
1.743     raeburn  2785: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2786: 
1.910     raeburn  2787: 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.
                   2788: 
1.1121    raeburn  2789: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2790: 
                   2791: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2792: 
1.1256    raeburn  2793: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2794: 
1.35      matthew  2795: =cut
                   2796: 
                   2797: #-------------------------------------------
1.34      matthew  2798: sub select_dom_form {
1.1256    raeburn  2799:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2800:     if ($onchange) {
1.874     raeburn  2801:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2802:     }
1.1256    raeburn  2803:     if ($disabled) {
                   2804:         $disabled = ' disabled="disabled"';
                   2805:     }
1.1121    raeburn  2806:     my (@domains,%exclude);
1.910     raeburn  2807:     if (ref($incdoms) eq 'ARRAY') {
                   2808:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2809:     } else {
                   2810:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2811:     }
1.90      www      2812:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2813:     if (ref($excdoms) eq 'ARRAY') {
                   2814:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2815:     }
1.1256    raeburn  2816:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2817:     foreach my $dom (@domains) {
1.1121    raeburn  2818:         next if ($exclude{$dom});
1.356     albertel 2819:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2820:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2821:         if ($showdomdesc) {
                   2822:             if ($dom ne '') {
                   2823:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2824:                 if ($domdesc ne '') {
                   2825:                     $selectdomain .= ' ('.$domdesc.')';
                   2826:                 }
                   2827:             } 
                   2828:         }
                   2829:         $selectdomain .= "</option>\n";
1.34      matthew  2830:     }
                   2831:     $selectdomain.="</select>";
                   2832:     return $selectdomain;
                   2833: }
                   2834: 
1.35      matthew  2835: #-------------------------------------------
                   2836: 
1.45      matthew  2837: =pod
                   2838: 
1.648     raeburn  2839: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2840: 
1.586     raeburn  2841: input: 4 arguments (two required, two optional) - 
                   2842:     $domain - domain of new user
                   2843:     $name - name of form element
                   2844:     $default - Value of 'default' causes a default item to be first 
                   2845:                             option, and selected by default. 
                   2846:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2847:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2848: output: returns 2 items: 
1.586     raeburn  2849: (a) form element which contains either:
                   2850:    (i) <select name="$name">
                   2851:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2852:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2853:        </select>
                   2854:        form item if there are multiple library servers in $domain, or
                   2855:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2856:        if there is only one library server in $domain.
                   2857: 
                   2858: (b) number of library servers found.
                   2859: 
                   2860: See loncreateuser.pm for example of use.
1.35      matthew  2861: 
                   2862: =cut
                   2863: 
                   2864: #-------------------------------------------
1.586     raeburn  2865: sub home_server_form_item {
                   2866:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2867:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2868:     my $result;
                   2869:     my $numlib = keys(%servers);
                   2870:     if ($numlib > 1) {
                   2871:         $result .= '<select name="'.$name.'" />'."\n";
                   2872:         if ($default) {
1.804     bisitz   2873:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2874:                        '</option>'."\n";
                   2875:         }
                   2876:         foreach my $hostid (sort(keys(%servers))) {
                   2877:             $result.= '<option value="'.$hostid.'">'.
                   2878: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2879:         }
                   2880:         $result .= '</select>'."\n";
                   2881:     } elsif ($numlib == 1) {
                   2882:         my $hostid;
                   2883:         foreach my $item (keys(%servers)) {
                   2884:             $hostid = $item;
                   2885:         }
                   2886:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2887:                    $hostid.'" />';
                   2888:                    if (!$hide) {
                   2889:                        $result .= $hostid.' '.$servers{$hostid};
                   2890:                    }
                   2891:                    $result .= "\n";
                   2892:     } elsif ($default) {
                   2893:         $result .= '<input type="hidden" name="'.$name.
                   2894:                    '" value="default" />';
                   2895:                    if (!$hide) {
                   2896:                        $result .= &mt('default');
                   2897:                    }
                   2898:                    $result .= "\n";
1.33      matthew  2899:     }
1.586     raeburn  2900:     return ($result,$numlib);
1.33      matthew  2901: }
1.112     bowersj2 2902: 
                   2903: =pod
                   2904: 
1.534     albertel 2905: =back 
                   2906: 
1.112     bowersj2 2907: =cut
1.87      matthew  2908: 
                   2909: ###############################################################
1.112     bowersj2 2910: ##                  Decoding User Agent                      ##
1.87      matthew  2911: ###############################################################
                   2912: 
                   2913: =pod
                   2914: 
1.112     bowersj2 2915: =head1 Decoding the User Agent
                   2916: 
                   2917: =over 4
                   2918: 
                   2919: =item * &decode_user_agent()
1.87      matthew  2920: 
                   2921: Inputs: $r
                   2922: 
                   2923: Outputs:
                   2924: 
                   2925: =over 4
                   2926: 
1.112     bowersj2 2927: =item * $httpbrowser
1.87      matthew  2928: 
1.112     bowersj2 2929: =item * $clientbrowser
1.87      matthew  2930: 
1.112     bowersj2 2931: =item * $clientversion
1.87      matthew  2932: 
1.112     bowersj2 2933: =item * $clientmathml
1.87      matthew  2934: 
1.112     bowersj2 2935: =item * $clientunicode
1.87      matthew  2936: 
1.112     bowersj2 2937: =item * $clientos
1.87      matthew  2938: 
1.1137    raeburn  2939: =item * $clientmobile
                   2940: 
1.1141    raeburn  2941: =item * $clientinfo
                   2942: 
1.1194    raeburn  2943: =item * $clientosversion
                   2944: 
1.87      matthew  2945: =back
                   2946: 
1.157     matthew  2947: =back 
                   2948: 
1.87      matthew  2949: =cut
                   2950: 
                   2951: ###############################################################
                   2952: ###############################################################
                   2953: sub decode_user_agent {
1.247     albertel 2954:     my ($r)=@_;
1.87      matthew  2955:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2956:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2957:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2958:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2959:     my $clientbrowser='unknown';
                   2960:     my $clientversion='0';
                   2961:     my $clientmathml='';
                   2962:     my $clientunicode='0';
1.1137    raeburn  2963:     my $clientmobile=0;
1.1194    raeburn  2964:     my $clientosversion='';
1.87      matthew  2965:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2966:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2967: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2968: 	    $clientbrowser=$bname;
                   2969:             $httpbrowser=~/$vreg/i;
                   2970: 	    $clientversion=$1;
                   2971:             $clientmathml=($clientversion>=$minv);
                   2972:             $clientunicode=($clientversion>=$univ);
                   2973: 	}
                   2974:     }
                   2975:     my $clientos='unknown';
1.1141    raeburn  2976:     my $clientinfo;
1.87      matthew  2977:     if (($httpbrowser=~/linux/i) ||
                   2978:         ($httpbrowser=~/unix/i) ||
                   2979:         ($httpbrowser=~/ux/i) ||
                   2980:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2981:     if (($httpbrowser=~/vax/i) ||
                   2982:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2983:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2984:     if (($httpbrowser=~/mac/i) ||
                   2985:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2986:     if ($httpbrowser=~/win/i) {
                   2987:         $clientos='win';
                   2988:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2989:             $clientosversion = $1;
                   2990:         }
                   2991:     }
1.87      matthew  2992:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2993:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2994:         $clientmobile=lc($1);
                   2995:     }
1.1141    raeburn  2996:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2997:         $clientinfo = 'firefox-'.$1;
                   2998:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2999:         $clientinfo = 'chromeframe-'.$1;
                   3000:     }
1.87      matthew  3001:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3002:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3003:             $clientosversion);
1.87      matthew  3004: }
                   3005: 
1.32      matthew  3006: ###############################################################
                   3007: ##    Authentication changing form generation subroutines    ##
                   3008: ###############################################################
                   3009: ##
                   3010: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3011: ## hash, and have reasonable default values.
                   3012: ##
                   3013: ##    formname = the name given in the <form> tag.
1.35      matthew  3014: #-------------------------------------------
                   3015: 
1.45      matthew  3016: =pod
                   3017: 
1.112     bowersj2 3018: =head1 Authentication Routines
                   3019: 
                   3020: =over 4
                   3021: 
1.648     raeburn  3022: =item * &authform_xxxxxx()
1.35      matthew  3023: 
                   3024: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3025: handle some of the conveniences required for authentication forms.  
                   3026: This is not an optimal method, but it works.  
                   3027: 
                   3028: =over 4
                   3029: 
1.112     bowersj2 3030: =item * authform_header
1.35      matthew  3031: 
1.112     bowersj2 3032: =item * authform_authorwarning
1.35      matthew  3033: 
1.112     bowersj2 3034: =item * authform_nochange
1.35      matthew  3035: 
1.112     bowersj2 3036: =item * authform_kerberos
1.35      matthew  3037: 
1.112     bowersj2 3038: =item * authform_internal
1.35      matthew  3039: 
1.112     bowersj2 3040: =item * authform_filesystem
1.35      matthew  3041: 
1.1310    raeburn  3042: =item * authform_lti
                   3043: 
1.35      matthew  3044: =back
                   3045: 
1.648     raeburn  3046: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3047: 
1.35      matthew  3048: =cut
                   3049: 
                   3050: #-------------------------------------------
1.32      matthew  3051: sub authform_header{  
                   3052:     my %in = (
                   3053:         formname => 'cu',
1.80      albertel 3054:         kerb_def_dom => '',
1.32      matthew  3055:         @_,
                   3056:     );
                   3057:     $in{'formname'} = 'document.' . $in{'formname'};
                   3058:     my $result='';
1.80      albertel 3059: 
                   3060: #---------------------------------------------- Code for upper case translation
                   3061:     my $Javascript_toUpperCase;
                   3062:     unless ($in{kerb_def_dom}) {
                   3063:         $Javascript_toUpperCase =<<"END";
                   3064:         switch (choice) {
                   3065:            case 'krb': currentform.elements[choicearg].value =
                   3066:                currentform.elements[choicearg].value.toUpperCase();
                   3067:                break;
                   3068:            default:
                   3069:         }
                   3070: END
                   3071:     } else {
                   3072:         $Javascript_toUpperCase = "";
                   3073:     }
                   3074: 
1.165     raeburn  3075:     my $radioval = "'nochange'";
1.591     raeburn  3076:     if (defined($in{'curr_authtype'})) {
                   3077:         if ($in{'curr_authtype'} ne '') {
                   3078:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3079:         }
1.174     matthew  3080:     }
1.165     raeburn  3081:     my $argfield = 'null';
1.591     raeburn  3082:     if (defined($in{'mode'})) {
1.165     raeburn  3083:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3084:             if (defined($in{'curr_autharg'})) {
                   3085:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3086:                     $argfield = "'$in{'curr_autharg'}'";
                   3087:                 }
                   3088:             }
                   3089:         }
                   3090:     }
                   3091: 
1.32      matthew  3092:     $result.=<<"END";
                   3093: var current = new Object();
1.165     raeburn  3094: current.radiovalue = $radioval;
                   3095: current.argfield = $argfield;
1.32      matthew  3096: 
                   3097: function changed_radio(choice,currentform) {
                   3098:     var choicearg = choice + 'arg';
                   3099:     // If a radio button in changed, we need to change the argfield
                   3100:     if (current.radiovalue != choice) {
                   3101:         current.radiovalue = choice;
                   3102:         if (current.argfield != null) {
                   3103:             currentform.elements[current.argfield].value = '';
                   3104:         }
                   3105:         if (choice == 'nochange') {
                   3106:             current.argfield = null;
                   3107:         } else {
                   3108:             current.argfield = choicearg;
                   3109:             switch(choice) {
                   3110:                 case 'krb': 
                   3111:                     currentform.elements[current.argfield].value = 
                   3112:                         "$in{'kerb_def_dom'}";
                   3113:                 break;
                   3114:               default:
                   3115:                 break;
                   3116:             }
                   3117:         }
                   3118:     }
                   3119:     return;
                   3120: }
1.22      www      3121: 
1.32      matthew  3122: function changed_text(choice,currentform) {
                   3123:     var choicearg = choice + 'arg';
                   3124:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3125:         $Javascript_toUpperCase
1.32      matthew  3126:         // clear old field
                   3127:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3128:             currentform.elements[current.argfield].value = '';
                   3129:         }
                   3130:         current.argfield = choicearg;
                   3131:     }
                   3132:     set_auth_radio_buttons(choice,currentform);
                   3133:     return;
1.20      www      3134: }
1.32      matthew  3135: 
                   3136: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3137:     var numauthchoices = currentform.login.length;
                   3138:     if (typeof numauthchoices  == "undefined") {
                   3139:         return;
                   3140:     } 
1.32      matthew  3141:     var i=0;
1.986     raeburn  3142:     while (i < numauthchoices) {
1.32      matthew  3143:         if (currentform.login[i].value == newvalue) { break; }
                   3144:         i++;
                   3145:     }
1.986     raeburn  3146:     if (i == numauthchoices) {
1.32      matthew  3147:         return;
                   3148:     }
                   3149:     current.radiovalue = newvalue;
                   3150:     currentform.login[i].checked = true;
                   3151:     return;
                   3152: }
                   3153: END
                   3154:     return $result;
                   3155: }
                   3156: 
1.1106    raeburn  3157: sub authform_authorwarning {
1.32      matthew  3158:     my $result='';
1.144     matthew  3159:     $result='<i>'.
                   3160:         &mt('As a general rule, only authors or co-authors should be '.
                   3161:             'filesystem authenticated '.
                   3162:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3163:     return $result;
                   3164: }
                   3165: 
1.1106    raeburn  3166: sub authform_nochange {
1.32      matthew  3167:     my %in = (
                   3168:               formname => 'document.cu',
                   3169:               kerb_def_dom => 'MSU.EDU',
                   3170:               @_,
                   3171:           );
1.1106    raeburn  3172:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3173:     my $result;
1.1104    raeburn  3174:     if (!$authnum) {
1.1105    raeburn  3175:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3176:     } else {
                   3177:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3178:                   '<input type="radio" name="login" value="nochange" '.
                   3179:                   'checked="checked" onclick="'.
1.281     albertel 3180:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3181: 	    '</label>';
1.586     raeburn  3182:     }
1.32      matthew  3183:     return $result;
                   3184: }
                   3185: 
1.591     raeburn  3186: sub authform_kerberos {
1.32      matthew  3187:     my %in = (
                   3188:               formname => 'document.cu',
                   3189:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3190:               kerb_def_auth => 'krb4',
1.32      matthew  3191:               @_,
                   3192:               );
1.586     raeburn  3193:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3194:         $autharg,$jscall,$disabled);
1.1106    raeburn  3195:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3196:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3197:        $check5 = ' checked="checked"';
1.80      albertel 3198:     } else {
1.772     bisitz   3199:        $check4 = ' checked="checked"';
1.80      albertel 3200:     }
1.1259    raeburn  3201:     if ($in{'readonly'}) {
                   3202:         $disabled = ' disabled="disabled"';
                   3203:     }
1.165     raeburn  3204:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3205:     if (defined($in{'curr_authtype'})) {
                   3206:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3207:             $krbcheck = ' checked="checked"';
1.623     raeburn  3208:             if (defined($in{'mode'})) {
                   3209:                 if ($in{'mode'} eq 'modifyuser') {
                   3210:                     $krbcheck = '';
                   3211:                 }
                   3212:             }
1.591     raeburn  3213:             if (defined($in{'curr_kerb_ver'})) {
                   3214:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3215:                     $check5 = ' checked="checked"';
1.591     raeburn  3216:                     $check4 = '';
                   3217:                 } else {
1.772     bisitz   3218:                     $check4 = ' checked="checked"';
1.591     raeburn  3219:                     $check5 = '';
                   3220:                 }
1.586     raeburn  3221:             }
1.591     raeburn  3222:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3223:                 $krbarg = $in{'curr_autharg'};
                   3224:             }
1.586     raeburn  3225:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3226:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3227:                     $result = 
                   3228:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3229:         $in{'curr_autharg'},$krbver);
                   3230:                 } else {
                   3231:                     $result =
                   3232:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3233:                 }
                   3234:                 return $result; 
                   3235:             }
                   3236:         }
                   3237:     } else {
                   3238:         if ($authnum == 1) {
1.784     bisitz   3239:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3240:         }
                   3241:     }
1.586     raeburn  3242:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3243:         return;
1.587     raeburn  3244:     } elsif ($authtype eq '') {
1.591     raeburn  3245:         if (defined($in{'mode'})) {
1.587     raeburn  3246:             if ($in{'mode'} eq 'modifycourse') {
                   3247:                 if ($authnum == 1) {
1.1259    raeburn  3248:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3249:                 }
                   3250:             }
                   3251:         }
1.586     raeburn  3252:     }
                   3253:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3254:     if ($authtype eq '') {
                   3255:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3256:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3257:                     $krbcheck.$disabled.' />';
1.586     raeburn  3258:     }
                   3259:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3260:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3261:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3262:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3263:          $in{'curr_authtype'} eq 'krb4')) {
                   3264:         $result .= &mt
1.144     matthew  3265:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3266:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3267:          '<label>'.$authtype,
1.281     albertel 3268:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3269:              'value="'.$krbarg.'" '.
1.1259    raeburn  3270:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3271:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3272:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3273: 	 '</label>');
1.586     raeburn  3274:     } elsif ($can_assign{'krb4'}) {
                   3275:         $result .= &mt
                   3276:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3277:          '[_3] Version 4 [_4]',
                   3278:          '<label>'.$authtype,
                   3279:          '</label><input type="text" size="10" name="krbarg" '.
                   3280:              'value="'.$krbarg.'" '.
1.1259    raeburn  3281:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3282:          '<label><input type="hidden" name="krbver" value="4" />',
                   3283:          '</label>');
                   3284:     } elsif ($can_assign{'krb5'}) {
                   3285:         $result .= &mt
                   3286:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3287:          '[_3] Version 5 [_4]',
                   3288:          '<label>'.$authtype,
                   3289:          '</label><input type="text" size="10" name="krbarg" '.
                   3290:              'value="'.$krbarg.'" '.
1.1259    raeburn  3291:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3292:          '<label><input type="hidden" name="krbver" value="5" />',
                   3293:          '</label>');
                   3294:     }
1.32      matthew  3295:     return $result;
                   3296: }
                   3297: 
1.1106    raeburn  3298: sub authform_internal {
1.586     raeburn  3299:     my %in = (
1.32      matthew  3300:                 formname => 'document.cu',
                   3301:                 kerb_def_dom => 'MSU.EDU',
                   3302:                 @_,
                   3303:                 );
1.1259    raeburn  3304:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3305:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3306:     if ($in{'readonly'}) {
                   3307:         $disabled = ' disabled="disabled"';
                   3308:     }
1.591     raeburn  3309:     if (defined($in{'curr_authtype'})) {
                   3310:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3311:             if ($can_assign{'int'}) {
1.772     bisitz   3312:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3313:                 if (defined($in{'mode'})) {
                   3314:                     if ($in{'mode'} eq 'modifyuser') {
                   3315:                         $intcheck = '';
                   3316:                     }
                   3317:                 }
1.591     raeburn  3318:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3319:                     $intarg = $in{'curr_autharg'};
                   3320:                 }
                   3321:             } else {
                   3322:                 $result = &mt('Currently internally authenticated.');
                   3323:                 return $result;
1.165     raeburn  3324:             }
                   3325:         }
1.586     raeburn  3326:     } else {
                   3327:         if ($authnum == 1) {
1.784     bisitz   3328:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3329:         }
                   3330:     }
                   3331:     if (!$can_assign{'int'}) {
                   3332:         return;
1.587     raeburn  3333:     } elsif ($authtype eq '') {
1.591     raeburn  3334:         if (defined($in{'mode'})) {
1.587     raeburn  3335:             if ($in{'mode'} eq 'modifycourse') {
                   3336:                 if ($authnum == 1) {
1.1259    raeburn  3337:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3338:                 }
                   3339:             }
                   3340:         }
1.165     raeburn  3341:     }
1.586     raeburn  3342:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3343:     if ($authtype eq '') {
                   3344:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3345:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3346:     }
1.605     bisitz   3347:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3348:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3349:     $result = &mt
1.144     matthew  3350:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3351:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3352:     $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>';
1.32      matthew  3353:     return $result;
                   3354: }
                   3355: 
1.1104    raeburn  3356: sub authform_local {
1.32      matthew  3357:     my %in = (
                   3358:               formname => 'document.cu',
                   3359:               kerb_def_dom => 'MSU.EDU',
                   3360:               @_,
                   3361:               );
1.1259    raeburn  3362:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3363:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3364:     if ($in{'readonly'}) {
                   3365:         $disabled = ' disabled="disabled"';
                   3366:     } 
1.591     raeburn  3367:     if (defined($in{'curr_authtype'})) {
                   3368:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3369:             if ($can_assign{'loc'}) {
1.772     bisitz   3370:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3371:                 if (defined($in{'mode'})) {
                   3372:                     if ($in{'mode'} eq 'modifyuser') {
                   3373:                         $loccheck = '';
                   3374:                     }
                   3375:                 }
1.591     raeburn  3376:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3377:                     $locarg = $in{'curr_autharg'};
                   3378:                 }
                   3379:             } else {
                   3380:                 $result = &mt('Currently using local (institutional) authentication.');
                   3381:                 return $result;
1.165     raeburn  3382:             }
                   3383:         }
1.586     raeburn  3384:     } else {
                   3385:         if ($authnum == 1) {
1.784     bisitz   3386:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3387:         }
                   3388:     }
                   3389:     if (!$can_assign{'loc'}) {
                   3390:         return;
1.587     raeburn  3391:     } elsif ($authtype eq '') {
1.591     raeburn  3392:         if (defined($in{'mode'})) {
1.587     raeburn  3393:             if ($in{'mode'} eq 'modifycourse') {
                   3394:                 if ($authnum == 1) {
1.1259    raeburn  3395:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3396:                 }
                   3397:             }
                   3398:         }
1.165     raeburn  3399:     }
1.586     raeburn  3400:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3401:     if ($authtype eq '') {
                   3402:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3403:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3404:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3405:     }
                   3406:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3407:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3408:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3409:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3410:     return $result;
                   3411: }
                   3412: 
1.1106    raeburn  3413: sub authform_filesystem {
1.32      matthew  3414:     my %in = (
                   3415:               formname => 'document.cu',
                   3416:               kerb_def_dom => 'MSU.EDU',
                   3417:               @_,
                   3418:               );
1.1259    raeburn  3419:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3420:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3421:     if ($in{'readonly'}) {
                   3422:         $disabled = ' disabled="disabled"';
                   3423:     }
1.591     raeburn  3424:     if (defined($in{'curr_authtype'})) {
                   3425:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3426:             if ($can_assign{'fsys'}) {
1.772     bisitz   3427:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3428:                 if (defined($in{'mode'})) {
                   3429:                     if ($in{'mode'} eq 'modifyuser') {
                   3430:                         $fsyscheck = '';
                   3431:                     }
                   3432:                 }
1.586     raeburn  3433:             } else {
                   3434:                 $result = &mt('Currently Filesystem Authenticated.');
                   3435:                 return $result;
1.1259    raeburn  3436:             }
1.586     raeburn  3437:         }
                   3438:     } else {
                   3439:         if ($authnum == 1) {
1.784     bisitz   3440:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3441:         }
                   3442:     }
                   3443:     if (!$can_assign{'fsys'}) {
                   3444:         return;
1.587     raeburn  3445:     } elsif ($authtype eq '') {
1.591     raeburn  3446:         if (defined($in{'mode'})) {
1.587     raeburn  3447:             if ($in{'mode'} eq 'modifycourse') {
                   3448:                 if ($authnum == 1) {
1.1259    raeburn  3449:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3450:                 }
                   3451:             }
                   3452:         }
1.586     raeburn  3453:     }
                   3454:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3455:     if ($authtype eq '') {
                   3456:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3457:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3458:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3459:     }
1.1310    raeburn  3460:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3461:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3462:     $result = &mt
1.144     matthew  3463:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3464:          '<label>'.$authtype,'</label>'.$autharg);
                   3465:     return $result;
                   3466: }
                   3467: 
                   3468: sub authform_lti {
                   3469:     my %in = (
                   3470:               formname => 'document.cu',
                   3471:               kerb_def_dom => 'MSU.EDU',
                   3472:               @_,
                   3473:               );
                   3474:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3475:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3476:     if ($in{'readonly'}) {
                   3477:         $disabled = ' disabled="disabled"';
                   3478:     }
                   3479:     if (defined($in{'curr_authtype'})) {
                   3480:         if ($in{'curr_authtype'} eq 'lti') {
                   3481:             if ($can_assign{'lti'}) {
                   3482:                 $lticheck = 'checked="checked" ';
                   3483:                 if (defined($in{'mode'})) {
                   3484:                     if ($in{'mode'} eq 'modifyuser') {
                   3485:                         $lticheck = '';
                   3486:                     }
                   3487:                 }
                   3488:             } else {
                   3489:                 $result = &mt('Currently LTI Authenticated.');
                   3490:                 return $result;
                   3491:             }
                   3492:         }
                   3493:     } else {
                   3494:         if ($authnum == 1) {
                   3495:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3496:         }
                   3497:     }
                   3498:     if (!$can_assign{'lti'}) {
                   3499:         return;
                   3500:     } elsif ($authtype eq '') {
                   3501:         if (defined($in{'mode'})) {
                   3502:             if ($in{'mode'} eq 'modifycourse') {
                   3503:                 if ($authnum == 1) {
                   3504:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3505:                 }
                   3506:             }
                   3507:         }
                   3508:     }
                   3509:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3510:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3511:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3512:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3513:                     $jscall.'"'.$disabled.' />';
                   3514:     }
                   3515:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3516:     if ($authtype) {
                   3517:         $result = &mt('[_1] LTI Authenticated',
                   3518:                       '<label>'.$authtype.'</label>'.$autharg);
                   3519:     } else {
                   3520:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3521:                   $autharg;
                   3522:     }
1.32      matthew  3523:     return $result;
                   3524: }
                   3525: 
1.586     raeburn  3526: sub get_assignable_auth {
                   3527:     my ($dom) = @_;
                   3528:     if ($dom eq '') {
                   3529:         $dom = $env{'request.role.domain'};
                   3530:     }
                   3531:     my %can_assign = (
                   3532:                           krb4 => 1,
                   3533:                           krb5 => 1,
                   3534:                           int  => 1,
                   3535:                           loc  => 1,
1.1310    raeburn  3536:                           lti  => 1,
1.586     raeburn  3537:                      );
                   3538:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3539:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3540:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3541:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3542:             my $context;
                   3543:             if ($env{'request.role'} =~ /^au/) {
                   3544:                 $context = 'author';
1.1259    raeburn  3545:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3546:                 $context = 'domain';
                   3547:             } elsif ($env{'request.course.id'}) {
                   3548:                 $context = 'course';
                   3549:             }
                   3550:             if ($context) {
                   3551:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3552:                    %can_assign = %{$authhash->{$context}}; 
                   3553:                 }
                   3554:             }
                   3555:         }
                   3556:     }
                   3557:     my $authnum = 0;
                   3558:     foreach my $key (keys(%can_assign)) {
                   3559:         if ($can_assign{$key}) {
                   3560:             $authnum ++;
                   3561:         }
                   3562:     }
                   3563:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3564:         $authnum --;
                   3565:     }
                   3566:     return ($authnum,%can_assign);
                   3567: }
                   3568: 
1.80      albertel 3569: ###############################################################
                   3570: ##    Get Kerberos Defaults for Domain                 ##
                   3571: ###############################################################
                   3572: ##
                   3573: ## Returns default kerberos version and an associated argument
                   3574: ## as listed in file domain.tab. If not listed, provides
                   3575: ## appropriate default domain and kerberos version.
                   3576: ##
                   3577: #-------------------------------------------
                   3578: 
                   3579: =pod
                   3580: 
1.648     raeburn  3581: =item * &get_kerberos_defaults()
1.80      albertel 3582: 
                   3583: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3584: version and domain. If not found, it defaults to version 4 and the 
                   3585: domain of the server.
1.80      albertel 3586: 
1.648     raeburn  3587: =over 4
                   3588: 
1.80      albertel 3589: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3590: 
1.648     raeburn  3591: =back
                   3592: 
                   3593: =back
                   3594: 
1.80      albertel 3595: =cut
                   3596: 
                   3597: #-------------------------------------------
                   3598: sub get_kerberos_defaults {
                   3599:     my $domain=shift;
1.641     raeburn  3600:     my ($krbdef,$krbdefdom);
                   3601:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3602:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3603:         $krbdef = $domdefaults{'auth_def'};
                   3604:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3605:     } else {
1.80      albertel 3606:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3607:         my $krbdefdom=$1;
                   3608:         $krbdefdom=~tr/a-z/A-Z/;
                   3609:         $krbdef = "krb4";
                   3610:     }
                   3611:     return ($krbdef,$krbdefdom);
                   3612: }
1.112     bowersj2 3613: 
1.32      matthew  3614: 
1.46      matthew  3615: ###############################################################
                   3616: ##                Thesaurus Functions                        ##
                   3617: ###############################################################
1.20      www      3618: 
1.46      matthew  3619: =pod
1.20      www      3620: 
1.112     bowersj2 3621: =head1 Thesaurus Functions
                   3622: 
                   3623: =over 4
                   3624: 
1.648     raeburn  3625: =item * &initialize_keywords()
1.46      matthew  3626: 
                   3627: Initializes the package variable %Keywords if it is empty.  Uses the
                   3628: package variable $thesaurus_db_file.
                   3629: 
                   3630: =cut
                   3631: 
                   3632: ###################################################
                   3633: 
                   3634: sub initialize_keywords {
                   3635:     return 1 if (scalar keys(%Keywords));
                   3636:     # If we are here, %Keywords is empty, so fill it up
                   3637:     #   Make sure the file we need exists...
                   3638:     if (! -e $thesaurus_db_file) {
                   3639:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3640:                                  " failed because it does not exist");
                   3641:         return 0;
                   3642:     }
                   3643:     #   Set up the hash as a database
                   3644:     my %thesaurus_db;
                   3645:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3646:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3647:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3648:                                  $thesaurus_db_file);
                   3649:         return 0;
                   3650:     } 
                   3651:     #  Get the average number of appearances of a word.
                   3652:     my $avecount = $thesaurus_db{'average.count'};
                   3653:     #  Put keywords (those that appear > average) into %Keywords
                   3654:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3655:         my ($count,undef) = split /:/,$data;
                   3656:         $Keywords{$word}++ if ($count > $avecount);
                   3657:     }
                   3658:     untie %thesaurus_db;
                   3659:     # Remove special values from %Keywords.
1.356     albertel 3660:     foreach my $value ('total.count','average.count') {
                   3661:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3662:   }
1.46      matthew  3663:     return 1;
                   3664: }
                   3665: 
                   3666: ###################################################
                   3667: 
                   3668: =pod
                   3669: 
1.648     raeburn  3670: =item * &keyword($word)
1.46      matthew  3671: 
                   3672: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3673: than the average number of times in the thesaurus database.  Calls 
                   3674: &initialize_keywords
                   3675: 
                   3676: =cut
                   3677: 
                   3678: ###################################################
1.20      www      3679: 
                   3680: sub keyword {
1.46      matthew  3681:     return if (!&initialize_keywords());
                   3682:     my $word=lc(shift());
                   3683:     $word=~s/\W//g;
                   3684:     return exists($Keywords{$word});
1.20      www      3685: }
1.46      matthew  3686: 
                   3687: ###############################################################
                   3688: 
                   3689: =pod 
1.20      www      3690: 
1.648     raeburn  3691: =item * &get_related_words()
1.46      matthew  3692: 
1.160     matthew  3693: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3694: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3695: will be returned.  The order of the words returned is determined by the
                   3696: database which holds them.
                   3697: 
                   3698: Uses global $thesaurus_db_file.
                   3699: 
1.1057    foxr     3700: 
1.46      matthew  3701: =cut
                   3702: 
                   3703: ###############################################################
                   3704: sub get_related_words {
                   3705:     my $keyword = shift;
                   3706:     my %thesaurus_db;
                   3707:     if (! -e $thesaurus_db_file) {
                   3708:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3709:                                  "failed because the file does not exist");
                   3710:         return ();
                   3711:     }
                   3712:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3713:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3714:         return ();
                   3715:     } 
                   3716:     my @Words=();
1.429     www      3717:     my $count=0;
1.46      matthew  3718:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3719: 	# The first element is the number of times
                   3720: 	# the word appears.  We do not need it now.
1.429     www      3721: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3722: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3723: 	my $threshold=$mostfrequentcount/10;
                   3724:         foreach my $possibleword (@RelatedWords) {
                   3725:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3726:             if ($wordcount>$threshold) {
                   3727: 		push(@Words,$word);
                   3728:                 $count++;
                   3729:                 if ($count>10) { last; }
                   3730: 	    }
1.20      www      3731:         }
                   3732:     }
1.46      matthew  3733:     untie %thesaurus_db;
                   3734:     return @Words;
1.14      harris41 3735: }
1.1090    foxr     3736: ###############################################################
                   3737: #
                   3738: #  Spell checking
                   3739: #
                   3740: 
                   3741: =pod
                   3742: 
1.1142    raeburn  3743: =back
                   3744: 
1.1090    foxr     3745: =head1 Spell checking
                   3746: 
                   3747: =over 4
                   3748: 
                   3749: =item * &check_spelling($wordlist $language)
                   3750: 
                   3751: Takes a string containing words and feeds it to an external
                   3752: spellcheck program via a pipeline. Returns a string containing
                   3753: them mis-spelled words.
                   3754: 
                   3755: Parameters:
                   3756: 
                   3757: =over 4
                   3758: 
                   3759: =item - $wordlist
                   3760: 
                   3761: String that will be fed into the spellcheck program.
                   3762: 
                   3763: =item - $language
                   3764: 
                   3765: Language string that specifies the language for which the spell
                   3766: check will be performed.
                   3767: 
                   3768: =back
                   3769: 
                   3770: =back
                   3771: 
                   3772: Note: This sub assumes that aspell is installed.
                   3773: 
                   3774: 
                   3775: =cut
                   3776: 
1.46      matthew  3777: 
1.1090    foxr     3778: sub check_spelling {
                   3779:     my ($wordlist, $language) = @_;
1.1091    foxr     3780:     my @misspellings;
                   3781:     
                   3782:     # Generate the speller and set the langauge.
                   3783:     # if explicitly selected:
1.1090    foxr     3784: 
1.1091    foxr     3785:     my $speller = Text::Aspell->new;
1.1090    foxr     3786:     if ($language) {
1.1091    foxr     3787: 	$speller->set_option('lang', $language);
1.1090    foxr     3788:     }
                   3789: 
1.1091    foxr     3790:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3791: 
1.1091    foxr     3792:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3793: 
1.1091    foxr     3794:     foreach my $word (@words) {
                   3795: 	if(! $speller->check($word)) {
                   3796: 	    push(@misspellings, $word);
1.1090    foxr     3797: 	}
                   3798:     }
1.1091    foxr     3799:     return join(' ', @misspellings);
                   3800:     
1.1090    foxr     3801: }
                   3802: 
1.61      www      3803: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3804: =pod
                   3805: 
1.112     bowersj2 3806: =head1 User Name Functions
                   3807: 
                   3808: =over 4
                   3809: 
1.648     raeburn  3810: =item * &plainname($uname,$udom,$first)
1.81      albertel 3811: 
1.112     bowersj2 3812: Takes a users logon name and returns it as a string in
1.226     albertel 3813: "first middle last generation" form 
                   3814: if $first is set to 'lastname' then it returns it as
                   3815: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3816: 
                   3817: =cut
1.61      www      3818: 
1.295     www      3819: 
1.81      albertel 3820: ###############################################################
1.61      www      3821: sub plainname {
1.226     albertel 3822:     my ($uname,$udom,$first)=@_;
1.537     albertel 3823:     return if (!defined($uname) || !defined($udom));
1.295     www      3824:     my %names=&getnames($uname,$udom);
1.226     albertel 3825:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3826: 					  $names{'middlename'},
                   3827: 					  $names{'lastname'},
                   3828: 					  $names{'generation'},$first);
                   3829:     $name=~s/^\s+//;
1.62      www      3830:     $name=~s/\s+$//;
                   3831:     $name=~s/\s+/ /g;
1.353     albertel 3832:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3833:     return $name;
1.61      www      3834: }
1.66      www      3835: 
                   3836: # -------------------------------------------------------------------- Nickname
1.81      albertel 3837: =pod
                   3838: 
1.648     raeburn  3839: =item * &nickname($uname,$udom)
1.81      albertel 3840: 
                   3841: Gets a users name and returns it as a string as
                   3842: 
                   3843: "&quot;nickname&quot;"
1.66      www      3844: 
1.81      albertel 3845: if the user has a nickname or
                   3846: 
                   3847: "first middle last generation"
                   3848: 
                   3849: if the user does not
                   3850: 
                   3851: =cut
1.66      www      3852: 
                   3853: sub nickname {
                   3854:     my ($uname,$udom)=@_;
1.537     albertel 3855:     return if (!defined($uname) || !defined($udom));
1.295     www      3856:     my %names=&getnames($uname,$udom);
1.68      albertel 3857:     my $name=$names{'nickname'};
1.66      www      3858:     if ($name) {
                   3859:        $name='&quot;'.$name.'&quot;'; 
                   3860:     } else {
                   3861:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3862: 	     $names{'lastname'}.' '.$names{'generation'};
                   3863:        $name=~s/\s+$//;
                   3864:        $name=~s/\s+/ /g;
                   3865:     }
                   3866:     return $name;
                   3867: }
                   3868: 
1.295     www      3869: sub getnames {
                   3870:     my ($uname,$udom)=@_;
1.537     albertel 3871:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3872:     if ($udom eq 'public' && $uname eq 'public') {
                   3873: 	return ('lastname' => &mt('Public'));
                   3874:     }
1.295     www      3875:     my $id=$uname.':'.$udom;
                   3876:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3877:     if ($cached) {
                   3878: 	return %{$names};
                   3879:     } else {
                   3880: 	my %loadnames=&Apache::lonnet::get('environment',
                   3881:                     ['firstname','middlename','lastname','generation','nickname'],
                   3882: 					 $udom,$uname);
                   3883: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3884: 	return %loadnames;
                   3885:     }
                   3886: }
1.61      www      3887: 
1.542     raeburn  3888: # -------------------------------------------------------------------- getemails
1.648     raeburn  3889: 
1.542     raeburn  3890: =pod
                   3891: 
1.648     raeburn  3892: =item * &getemails($uname,$udom)
1.542     raeburn  3893: 
                   3894: Gets a user's email information and returns it as a hash with keys:
                   3895: notification, critnotification, permanentemail
                   3896: 
                   3897: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3898: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3899:  
1.648     raeburn  3900: 
1.542     raeburn  3901: =cut
                   3902: 
1.648     raeburn  3903: 
1.466     albertel 3904: sub getemails {
                   3905:     my ($uname,$udom)=@_;
                   3906:     if ($udom eq 'public' && $uname eq 'public') {
                   3907: 	return;
                   3908:     }
1.467     www      3909:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3910:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3911:     my $id=$uname.':'.$udom;
                   3912:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3913:     if ($cached) {
                   3914: 	return %{$names};
                   3915:     } else {
                   3916: 	my %loadnames=&Apache::lonnet::get('environment',
                   3917:                     			   ['notification','critnotification',
                   3918: 					    'permanentemail'],
                   3919: 					   $udom,$uname);
                   3920: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3921: 	return %loadnames;
                   3922:     }
                   3923: }
                   3924: 
1.551     albertel 3925: sub flush_email_cache {
                   3926:     my ($uname,$udom)=@_;
                   3927:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3928:     if (!$uname) { $uname=$env{'user.name'};   }
                   3929:     return if ($udom eq 'public' && $uname eq 'public');
                   3930:     my $id=$uname.':'.$udom;
                   3931:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3932: }
                   3933: 
1.728     raeburn  3934: # -------------------------------------------------------------------- getlangs
                   3935: 
                   3936: =pod
                   3937: 
                   3938: =item * &getlangs($uname,$udom)
                   3939: 
                   3940: Gets a user's language preference and returns it as a hash with key:
                   3941: language.
                   3942: 
                   3943: =cut
                   3944: 
                   3945: 
                   3946: sub getlangs {
                   3947:     my ($uname,$udom) = @_;
                   3948:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3949:     if (!$uname) { $uname=$env{'user.name'};   }
                   3950:     my $id=$uname.':'.$udom;
                   3951:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3952:     if ($cached) {
                   3953:         return %{$langs};
                   3954:     } else {
                   3955:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3956:                                            $udom,$uname);
                   3957:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3958:         return %loadlangs;
                   3959:     }
                   3960: }
                   3961: 
                   3962: sub flush_langs_cache {
                   3963:     my ($uname,$udom)=@_;
                   3964:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3965:     if (!$uname) { $uname=$env{'user.name'};   }
                   3966:     return if ($udom eq 'public' && $uname eq 'public');
                   3967:     my $id=$uname.':'.$udom;
                   3968:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3969: }
                   3970: 
1.61      www      3971: # ------------------------------------------------------------------ Screenname
1.81      albertel 3972: 
                   3973: =pod
                   3974: 
1.648     raeburn  3975: =item * &screenname($uname,$udom)
1.81      albertel 3976: 
                   3977: Gets a users screenname and returns it as a string
                   3978: 
                   3979: =cut
1.61      www      3980: 
                   3981: sub screenname {
                   3982:     my ($uname,$udom)=@_;
1.258     albertel 3983:     if ($uname eq $env{'user.name'} &&
                   3984: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3985:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3986:     return $names{'screenname'};
1.62      www      3987: }
                   3988: 
1.212     albertel 3989: 
1.802     bisitz   3990: # ------------------------------------------------------------- Confirm Wrapper
                   3991: =pod
                   3992: 
1.1142    raeburn  3993: =item * &confirmwrapper($message)
1.802     bisitz   3994: 
                   3995: Wrap messages about completion of operation in box
                   3996: 
                   3997: =cut
                   3998: 
                   3999: sub confirmwrapper {
                   4000:     my ($message)=@_;
                   4001:     if ($message) {
                   4002:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4003:                .$message."\n"
                   4004:                .'</div>'."\n";
                   4005:     } else {
                   4006:         return $message;
                   4007:     }
                   4008: }
                   4009: 
1.62      www      4010: # ------------------------------------------------------------- Message Wrapper
                   4011: 
                   4012: sub messagewrapper {
1.369     www      4013:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4014:     return 
1.441     albertel 4015:         '<a href="/adm/email?compose=individual&amp;'.
                   4016:         'recname='.$username.'&amp;recdom='.$domain.
                   4017: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4018:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4019: }
1.802     bisitz   4020: 
1.74      www      4021: # --------------------------------------------------------------- Notes Wrapper
                   4022: 
                   4023: sub noteswrapper {
                   4024:     my ($link,$un,$do)=@_;
                   4025:     return 
1.896     amueller 4026: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4027: }
1.802     bisitz   4028: 
1.62      www      4029: # ------------------------------------------------------------- Aboutme Wrapper
                   4030: 
                   4031: sub aboutmewrapper {
1.1070    raeburn  4032:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4033:     if (!defined($username)  && !defined($domain)) {
                   4034:         return;
                   4035:     }
1.1096    raeburn  4036:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4037: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4038: }
                   4039: 
                   4040: # ------------------------------------------------------------ Syllabus Wrapper
                   4041: 
                   4042: sub syllabuswrapper {
1.707     bisitz   4043:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4044:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4045: }
1.14      harris41 4046: 
1.802     bisitz   4047: # -----------------------------------------------------------------------------
                   4048: 
1.208     matthew  4049: sub track_student_link {
1.887     raeburn  4050:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4051:     my $link ="/adm/trackstudent?";
1.208     matthew  4052:     my $title = 'View recent activity';
                   4053:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4054:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4055:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4056:         $title .= ' of this student';
1.268     albertel 4057:     } 
1.208     matthew  4058:     if (defined($target) && $target !~ /^\s*$/) {
                   4059:         $target = qq{target="$target"};
                   4060:     } else {
                   4061:         $target = '';
                   4062:     }
1.268     albertel 4063:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4064:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4065:     $title = &mt($title);
                   4066:     $linktext = &mt($linktext);
1.448     albertel 4067:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4068: 	&help_open_topic('View_recent_activity');
1.208     matthew  4069: }
                   4070: 
1.781     raeburn  4071: sub slot_reservations_link {
                   4072:     my ($linktext,$sname,$sdom,$target) = @_;
                   4073:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4074:     my $title = 'View slot reservation history';
                   4075:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4076:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4077:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4078:         $title .= ' of this student';
                   4079:     }
                   4080:     if (defined($target) && $target !~ /^\s*$/) {
                   4081:         $target = qq{target="$target"};
                   4082:     } else {
                   4083:         $target = '';
                   4084:     }
                   4085:     $title = &mt($title);
                   4086:     $linktext = &mt($linktext);
                   4087:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4088: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4089: 
                   4090: }
                   4091: 
1.508     www      4092: # ===================================================== Display a student photo
                   4093: 
                   4094: 
1.509     albertel 4095: sub student_image_tag {
1.508     www      4096:     my ($domain,$user)=@_;
                   4097:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4098:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4099: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4100:     } else {
                   4101: 	return '';
                   4102:     }
                   4103: }
                   4104: 
1.112     bowersj2 4105: =pod
                   4106: 
                   4107: =back
                   4108: 
                   4109: =head1 Access .tab File Data
                   4110: 
                   4111: =over 4
                   4112: 
1.648     raeburn  4113: =item * &languageids() 
1.112     bowersj2 4114: 
                   4115: returns list of all language ids
                   4116: 
                   4117: =cut
                   4118: 
1.14      harris41 4119: sub languageids {
1.16      harris41 4120:     return sort(keys(%language));
1.14      harris41 4121: }
                   4122: 
1.112     bowersj2 4123: =pod
                   4124: 
1.648     raeburn  4125: =item * &languagedescription() 
1.112     bowersj2 4126: 
                   4127: returns description of a specified language id
                   4128: 
                   4129: =cut
                   4130: 
1.14      harris41 4131: sub languagedescription {
1.125     www      4132:     my $code=shift;
                   4133:     return  ($supported_language{$code}?'* ':'').
                   4134:             $language{$code}.
1.126     www      4135: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4136: }
                   4137: 
1.1048    foxr     4138: =pod
                   4139: 
                   4140: =item * &plainlanguagedescription
                   4141: 
                   4142: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4143: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4144: 
                   4145: =cut
                   4146: 
1.145     www      4147: sub plainlanguagedescription {
                   4148:     my $code=shift;
                   4149:     return $language{$code};
                   4150: }
                   4151: 
1.1048    foxr     4152: =pod
                   4153: 
                   4154: =item * &supportedlanguagecode
                   4155: 
                   4156: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4157: code.
                   4158: 
                   4159: =cut
                   4160: 
1.145     www      4161: sub supportedlanguagecode {
                   4162:     my $code=shift;
                   4163:     return $supported_language{$code};
1.97      www      4164: }
                   4165: 
1.112     bowersj2 4166: =pod
                   4167: 
1.1048    foxr     4168: =item * &latexlanguage()
                   4169: 
                   4170: Given a language key code returns the correspondnig language to use
                   4171: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4172: is no supported hyphenation for the language code.
                   4173: 
                   4174: =cut
                   4175: 
                   4176: sub latexlanguage {
                   4177:     my $code = shift;
                   4178:     return $latex_language{$code};
                   4179: }
                   4180: 
                   4181: =pod
                   4182: 
                   4183: =item * &latexhyphenation()
                   4184: 
                   4185: Same as above but what's supplied is the language as it might be stored
                   4186: in the metadata.
                   4187: 
                   4188: =cut
                   4189: 
                   4190: sub latexhyphenation {
                   4191:     my $key = shift;
                   4192:     return $latex_language_bykey{$key};
                   4193: }
                   4194: 
                   4195: =pod
                   4196: 
1.648     raeburn  4197: =item * &copyrightids() 
1.112     bowersj2 4198: 
                   4199: returns list of all copyrights
                   4200: 
                   4201: =cut
                   4202: 
                   4203: sub copyrightids {
                   4204:     return sort(keys(%cprtag));
                   4205: }
                   4206: 
                   4207: =pod
                   4208: 
1.648     raeburn  4209: =item * &copyrightdescription() 
1.112     bowersj2 4210: 
                   4211: returns description of a specified copyright id
                   4212: 
                   4213: =cut
                   4214: 
                   4215: sub copyrightdescription {
1.166     www      4216:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4217: }
1.197     matthew  4218: 
                   4219: =pod
                   4220: 
1.648     raeburn  4221: =item * &source_copyrightids() 
1.192     taceyjo1 4222: 
                   4223: returns list of all source copyrights
                   4224: 
                   4225: =cut
                   4226: 
                   4227: sub source_copyrightids {
                   4228:     return sort(keys(%scprtag));
                   4229: }
                   4230: 
                   4231: =pod
                   4232: 
1.648     raeburn  4233: =item * &source_copyrightdescription() 
1.192     taceyjo1 4234: 
                   4235: returns description of a specified source copyright id
                   4236: 
                   4237: =cut
                   4238: 
                   4239: sub source_copyrightdescription {
                   4240:     return &mt($scprtag{shift(@_)});
                   4241: }
1.112     bowersj2 4242: 
                   4243: =pod
                   4244: 
1.648     raeburn  4245: =item * &filecategories() 
1.112     bowersj2 4246: 
                   4247: returns list of all file categories
                   4248: 
                   4249: =cut
                   4250: 
                   4251: sub filecategories {
                   4252:     return sort(keys(%category_extensions));
                   4253: }
                   4254: 
                   4255: =pod
                   4256: 
1.648     raeburn  4257: =item * &filecategorytypes() 
1.112     bowersj2 4258: 
                   4259: returns list of file types belonging to a given file
                   4260: category
                   4261: 
                   4262: =cut
                   4263: 
                   4264: sub filecategorytypes {
1.356     albertel 4265:     my ($cat) = @_;
1.1248    raeburn  4266:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4267:         return @{$category_extensions{lc($cat)}};
                   4268:     } else {
                   4269:         return ();
                   4270:     }
1.112     bowersj2 4271: }
                   4272: 
                   4273: =pod
                   4274: 
1.648     raeburn  4275: =item * &fileembstyle() 
1.112     bowersj2 4276: 
                   4277: returns embedding style for a specified file type
                   4278: 
                   4279: =cut
                   4280: 
                   4281: sub fileembstyle {
                   4282:     return $fe{lc(shift(@_))};
1.169     www      4283: }
                   4284: 
1.351     www      4285: sub filemimetype {
                   4286:     return $fm{lc(shift(@_))};
                   4287: }
                   4288: 
1.169     www      4289: 
                   4290: sub filecategoryselect {
                   4291:     my ($name,$value)=@_;
1.189     matthew  4292:     return &select_form($value,$name,
1.970     raeburn  4293:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4294: }
                   4295: 
                   4296: =pod
                   4297: 
1.648     raeburn  4298: =item * &filedescription() 
1.112     bowersj2 4299: 
                   4300: returns description for a specified file type
                   4301: 
                   4302: =cut
                   4303: 
                   4304: sub filedescription {
1.188     matthew  4305:     my $file_description = $fd{lc(shift())};
                   4306:     $file_description =~ s:([\[\]]):~$1:g;
                   4307:     return &mt($file_description);
1.112     bowersj2 4308: }
                   4309: 
                   4310: =pod
                   4311: 
1.648     raeburn  4312: =item * &filedescriptionex() 
1.112     bowersj2 4313: 
                   4314: returns description for a specified file type with
                   4315: extra formatting
                   4316: 
                   4317: =cut
                   4318: 
                   4319: sub filedescriptionex {
                   4320:     my $ex=shift;
1.188     matthew  4321:     my $file_description = $fd{lc($ex)};
                   4322:     $file_description =~ s:([\[\]]):~$1:g;
                   4323:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4324: }
                   4325: 
                   4326: # End of .tab access
                   4327: =pod
                   4328: 
                   4329: =back
                   4330: 
                   4331: =cut
                   4332: 
                   4333: # ------------------------------------------------------------------ File Types
                   4334: sub fileextensions {
                   4335:     return sort(keys(%fe));
                   4336: }
                   4337: 
1.97      www      4338: # ----------------------------------------------------------- Display Languages
                   4339: # returns a hash with all desired display languages
                   4340: #
                   4341: 
                   4342: sub display_languages {
                   4343:     my %languages=();
1.695     raeburn  4344:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4345: 	$languages{$lang}=1;
1.97      www      4346:     }
                   4347:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4348:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4349: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4350: 	    $languages{$lang}=1;
1.97      www      4351:         }
                   4352:     }
                   4353:     return %languages;
1.14      harris41 4354: }
                   4355: 
1.582     albertel 4356: sub languages {
                   4357:     my ($possible_langs) = @_;
1.695     raeburn  4358:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4359:     if (!ref($possible_langs)) {
                   4360: 	if( wantarray ) {
                   4361: 	    return @preferred_langs;
                   4362: 	} else {
                   4363: 	    return $preferred_langs[0];
                   4364: 	}
                   4365:     }
                   4366:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4367:     my @preferred_possibilities;
                   4368:     foreach my $preferred_lang (@preferred_langs) {
                   4369: 	if (exists($possibilities{$preferred_lang})) {
                   4370: 	    push(@preferred_possibilities, $preferred_lang);
                   4371: 	}
                   4372:     }
                   4373:     if( wantarray ) {
                   4374: 	return @preferred_possibilities;
                   4375:     }
                   4376:     return $preferred_possibilities[0];
                   4377: }
                   4378: 
1.742     raeburn  4379: sub user_lang {
                   4380:     my ($touname,$toudom,$fromcid) = @_;
                   4381:     my @userlangs;
                   4382:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4383:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4384:                     $env{'course.'.$fromcid.'.languages'}));
                   4385:     } else {
                   4386:         my %langhash = &getlangs($touname,$toudom);
                   4387:         if ($langhash{'languages'} ne '') {
                   4388:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4389:         } else {
                   4390:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4391:             if ($domdefs{'lang_def'} ne '') {
                   4392:                 @userlangs = ($domdefs{'lang_def'});
                   4393:             }
                   4394:         }
                   4395:     }
                   4396:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4397:     my $user_lh = Apache::localize->get_handle(@languages);
                   4398:     return $user_lh;
                   4399: }
                   4400: 
                   4401: 
1.112     bowersj2 4402: ###############################################################
                   4403: ##               Student Answer Attempts                     ##
                   4404: ###############################################################
                   4405: 
                   4406: =pod
                   4407: 
                   4408: =head1 Alternate Problem Views
                   4409: 
                   4410: =over 4
                   4411: 
1.648     raeburn  4412: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4413:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4414: 
                   4415: Return string with previous attempt on problem. Arguments:
                   4416: 
                   4417: =over 4
                   4418: 
                   4419: =item * $symb: Problem, including path
                   4420: 
                   4421: =item * $username: username of the desired student
                   4422: 
                   4423: =item * $domain: domain of the desired student
1.14      harris41 4424: 
1.112     bowersj2 4425: =item * $course: Course ID
1.14      harris41 4426: 
1.112     bowersj2 4427: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4428:     something
1.14      harris41 4429: 
1.112     bowersj2 4430: =item * $regexp: if string matches this regexp, the string will be
                   4431:     sent to $gradesub
1.14      harris41 4432: 
1.112     bowersj2 4433: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4434: 
1.1199    raeburn  4435: =item * $usec: section of the desired student
                   4436: 
                   4437: =item * $identifier: counter for student (multiple students one problem) or 
                   4438:     problem (one student; whole sequence).
                   4439: 
1.112     bowersj2 4440: =back
1.14      harris41 4441: 
1.112     bowersj2 4442: The output string is a table containing all desired attempts, if any.
1.16      harris41 4443: 
1.112     bowersj2 4444: =cut
1.1       albertel 4445: 
                   4446: sub get_previous_attempt {
1.1199    raeburn  4447:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4448:   my $prevattempts='';
1.43      ng       4449:   no strict 'refs';
1.1       albertel 4450:   if ($symb) {
1.3       albertel 4451:     my (%returnhash)=
                   4452:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4453:     if ($returnhash{'version'}) {
                   4454:       my %lasthash=();
                   4455:       my $version;
                   4456:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4457:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4458:             if ($key =~ /\.rawrndseed$/) {
                   4459:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4460:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4461:             } else {
                   4462:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4463:             }
1.19      harris41 4464:         }
1.1       albertel 4465:       }
1.596     albertel 4466:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4467:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4468:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4469:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4470:       foreach my $key (sort(keys(%lasthash))) {
                   4471: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4472: 	if ($#parts > 0) {
1.31      albertel 4473: 	  my $data=$parts[-1];
1.989     raeburn  4474:           next if ($data eq 'foilorder');
1.31      albertel 4475: 	  pop(@parts);
1.1010    www      4476:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4477:           if ($data eq 'type') {
                   4478:               unless ($showsurv) {
                   4479:                   my $id = join(',',@parts);
                   4480:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4481:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4482:                       $lasthidden{$ign.'.'.$id} = 1;
                   4483:                   }
1.945     raeburn  4484:               }
1.1199    raeburn  4485:               if ($identifier ne '') {
                   4486:                   my $id = join(',',@parts);
                   4487:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4488:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4489:                       $hidestatus{$ign.'.'.$id} = 1;
                   4490:                   }
                   4491:               }
                   4492:           } elsif ($data eq 'regrader') {
                   4493:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4494:                   my $id = join(',',@parts);
                   4495:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4496:               }
1.1010    www      4497:           } 
1.31      albertel 4498: 	} else {
1.41      ng       4499: 	  if ($#parts == 0) {
                   4500: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4501: 	  } else {
                   4502: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4503: 	  }
1.31      albertel 4504: 	}
1.16      harris41 4505:       }
1.596     albertel 4506:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4507:       if ($getattempt eq '') {
1.1199    raeburn  4508:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4509:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4510:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4511:                 foreach my $id (keys(%regraded)) {
                   4512:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4513:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4514:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4515:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4516:                     }
                   4517:                 }
                   4518:             }
1.1200    raeburn  4519:         }
                   4520: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4521:             my (@hidden,@unsolved);
1.945     raeburn  4522:             if (%typeparts) {
                   4523:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4524:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4525:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4526:                         push(@hidden,$id);
1.1199    raeburn  4527:                     } elsif ($identifier ne '') {
                   4528:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4529:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4530:                                 ($hidestatus{$id})) {
1.1200    raeburn  4531:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4532:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4533:                                 push(@{$solved{$id}},$version);
                   4534:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4535:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4536:                                 my $skip;
                   4537:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4538:                                     foreach my $reset (@{$resets{$id}}) {
                   4539:                                         if ($reset > $solved{$id}[-1]) {
                   4540:                                             $skip=1;
                   4541:                                             last;
                   4542:                                         }
                   4543:                                     }
                   4544:                                 }
                   4545:                                 unless ($skip) {
                   4546:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4547:                                     push(@unsolved,$partslist);
                   4548:                                 }
                   4549:                             }
                   4550:                         }
1.945     raeburn  4551:                     }
                   4552:                 }
                   4553:             }
                   4554:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4555:                            '<td>'.&mt('Transaction [_1]',$version);
                   4556:             if (@unsolved) {
                   4557:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4558:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4559:                                  &mt('Hide').'</label></span>';
                   4560:             }
                   4561:             $prevattempts .= '</td>';
1.945     raeburn  4562:             if (@hidden) {
                   4563:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4564:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4565:                     my $hide;
                   4566:                     foreach my $id (@hidden) {
                   4567:                         if ($key =~ /^\Q$id\E/) {
                   4568:                             $hide = 1;
                   4569:                             last;
                   4570:                         }
                   4571:                     }
                   4572:                     if ($hide) {
                   4573:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4574:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4575:                             my $value = &format_previous_attempt_value($key,
                   4576:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4577:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4578:                         } else {
                   4579:                             $prevattempts.='<td>&nbsp;</td>';
                   4580:                         }
                   4581:                     } else {
                   4582:                         if ($key =~ /\./) {
1.1212    raeburn  4583:                             my $value = $returnhash{$version.':'.$key};
                   4584:                             if ($key =~ /\.rndseed$/) {
                   4585:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4586:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4587:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4588:                                 }
                   4589:                             }
                   4590:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4591:                                            '&nbsp;</td>';
1.945     raeburn  4592:                         } else {
                   4593:                             $prevattempts.='<td>&nbsp;</td>';
                   4594:                         }
                   4595:                     }
                   4596:                 }
                   4597:             } else {
                   4598: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4599:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4600:                     my $value = $returnhash{$version.':'.$key};
                   4601:                     if ($key =~ /\.rndseed$/) {
                   4602:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4603:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4604:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4605:                         }
                   4606:                     }
                   4607:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4608:                                    '&nbsp;</td>';
1.945     raeburn  4609: 	        }
                   4610:             }
                   4611: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4612: 	 }
1.1       albertel 4613:       }
1.945     raeburn  4614:       my @currhidden = keys(%lasthidden);
1.596     albertel 4615:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4616:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4617:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4618:           if (%typeparts) {
                   4619:               my $hidden;
                   4620:               foreach my $id (@currhidden) {
                   4621:                   if ($key =~ /^\Q$id\E/) {
                   4622:                       $hidden = 1;
                   4623:                       last;
                   4624:                   }
                   4625:               }
                   4626:               if ($hidden) {
                   4627:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4628:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4629:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4630:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4631:                           $value = &$gradesub($value);
                   4632:                       }
1.1173    kruse    4633:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4634:                   } else {
                   4635:                       $prevattempts.='<td>&nbsp;</td>';
                   4636:                   }
                   4637:               } else {
                   4638:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4639:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4640:                       $value = &$gradesub($value);
                   4641:                   }
1.1173    kruse    4642:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4643:               }
                   4644:           } else {
                   4645: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4646: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4647:                   $value = &$gradesub($value);
                   4648:               }
1.1173    kruse    4649: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4650:           }
1.16      harris41 4651:       }
1.596     albertel 4652:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4653:     } else {
1.1305    raeburn  4654:       my $msg;
                   4655:       if ($symb =~ /ext\.tool$/) {
                   4656:           $msg = &mt('No grade passed back.');
                   4657:       } else {
                   4658:           $msg = &mt('Nothing submitted - no attempts.');
                   4659:       }
1.596     albertel 4660:       $prevattempts=
                   4661: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4662: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4663: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4664:     }
                   4665:   } else {
1.596     albertel 4666:     $prevattempts=
                   4667: 	  &start_data_table().&start_data_table_row().
                   4668: 	  '<td>'.&mt('No data.').'</td>'.
                   4669: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4670:   }
1.10      albertel 4671: }
                   4672: 
1.581     albertel 4673: sub format_previous_attempt_value {
                   4674:     my ($key,$value) = @_;
1.1011    www      4675:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4676:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4677:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4678:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4679:     } elsif ($key =~ /answerstring$/) {
                   4680:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4681:         my @answer = %answers;
                   4682:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4683:         my @anskeys = sort(keys(%answers));
                   4684:         if (@anskeys == 1) {
                   4685:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4686:             if ($answer =~ m{\0}) {
                   4687:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4688:             }
                   4689:             my $tag_internal_answer_name = 'INTERNAL';
                   4690:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4691:                 $value = $answer; 
                   4692:             } else {
                   4693:                 $value = $anskeys[0].'='.$answer;
                   4694:             }
                   4695:         } else {
                   4696:             foreach my $ans (@anskeys) {
                   4697:                 my $answer = $answers{$ans};
1.1001    raeburn  4698:                 if ($answer =~ m{\0}) {
                   4699:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4700:                 }
                   4701:                 $value .=  $ans.'='.$answer.'<br />';;
                   4702:             } 
                   4703:         }
1.581     albertel 4704:     } else {
1.1173    kruse    4705:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4706:     }
                   4707:     return $value;
                   4708: }
                   4709: 
                   4710: 
1.107     albertel 4711: sub relative_to_absolute {
                   4712:     my ($url,$output)=@_;
                   4713:     my $parser=HTML::TokeParser->new(\$output);
                   4714:     my $token;
                   4715:     my $thisdir=$url;
                   4716:     my @rlinks=();
                   4717:     while ($token=$parser->get_token) {
                   4718: 	if ($token->[0] eq 'S') {
                   4719: 	    if ($token->[1] eq 'a') {
                   4720: 		if ($token->[2]->{'href'}) {
                   4721: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4722: 		}
                   4723: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4724: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4725: 	    } elsif ($token->[1] eq 'base') {
                   4726: 		$thisdir=$token->[2]->{'href'};
                   4727: 	    }
                   4728: 	}
                   4729:     }
                   4730:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4731:     foreach my $link (@rlinks) {
1.726     raeburn  4732: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4733: 		($link=~/^\//) ||
                   4734: 		($link=~/^javascript:/i) ||
                   4735: 		($link=~/^mailto:/i) ||
                   4736: 		($link=~/^\#/)) {
                   4737: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4738: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4739: 	}
                   4740:     }
                   4741: # -------------------------------------------------- Deal with Applet codebases
                   4742:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4743:     return $output;
                   4744: }
                   4745: 
1.112     bowersj2 4746: =pod
                   4747: 
1.648     raeburn  4748: =item * &get_student_view()
1.112     bowersj2 4749: 
                   4750: show a snapshot of what student was looking at
                   4751: 
                   4752: =cut
                   4753: 
1.10      albertel 4754: sub get_student_view {
1.186     albertel 4755:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4756:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4757:   my (%form);
1.10      albertel 4758:   my @elements=('symb','courseid','domain','username');
                   4759:   foreach my $element (@elements) {
1.186     albertel 4760:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4761:   }
1.186     albertel 4762:   if (defined($moreenv)) {
                   4763:       %form=(%form,%{$moreenv});
                   4764:   }
1.236     albertel 4765:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4766:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4767:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4768:       $feedurl =~ s{^/adm/wrapper}{};
                   4769:   }
1.650     www      4770:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4771:   $userview=~s/\<body[^\>]*\>//gi;
                   4772:   $userview=~s/\<\/body\>//gi;
                   4773:   $userview=~s/\<html\>//gi;
                   4774:   $userview=~s/\<\/html\>//gi;
                   4775:   $userview=~s/\<head\>//gi;
                   4776:   $userview=~s/\<\/head\>//gi;
                   4777:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4778:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4779:   if (wantarray) {
                   4780:      return ($userview,$response);
                   4781:   } else {
                   4782:      return $userview;
                   4783:   }
                   4784: }
                   4785: 
                   4786: sub get_student_view_with_retries {
                   4787:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4788: 
                   4789:     my $ok = 0;                 # True if we got a good response.
                   4790:     my $content;
                   4791:     my $response;
                   4792: 
                   4793:     # Try to get the student_view done. within the retries count:
                   4794:     
                   4795:     do {
                   4796:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4797:          $ok      = $response->is_success;
                   4798:          if (!$ok) {
                   4799:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4800:          }
                   4801:          $retries--;
                   4802:     } while (!$ok && ($retries > 0));
                   4803:     
                   4804:     if (!$ok) {
                   4805:        $content = '';          # On error return an empty content.
                   4806:     }
1.651     www      4807:     if (wantarray) {
                   4808:        return ($content, $response);
                   4809:     } else {
                   4810:        return $content;
                   4811:     }
1.11      albertel 4812: }
                   4813: 
1.112     bowersj2 4814: =pod
                   4815: 
1.648     raeburn  4816: =item * &get_student_answers() 
1.112     bowersj2 4817: 
                   4818: show a snapshot of how student was answering problem
                   4819: 
                   4820: =cut
                   4821: 
1.11      albertel 4822: sub get_student_answers {
1.100     sakharuk 4823:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4824:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4825:   my (%moreenv);
1.11      albertel 4826:   my @elements=('symb','courseid','domain','username');
                   4827:   foreach my $element (@elements) {
1.186     albertel 4828:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4829:   }
1.186     albertel 4830:   $moreenv{'grade_target'}='answer';
                   4831:   %moreenv=(%form,%moreenv);
1.497     raeburn  4832:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4833:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4834:   return $userview;
1.1       albertel 4835: }
1.116     albertel 4836: 
                   4837: =pod
                   4838: 
                   4839: =item * &submlink()
                   4840: 
1.242     albertel 4841: Inputs: $text $uname $udom $symb $target
1.116     albertel 4842: 
                   4843: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4844: 
                   4845: =cut
                   4846: 
                   4847: ###############################################
                   4848: sub submlink {
1.242     albertel 4849:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4850:     if (!($uname && $udom)) {
                   4851: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4852: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4853: 	if (!$symb) { $symb=$cursymb; }
                   4854:     }
1.254     matthew  4855:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4856:     $symb=&escape($symb);
1.960     bisitz   4857:     if ($target) { $target=" target=\"$target\""; }
                   4858:     return
                   4859:         '<a href="/adm/grades?command=submission'.
                   4860:         '&amp;symb='.$symb.
                   4861:         '&amp;student='.$uname.
                   4862:         '&amp;userdom='.$udom.'"'.
                   4863:         $target.'>'.$text.'</a>';
1.242     albertel 4864: }
                   4865: ##############################################
                   4866: 
                   4867: =pod
                   4868: 
                   4869: =item * &pgrdlink()
                   4870: 
                   4871: Inputs: $text $uname $udom $symb $target
                   4872: 
                   4873: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4874: 
                   4875: =cut
                   4876: 
                   4877: ###############################################
                   4878: sub pgrdlink {
                   4879:     my $link=&submlink(@_);
                   4880:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4881:     return $link;
                   4882: }
                   4883: ##############################################
                   4884: 
                   4885: =pod
                   4886: 
                   4887: =item * &pprmlink()
                   4888: 
                   4889: Inputs: $text $uname $udom $symb $target
                   4890: 
                   4891: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4892: student and a specific resource
1.242     albertel 4893: 
                   4894: =cut
                   4895: 
                   4896: ###############################################
                   4897: sub pprmlink {
                   4898:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4899:     if (!($uname && $udom)) {
                   4900: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4901: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4902: 	if (!$symb) { $symb=$cursymb; }
                   4903:     }
1.254     matthew  4904:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4905:     $symb=&escape($symb);
1.242     albertel 4906:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4907:     return '<a href="/adm/parmset?command=set&amp;'.
                   4908: 	'symb='.$symb.'&amp;uname='.$uname.
                   4909: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4910: }
                   4911: ##############################################
1.37      matthew  4912: 
1.112     bowersj2 4913: =pod
                   4914: 
                   4915: =back
                   4916: 
                   4917: =cut
                   4918: 
1.37      matthew  4919: ###############################################
1.51      www      4920: 
                   4921: 
                   4922: sub timehash {
1.687     raeburn  4923:     my ($thistime) = @_;
                   4924:     my $timezone = &Apache::lonlocal::gettimezone();
                   4925:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4926:                      ->set_time_zone($timezone);
                   4927:     my $wday = $dt->day_of_week();
                   4928:     if ($wday == 7) { $wday = 0; }
                   4929:     return ( 'second' => $dt->second(),
                   4930:              'minute' => $dt->minute(),
                   4931:              'hour'   => $dt->hour(),
                   4932:              'day'     => $dt->day_of_month(),
                   4933:              'month'   => $dt->month(),
                   4934:              'year'    => $dt->year(),
                   4935:              'weekday' => $wday,
                   4936:              'dayyear' => $dt->day_of_year(),
                   4937:              'dlsav'   => $dt->is_dst() );
1.51      www      4938: }
                   4939: 
1.370     www      4940: sub utc_string {
                   4941:     my ($date)=@_;
1.371     www      4942:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4943: }
                   4944: 
1.51      www      4945: sub maketime {
                   4946:     my %th=@_;
1.687     raeburn  4947:     my ($epoch_time,$timezone,$dt);
                   4948:     $timezone = &Apache::lonlocal::gettimezone();
                   4949:     eval {
                   4950:         $dt = DateTime->new( year   => $th{'year'},
                   4951:                              month  => $th{'month'},
                   4952:                              day    => $th{'day'},
                   4953:                              hour   => $th{'hour'},
                   4954:                              minute => $th{'minute'},
                   4955:                              second => $th{'second'},
                   4956:                              time_zone => $timezone,
                   4957:                          );
                   4958:     };
                   4959:     if (!$@) {
                   4960:         $epoch_time = $dt->epoch;
                   4961:         if ($epoch_time) {
                   4962:             return $epoch_time;
                   4963:         }
                   4964:     }
1.51      www      4965:     return POSIX::mktime(
                   4966:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4967:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4968: }
                   4969: 
                   4970: #########################################
1.51      www      4971: 
                   4972: sub findallcourses {
1.482     raeburn  4973:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4974:     my %roles;
                   4975:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4976:     my %courses;
1.51      www      4977:     my $now=time;
1.482     raeburn  4978:     if (!defined($uname)) {
                   4979:         $uname = $env{'user.name'};
                   4980:     }
                   4981:     if (!defined($udom)) {
                   4982:         $udom = $env{'user.domain'};
                   4983:     }
                   4984:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4985:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4986:         if (!%roles) {
                   4987:             %roles = (
                   4988:                        cc => 1,
1.907     raeburn  4989:                        co => 1,
1.482     raeburn  4990:                        in => 1,
                   4991:                        ep => 1,
                   4992:                        ta => 1,
                   4993:                        cr => 1,
                   4994:                        st => 1,
                   4995:              );
                   4996:         }
                   4997:         foreach my $entry (keys(%roleshash)) {
                   4998:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4999:             if ($trole =~ /^cr/) { 
                   5000:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5001:             } else {
                   5002:                 next if (!exists($roles{$trole}));
                   5003:             }
                   5004:             if ($tend) {
                   5005:                 next if ($tend < $now);
                   5006:             }
                   5007:             if ($tstart) {
                   5008:                 next if ($tstart > $now);
                   5009:             }
1.1058    raeburn  5010:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5011:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5012:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5013:             if ($secpart eq '') {
                   5014:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5015:                 $sec = 'none';
1.1058    raeburn  5016:                 $value .= $cnum.'/';
1.482     raeburn  5017:             } else {
                   5018:                 $cnum = $cnumpart;
                   5019:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5020:                 $value .= $cnum.'/'.$sec;
                   5021:             }
                   5022:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5023:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5024:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5025:                 }
                   5026:             } else {
                   5027:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5028:             }
1.482     raeburn  5029:         }
                   5030:     } else {
                   5031:         foreach my $key (keys(%env)) {
1.483     albertel 5032: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5033:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5034: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5035: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5036: 	        next if (%roles && !exists($roles{$role}));
                   5037: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5038:                 my $active=1;
                   5039:                 if ($starttime) {
                   5040: 		    if ($now<$starttime) { $active=0; }
                   5041:                 }
                   5042:                 if ($endtime) {
                   5043:                     if ($now>$endtime) { $active=0; }
                   5044:                 }
                   5045:                 if ($active) {
1.1058    raeburn  5046:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5047:                     if ($sec eq '') {
                   5048:                         $sec = 'none';
1.1058    raeburn  5049:                     } else {
                   5050:                         $value .= $sec;
                   5051:                     }
                   5052:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5053:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5054:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5055:                         }
                   5056:                     } else {
                   5057:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5058:                     }
1.474     raeburn  5059:                 }
                   5060:             }
1.51      www      5061:         }
                   5062:     }
1.474     raeburn  5063:     return %courses;
1.51      www      5064: }
1.37      matthew  5065: 
1.54      www      5066: ###############################################
1.474     raeburn  5067: 
                   5068: sub blockcheck {
1.1189    raeburn  5069:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  5070: 
1.1189    raeburn  5071:     if (defined($udom) && defined($uname)) {
                   5072:         # If uname and udom are for a course, check for blocks in the course.
                   5073:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5074:             my ($startblock,$endblock,$triggerblock) =
                   5075:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   5076:             return ($startblock,$endblock,$triggerblock);
                   5077:         }
                   5078:     } else {
1.490     raeburn  5079:         $udom = $env{'user.domain'};
                   5080:         $uname = $env{'user.name'};
                   5081:     }
                   5082: 
1.502     raeburn  5083:     my $startblock = 0;
                   5084:     my $endblock = 0;
1.1062    raeburn  5085:     my $triggerblock = '';
1.482     raeburn  5086:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5087: 
1.490     raeburn  5088:     # If uname is for a user, and activity is course-specific, i.e.,
                   5089:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5090: 
1.490     raeburn  5091:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5092:          $activity eq 'groups' || $activity eq 'printout' ||
                   5093:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5094:         ($env{'request.course.id'})) {
1.490     raeburn  5095:         foreach my $key (keys(%live_courses)) {
                   5096:             if ($key ne $env{'request.course.id'}) {
                   5097:                 delete($live_courses{$key});
                   5098:             }
                   5099:         }
                   5100:     }
                   5101: 
                   5102:     my $otheruser = 0;
                   5103:     my %own_courses;
                   5104:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5105:         # Resource belongs to user other than current user.
                   5106:         $otheruser = 1;
                   5107:         # Gather courses for current user
                   5108:         %own_courses = 
                   5109:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5110:     }
                   5111: 
                   5112:     # Gather active course roles - course coordinator, instructor, 
                   5113:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5114: 
                   5115:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5116:         my ($cdom,$cnum);
                   5117:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5118:             $cdom = $env{'course.'.$course.'.domain'};
                   5119:             $cnum = $env{'course.'.$course.'.num'};
                   5120:         } else {
1.490     raeburn  5121:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5122:         }
                   5123:         my $no_ownblock = 0;
                   5124:         my $no_userblock = 0;
1.533     raeburn  5125:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5126:             # Check if current user has 'evb' priv for this
                   5127:             if (defined($own_courses{$course})) {
                   5128:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5129:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5130:                     if ($sec ne 'none') {
                   5131:                         $checkrole .= '/'.$sec;
                   5132:                     }
                   5133:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5134:                         $no_ownblock = 1;
                   5135:                         last;
                   5136:                     }
                   5137:                 }
                   5138:             }
                   5139:             # if they have 'evb' priv and are currently not playing student
                   5140:             next if (($no_ownblock) &&
                   5141:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5142:         }
1.474     raeburn  5143:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5144:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5145:             if ($sec ne 'none') {
1.482     raeburn  5146:                 $checkrole .= '/'.$sec;
1.474     raeburn  5147:             }
1.490     raeburn  5148:             if ($otheruser) {
                   5149:                 # Resource belongs to user other than current user.
                   5150:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5151:                 my (%allroles,%userroles);
                   5152:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5153:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5154:                         my ($trole,$tdom,$tnum,$tsec);
                   5155:                         if ($entry =~ /^cr/) {
                   5156:                             ($trole,$tdom,$tnum,$tsec) = 
                   5157:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5158:                         } else {
                   5159:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5160:                         }
                   5161:                         my ($spec,$area,$trest);
                   5162:                         $area = '/'.$tdom.'/'.$tnum;
                   5163:                         $trest = $tnum;
                   5164:                         if ($tsec ne '') {
                   5165:                             $area .= '/'.$tsec;
                   5166:                             $trest .= '/'.$tsec;
                   5167:                         }
                   5168:                         $spec = $trole.'.'.$area;
                   5169:                         if ($trole =~ /^cr/) {
                   5170:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5171:                                                               $tdom,$spec,$trest,$area);
                   5172:                         } else {
                   5173:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5174:                                                                 $tdom,$spec,$trest,$area);
                   5175:                         }
                   5176:                     }
1.1276    raeburn  5177:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5178:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5179:                         if ($1) {
                   5180:                             $no_userblock = 1;
                   5181:                             last;
                   5182:                         }
1.486     raeburn  5183:                     }
                   5184:                 }
1.490     raeburn  5185:             } else {
                   5186:                 # Resource belongs to current user
                   5187:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5188:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5189:                     $no_ownblock = 1;
                   5190:                     last;
                   5191:                 }
1.474     raeburn  5192:             }
                   5193:         }
                   5194:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5195:         next if (($no_ownblock) &&
1.491     albertel 5196:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5197:         next if ($no_userblock);
1.474     raeburn  5198: 
1.1303    raeburn  5199:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5200:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5201: 
1.1062    raeburn  5202:         my ($start,$end,$trigger) = 
                   5203:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5204:         if (($start != 0) && 
                   5205:             (($startblock == 0) || ($startblock > $start))) {
                   5206:             $startblock = $start;
1.1062    raeburn  5207:             if ($trigger ne '') {
                   5208:                 $triggerblock = $trigger;
                   5209:             }
1.502     raeburn  5210:         }
                   5211:         if (($end != 0)  &&
                   5212:             (($endblock == 0) || ($endblock < $end))) {
                   5213:             $endblock = $end;
1.1062    raeburn  5214:             if ($trigger ne '') {
                   5215:                 $triggerblock = $trigger;
                   5216:             }
1.502     raeburn  5217:         }
1.490     raeburn  5218:     }
1.1062    raeburn  5219:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5220: }
                   5221: 
                   5222: sub get_blocks {
1.1062    raeburn  5223:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5224:     my $startblock = 0;
                   5225:     my $endblock = 0;
1.1062    raeburn  5226:     my $triggerblock = '';
1.490     raeburn  5227:     my $course = $cdom.'_'.$cnum;
                   5228:     $setters->{$course} = {};
                   5229:     $setters->{$course}{'staff'} = [];
                   5230:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5231:     $setters->{$course}{'triggers'} = [];
                   5232:     my (@blockers,%triggered);
                   5233:     my $now = time;
                   5234:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5235:     if ($activity eq 'docs') {
                   5236:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5237:         foreach my $block (@blockers) {
                   5238:             if ($block =~ /^firstaccess____(.+)$/) {
                   5239:                 my $item = $1;
                   5240:                 my $type = 'map';
                   5241:                 my $timersymb = $item;
                   5242:                 if ($item eq 'course') {
                   5243:                     $type = 'course';
                   5244:                 } elsif ($item =~ /___\d+___/) {
                   5245:                     $type = 'resource';
                   5246:                 } else {
                   5247:                     $timersymb = &Apache::lonnet::symbread($item);
                   5248:                 }
                   5249:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5250:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5251:                 $triggered{$block} = {
                   5252:                                        start => $start,
                   5253:                                        end   => $end,
                   5254:                                        type  => $type,
                   5255:                                      };
                   5256:             }
                   5257:         }
                   5258:     } else {
                   5259:         foreach my $block (keys(%commblocks)) {
                   5260:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5261:                 my ($start,$end) = ($1,$2);
                   5262:                 if ($start <= time && $end >= time) {
                   5263:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5264:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5265:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5266:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5267:                                     push(@blockers,$block);
                   5268:                                 }
                   5269:                             }
                   5270:                         }
                   5271:                     }
                   5272:                 }
                   5273:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5274:                 my $item = $1;
                   5275:                 my $timersymb = $item; 
                   5276:                 my $type = 'map';
                   5277:                 if ($item eq 'course') {
                   5278:                     $type = 'course';
                   5279:                 } elsif ($item =~ /___\d+___/) {
                   5280:                     $type = 'resource';
                   5281:                 } else {
                   5282:                     $timersymb = &Apache::lonnet::symbread($item);
                   5283:                 }
                   5284:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5285:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5286:                 if ($start && $end) {
                   5287:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5288:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5289:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5290:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5291:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5292:                                         push(@blockers,$block);
                   5293:                                         $triggered{$block} = {
                   5294:                                                                start => $start,
                   5295:                                                                end   => $end,
                   5296:                                                                type  => $type,
                   5297:                                                              };
                   5298:                                     }
                   5299:                                 }
                   5300:                             }
1.1062    raeburn  5301:                         }
                   5302:                     }
1.490     raeburn  5303:                 }
1.1062    raeburn  5304:             }
                   5305:         }
                   5306:     }
                   5307:     foreach my $blocker (@blockers) {
                   5308:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5309:             &parse_block_record($commblocks{$blocker});
                   5310:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5311:         my ($start,$end,$triggertype);
                   5312:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5313:             ($start,$end) = ($1,$2);
                   5314:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5315:             $start = $triggered{$blocker}{'start'};
                   5316:             $end = $triggered{$blocker}{'end'};
                   5317:             $triggertype = $triggered{$blocker}{'type'};
                   5318:         }
                   5319:         if ($start) {
                   5320:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5321:             if ($triggertype) {
                   5322:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5323:             } else {
                   5324:                 push(@{$$setters{$course}{'triggers'}},0);
                   5325:             }
                   5326:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5327:                 $startblock = $start;
                   5328:                 if ($triggertype) {
                   5329:                     $triggerblock = $blocker;
1.474     raeburn  5330:                 }
                   5331:             }
1.1062    raeburn  5332:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5333:                $endblock = $end;
                   5334:                if ($triggertype) {
                   5335:                    $triggerblock = $blocker;
                   5336:                }
                   5337:             }
1.474     raeburn  5338:         }
                   5339:     }
1.1062    raeburn  5340:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5341: }
                   5342: 
                   5343: sub parse_block_record {
                   5344:     my ($record) = @_;
                   5345:     my ($setuname,$setudom,$title,$blocks);
                   5346:     if (ref($record) eq 'HASH') {
                   5347:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5348:         $title = &unescape($record->{'event'});
                   5349:         $blocks = $record->{'blocks'};
                   5350:     } else {
                   5351:         my @data = split(/:/,$record,3);
                   5352:         if (scalar(@data) eq 2) {
                   5353:             $title = $data[1];
                   5354:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5355:         } else {
                   5356:             ($setuname,$setudom,$title) = @data;
                   5357:         }
                   5358:         $blocks = { 'com' => 'on' };
                   5359:     }
                   5360:     return ($setuname,$setudom,$title,$blocks);
                   5361: }
                   5362: 
1.854     kalberla 5363: sub blocking_status {
1.1189    raeburn  5364:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5365:     my %setters;
1.890     droeschl 5366: 
1.1061    raeburn  5367: # check for active blocking
1.1062    raeburn  5368:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5369:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5370:     my $blocked = 0;
                   5371:     if ($startblock && $endblock) {
                   5372:         $blocked = 1;
                   5373:     }
1.890     droeschl 5374: 
1.1061    raeburn  5375: # caller just wants to know whether a block is active
                   5376:     if (!wantarray) { return $blocked; }
                   5377: 
                   5378: # build a link to a popup window containing the details
                   5379:     my $querystring  = "?activity=$activity";
                   5380: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5381:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5382:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5383:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5384:     } elsif ($activity eq 'docs') {
                   5385:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5386:     }
1.1061    raeburn  5387: 
                   5388:     my $output .= <<'END_MYBLOCK';
                   5389: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5390:     var options = "width=" + w + ",height=" + h + ",";
                   5391:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5392:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5393:     var newWin = window.open(url, wdwName, options);
                   5394:     newWin.focus();
                   5395: }
1.890     droeschl 5396: END_MYBLOCK
1.854     kalberla 5397: 
1.1061    raeburn  5398:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5399:   
1.1061    raeburn  5400:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5401:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5402:     my $class = 'LC_comblock';
1.1062    raeburn  5403:     if ($activity eq 'docs') {
                   5404:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5405:         $class = '';
1.1063    raeburn  5406:     } elsif ($activity eq 'printout') {
                   5407:         $text = &mt('Printing Blocked');
1.1232    raeburn  5408:     } elsif ($activity eq 'passwd') {
                   5409:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5410:     } elsif ($activity eq 'alert') {
                   5411:         $text = &mt('Checking Critical Messages Blocked');
                   5412:     } elsif ($activity eq 'reinit') {
                   5413:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5414:     }
1.1061    raeburn  5415:     $output .= <<"END_BLOCK";
1.1217    raeburn  5416: <div class='$class'>
1.869     kalberla 5417:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5418:   title='$text'>
                   5419:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5420:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5421:   title='$text'>$text</a>
1.867     kalberla 5422: </div>
                   5423: 
                   5424: END_BLOCK
1.474     raeburn  5425: 
1.1061    raeburn  5426:     return ($blocked, $output);
1.854     kalberla 5427: }
1.490     raeburn  5428: 
1.60      matthew  5429: ###############################################
                   5430: 
1.682     raeburn  5431: sub check_ip_acc {
1.1201    raeburn  5432:     my ($acc,$clientip)=@_;
1.682     raeburn  5433:     &Apache::lonxml::debug("acc is $acc");
                   5434:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5435:         return 1;
                   5436:     }
1.1219    raeburn  5437:     my $allowed;
1.1252    raeburn  5438:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5439: 
                   5440:     my $name;
1.1219    raeburn  5441:     my %access = (
                   5442:                      allowfrom => 1,
                   5443:                      denyfrom  => 0,
                   5444:                  );
                   5445:     my @allows;
                   5446:     my @denies;
                   5447:     foreach my $item (split(',',$acc)) {
                   5448:         $item =~ s/^\s*//;
                   5449:         $item =~ s/\s*$//;
                   5450:         my $pattern;
                   5451:         if ($item =~ /^\!(.+)$/) {
                   5452:             push(@denies,$1);
                   5453:         } else {
                   5454:             push(@allows,$item);
                   5455:         }
                   5456:    }
                   5457:    my $numdenies = scalar(@denies);
                   5458:    my $numallows = scalar(@allows);
                   5459:    my $count = 0;
                   5460:    foreach my $pattern (@denies,@allows) {
                   5461:         $count ++; 
                   5462:         my $acctype = 'allowfrom';
                   5463:         if ($count <= $numdenies) {
                   5464:             $acctype = 'denyfrom';
                   5465:         }
1.682     raeburn  5466:         if ($pattern =~ /\*$/) {
                   5467:             #35.8.*
                   5468:             $pattern=~s/\*//;
1.1219    raeburn  5469:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5470:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5471:             #35.8.3.[34-56]
                   5472:             my $low=$2;
                   5473:             my $high=$3;
                   5474:             $pattern=$1;
                   5475:             if ($ip =~ /^\Q$pattern\E/) {
                   5476:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5477:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5478:             }
                   5479:         } elsif ($pattern =~ /^\*/) {
                   5480:             #*.msu.edu
                   5481:             $pattern=~s/\*//;
                   5482:             if (!defined($name)) {
                   5483:                 use Socket;
                   5484:                 my $netaddr=inet_aton($ip);
                   5485:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5486:             }
1.1219    raeburn  5487:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5488:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5489:             #127.0.0.1
1.1219    raeburn  5490:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5491:         } else {
                   5492:             #some.name.com
                   5493:             if (!defined($name)) {
                   5494:                 use Socket;
                   5495:                 my $netaddr=inet_aton($ip);
                   5496:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5497:             }
1.1219    raeburn  5498:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5499:         }
                   5500:         if ($allowed =~ /^(0|1)$/) { last; }
                   5501:     }
                   5502:     if ($allowed eq '') {
                   5503:         if ($numdenies && !$numallows) {
                   5504:             $allowed = 1;
                   5505:         } else {
                   5506:             $allowed = 0;
1.682     raeburn  5507:         }
                   5508:     }
                   5509:     return $allowed;
                   5510: }
                   5511: 
                   5512: ###############################################
                   5513: 
1.60      matthew  5514: =pod
                   5515: 
1.112     bowersj2 5516: =head1 Domain Template Functions
                   5517: 
                   5518: =over 4
                   5519: 
                   5520: =item * &determinedomain()
1.60      matthew  5521: 
                   5522: Inputs: $domain (usually will be undef)
                   5523: 
1.63      www      5524: Returns: Determines which domain should be used for designs
1.60      matthew  5525: 
                   5526: =cut
1.54      www      5527: 
1.60      matthew  5528: ###############################################
1.63      www      5529: sub determinedomain {
                   5530:     my $domain=shift;
1.531     albertel 5531:     if (! $domain) {
1.60      matthew  5532:         # Determine domain if we have not been given one
1.893     raeburn  5533:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5534:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5535:         if ($env{'request.role.domain'}) { 
                   5536:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5537:         }
                   5538:     }
1.63      www      5539:     return $domain;
                   5540: }
                   5541: ###############################################
1.517     raeburn  5542: 
1.518     albertel 5543: sub devalidate_domconfig_cache {
                   5544:     my ($udom)=@_;
                   5545:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5546: }
                   5547: 
                   5548: # ---------------------- Get domain configuration for a domain
                   5549: sub get_domainconf {
                   5550:     my ($udom) = @_;
                   5551:     my $cachetime=1800;
                   5552:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5553:     if (defined($cached)) { return %{$result}; }
                   5554: 
                   5555:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5556: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5557:     my (%designhash,%legacy);
1.518     albertel 5558:     if (keys(%domconfig) > 0) {
                   5559:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5560:             if (keys(%{$domconfig{'login'}})) {
                   5561:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5562:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5563:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5564:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5565:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5566:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5567:                                         if ($key eq 'loginvia') {
                   5568:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5569:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5570:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5571:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5572: 
                   5573:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5574:                                                 } else {
                   5575:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5576:                                                 }
1.948     raeburn  5577:                                             }
1.1208    raeburn  5578:                                         } elsif ($key eq 'headtag') {
                   5579:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5580:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5581:                                             }
1.946     raeburn  5582:                                         }
1.1208    raeburn  5583:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5584:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5585:                                         }
1.946     raeburn  5586:                                     }
                   5587:                                 }
                   5588:                             }
                   5589:                         } else {
                   5590:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5591:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5592:                                     $domconfig{'login'}{$key}{$img};
                   5593:                             }
1.699     raeburn  5594:                         }
                   5595:                     } else {
                   5596:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5597:                     }
1.632     raeburn  5598:                 }
                   5599:             } else {
                   5600:                 $legacy{'login'} = 1;
1.518     albertel 5601:             }
1.632     raeburn  5602:         } else {
                   5603:             $legacy{'login'} = 1;
1.518     albertel 5604:         }
                   5605:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5606:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5607:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5608:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5609:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5610:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5611:                         }
1.518     albertel 5612:                     }
                   5613:                 }
1.632     raeburn  5614:             } else {
                   5615:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5616:             }
1.632     raeburn  5617:         } else {
                   5618:             $legacy{'rolecolors'} = 1;
1.518     albertel 5619:         }
1.948     raeburn  5620:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5621:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5622:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5623:             }
                   5624:         }
1.632     raeburn  5625:         if (keys(%legacy) > 0) {
                   5626:             my %legacyhash = &get_legacy_domconf($udom);
                   5627:             foreach my $item (keys(%legacyhash)) {
                   5628:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5629:                     if ($legacy{'login'}) { 
                   5630:                         $designhash{$item} = $legacyhash{$item};
                   5631:                     }
                   5632:                 } else {
                   5633:                     if ($legacy{'rolecolors'}) {
                   5634:                         $designhash{$item} = $legacyhash{$item};
                   5635:                     }
1.518     albertel 5636:                 }
                   5637:             }
                   5638:         }
1.632     raeburn  5639:     } else {
                   5640:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5641:     }
                   5642:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5643: 				  $cachetime);
                   5644:     return %designhash;
                   5645: }
                   5646: 
1.632     raeburn  5647: sub get_legacy_domconf {
                   5648:     my ($udom) = @_;
                   5649:     my %legacyhash;
                   5650:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5651:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5652:     if (-e $designfile) {
                   5653:         if ( open (my $fh,"<$designfile") ) {
                   5654:             while (my $line = <$fh>) {
                   5655:                 next if ($line =~ /^\#/);
                   5656:                 chomp($line);
                   5657:                 my ($key,$val)=(split(/\=/,$line));
                   5658:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5659:             }
                   5660:             close($fh);
                   5661:         }
                   5662:     }
1.1026    raeburn  5663:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5664:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5665:     }
                   5666:     return %legacyhash;
                   5667: }
                   5668: 
1.63      www      5669: =pod
                   5670: 
1.112     bowersj2 5671: =item * &domainlogo()
1.63      www      5672: 
                   5673: Inputs: $domain (usually will be undef)
                   5674: 
                   5675: Returns: A link to a domain logo, if the domain logo exists.
                   5676: If the domain logo does not exist, a description of the domain.
                   5677: 
                   5678: =cut
1.112     bowersj2 5679: 
1.63      www      5680: ###############################################
                   5681: sub domainlogo {
1.517     raeburn  5682:     my $domain = &determinedomain(shift);
1.518     albertel 5683:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5684:     # See if there is a logo
                   5685:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5686:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5687:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5688: 	    if ($imgsrc =~ m{^/res/}) {
                   5689: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5690: 		&Apache::lonnet::repcopy($local_name);
                   5691: 	    }
                   5692: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5693:         } 
                   5694:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5695:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5696:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5697:     } else {
1.60      matthew  5698:         return '';
1.59      www      5699:     }
                   5700: }
1.63      www      5701: ##############################################
                   5702: 
                   5703: =pod
                   5704: 
1.112     bowersj2 5705: =item * &designparm()
1.63      www      5706: 
                   5707: Inputs: $which parameter; $domain (usually will be undef)
                   5708: 
                   5709: Returns: value of designparamter $which
                   5710: 
                   5711: =cut
1.112     bowersj2 5712: 
1.397     albertel 5713: 
1.400     albertel 5714: ##############################################
1.397     albertel 5715: sub designparm {
                   5716:     my ($which,$domain)=@_;
                   5717:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5718:         return $env{'environment.color.'.$which};
1.96      www      5719:     }
1.63      www      5720:     $domain=&determinedomain($domain);
1.1016    raeburn  5721:     my %domdesign;
                   5722:     unless ($domain eq 'public') {
                   5723:         %domdesign = &get_domainconf($domain);
                   5724:     }
1.520     raeburn  5725:     my $output;
1.517     raeburn  5726:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5727:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5728:     } else {
1.520     raeburn  5729:         $output = $defaultdesign{$which};
                   5730:     }
                   5731:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5732:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5733:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5734:             if ($output =~ m{^/res/}) {
                   5735:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5736:                 &Apache::lonnet::repcopy($local_name);
                   5737:             }
1.520     raeburn  5738:             $output = &lonhttpdurl($output);
                   5739:         }
1.63      www      5740:     }
1.520     raeburn  5741:     return $output;
1.63      www      5742: }
1.59      www      5743: 
1.822     bisitz   5744: ##############################################
                   5745: =pod
                   5746: 
1.832     bisitz   5747: =item * &authorspace()
                   5748: 
1.1028    raeburn  5749: Inputs: $url (usually will be undef).
1.832     bisitz   5750: 
1.1132    raeburn  5751: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5752:          directory being viewed (or for which action is being taken). 
                   5753:          If $url is provided, and begins /priv/<domain>/<uname>
                   5754:          the path will be that portion of the $context argument.
                   5755:          Otherwise the path will be for the author space of the current
                   5756:          user when the current role is author, or for that of the 
                   5757:          co-author/assistant co-author space when the current role 
                   5758:          is co-author or assistant co-author.
1.832     bisitz   5759: 
                   5760: =cut
                   5761: 
                   5762: sub authorspace {
1.1028    raeburn  5763:     my ($url) = @_;
                   5764:     if ($url ne '') {
                   5765:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5766:            return $1;
                   5767:         }
                   5768:     }
1.832     bisitz   5769:     my $caname = '';
1.1024    www      5770:     my $cadom = '';
1.1028    raeburn  5771:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5772:         ($cadom,$caname) =
1.832     bisitz   5773:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5774:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5775:         $caname = $env{'user.name'};
1.1024    www      5776:         $cadom = $env{'user.domain'};
1.832     bisitz   5777:     }
1.1028    raeburn  5778:     if (($caname ne '') && ($cadom ne '')) {
                   5779:         return "/priv/$cadom/$caname/";
                   5780:     }
                   5781:     return;
1.832     bisitz   5782: }
                   5783: 
                   5784: ##############################################
                   5785: =pod
                   5786: 
1.822     bisitz   5787: =item * &head_subbox()
                   5788: 
                   5789: Inputs: $content (contains HTML code with page functions, etc.)
                   5790: 
                   5791: Returns: HTML div with $content
                   5792:          To be included in page header
                   5793: 
                   5794: =cut
                   5795: 
                   5796: sub head_subbox {
                   5797:     my ($content)=@_;
                   5798:     my $output =
1.993     raeburn  5799:         '<div class="LC_head_subbox">'
1.822     bisitz   5800:        .$content
                   5801:        .'</div>'
                   5802: }
                   5803: 
                   5804: ##############################################
                   5805: =pod
                   5806: 
                   5807: =item * &CSTR_pageheader()
                   5808: 
1.1026    raeburn  5809: Input: (optional) filename from which breadcrumb trail is built.
                   5810:        In most cases no input as needed, as $env{'request.filename'}
                   5811:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5812: 
                   5813: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5814:          To be included on Authoring Space pages
1.822     bisitz   5815: 
                   5816: =cut
                   5817: 
                   5818: sub CSTR_pageheader {
1.1026    raeburn  5819:     my ($trailfile) = @_;
                   5820:     if ($trailfile eq '') {
                   5821:         $trailfile = $env{'request.filename'};
                   5822:     }
                   5823: 
                   5824: # this is for resources; directories have customtitle, and crumbs
                   5825: # and select recent are created in lonpubdir.pm
                   5826: 
                   5827:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5828:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5829:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5830:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5831:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5832: 
                   5833:     my $parentpath = '';
                   5834:     my $lastitem = '';
                   5835:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5836:         $parentpath = $1;
                   5837:         $lastitem = $2;
                   5838:     } else {
                   5839:         $lastitem = $thisdisfn;
                   5840:     }
1.921     bisitz   5841: 
1.1246    raeburn  5842:     my ($crsauthor,$title);
                   5843:     if (($env{'request.course.id'}) &&
                   5844:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5845:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5846:         $crsauthor = 1;
                   5847:         $title = &mt('Course Authoring Space');
                   5848:     } else {
                   5849:         $title = &mt('Authoring Space');
                   5850:     }
                   5851: 
1.1314    raeburn  5852:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  5853:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  5854:         $target = '';
                   5855:         $crumbtarget = '';
1.1313    raeburn  5856:     }
                   5857: 
1.921     bisitz   5858:     my $output =
1.822     bisitz   5859:          '<div>'
                   5860:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5861:         .'<b>'.$title.'</b> '
1.1314    raeburn  5862:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5863:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5864: 
                   5865:     if ($lastitem) {
                   5866:         $output .=
                   5867:              '<span class="LC_filename">'
                   5868:             .$lastitem
                   5869:             .'</span>';
                   5870:     }
1.1245    raeburn  5871: 
1.1246    raeburn  5872:     if ($crsauthor) {
                   5873:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5874:     } else {
                   5875:         $output .=
                   5876:              '<br />'
1.1314    raeburn  5877:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  5878:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5879:             .'</form>'
                   5880:             .&Apache::lonmenu::constspaceform();
                   5881:     }
                   5882:     $output .= '</div>';
1.921     bisitz   5883: 
                   5884:     return $output;
1.822     bisitz   5885: }
                   5886: 
1.60      matthew  5887: ###############################################
                   5888: ###############################################
                   5889: 
                   5890: =pod
                   5891: 
1.112     bowersj2 5892: =back
                   5893: 
1.549     albertel 5894: =head1 HTML Helpers
1.112     bowersj2 5895: 
                   5896: =over 4
                   5897: 
                   5898: =item * &bodytag()
1.60      matthew  5899: 
                   5900: Returns a uniform header for LON-CAPA web pages.
                   5901: 
                   5902: Inputs: 
                   5903: 
1.112     bowersj2 5904: =over 4
                   5905: 
                   5906: =item * $title, A title to be displayed on the page.
                   5907: 
                   5908: =item * $function, the current role (can be undef).
                   5909: 
                   5910: =item * $addentries, extra parameters for the <body> tag.
                   5911: 
                   5912: =item * $bodyonly, if defined, only return the <body> tag.
                   5913: 
                   5914: =item * $domain, if defined, force a given domain.
                   5915: 
                   5916: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5917:             text interface only)
1.60      matthew  5918: 
1.814     bisitz   5919: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5920:                      navigational links
1.317     albertel 5921: 
1.338     albertel 5922: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5923: 
1.460     albertel 5924: =item * $args, optional argument valid values are
                   5925:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5926:             use_absolute     -> for external resource or syllabus, this will
                   5927:                                 contain https://<hostname> if server uses
                   5928:                                 https (as per hosts.tab), but request is for http
                   5929:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5930: 
1.1096    raeburn  5931: =item * $advtoolsref, optional argument, ref to an array containing
                   5932:             inlineremote items to be added in "Functions" menu below
                   5933:             breadcrumbs.
                   5934: 
1.1316  ! raeburn  5935: =item * $ltiscope, optional argument, will be one of: resource, map or
        !          5936:             course, if LON-CAPA is in LTI Provider context. Value is
        !          5937:             the scope of use, i.e., launch was for access to a single, a map
        !          5938:             or the entire course.
        !          5939: 
        !          5940: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
        !          5941:             context, this will contain the URL for the landing item in
        !          5942:             the course, after launch from an LTI Consumer
        !          5943: 
1.112     bowersj2 5944: =back
                   5945: 
1.60      matthew  5946: Returns: A uniform header for LON-CAPA web pages.  
                   5947: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5948: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5949: other decorations will be returned.
                   5950: 
                   5951: =cut
                   5952: 
1.54      www      5953: sub bodytag {
1.831     bisitz   5954:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1316  ! raeburn  5955:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri)=@_;
1.339     albertel 5956: 
1.954     raeburn  5957:     my $public;
                   5958:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5959:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5960:         $public = 1;
                   5961:     }
1.460     albertel 5962:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5963:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  5964:     my $hostname = $args->{'hostname'};
1.339     albertel 5965: 
1.183     matthew  5966:     $function = &get_users_function() if (!$function);
1.339     albertel 5967:     my $img =    &designparm($function.'.img',$domain);
                   5968:     my $font =   &designparm($function.'.font',$domain);
                   5969:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5970: 
1.803     bisitz   5971:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5972: 		   'bgcolor' => $pgbg,
1.339     albertel 5973: 		   'text'    => $font,
                   5974:                    'alink'   => &designparm($function.'.alink',$domain),
                   5975: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5976: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5977:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5978: 
1.63      www      5979:  # role and realm
1.1178    raeburn  5980:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5981:     if ($realm) {
                   5982:         $realm = '/'.$realm;
                   5983:     }
1.378     raeburn  5984:     if ($role  eq 'ca') {
1.479     albertel 5985:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5986:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5987:     } 
1.55      www      5988: # realm
1.258     albertel 5989:     if ($env{'request.course.id'}) {
1.378     raeburn  5990:         if ($env{'request.role'} !~ /^cr/) {
                   5991:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5992:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  5993:             if ($env{'request.role.desc'}) {
                   5994:                 $role = $env{'request.role.desc'};
                   5995:             } else {
                   5996:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5997:             }
1.1257    raeburn  5998:         } else {
                   5999:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6000:         }
1.898     raeburn  6001:         if ($env{'request.course.sec'}) {
                   6002:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   6003:         }   
1.359     albertel 6004: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  6005:     } else {
                   6006:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6007:     }
1.433     albertel 6008: 
1.359     albertel 6009:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6010: 
1.438     albertel 6011:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6012: 
1.101     www      6013: # construct main body tag
1.359     albertel 6014:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6015: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6016: 
1.1131    raeburn  6017:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6018: 
1.1130    raeburn  6019:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6020:         return $bodytag;
1.1130    raeburn  6021:     }
1.359     albertel 6022: 
1.954     raeburn  6023:     if ($public) {
1.433     albertel 6024: 	undef($role);
                   6025:     }
1.359     albertel 6026:     
1.762     bisitz   6027:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6028:     #
                   6029:     # Extra info if you are the DC
                   6030:     my $dc_info = '';
                   6031:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   6032:                         $env{'course.'.$env{'request.course.id'}.
                   6033:                                  '.domain'}.'/'})) {
                   6034:         my $cid = $env{'request.course.id'};
1.917     raeburn  6035:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6036:         $dc_info =~ s/\s+$//;
1.359     albertel 6037:     }
                   6038: 
1.1237    raeburn  6039:     my $crstype;
                   6040:     if ($env{'request.course.id'}) {
                   6041:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   6042:     } elsif ($args->{'crstype'}) {
                   6043:         $crstype = $args->{'crstype'};
                   6044:     }
                   6045:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6046:         undef($role);
                   6047:     } else {
1.1242    raeburn  6048:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6049:     }
1.853     droeschl 6050: 
1.903     droeschl 6051:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6052: 
                   6053:         #    if ($env{'request.state'} eq 'construct') {
                   6054:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6055:         #    }
                   6056: 
1.1130    raeburn  6057:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6058:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6059: 
1.1237    raeburn  6060:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 6061: 
1.916     droeschl 6062:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  6063:              if ($dc_info) {
                   6064:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6065:              }
1.1130    raeburn  6066:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 6067:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 6068:             return $bodytag;
                   6069:         }
1.894     droeschl 6070: 
1.927     raeburn  6071:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  6072:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  6073:         }
1.916     droeschl 6074: 
1.1130    raeburn  6075:         $bodytag .= $right;
1.852     droeschl 6076: 
1.917     raeburn  6077:         if ($dc_info) {
                   6078:             $dc_info = &dc_courseid_toggle($dc_info);
                   6079:         }
                   6080:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 6081: 
1.1169    raeburn  6082:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6083:         if ($args->{'no_secondary_menu'}) {
                   6084:             return $bodytag;
                   6085:         }
1.1169    raeburn  6086:         #don't show menus for public users
1.954     raeburn  6087:         if (!$public){
1.1316  ! raeburn  6088:             $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope);
1.903     droeschl 6089:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6090:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6091:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6092:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316  ! raeburn  6093:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6094:             } elsif ($forcereg) {
                   6095:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6096:                                                             $args->{'group'},
1.1274    raeburn  6097:                                                             $args->{'hide_buttons'},
1.1316  ! raeburn  6098:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6099:             } else {
                   6100:                 $bodytag .= 
                   6101:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6102:                                                         $forcereg,$args->{'group'},
                   6103:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6104:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6105:             }
1.903     droeschl 6106:         }else{
                   6107:             # this is to seperate menu from content when there's no secondary
                   6108:             # menu. Especially needed for public accessible ressources.
                   6109:             $bodytag .= '<hr style="clear:both" />';
                   6110:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6111:         }
1.903     droeschl 6112: 
1.235     raeburn  6113:         return $bodytag;
1.182     matthew  6114: }
                   6115: 
1.917     raeburn  6116: sub dc_courseid_toggle {
                   6117:     my ($dc_info) = @_;
1.980     raeburn  6118:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6119:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6120:            &mt('(More ...)').'</a></span>'.
                   6121:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6122: }
                   6123: 
1.330     albertel 6124: sub make_attr_string {
                   6125:     my ($register,$attr_ref) = @_;
                   6126: 
                   6127:     if ($attr_ref && !ref($attr_ref)) {
                   6128: 	die("addentries Must be a hash ref ".
                   6129: 	    join(':',caller(1))." ".
                   6130: 	    join(':',caller(0))." ");
                   6131:     }
                   6132: 
                   6133:     if ($register) {
1.339     albertel 6134: 	my ($on_load,$on_unload);
                   6135: 	foreach my $key (keys(%{$attr_ref})) {
                   6136: 	    if      (lc($key) eq 'onload') {
                   6137: 		$on_load.=$attr_ref->{$key}.';';
                   6138: 		delete($attr_ref->{$key});
                   6139: 
                   6140: 	    } elsif (lc($key) eq 'onunload') {
                   6141: 		$on_unload.=$attr_ref->{$key}.';';
                   6142: 		delete($attr_ref->{$key});
                   6143: 	    }
                   6144: 	}
1.953     droeschl 6145: 	$attr_ref->{'onload'}  = $on_load;
                   6146: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6147:     }
1.339     albertel 6148: 
1.330     albertel 6149:     my $attr_string;
1.1159    raeburn  6150:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6151: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6152:     }
                   6153:     return $attr_string;
                   6154: }
                   6155: 
                   6156: 
1.182     matthew  6157: ###############################################
1.251     albertel 6158: ###############################################
                   6159: 
                   6160: =pod
                   6161: 
                   6162: =item * &endbodytag()
                   6163: 
                   6164: Returns a uniform footer for LON-CAPA web pages.
                   6165: 
1.635     raeburn  6166: Inputs: 1 - optional reference to an args hash
                   6167: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6168: a 'Continue' link is not displayed if the page contains an
                   6169: internal redirect in the <head></head> section,
                   6170: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6171: 
                   6172: =cut
                   6173: 
                   6174: sub endbodytag {
1.635     raeburn  6175:     my ($args) = @_;
1.1080    raeburn  6176:     my $endbodytag;
                   6177:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6178:         $endbodytag='</body>';
                   6179:     }
1.315     albertel 6180:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6181:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6182: 	    $endbodytag=
                   6183: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6184: 	        &mt('Continue').'</a>'.
                   6185: 	        $endbodytag;
                   6186:         }
1.315     albertel 6187:     }
1.251     albertel 6188:     return $endbodytag;
                   6189: }
                   6190: 
1.352     albertel 6191: =pod
                   6192: 
                   6193: =item * &standard_css()
                   6194: 
                   6195: Returns a style sheet
                   6196: 
                   6197: Inputs: (all optional)
                   6198:             domain         -> force to color decorate a page for a specific
                   6199:                                domain
                   6200:             function       -> force usage of a specific rolish color scheme
                   6201:             bgcolor        -> override the default page bgcolor
                   6202: 
                   6203: =cut
                   6204: 
1.343     albertel 6205: sub standard_css {
1.345     albertel 6206:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6207:     $function  = &get_users_function() if (!$function);
                   6208:     my $img    = &designparm($function.'.img',   $domain);
                   6209:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6210:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6211:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6212: #second colour for later usage
1.345     albertel 6213:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6214:     my $pgbg_or_bgcolor =
                   6215: 	         $bgcolor ||
1.352     albertel 6216: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6217:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6218:     my $alink  = &designparm($function.'.alink', $domain);
                   6219:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6220:     my $link   = &designparm($function.'.link',  $domain);
                   6221: 
1.602     albertel 6222:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6223:     my $mono                 = 'monospace';
1.850     bisitz   6224:     my $data_table_head      = $sidebg;
                   6225:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6226:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6227:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6228:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6229:     my $mail_new             = '#FFBB77';
                   6230:     my $mail_new_hover       = '#DD9955';
                   6231:     my $mail_read            = '#BBBB77';
                   6232:     my $mail_read_hover      = '#999944';
                   6233:     my $mail_replied         = '#AAAA88';
                   6234:     my $mail_replied_hover   = '#888855';
                   6235:     my $mail_other           = '#99BBBB';
                   6236:     my $mail_other_hover     = '#669999';
1.391     albertel 6237:     my $table_header         = '#DDDDDD';
1.489     raeburn  6238:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6239:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6240:     my $button_hover         = '#BF2317';
1.392     albertel 6241: 
1.608     albertel 6242:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6243:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6244:                                              : '0 3px 0 4px';
1.448     albertel 6245: 
1.523     albertel 6246: 
1.343     albertel 6247:     return <<END;
1.947     droeschl 6248: 
                   6249: /* needed for iframe to allow 100% height in FF */
                   6250: body, html { 
                   6251:     margin: 0;
                   6252:     padding: 0 0.5%;
                   6253:     height: 99%; /* to avoid scrollbars */
                   6254: }
                   6255: 
1.795     www      6256: body {
1.911     bisitz   6257:   font-family: $sans;
                   6258:   line-height:130%;
                   6259:   font-size:0.83em;
                   6260:   color:$font;
1.795     www      6261: }
                   6262: 
1.959     onken    6263: a:focus,
                   6264: a:focus img {
1.795     www      6265:   color: red;
                   6266: }
1.698     harmsja  6267: 
1.911     bisitz   6268: form, .inline {
                   6269:   display: inline;
1.795     www      6270: }
1.721     harmsja  6271: 
1.795     www      6272: .LC_right {
1.911     bisitz   6273:   text-align:right;
1.795     www      6274: }
                   6275: 
                   6276: .LC_middle {
1.911     bisitz   6277:   vertical-align:middle;
1.795     www      6278: }
1.721     harmsja  6279: 
1.1130    raeburn  6280: .LC_floatleft {
                   6281:   float: left;
                   6282: }
                   6283: 
                   6284: .LC_floatright {
                   6285:   float: right;
                   6286: }
                   6287: 
1.911     bisitz   6288: .LC_400Box {
                   6289:   width:400px;
                   6290: }
1.721     harmsja  6291: 
1.947     droeschl 6292: .LC_iframecontainer {
                   6293:     width: 98%;
                   6294:     margin: 0;
                   6295:     position: fixed;
                   6296:     top: 8.5em;
                   6297:     bottom: 0;
                   6298: }
                   6299: 
                   6300: .LC_iframecontainer iframe{
                   6301:     border: none;
                   6302:     width: 100%;
                   6303:     height: 100%;
                   6304: }
                   6305: 
1.778     bisitz   6306: .LC_filename {
                   6307:   font-family: $mono;
                   6308:   white-space:pre;
1.921     bisitz   6309:   font-size: 120%;
1.778     bisitz   6310: }
                   6311: 
                   6312: .LC_fileicon {
                   6313:   border: none;
                   6314:   height: 1.3em;
                   6315:   vertical-align: text-bottom;
                   6316:   margin-right: 0.3em;
                   6317:   text-decoration:none;
                   6318: }
                   6319: 
1.1008    www      6320: .LC_setting {
                   6321:   text-decoration:underline;
                   6322: }
                   6323: 
1.350     albertel 6324: .LC_error {
                   6325:   color: red;
                   6326: }
1.795     www      6327: 
1.1097    bisitz   6328: .LC_warning {
                   6329:   color: darkorange;
                   6330: }
                   6331: 
1.457     albertel 6332: .LC_diff_removed {
1.733     bisitz   6333:   color: red;
1.394     albertel 6334: }
1.532     albertel 6335: 
                   6336: .LC_info,
1.457     albertel 6337: .LC_success,
                   6338: .LC_diff_added {
1.350     albertel 6339:   color: green;
                   6340: }
1.795     www      6341: 
1.802     bisitz   6342: div.LC_confirm_box {
                   6343:   background-color: #FAFAFA;
                   6344:   border: 1px solid $lg_border_color;
                   6345:   margin-right: 0;
                   6346:   padding: 5px;
                   6347: }
                   6348: 
                   6349: div.LC_confirm_box .LC_error img,
                   6350: div.LC_confirm_box .LC_success img {
                   6351:   vertical-align: middle;
                   6352: }
                   6353: 
1.1242    raeburn  6354: .LC_maxwidth {
                   6355:   max-width: 100%;
                   6356:   height: auto;
                   6357: }
                   6358: 
1.1243    raeburn  6359: .LC_textsize_mobile {
                   6360:   \@media only screen and (max-device-width: 480px) {
                   6361:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6362:   }
                   6363: }
                   6364: 
1.440     albertel 6365: .LC_icon {
1.771     droeschl 6366:   border: none;
1.790     droeschl 6367:   vertical-align: middle;
1.771     droeschl 6368: }
                   6369: 
1.543     albertel 6370: .LC_docs_spacer {
                   6371:   width: 25px;
                   6372:   height: 1px;
1.771     droeschl 6373:   border: none;
1.543     albertel 6374: }
1.346     albertel 6375: 
1.532     albertel 6376: .LC_internal_info {
1.735     bisitz   6377:   color: #999999;
1.532     albertel 6378: }
                   6379: 
1.794     www      6380: .LC_discussion {
1.1050    www      6381:   background: $data_table_dark;
1.911     bisitz   6382:   border: 1px solid black;
                   6383:   margin: 2px;
1.794     www      6384: }
                   6385: 
                   6386: .LC_disc_action_left {
1.1050    www      6387:   background: $sidebg;
1.911     bisitz   6388:   text-align: left;
1.1050    www      6389:   padding: 4px;
                   6390:   margin: 2px;
1.794     www      6391: }
                   6392: 
                   6393: .LC_disc_action_right {
1.1050    www      6394:   background: $sidebg;
1.911     bisitz   6395:   text-align: right;
1.1050    www      6396:   padding: 4px;
                   6397:   margin: 2px;
1.794     www      6398: }
                   6399: 
                   6400: .LC_disc_new_item {
1.911     bisitz   6401:   background: white;
                   6402:   border: 2px solid red;
1.1050    www      6403:   margin: 4px;
                   6404:   padding: 4px;
1.794     www      6405: }
                   6406: 
                   6407: .LC_disc_old_item {
1.911     bisitz   6408:   background: white;
1.1050    www      6409:   margin: 4px;
                   6410:   padding: 4px;
1.794     www      6411: }
                   6412: 
1.458     albertel 6413: table.LC_pastsubmission {
                   6414:   border: 1px solid black;
                   6415:   margin: 2px;
                   6416: }
                   6417: 
1.924     bisitz   6418: table#LC_menubuttons {
1.345     albertel 6419:   width: 100%;
                   6420:   background: $pgbg;
1.392     albertel 6421:   border: 2px;
1.402     albertel 6422:   border-collapse: separate;
1.803     bisitz   6423:   padding: 0;
1.345     albertel 6424: }
1.392     albertel 6425: 
1.801     tempelho 6426: table#LC_title_bar a {
                   6427:   color: $fontmenu;
                   6428: }
1.836     bisitz   6429: 
1.807     droeschl 6430: table#LC_title_bar {
1.819     tempelho 6431:   clear: both;
1.836     bisitz   6432:   display: none;
1.807     droeschl 6433: }
                   6434: 
1.795     www      6435: table#LC_title_bar,
1.933     droeschl 6436: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6437: table#LC_title_bar.LC_with_remote {
1.359     albertel 6438:   width: 100%;
1.392     albertel 6439:   border-color: $pgbg;
                   6440:   border-style: solid;
                   6441:   border-width: $border;
1.379     albertel 6442:   background: $pgbg;
1.801     tempelho 6443:   color: $fontmenu;
1.392     albertel 6444:   border-collapse: collapse;
1.803     bisitz   6445:   padding: 0;
1.819     tempelho 6446:   margin: 0;
1.359     albertel 6447: }
1.795     www      6448: 
1.933     droeschl 6449: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6450:     margin: 0;
                   6451:     padding: 0;
1.933     droeschl 6452:     position: relative;
                   6453:     list-style: none;
1.913     droeschl 6454: }
1.933     droeschl 6455: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6456:     display: inline;
                   6457: }
1.933     droeschl 6458: 
                   6459: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6460:     padding: 0;
1.933     droeschl 6461:     margin: 0;
                   6462:     float: left;
1.913     droeschl 6463: }
1.933     droeschl 6464: .LC_breadcrumb_tools_tools {
                   6465:     padding: 0;
                   6466:     margin: 0;
1.913     droeschl 6467:     float: right;
                   6468: }
                   6469: 
1.1240    raeburn  6470: .LC_placement_prog {
                   6471:     padding-right: 20px;
                   6472:     font-weight: bold;
                   6473:     font-size: 90%;
                   6474: }
                   6475: 
1.359     albertel 6476: table#LC_title_bar td {
                   6477:   background: $tabbg;
                   6478: }
1.795     www      6479: 
1.911     bisitz   6480: table#LC_menubuttons img {
1.803     bisitz   6481:   border: none;
1.346     albertel 6482: }
1.795     www      6483: 
1.842     droeschl 6484: .LC_breadcrumbs_component {
1.911     bisitz   6485:   float: right;
                   6486:   margin: 0 1em;
1.357     albertel 6487: }
1.842     droeschl 6488: .LC_breadcrumbs_component img {
1.911     bisitz   6489:   vertical-align: middle;
1.777     tempelho 6490: }
1.795     www      6491: 
1.1243    raeburn  6492: .LC_breadcrumbs_hoverable {
                   6493:   background: $sidebg;
                   6494: }
                   6495: 
1.383     albertel 6496: td.LC_table_cell_checkbox {
                   6497:   text-align: center;
                   6498: }
1.795     www      6499: 
                   6500: .LC_fontsize_small {
1.911     bisitz   6501:   font-size: 70%;
1.705     tempelho 6502: }
                   6503: 
1.844     bisitz   6504: #LC_breadcrumbs {
1.911     bisitz   6505:   clear:both;
                   6506:   background: $sidebg;
                   6507:   border-bottom: 1px solid $lg_border_color;
                   6508:   line-height: 2.5em;
1.933     droeschl 6509:   overflow: hidden;
1.911     bisitz   6510:   margin: 0;
                   6511:   padding: 0;
1.995     raeburn  6512:   text-align: left;
1.819     tempelho 6513: }
1.862     bisitz   6514: 
1.1098    bisitz   6515: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6516:   clear:both;
                   6517:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6518:   border: 1px solid $sidebg;
1.1098    bisitz   6519:   margin: 0 0 10px 0;
1.966     bisitz   6520:   padding: 3px;
1.995     raeburn  6521:   text-align: left;
1.822     bisitz   6522: }
                   6523: 
1.795     www      6524: .LC_fontsize_medium {
1.911     bisitz   6525:   font-size: 85%;
1.705     tempelho 6526: }
                   6527: 
1.795     www      6528: .LC_fontsize_large {
1.911     bisitz   6529:   font-size: 120%;
1.705     tempelho 6530: }
                   6531: 
1.346     albertel 6532: .LC_menubuttons_inline_text {
                   6533:   color: $font;
1.698     harmsja  6534:   font-size: 90%;
1.701     harmsja  6535:   padding-left:3px;
1.346     albertel 6536: }
                   6537: 
1.934     droeschl 6538: .LC_menubuttons_inline_text img{
                   6539:   vertical-align: middle;
                   6540: }
                   6541: 
1.1051    www      6542: li.LC_menubuttons_inline_text img {
1.951     onken    6543:   cursor:pointer;
1.1002    droeschl 6544:   text-decoration: none;
1.951     onken    6545: }
                   6546: 
1.526     www      6547: .LC_menubuttons_link {
                   6548:   text-decoration: none;
                   6549: }
1.795     www      6550: 
1.522     albertel 6551: .LC_menubuttons_category {
1.521     www      6552:   color: $font;
1.526     www      6553:   background: $pgbg;
1.521     www      6554:   font-size: larger;
                   6555:   font-weight: bold;
                   6556: }
                   6557: 
1.346     albertel 6558: td.LC_menubuttons_text {
1.911     bisitz   6559:   color: $font;
1.346     albertel 6560: }
1.706     harmsja  6561: 
1.346     albertel 6562: .LC_current_location {
                   6563:   background: $tabbg;
                   6564: }
1.795     www      6565: 
1.1286    raeburn  6566: td.LC_zero_height {
                   6567:   line-height: 0; 
                   6568:   cellpadding: 0;
                   6569: }
                   6570: 
1.938     bisitz   6571: table.LC_data_table {
1.347     albertel 6572:   border: 1px solid #000000;
1.402     albertel 6573:   border-collapse: separate;
1.426     albertel 6574:   border-spacing: 1px;
1.610     albertel 6575:   background: $pgbg;
1.347     albertel 6576: }
1.795     www      6577: 
1.422     albertel 6578: .LC_data_table_dense {
                   6579:   font-size: small;
                   6580: }
1.795     www      6581: 
1.507     raeburn  6582: table.LC_nested_outer {
                   6583:   border: 1px solid #000000;
1.589     raeburn  6584:   border-collapse: collapse;
1.803     bisitz   6585:   border-spacing: 0;
1.507     raeburn  6586:   width: 100%;
                   6587: }
1.795     www      6588: 
1.879     raeburn  6589: table.LC_innerpickbox,
1.507     raeburn  6590: table.LC_nested {
1.803     bisitz   6591:   border: none;
1.589     raeburn  6592:   border-collapse: collapse;
1.803     bisitz   6593:   border-spacing: 0;
1.507     raeburn  6594:   width: 100%;
                   6595: }
1.795     www      6596: 
1.911     bisitz   6597: table.LC_data_table tr th,
                   6598: table.LC_calendar tr th,
1.879     raeburn  6599: table.LC_prior_tries tr th,
                   6600: table.LC_innerpickbox tr th {
1.349     albertel 6601:   font-weight: bold;
                   6602:   background-color: $data_table_head;
1.801     tempelho 6603:   color:$fontmenu;
1.701     harmsja  6604:   font-size:90%;
1.347     albertel 6605: }
1.795     www      6606: 
1.879     raeburn  6607: table.LC_innerpickbox tr th,
                   6608: table.LC_innerpickbox tr td {
                   6609:   vertical-align: top;
                   6610: }
                   6611: 
1.711     raeburn  6612: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6613:   background-color: #CCCCCC;
1.711     raeburn  6614:   font-weight: bold;
                   6615:   text-align: left;
                   6616: }
1.795     www      6617: 
1.912     bisitz   6618: table.LC_data_table tr.LC_odd_row > td {
                   6619:   background-color: $data_table_light;
                   6620:   padding: 2px;
                   6621:   vertical-align: top;
                   6622: }
                   6623: 
1.809     bisitz   6624: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6625:   background-color: $data_table_light;
1.912     bisitz   6626:   vertical-align: top;
                   6627: }
                   6628: 
                   6629: table.LC_data_table tr.LC_even_row > td {
                   6630:   background-color: $data_table_dark;
1.425     albertel 6631:   padding: 2px;
1.900     bisitz   6632:   vertical-align: top;
1.347     albertel 6633: }
1.795     www      6634: 
1.809     bisitz   6635: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6636:   background-color: $data_table_dark;
1.900     bisitz   6637:   vertical-align: top;
1.347     albertel 6638: }
1.795     www      6639: 
1.425     albertel 6640: table.LC_data_table tr.LC_data_table_highlight td {
                   6641:   background-color: $data_table_darker;
                   6642: }
1.795     www      6643: 
1.639     raeburn  6644: table.LC_data_table tr td.LC_leftcol_header {
                   6645:   background-color: $data_table_head;
                   6646:   font-weight: bold;
                   6647: }
1.795     www      6648: 
1.451     albertel 6649: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6650: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6651:   font-weight: bold;
                   6652:   font-style: italic;
                   6653:   text-align: center;
                   6654:   padding: 8px;
1.347     albertel 6655: }
1.795     www      6656: 
1.1114    raeburn  6657: table.LC_data_table tr.LC_empty_row td,
                   6658: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6659:   background-color: $sidebg;
                   6660: }
                   6661: 
                   6662: table.LC_nested tr.LC_empty_row td {
                   6663:   background-color: #FFFFFF;
                   6664: }
                   6665: 
1.890     droeschl 6666: table.LC_caption {
                   6667: }
                   6668: 
1.507     raeburn  6669: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6670:   padding: 4ex
                   6671: }
1.795     www      6672: 
1.507     raeburn  6673: table.LC_nested_outer tr th {
                   6674:   font-weight: bold;
1.801     tempelho 6675:   color:$fontmenu;
1.507     raeburn  6676:   background-color: $data_table_head;
1.701     harmsja  6677:   font-size: small;
1.507     raeburn  6678:   border-bottom: 1px solid #000000;
                   6679: }
1.795     www      6680: 
1.507     raeburn  6681: table.LC_nested_outer tr td.LC_subheader {
                   6682:   background-color: $data_table_head;
                   6683:   font-weight: bold;
                   6684:   font-size: small;
                   6685:   border-bottom: 1px solid #000000;
                   6686:   text-align: right;
1.451     albertel 6687: }
1.795     www      6688: 
1.507     raeburn  6689: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6690:   background-color: #CCCCCC;
1.451     albertel 6691:   font-weight: bold;
                   6692:   font-size: small;
1.507     raeburn  6693:   text-align: center;
                   6694: }
1.795     www      6695: 
1.589     raeburn  6696: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6697: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6698:   text-align: left;
1.451     albertel 6699: }
1.795     www      6700: 
1.507     raeburn  6701: table.LC_nested td {
1.735     bisitz   6702:   background-color: #FFFFFF;
1.451     albertel 6703:   font-size: small;
1.507     raeburn  6704: }
1.795     www      6705: 
1.507     raeburn  6706: table.LC_nested_outer tr th.LC_right_item,
                   6707: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6708: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6709: table.LC_nested tr td.LC_right_item {
1.451     albertel 6710:   text-align: right;
                   6711: }
                   6712: 
1.507     raeburn  6713: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6714:   background-color: #EEEEEE;
1.451     albertel 6715: }
                   6716: 
1.473     raeburn  6717: table.LC_createuser {
                   6718: }
                   6719: 
                   6720: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6721:   font-size: small;
1.473     raeburn  6722: }
                   6723: 
                   6724: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6725:   background-color: #CCCCCC;
1.473     raeburn  6726:   font-weight: bold;
                   6727:   text-align: center;
                   6728: }
                   6729: 
1.349     albertel 6730: table.LC_calendar {
                   6731:   border: 1px solid #000000;
                   6732:   border-collapse: collapse;
1.917     raeburn  6733:   width: 98%;
1.349     albertel 6734: }
1.795     www      6735: 
1.349     albertel 6736: table.LC_calendar_pickdate {
                   6737:   font-size: xx-small;
                   6738: }
1.795     www      6739: 
1.349     albertel 6740: table.LC_calendar tr td {
                   6741:   border: 1px solid #000000;
                   6742:   vertical-align: top;
1.917     raeburn  6743:   width: 14%;
1.349     albertel 6744: }
1.795     www      6745: 
1.349     albertel 6746: table.LC_calendar tr td.LC_calendar_day_empty {
                   6747:   background-color: $data_table_dark;
                   6748: }
1.795     www      6749: 
1.779     bisitz   6750: table.LC_calendar tr td.LC_calendar_day_current {
                   6751:   background-color: $data_table_highlight;
1.777     tempelho 6752: }
1.795     www      6753: 
1.938     bisitz   6754: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6755:   background-color: $mail_new;
                   6756: }
1.795     www      6757: 
1.938     bisitz   6758: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6759:   background-color: $mail_new_hover;
                   6760: }
1.795     www      6761: 
1.938     bisitz   6762: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6763:   background-color: $mail_read;
                   6764: }
1.795     www      6765: 
1.938     bisitz   6766: /*
                   6767: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6768:   background-color: $mail_read_hover;
                   6769: }
1.938     bisitz   6770: */
1.795     www      6771: 
1.938     bisitz   6772: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6773:   background-color: $mail_replied;
                   6774: }
1.795     www      6775: 
1.938     bisitz   6776: /*
                   6777: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6778:   background-color: $mail_replied_hover;
                   6779: }
1.938     bisitz   6780: */
1.795     www      6781: 
1.938     bisitz   6782: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6783:   background-color: $mail_other;
                   6784: }
1.795     www      6785: 
1.938     bisitz   6786: /*
                   6787: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6788:   background-color: $mail_other_hover;
                   6789: }
1.938     bisitz   6790: */
1.494     raeburn  6791: 
1.777     tempelho 6792: table.LC_data_table tr > td.LC_browser_file,
                   6793: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6794:   background: #AAEE77;
1.389     albertel 6795: }
1.795     www      6796: 
1.777     tempelho 6797: table.LC_data_table tr > td.LC_browser_file_locked,
                   6798: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6799:   background: #FFAA99;
1.387     albertel 6800: }
1.795     www      6801: 
1.777     tempelho 6802: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6803:   background: #888888;
1.779     bisitz   6804: }
1.795     www      6805: 
1.777     tempelho 6806: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6807: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6808:   background: #F8F866;
1.777     tempelho 6809: }
1.795     www      6810: 
1.696     bisitz   6811: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6812:   background: #E0E8FF;
1.387     albertel 6813: }
1.696     bisitz   6814: 
1.707     bisitz   6815: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6816:   /* background: #77FF77; */
1.707     bisitz   6817: }
1.795     www      6818: 
1.707     bisitz   6819: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6820:   border-right: 8px solid #FFFF77;
1.707     bisitz   6821: }
1.795     www      6822: 
1.707     bisitz   6823: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6824:   border-right: 8px solid #FFAA77;
1.707     bisitz   6825: }
1.795     www      6826: 
1.707     bisitz   6827: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6828:   border-right: 8px solid #FF7777;
1.707     bisitz   6829: }
1.795     www      6830: 
1.707     bisitz   6831: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6832:   border-right: 8px solid #AAFF77;
1.707     bisitz   6833: }
1.795     www      6834: 
1.707     bisitz   6835: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6836:   border-right: 8px solid #11CC55;
1.707     bisitz   6837: }
                   6838: 
1.388     albertel 6839: span.LC_current_location {
1.701     harmsja  6840:   font-size:larger;
1.388     albertel 6841:   background: $pgbg;
                   6842: }
1.387     albertel 6843: 
1.1029    www      6844: span.LC_current_nav_location {
                   6845:   font-weight:bold;
                   6846:   background: $sidebg;
                   6847: }
                   6848: 
1.395     albertel 6849: span.LC_parm_menu_item {
                   6850:   font-size: larger;
                   6851: }
1.795     www      6852: 
1.395     albertel 6853: span.LC_parm_scope_all {
                   6854:   color: red;
                   6855: }
1.795     www      6856: 
1.395     albertel 6857: span.LC_parm_scope_folder {
                   6858:   color: green;
                   6859: }
1.795     www      6860: 
1.395     albertel 6861: span.LC_parm_scope_resource {
                   6862:   color: orange;
                   6863: }
1.795     www      6864: 
1.395     albertel 6865: span.LC_parm_part {
                   6866:   color: blue;
                   6867: }
1.795     www      6868: 
1.911     bisitz   6869: span.LC_parm_folder,
                   6870: span.LC_parm_symb {
1.395     albertel 6871:   font-size: x-small;
                   6872:   font-family: $mono;
                   6873:   color: #AAAAAA;
                   6874: }
                   6875: 
1.977     bisitz   6876: ul.LC_parm_parmlist li {
                   6877:   display: inline-block;
                   6878:   padding: 0.3em 0.8em;
                   6879:   vertical-align: top;
                   6880:   width: 150px;
                   6881:   border-top:1px solid $lg_border_color;
                   6882: }
                   6883: 
1.795     www      6884: td.LC_parm_overview_level_menu,
                   6885: td.LC_parm_overview_map_menu,
                   6886: td.LC_parm_overview_parm_selectors,
                   6887: td.LC_parm_overview_restrictions  {
1.396     albertel 6888:   border: 1px solid black;
                   6889:   border-collapse: collapse;
                   6890: }
1.795     www      6891: 
1.1285    raeburn  6892: span.LC_parm_recursive,
                   6893: td.LC_parm_recursive {
                   6894:   font-weight: bold;
                   6895:   font-size: smaller;
                   6896: }
                   6897: 
1.396     albertel 6898: table.LC_parm_overview_restrictions td {
                   6899:   border-width: 1px 4px 1px 4px;
                   6900:   border-style: solid;
                   6901:   border-color: $pgbg;
                   6902:   text-align: center;
                   6903: }
1.795     www      6904: 
1.396     albertel 6905: table.LC_parm_overview_restrictions th {
                   6906:   background: $tabbg;
                   6907:   border-width: 1px 4px 1px 4px;
                   6908:   border-style: solid;
                   6909:   border-color: $pgbg;
                   6910: }
1.795     www      6911: 
1.398     albertel 6912: table#LC_helpmenu {
1.803     bisitz   6913:   border: none;
1.398     albertel 6914:   height: 55px;
1.803     bisitz   6915:   border-spacing: 0;
1.398     albertel 6916: }
                   6917: 
                   6918: table#LC_helpmenu fieldset legend {
                   6919:   font-size: larger;
                   6920: }
1.795     www      6921: 
1.397     albertel 6922: table#LC_helpmenu_links {
                   6923:   width: 100%;
                   6924:   border: 1px solid black;
                   6925:   background: $pgbg;
1.803     bisitz   6926:   padding: 0;
1.397     albertel 6927:   border-spacing: 1px;
                   6928: }
1.795     www      6929: 
1.397     albertel 6930: table#LC_helpmenu_links tr td {
                   6931:   padding: 1px;
                   6932:   background: $tabbg;
1.399     albertel 6933:   text-align: center;
                   6934:   font-weight: bold;
1.397     albertel 6935: }
1.396     albertel 6936: 
1.795     www      6937: table#LC_helpmenu_links a:link,
                   6938: table#LC_helpmenu_links a:visited,
1.397     albertel 6939: table#LC_helpmenu_links a:active {
                   6940:   text-decoration: none;
                   6941:   color: $font;
                   6942: }
1.795     www      6943: 
1.397     albertel 6944: table#LC_helpmenu_links a:hover {
                   6945:   text-decoration: underline;
                   6946:   color: $vlink;
                   6947: }
1.396     albertel 6948: 
1.417     albertel 6949: .LC_chrt_popup_exists {
                   6950:   border: 1px solid #339933;
                   6951:   margin: -1px;
                   6952: }
1.795     www      6953: 
1.417     albertel 6954: .LC_chrt_popup_up {
                   6955:   border: 1px solid yellow;
                   6956:   margin: -1px;
                   6957: }
1.795     www      6958: 
1.417     albertel 6959: .LC_chrt_popup {
                   6960:   border: 1px solid #8888FF;
                   6961:   background: #CCCCFF;
                   6962: }
1.795     www      6963: 
1.421     albertel 6964: table.LC_pick_box {
                   6965:   border-collapse: separate;
                   6966:   background: white;
                   6967:   border: 1px solid black;
                   6968:   border-spacing: 1px;
                   6969: }
1.795     www      6970: 
1.421     albertel 6971: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6972:   background: $sidebg;
1.421     albertel 6973:   font-weight: bold;
1.900     bisitz   6974:   text-align: left;
1.740     bisitz   6975:   vertical-align: top;
1.421     albertel 6976:   width: 184px;
                   6977:   padding: 8px;
                   6978: }
1.795     www      6979: 
1.579     raeburn  6980: table.LC_pick_box td.LC_pick_box_value {
                   6981:   text-align: left;
                   6982:   padding: 8px;
                   6983: }
1.795     www      6984: 
1.579     raeburn  6985: table.LC_pick_box td.LC_pick_box_select {
                   6986:   text-align: left;
                   6987:   padding: 8px;
                   6988: }
1.795     www      6989: 
1.424     albertel 6990: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6991:   padding: 0;
1.421     albertel 6992:   height: 1px;
                   6993:   background: black;
                   6994: }
1.795     www      6995: 
1.421     albertel 6996: table.LC_pick_box td.LC_pick_box_submit {
                   6997:   text-align: right;
                   6998: }
1.795     www      6999: 
1.579     raeburn  7000: table.LC_pick_box td.LC_evenrow_value {
                   7001:   text-align: left;
                   7002:   padding: 8px;
                   7003:   background-color: $data_table_light;
                   7004: }
1.795     www      7005: 
1.579     raeburn  7006: table.LC_pick_box td.LC_oddrow_value {
                   7007:   text-align: left;
                   7008:   padding: 8px;
                   7009:   background-color: $data_table_light;
                   7010: }
1.795     www      7011: 
1.579     raeburn  7012: span.LC_helpform_receipt_cat {
                   7013:   font-weight: bold;
                   7014: }
1.795     www      7015: 
1.424     albertel 7016: table.LC_group_priv_box {
                   7017:   background: white;
                   7018:   border: 1px solid black;
                   7019:   border-spacing: 1px;
                   7020: }
1.795     www      7021: 
1.424     albertel 7022: table.LC_group_priv_box td.LC_pick_box_title {
                   7023:   background: $tabbg;
                   7024:   font-weight: bold;
                   7025:   text-align: right;
                   7026:   width: 184px;
                   7027: }
1.795     www      7028: 
1.424     albertel 7029: table.LC_group_priv_box td.LC_groups_fixed {
                   7030:   background: $data_table_light;
                   7031:   text-align: center;
                   7032: }
1.795     www      7033: 
1.424     albertel 7034: table.LC_group_priv_box td.LC_groups_optional {
                   7035:   background: $data_table_dark;
                   7036:   text-align: center;
                   7037: }
1.795     www      7038: 
1.424     albertel 7039: table.LC_group_priv_box td.LC_groups_functionality {
                   7040:   background: $data_table_darker;
                   7041:   text-align: center;
                   7042:   font-weight: bold;
                   7043: }
1.795     www      7044: 
1.424     albertel 7045: table.LC_group_priv td {
                   7046:   text-align: left;
1.803     bisitz   7047:   padding: 0;
1.424     albertel 7048: }
                   7049: 
                   7050: .LC_navbuttons {
                   7051:   margin: 2ex 0ex 2ex 0ex;
                   7052: }
1.795     www      7053: 
1.423     albertel 7054: .LC_topic_bar {
                   7055:   font-weight: bold;
                   7056:   background: $tabbg;
1.918     wenzelju 7057:   margin: 1em 0em 1em 2em;
1.805     bisitz   7058:   padding: 3px;
1.918     wenzelju 7059:   font-size: 1.2em;
1.423     albertel 7060: }
1.795     www      7061: 
1.423     albertel 7062: .LC_topic_bar span {
1.918     wenzelju 7063:   left: 0.5em;
                   7064:   position: absolute;
1.423     albertel 7065:   vertical-align: middle;
1.918     wenzelju 7066:   font-size: 1.2em;
1.423     albertel 7067: }
1.795     www      7068: 
1.423     albertel 7069: table.LC_course_group_status {
                   7070:   margin: 20px;
                   7071: }
1.795     www      7072: 
1.423     albertel 7073: table.LC_status_selector td {
                   7074:   vertical-align: top;
                   7075:   text-align: center;
1.424     albertel 7076:   padding: 4px;
                   7077: }
1.795     www      7078: 
1.599     albertel 7079: div.LC_feedback_link {
1.616     albertel 7080:   clear: both;
1.829     kalberla 7081:   background: $sidebg;
1.779     bisitz   7082:   width: 100%;
1.829     kalberla 7083:   padding-bottom: 10px;
                   7084:   border: 1px $tabbg solid;
1.833     kalberla 7085:   height: 22px;
                   7086:   line-height: 22px;
                   7087:   padding-top: 5px;
                   7088: }
                   7089: 
                   7090: div.LC_feedback_link img {
                   7091:   height: 22px;
1.867     kalberla 7092:   vertical-align:middle;
1.829     kalberla 7093: }
                   7094: 
1.911     bisitz   7095: div.LC_feedback_link a {
1.829     kalberla 7096:   text-decoration: none;
1.489     raeburn  7097: }
1.795     www      7098: 
1.867     kalberla 7099: div.LC_comblock {
1.911     bisitz   7100:   display:inline;
1.867     kalberla 7101:   color:$font;
                   7102:   font-size:90%;
                   7103: }
                   7104: 
                   7105: div.LC_feedback_link div.LC_comblock {
                   7106:   padding-left:5px;
                   7107: }
                   7108: 
                   7109: div.LC_feedback_link div.LC_comblock a {
                   7110:   color:$font;
                   7111: }
                   7112: 
1.489     raeburn  7113: span.LC_feedback_link {
1.858     bisitz   7114:   /* background: $feedback_link_bg; */
1.599     albertel 7115:   font-size: larger;
                   7116: }
1.795     www      7117: 
1.599     albertel 7118: span.LC_message_link {
1.858     bisitz   7119:   /* background: $feedback_link_bg; */
1.599     albertel 7120:   font-size: larger;
                   7121:   position: absolute;
                   7122:   right: 1em;
1.489     raeburn  7123: }
1.421     albertel 7124: 
1.515     albertel 7125: table.LC_prior_tries {
1.524     albertel 7126:   border: 1px solid #000000;
                   7127:   border-collapse: separate;
                   7128:   border-spacing: 1px;
1.515     albertel 7129: }
1.523     albertel 7130: 
1.515     albertel 7131: table.LC_prior_tries td {
1.524     albertel 7132:   padding: 2px;
1.515     albertel 7133: }
1.523     albertel 7134: 
                   7135: .LC_answer_correct {
1.795     www      7136:   background: lightgreen;
                   7137:   color: darkgreen;
                   7138:   padding: 6px;
1.523     albertel 7139: }
1.795     www      7140: 
1.523     albertel 7141: .LC_answer_charged_try {
1.797     www      7142:   background: #FFAAAA;
1.795     www      7143:   color: darkred;
                   7144:   padding: 6px;
1.523     albertel 7145: }
1.795     www      7146: 
1.779     bisitz   7147: .LC_answer_not_charged_try,
1.523     albertel 7148: .LC_answer_no_grade,
                   7149: .LC_answer_late {
1.795     www      7150:   background: lightyellow;
1.523     albertel 7151:   color: black;
1.795     www      7152:   padding: 6px;
1.523     albertel 7153: }
1.795     www      7154: 
1.523     albertel 7155: .LC_answer_previous {
1.795     www      7156:   background: lightblue;
                   7157:   color: darkblue;
                   7158:   padding: 6px;
1.523     albertel 7159: }
1.795     www      7160: 
1.779     bisitz   7161: .LC_answer_no_message {
1.777     tempelho 7162:   background: #FFFFFF;
                   7163:   color: black;
1.795     www      7164:   padding: 6px;
1.779     bisitz   7165: }
1.795     www      7166: 
1.779     bisitz   7167: .LC_answer_unknown {
                   7168:   background: orange;
                   7169:   color: black;
1.795     www      7170:   padding: 6px;
1.777     tempelho 7171: }
1.795     www      7172: 
1.529     albertel 7173: span.LC_prior_numerical,
                   7174: span.LC_prior_string,
                   7175: span.LC_prior_custom,
                   7176: span.LC_prior_reaction,
                   7177: span.LC_prior_math {
1.925     bisitz   7178:   font-family: $mono;
1.523     albertel 7179:   white-space: pre;
                   7180: }
                   7181: 
1.525     albertel 7182: span.LC_prior_string {
1.925     bisitz   7183:   font-family: $mono;
1.525     albertel 7184:   white-space: pre;
                   7185: }
                   7186: 
1.523     albertel 7187: table.LC_prior_option {
                   7188:   width: 100%;
                   7189:   border-collapse: collapse;
                   7190: }
1.795     www      7191: 
1.911     bisitz   7192: table.LC_prior_rank,
1.795     www      7193: table.LC_prior_match {
1.528     albertel 7194:   border-collapse: collapse;
                   7195: }
1.795     www      7196: 
1.528     albertel 7197: table.LC_prior_option tr td,
                   7198: table.LC_prior_rank tr td,
                   7199: table.LC_prior_match tr td {
1.524     albertel 7200:   border: 1px solid #000000;
1.515     albertel 7201: }
                   7202: 
1.855     bisitz   7203: .LC_nobreak {
1.544     albertel 7204:   white-space: nowrap;
1.519     raeburn  7205: }
                   7206: 
1.576     raeburn  7207: span.LC_cusr_emph {
                   7208:   font-style: italic;
                   7209: }
                   7210: 
1.633     raeburn  7211: span.LC_cusr_subheading {
                   7212:   font-weight: normal;
                   7213:   font-size: 85%;
                   7214: }
                   7215: 
1.861     bisitz   7216: div.LC_docs_entry_move {
1.859     bisitz   7217:   border: 1px solid #BBBBBB;
1.545     albertel 7218:   background: #DDDDDD;
1.861     bisitz   7219:   width: 22px;
1.859     bisitz   7220:   padding: 1px;
                   7221:   margin: 0;
1.545     albertel 7222: }
                   7223: 
1.861     bisitz   7224: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7225: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7226:   font-size: x-small;
                   7227: }
1.795     www      7228: 
1.861     bisitz   7229: .LC_docs_entry_parameter {
                   7230:   white-space: nowrap;
                   7231: }
                   7232: 
1.544     albertel 7233: .LC_docs_copy {
1.545     albertel 7234:   color: #000099;
1.544     albertel 7235: }
1.795     www      7236: 
1.544     albertel 7237: .LC_docs_cut {
1.545     albertel 7238:   color: #550044;
1.544     albertel 7239: }
1.795     www      7240: 
1.544     albertel 7241: .LC_docs_rename {
1.545     albertel 7242:   color: #009900;
1.544     albertel 7243: }
1.795     www      7244: 
1.544     albertel 7245: .LC_docs_remove {
1.545     albertel 7246:   color: #990000;
                   7247: }
                   7248: 
1.1284    raeburn  7249: .LC_docs_alias {
                   7250:   color: #440055;  
                   7251: }
                   7252: 
1.1286    raeburn  7253: .LC_domprefs_email,
1.1284    raeburn  7254: .LC_docs_alias_name,
1.547     albertel 7255: .LC_docs_reinit_warn,
                   7256: .LC_docs_ext_edit {
                   7257:   font-size: x-small;
                   7258: }
                   7259: 
1.545     albertel 7260: table.LC_docs_adddocs td,
                   7261: table.LC_docs_adddocs th {
                   7262:   border: 1px solid #BBBBBB;
                   7263:   padding: 4px;
                   7264:   background: #DDDDDD;
1.543     albertel 7265: }
                   7266: 
1.584     albertel 7267: table.LC_sty_begin {
                   7268:   background: #BBFFBB;
                   7269: }
1.795     www      7270: 
1.584     albertel 7271: table.LC_sty_end {
                   7272:   background: #FFBBBB;
                   7273: }
                   7274: 
1.589     raeburn  7275: table.LC_double_column {
1.803     bisitz   7276:   border-width: 0;
1.589     raeburn  7277:   border-collapse: collapse;
                   7278:   width: 100%;
                   7279:   padding: 2px;
                   7280: }
                   7281: 
                   7282: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7283:   top: 2px;
1.589     raeburn  7284:   left: 2px;
                   7285:   width: 47%;
                   7286:   vertical-align: top;
                   7287: }
                   7288: 
                   7289: table.LC_double_column tr td.LC_right_col {
                   7290:   top: 2px;
1.779     bisitz   7291:   right: 2px;
1.589     raeburn  7292:   width: 47%;
                   7293:   vertical-align: top;
                   7294: }
                   7295: 
1.591     raeburn  7296: div.LC_left_float {
                   7297:   float: left;
                   7298:   padding-right: 5%;
1.597     albertel 7299:   padding-bottom: 4px;
1.591     raeburn  7300: }
                   7301: 
                   7302: div.LC_clear_float_header {
1.597     albertel 7303:   padding-bottom: 2px;
1.591     raeburn  7304: }
                   7305: 
                   7306: div.LC_clear_float_footer {
1.597     albertel 7307:   padding-top: 10px;
1.591     raeburn  7308:   clear: both;
                   7309: }
                   7310: 
1.597     albertel 7311: div.LC_grade_show_user {
1.941     bisitz   7312: /*  border-left: 5px solid $sidebg; */
                   7313:   border-top: 5px solid #000000;
                   7314:   margin: 50px 0 0 0;
1.936     bisitz   7315:   padding: 15px 0 5px 10px;
1.597     albertel 7316: }
1.795     www      7317: 
1.936     bisitz   7318: div.LC_grade_show_user_odd_row {
1.941     bisitz   7319: /*  border-left: 5px solid #000000; */
                   7320: }
                   7321: 
                   7322: div.LC_grade_show_user div.LC_Box {
                   7323:   margin-right: 50px;
1.597     albertel 7324: }
                   7325: 
                   7326: div.LC_grade_submissions,
                   7327: div.LC_grade_message_center,
1.936     bisitz   7328: div.LC_grade_info_links {
1.597     albertel 7329:   margin: 5px;
                   7330:   width: 99%;
                   7331:   background: #FFFFFF;
                   7332: }
1.795     www      7333: 
1.597     albertel 7334: div.LC_grade_submissions_header,
1.936     bisitz   7335: div.LC_grade_message_center_header {
1.705     tempelho 7336:   font-weight: bold;
                   7337:   font-size: large;
1.597     albertel 7338: }
1.795     www      7339: 
1.597     albertel 7340: div.LC_grade_submissions_body,
1.936     bisitz   7341: div.LC_grade_message_center_body {
1.597     albertel 7342:   border: 1px solid black;
                   7343:   width: 99%;
                   7344:   background: #FFFFFF;
                   7345: }
1.795     www      7346: 
1.613     albertel 7347: table.LC_scantron_action {
                   7348:   width: 100%;
                   7349: }
1.795     www      7350: 
1.613     albertel 7351: table.LC_scantron_action tr th {
1.698     harmsja  7352:   font-weight:bold;
                   7353:   font-style:normal;
1.613     albertel 7354: }
1.795     www      7355: 
1.779     bisitz   7356: .LC_edit_problem_header,
1.614     albertel 7357: div.LC_edit_problem_footer {
1.705     tempelho 7358:   font-weight: normal;
                   7359:   font-size:  medium;
1.602     albertel 7360:   margin: 2px;
1.1060    bisitz   7361:   background-color: $sidebg;
1.600     albertel 7362: }
1.795     www      7363: 
1.600     albertel 7364: div.LC_edit_problem_header,
1.602     albertel 7365: div.LC_edit_problem_header div,
1.614     albertel 7366: div.LC_edit_problem_footer,
                   7367: div.LC_edit_problem_footer div,
1.602     albertel 7368: div.LC_edit_problem_editxml_header,
                   7369: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7370:   z-index: 100;
1.600     albertel 7371: }
1.795     www      7372: 
1.600     albertel 7373: div.LC_edit_problem_header_title {
1.705     tempelho 7374:   font-weight: bold;
                   7375:   font-size: larger;
1.602     albertel 7376:   background: $tabbg;
                   7377:   padding: 3px;
1.1060    bisitz   7378:   margin: 0 0 5px 0;
1.602     albertel 7379: }
1.795     www      7380: 
1.602     albertel 7381: table.LC_edit_problem_header_title {
                   7382:   width: 100%;
1.600     albertel 7383:   background: $tabbg;
1.602     albertel 7384: }
                   7385: 
1.1205    golterma 7386: div.LC_edit_actionbar {
                   7387:     background-color: $sidebg;
1.1218    droeschl 7388:     margin: 0;
                   7389:     padding: 0;
                   7390:     line-height: 200%;
1.602     albertel 7391: }
1.795     www      7392: 
1.1218    droeschl 7393: div.LC_edit_actionbar div{
                   7394:     padding: 0;
                   7395:     margin: 0;
                   7396:     display: inline-block;
1.600     albertel 7397: }
1.795     www      7398: 
1.1124    bisitz   7399: .LC_edit_opt {
                   7400:   padding-left: 1em;
                   7401:   white-space: nowrap;
                   7402: }
                   7403: 
1.1152    golterma 7404: .LC_edit_problem_latexhelper{
                   7405:     text-align: right;
                   7406: }
                   7407: 
                   7408: #LC_edit_problem_colorful div{
                   7409:     margin-left: 40px;
                   7410: }
                   7411: 
1.1205    golterma 7412: #LC_edit_problem_codemirror div{
                   7413:     margin-left: 0px;
                   7414: }
                   7415: 
1.911     bisitz   7416: img.stift {
1.803     bisitz   7417:   border-width: 0;
                   7418:   vertical-align: middle;
1.677     riegler  7419: }
1.680     riegler  7420: 
1.923     bisitz   7421: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7422:   vertical-align: top;
1.777     tempelho 7423: }
1.795     www      7424: 
1.716     raeburn  7425: div.LC_createcourse {
1.911     bisitz   7426:   margin: 10px 10px 10px 10px;
1.716     raeburn  7427: }
                   7428: 
1.917     raeburn  7429: .LC_dccid {
1.1130    raeburn  7430:   float: right;
1.917     raeburn  7431:   margin: 0.2em 0 0 0;
                   7432:   padding: 0;
                   7433:   font-size: 90%;
                   7434:   display:none;
                   7435: }
                   7436: 
1.897     wenzelju 7437: ol.LC_primary_menu a:hover,
1.721     harmsja  7438: ol#LC_MenuBreadcrumbs a:hover,
                   7439: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7440: ul#LC_secondary_menu a:hover,
1.721     harmsja  7441: .LC_FormSectionClearButton input:hover
1.795     www      7442: ul.LC_TabContent   li:hover a {
1.952     onken    7443:   color:$button_hover;
1.911     bisitz   7444:   text-decoration:none;
1.693     droeschl 7445: }
                   7446: 
1.779     bisitz   7447: h1 {
1.911     bisitz   7448:   padding: 0;
                   7449:   line-height:130%;
1.693     droeschl 7450: }
1.698     harmsja  7451: 
1.911     bisitz   7452: h2,
                   7453: h3,
                   7454: h4,
                   7455: h5,
                   7456: h6 {
                   7457:   margin: 5px 0 5px 0;
                   7458:   padding: 0;
                   7459:   line-height:130%;
1.693     droeschl 7460: }
1.795     www      7461: 
                   7462: .LC_hcell {
1.911     bisitz   7463:   padding:3px 15px 3px 15px;
                   7464:   margin: 0;
                   7465:   background-color:$tabbg;
                   7466:   color:$fontmenu;
                   7467:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7468: }
1.795     www      7469: 
1.840     bisitz   7470: .LC_Box > .LC_hcell {
1.911     bisitz   7471:   margin: 0 -10px 10px -10px;
1.835     bisitz   7472: }
                   7473: 
1.721     harmsja  7474: .LC_noBorder {
1.911     bisitz   7475:   border: 0;
1.698     harmsja  7476: }
1.693     droeschl 7477: 
1.721     harmsja  7478: .LC_FormSectionClearButton input {
1.911     bisitz   7479:   background-color:transparent;
                   7480:   border: none;
                   7481:   cursor:pointer;
                   7482:   text-decoration:underline;
1.693     droeschl 7483: }
1.763     bisitz   7484: 
                   7485: .LC_help_open_topic {
1.911     bisitz   7486:   color: #FFFFFF;
                   7487:   background-color: #EEEEFF;
                   7488:   margin: 1px;
                   7489:   padding: 4px;
                   7490:   border: 1px solid #000033;
                   7491:   white-space: nowrap;
                   7492:   /* vertical-align: middle; */
1.759     neumanie 7493: }
1.693     droeschl 7494: 
1.911     bisitz   7495: dl,
                   7496: ul,
                   7497: div,
                   7498: fieldset {
                   7499:   margin: 10px 10px 10px 0;
                   7500:   /* overflow: hidden; */
1.693     droeschl 7501: }
1.795     www      7502: 
1.1211    raeburn  7503: article.geogebraweb div {
                   7504:     margin: 0;
                   7505: }
                   7506: 
1.838     bisitz   7507: fieldset > legend {
1.911     bisitz   7508:   font-weight: bold;
                   7509:   padding: 0 5px 0 5px;
1.838     bisitz   7510: }
                   7511: 
1.813     bisitz   7512: #LC_nav_bar {
1.911     bisitz   7513:   float: left;
1.995     raeburn  7514:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7515:   margin: 0 0 2px 0;
1.807     droeschl 7516: }
                   7517: 
1.916     droeschl 7518: #LC_realm {
                   7519:   margin: 0.2em 0 0 0;
                   7520:   padding: 0;
                   7521:   font-weight: bold;
                   7522:   text-align: center;
1.995     raeburn  7523:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7524: }
                   7525: 
1.911     bisitz   7526: #LC_nav_bar em {
                   7527:   font-weight: bold;
                   7528:   font-style: normal;
1.807     droeschl 7529: }
                   7530: 
1.897     wenzelju 7531: ol.LC_primary_menu {
1.934     droeschl 7532:   margin: 0;
1.1076    raeburn  7533:   padding: 0;
1.807     droeschl 7534: }
                   7535: 
1.852     droeschl 7536: ol#LC_PathBreadcrumbs {
1.911     bisitz   7537:   margin: 0;
1.693     droeschl 7538: }
                   7539: 
1.897     wenzelju 7540: ol.LC_primary_menu li {
1.1076    raeburn  7541:   color: RGB(80, 80, 80);
                   7542:   vertical-align: middle;
                   7543:   text-align: left;
                   7544:   list-style: none;
1.1205    golterma 7545:   position: relative;
1.1076    raeburn  7546:   float: left;
1.1205    golterma 7547:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7548:   line-height: 1.5em;
1.1076    raeburn  7549: }
                   7550: 
1.1205    golterma 7551: ol.LC_primary_menu li a,
                   7552: ol.LC_primary_menu li p {
1.1076    raeburn  7553:   display: block;
                   7554:   margin: 0;
                   7555:   padding: 0 5px 0 10px;
                   7556:   text-decoration: none;
                   7557: }
                   7558: 
1.1205    golterma 7559: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7560:   display: inline-block;
                   7561:   width: 95%;
                   7562:   text-align: left;
                   7563: }
                   7564: 
                   7565: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7566:   display: inline-block;	
                   7567:   width: 5%;
                   7568:   float: right;
                   7569:   text-align: right;
                   7570:   font-size: 70%;
                   7571: }
                   7572: 
                   7573: ol.LC_primary_menu ul {
1.1076    raeburn  7574:   display: none;
1.1205    golterma 7575:   width: 15em;
1.1076    raeburn  7576:   background-color: $data_table_light;
1.1205    golterma 7577:   position: absolute;
                   7578:   top: 100%;
1.1076    raeburn  7579: }
                   7580: 
1.1205    golterma 7581: ol.LC_primary_menu ul ul {
                   7582:   left: 100%;
                   7583:   top: 0;
                   7584: }
                   7585: 
                   7586: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7587:   display: block;
                   7588:   position: absolute;
                   7589:   margin: 0;
                   7590:   padding: 0;
1.1078    raeburn  7591:   z-index: 2;
1.1076    raeburn  7592: }
                   7593: 
                   7594: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7595: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7596:   font-size: 90%;
1.911     bisitz   7597:   vertical-align: top;
1.1076    raeburn  7598:   float: none;
1.1079    raeburn  7599:   border-left: 1px solid black;
                   7600:   border-right: 1px solid black;
1.1205    golterma 7601: /* A dark bottom border to visualize different menu options; 
                   7602: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7603:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7604: }
                   7605: 
1.1205    golterma 7606: ol.LC_primary_menu li li p:hover {
                   7607:   color:$button_hover;
                   7608:   text-decoration:none;
                   7609:   background-color:$data_table_dark;
1.1076    raeburn  7610: }
                   7611: 
                   7612: ol.LC_primary_menu li li a:hover {
                   7613:    color:$button_hover;
                   7614:    background-color:$data_table_dark;
1.693     droeschl 7615: }
                   7616: 
1.1205    golterma 7617: /* Font-size equal to the size of the predecessors*/
                   7618: ol.LC_primary_menu li:hover li li {
                   7619:   font-size: 100%;
                   7620: }
                   7621: 
1.897     wenzelju 7622: ol.LC_primary_menu li img {
1.911     bisitz   7623:   vertical-align: bottom;
1.934     droeschl 7624:   height: 1.1em;
1.1077    raeburn  7625:   margin: 0.2em 0 0 0;
1.693     droeschl 7626: }
                   7627: 
1.897     wenzelju 7628: ol.LC_primary_menu a {
1.911     bisitz   7629:   color: RGB(80, 80, 80);
                   7630:   text-decoration: none;
1.693     droeschl 7631: }
1.795     www      7632: 
1.949     droeschl 7633: ol.LC_primary_menu a.LC_new_message {
                   7634:   font-weight:bold;
                   7635:   color: darkred;
                   7636: }
                   7637: 
1.975     raeburn  7638: ol.LC_docs_parameters {
                   7639:   margin-left: 0;
                   7640:   padding: 0;
                   7641:   list-style: none;
                   7642: }
                   7643: 
                   7644: ol.LC_docs_parameters li {
                   7645:   margin: 0;
                   7646:   padding-right: 20px;
                   7647:   display: inline;
                   7648: }
                   7649: 
1.976     raeburn  7650: ol.LC_docs_parameters li:before {
                   7651:   content: "\\002022 \\0020";
                   7652: }
                   7653: 
                   7654: li.LC_docs_parameters_title {
                   7655:   font-weight: bold;
                   7656: }
                   7657: 
                   7658: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7659:   content: "";
                   7660: }
                   7661: 
1.897     wenzelju 7662: ul#LC_secondary_menu {
1.1107    raeburn  7663:   clear: right;
1.911     bisitz   7664:   color: $fontmenu;
                   7665:   background: $tabbg;
                   7666:   list-style: none;
                   7667:   padding: 0;
                   7668:   margin: 0;
                   7669:   width: 100%;
1.995     raeburn  7670:   text-align: left;
1.1107    raeburn  7671:   float: left;
1.808     droeschl 7672: }
                   7673: 
1.897     wenzelju 7674: ul#LC_secondary_menu li {
1.911     bisitz   7675:   font-weight: bold;
                   7676:   line-height: 1.8em;
1.1107    raeburn  7677:   border-right: 1px solid black;
                   7678:   float: left;
                   7679: }
                   7680: 
                   7681: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7682:   background-color: $data_table_light;
                   7683: }
                   7684: 
                   7685: ul#LC_secondary_menu li a {
1.911     bisitz   7686:   padding: 0 0.8em;
1.1107    raeburn  7687: }
                   7688: 
                   7689: ul#LC_secondary_menu li ul {
                   7690:   display: none;
                   7691: }
                   7692: 
                   7693: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7694:   display: block;
                   7695:   position: absolute;
                   7696:   margin: 0;
                   7697:   padding: 0;
                   7698:   list-style:none;
                   7699:   float: none;
                   7700:   background-color: $data_table_light;
                   7701:   z-index: 2;
                   7702:   margin-left: -1px;
                   7703: }
                   7704: 
                   7705: ul#LC_secondary_menu li ul li {
                   7706:   font-size: 90%;
                   7707:   vertical-align: top;
                   7708:   border-left: 1px solid black;
1.911     bisitz   7709:   border-right: 1px solid black;
1.1119    raeburn  7710:   background-color: $data_table_light;
1.1107    raeburn  7711:   list-style:none;
                   7712:   float: none;
                   7713: }
                   7714: 
                   7715: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7716:   background-color: $data_table_dark;
1.807     droeschl 7717: }
                   7718: 
1.847     tempelho 7719: ul.LC_TabContent {
1.911     bisitz   7720:   display:block;
                   7721:   background: $sidebg;
                   7722:   border-bottom: solid 1px $lg_border_color;
                   7723:   list-style:none;
1.1020    raeburn  7724:   margin: -1px -10px 0 -10px;
1.911     bisitz   7725:   padding: 0;
1.693     droeschl 7726: }
                   7727: 
1.795     www      7728: ul.LC_TabContent li,
                   7729: ul.LC_TabContentBigger li {
1.911     bisitz   7730:   float:left;
1.741     harmsja  7731: }
1.795     www      7732: 
1.897     wenzelju 7733: ul#LC_secondary_menu li a {
1.911     bisitz   7734:   color: $fontmenu;
                   7735:   text-decoration: none;
1.693     droeschl 7736: }
1.795     www      7737: 
1.721     harmsja  7738: ul.LC_TabContent {
1.952     onken    7739:   min-height:20px;
1.721     harmsja  7740: }
1.795     www      7741: 
                   7742: ul.LC_TabContent li {
1.911     bisitz   7743:   vertical-align:middle;
1.959     onken    7744:   padding: 0 16px 0 10px;
1.911     bisitz   7745:   background-color:$tabbg;
                   7746:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7747:   border-left: solid 1px $font;
1.721     harmsja  7748: }
1.795     www      7749: 
1.847     tempelho 7750: ul.LC_TabContent .right {
1.911     bisitz   7751:   float:right;
1.847     tempelho 7752: }
                   7753: 
1.911     bisitz   7754: ul.LC_TabContent li a,
                   7755: ul.LC_TabContent li {
                   7756:   color:rgb(47,47,47);
                   7757:   text-decoration:none;
                   7758:   font-size:95%;
                   7759:   font-weight:bold;
1.952     onken    7760:   min-height:20px;
                   7761: }
                   7762: 
1.959     onken    7763: ul.LC_TabContent li a:hover,
                   7764: ul.LC_TabContent li a:focus {
1.952     onken    7765:   color: $button_hover;
1.959     onken    7766:   background:none;
                   7767:   outline:none;
1.952     onken    7768: }
                   7769: 
                   7770: ul.LC_TabContent li:hover {
                   7771:   color: $button_hover;
                   7772:   cursor:pointer;
1.721     harmsja  7773: }
1.795     www      7774: 
1.911     bisitz   7775: ul.LC_TabContent li.active {
1.952     onken    7776:   color: $font;
1.911     bisitz   7777:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7778:   border-bottom:solid 1px #FFFFFF;
                   7779:   cursor: default;
1.744     ehlerst  7780: }
1.795     www      7781: 
1.959     onken    7782: ul.LC_TabContent li.active a {
                   7783:   color:$font;
                   7784:   background:#FFFFFF;
                   7785:   outline: none;
                   7786: }
1.1047    raeburn  7787: 
                   7788: ul.LC_TabContent li.goback {
                   7789:   float: left;
                   7790:   border-left: none;
                   7791: }
                   7792: 
1.870     tempelho 7793: #maincoursedoc {
1.911     bisitz   7794:   clear:both;
1.870     tempelho 7795: }
                   7796: 
                   7797: ul.LC_TabContentBigger {
1.911     bisitz   7798:   display:block;
                   7799:   list-style:none;
                   7800:   padding: 0;
1.870     tempelho 7801: }
                   7802: 
1.795     www      7803: ul.LC_TabContentBigger li {
1.911     bisitz   7804:   vertical-align:bottom;
                   7805:   height: 30px;
                   7806:   font-size:110%;
                   7807:   font-weight:bold;
                   7808:   color: #737373;
1.841     tempelho 7809: }
                   7810: 
1.957     onken    7811: ul.LC_TabContentBigger li.active {
                   7812:   position: relative;
                   7813:   top: 1px;
                   7814: }
                   7815: 
1.870     tempelho 7816: ul.LC_TabContentBigger li a {
1.911     bisitz   7817:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7818:   height: 30px;
                   7819:   line-height: 30px;
                   7820:   text-align: center;
                   7821:   display: block;
                   7822:   text-decoration: none;
1.958     onken    7823:   outline: none;  
1.741     harmsja  7824: }
1.795     www      7825: 
1.870     tempelho 7826: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7827:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7828:   color:$font;
1.744     ehlerst  7829: }
1.795     www      7830: 
1.870     tempelho 7831: ul.LC_TabContentBigger li b {
1.911     bisitz   7832:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7833:   display: block;
                   7834:   float: left;
                   7835:   padding: 0 30px;
1.957     onken    7836:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7837: }
                   7838: 
1.956     onken    7839: ul.LC_TabContentBigger li:hover b {
                   7840:   color:$button_hover;
                   7841: }
                   7842: 
1.870     tempelho 7843: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7844:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7845:   color:$font;
1.957     onken    7846:   border: 0;
1.741     harmsja  7847: }
1.693     droeschl 7848: 
1.870     tempelho 7849: 
1.862     bisitz   7850: ul.LC_CourseBreadcrumbs {
                   7851:   background: $sidebg;
1.1020    raeburn  7852:   height: 2em;
1.862     bisitz   7853:   padding-left: 10px;
1.1020    raeburn  7854:   margin: 0;
1.862     bisitz   7855:   list-style-position: inside;
                   7856: }
                   7857: 
1.911     bisitz   7858: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7859: ol#LC_PathBreadcrumbs {
1.911     bisitz   7860:   padding-left: 10px;
                   7861:   margin: 0;
1.933     droeschl 7862:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7863: }
                   7864: 
1.911     bisitz   7865: ol#LC_MenuBreadcrumbs li,
                   7866: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7867: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7868:   display: inline;
1.933     droeschl 7869:   white-space: normal;  
1.693     droeschl 7870: }
                   7871: 
1.823     bisitz   7872: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7873: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7874:   text-decoration: none;
                   7875:   font-size:90%;
1.693     droeschl 7876: }
1.795     www      7877: 
1.969     droeschl 7878: ol#LC_MenuBreadcrumbs h1 {
                   7879:   display: inline;
                   7880:   font-size: 90%;
                   7881:   line-height: 2.5em;
                   7882:   margin: 0;
                   7883:   padding: 0;
                   7884: }
                   7885: 
1.795     www      7886: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7887:   text-decoration:none;
                   7888:   font-size:100%;
                   7889:   font-weight:bold;
1.693     droeschl 7890: }
1.795     www      7891: 
1.840     bisitz   7892: .LC_Box {
1.911     bisitz   7893:   border: solid 1px $lg_border_color;
                   7894:   padding: 0 10px 10px 10px;
1.746     neumanie 7895: }
1.795     www      7896: 
1.1020    raeburn  7897: .LC_DocsBox {
                   7898:   border: solid 1px $lg_border_color;
                   7899:   padding: 0 0 10px 10px;
                   7900: }
                   7901: 
1.795     www      7902: .LC_AboutMe_Image {
1.911     bisitz   7903:   float:left;
                   7904:   margin-right:10px;
1.747     neumanie 7905: }
1.795     www      7906: 
                   7907: .LC_Clear_AboutMe_Image {
1.911     bisitz   7908:   clear:left;
1.747     neumanie 7909: }
1.795     www      7910: 
1.721     harmsja  7911: dl.LC_ListStyleClean dt {
1.911     bisitz   7912:   padding-right: 5px;
                   7913:   display: table-header-group;
1.693     droeschl 7914: }
                   7915: 
1.721     harmsja  7916: dl.LC_ListStyleClean dd {
1.911     bisitz   7917:   display: table-row;
1.693     droeschl 7918: }
                   7919: 
1.721     harmsja  7920: .LC_ListStyleClean,
                   7921: .LC_ListStyleSimple,
                   7922: .LC_ListStyleNormal,
1.795     www      7923: .LC_ListStyleSpecial {
1.911     bisitz   7924:   /* display:block; */
                   7925:   list-style-position: inside;
                   7926:   list-style-type: none;
                   7927:   overflow: hidden;
                   7928:   padding: 0;
1.693     droeschl 7929: }
                   7930: 
1.721     harmsja  7931: .LC_ListStyleSimple li,
                   7932: .LC_ListStyleSimple dd,
                   7933: .LC_ListStyleNormal li,
                   7934: .LC_ListStyleNormal dd,
                   7935: .LC_ListStyleSpecial li,
1.795     www      7936: .LC_ListStyleSpecial dd {
1.911     bisitz   7937:   margin: 0;
                   7938:   padding: 5px 5px 5px 10px;
                   7939:   clear: both;
1.693     droeschl 7940: }
                   7941: 
1.721     harmsja  7942: .LC_ListStyleClean li,
                   7943: .LC_ListStyleClean dd {
1.911     bisitz   7944:   padding-top: 0;
                   7945:   padding-bottom: 0;
1.693     droeschl 7946: }
                   7947: 
1.721     harmsja  7948: .LC_ListStyleSimple dd,
1.795     www      7949: .LC_ListStyleSimple li {
1.911     bisitz   7950:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7951: }
                   7952: 
1.721     harmsja  7953: .LC_ListStyleSpecial li,
                   7954: .LC_ListStyleSpecial dd {
1.911     bisitz   7955:   list-style-type: none;
                   7956:   background-color: RGB(220, 220, 220);
                   7957:   margin-bottom: 4px;
1.693     droeschl 7958: }
                   7959: 
1.721     harmsja  7960: table.LC_SimpleTable {
1.911     bisitz   7961:   margin:5px;
                   7962:   border:solid 1px $lg_border_color;
1.795     www      7963: }
1.693     droeschl 7964: 
1.721     harmsja  7965: table.LC_SimpleTable tr {
1.911     bisitz   7966:   padding: 0;
                   7967:   border:solid 1px $lg_border_color;
1.693     droeschl 7968: }
1.795     www      7969: 
                   7970: table.LC_SimpleTable thead {
1.911     bisitz   7971:   background:rgb(220,220,220);
1.693     droeschl 7972: }
                   7973: 
1.721     harmsja  7974: div.LC_columnSection {
1.911     bisitz   7975:   display: block;
                   7976:   clear: both;
                   7977:   overflow: hidden;
                   7978:   margin: 0;
1.693     droeschl 7979: }
                   7980: 
1.721     harmsja  7981: div.LC_columnSection>* {
1.911     bisitz   7982:   float: left;
                   7983:   margin: 10px 20px 10px 0;
                   7984:   overflow:hidden;
1.693     droeschl 7985: }
1.721     harmsja  7986: 
1.795     www      7987: table em {
1.911     bisitz   7988:   font-weight: bold;
                   7989:   font-style: normal;
1.748     schulted 7990: }
1.795     www      7991: 
1.779     bisitz   7992: table.LC_tableBrowseRes,
1.795     www      7993: table.LC_tableOfContent {
1.911     bisitz   7994:   border:none;
                   7995:   border-spacing: 1px;
                   7996:   padding: 3px;
                   7997:   background-color: #FFFFFF;
                   7998:   font-size: 90%;
1.753     droeschl 7999: }
1.789     droeschl 8000: 
1.911     bisitz   8001: table.LC_tableOfContent {
                   8002:   border-collapse: collapse;
1.789     droeschl 8003: }
                   8004: 
1.771     droeschl 8005: table.LC_tableBrowseRes a,
1.768     schulted 8006: table.LC_tableOfContent a {
1.911     bisitz   8007:   background-color: transparent;
                   8008:   text-decoration: none;
1.753     droeschl 8009: }
                   8010: 
1.795     www      8011: table.LC_tableOfContent img {
1.911     bisitz   8012:   border: none;
                   8013:   height: 1.3em;
                   8014:   vertical-align: text-bottom;
                   8015:   margin-right: 0.3em;
1.753     droeschl 8016: }
1.757     schulted 8017: 
1.795     www      8018: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8019:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8020: }
                   8021: 
1.795     www      8022: a#LC_content_toolbar_everything {
1.911     bisitz   8023:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8024: }
                   8025: 
1.795     www      8026: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8027:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8028: }
                   8029: 
1.795     www      8030: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8031:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8032: }
                   8033: 
1.795     www      8034: a#LC_content_toolbar_changefolder {
1.911     bisitz   8035:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8036: }
                   8037: 
1.795     www      8038: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8039:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8040: }
                   8041: 
1.1043    raeburn  8042: a#LC_content_toolbar_edittoplevel {
                   8043:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8044: }
                   8045: 
1.795     www      8046: ul#LC_toolbar li a:hover {
1.911     bisitz   8047:   background-position: bottom center;
1.757     schulted 8048: }
                   8049: 
1.795     www      8050: ul#LC_toolbar {
1.911     bisitz   8051:   padding: 0;
                   8052:   margin: 2px;
                   8053:   list-style:none;
                   8054:   position:relative;
                   8055:   background-color:white;
1.1082    raeburn  8056:   overflow: auto;
1.757     schulted 8057: }
                   8058: 
1.795     www      8059: ul#LC_toolbar li {
1.911     bisitz   8060:   border:1px solid white;
                   8061:   padding: 0;
                   8062:   margin: 0;
                   8063:   float: left;
                   8064:   display:inline;
                   8065:   vertical-align:middle;
1.1082    raeburn  8066:   white-space: nowrap;
1.911     bisitz   8067: }
1.757     schulted 8068: 
1.783     amueller 8069: 
1.795     www      8070: a.LC_toolbarItem {
1.911     bisitz   8071:   display:block;
                   8072:   padding: 0;
                   8073:   margin: 0;
                   8074:   height: 32px;
                   8075:   width: 32px;
                   8076:   color:white;
                   8077:   border: none;
                   8078:   background-repeat:no-repeat;
                   8079:   background-color:transparent;
1.757     schulted 8080: }
                   8081: 
1.915     droeschl 8082: ul.LC_funclist {
                   8083:     margin: 0;
                   8084:     padding: 0.5em 1em 0.5em 0;
                   8085: }
                   8086: 
1.933     droeschl 8087: ul.LC_funclist > li:first-child {
                   8088:     font-weight:bold; 
                   8089:     margin-left:0.8em;
                   8090: }
                   8091: 
1.915     droeschl 8092: ul.LC_funclist + ul.LC_funclist {
                   8093:     /* 
                   8094:        left border as a seperator if we have more than
                   8095:        one list 
                   8096:     */
                   8097:     border-left: 1px solid $sidebg;
                   8098:     /* 
                   8099:        this hides the left border behind the border of the 
                   8100:        outer box if element is wrapped to the next 'line' 
                   8101:     */
                   8102:     margin-left: -1px;
                   8103: }
                   8104: 
1.843     bisitz   8105: ul.LC_funclist li {
1.915     droeschl 8106:   display: inline;
1.782     bisitz   8107:   white-space: nowrap;
1.915     droeschl 8108:   margin: 0 0 0 25px;
                   8109:   line-height: 150%;
1.782     bisitz   8110: }
                   8111: 
1.974     wenzelju 8112: .LC_hidden {
                   8113:   display: none;
                   8114: }
                   8115: 
1.1030    www      8116: .LCmodal-overlay {
                   8117: 		position:fixed;
                   8118: 		top:0;
                   8119: 		right:0;
                   8120: 		bottom:0;
                   8121: 		left:0;
                   8122: 		height:100%;
                   8123: 		width:100%;
                   8124: 		margin:0;
                   8125: 		padding:0;
                   8126: 		background:#999;
                   8127: 		opacity:.75;
                   8128: 		filter: alpha(opacity=75);
                   8129: 		-moz-opacity: 0.75;
                   8130: 		z-index:101;
                   8131: }
                   8132: 
                   8133: * html .LCmodal-overlay {   
                   8134: 		position: absolute;
                   8135: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8136: }
                   8137: 
                   8138: .LCmodal-window {
                   8139: 		position:fixed;
                   8140: 		top:50%;
                   8141: 		left:50%;
                   8142: 		margin:0;
                   8143: 		padding:0;
                   8144: 		z-index:102;
                   8145: 	}
                   8146: 
                   8147: * html .LCmodal-window {
                   8148: 		position:absolute;
                   8149: }
                   8150: 
                   8151: .LCclose-window {
                   8152: 		position:absolute;
                   8153: 		width:32px;
                   8154: 		height:32px;
                   8155: 		right:8px;
                   8156: 		top:8px;
                   8157: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8158: 		text-indent:-99999px;
                   8159: 		overflow:hidden;
                   8160: 		cursor:pointer;
                   8161: }
                   8162: 
1.1100    raeburn  8163: /*
1.1231    damieng  8164:   styles used for response display
                   8165: */
                   8166: div.LC_radiofoil, div.LC_rankfoil {
                   8167:   margin: .5em 0em .5em 0em;
                   8168: }
                   8169: table.LC_itemgroup {
                   8170:   margin-top: 1em;
                   8171: }
                   8172: 
                   8173: /*
1.1100    raeburn  8174:   styles used by TTH when "Default set of options to pass to tth/m
                   8175:   when converting TeX" in course settings has been set
                   8176: 
                   8177:   option passed: -t
                   8178: 
                   8179: */
                   8180: 
                   8181: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8182: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8183: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8184: td div.norm {line-height:normal;}
                   8185: 
                   8186: /*
                   8187:   option passed -y3
                   8188: */
                   8189: 
                   8190: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8191: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8192: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8193: 
1.1230    damieng  8194: /*
                   8195:   sections with roles, for content only
                   8196: */
                   8197: section[class^="role-"] {
                   8198:   padding-left: 10px;
                   8199:   padding-right: 5px;
                   8200:   margin-top: 8px;
                   8201:   margin-bottom: 8px;
                   8202:   border: 1px solid #2A4;
                   8203:   border-radius: 5px;
                   8204:   box-shadow: 0px 1px 1px #BBB;
                   8205: }
                   8206: section[class^="role-"]>h1 {
                   8207:   position: relative;
                   8208:   margin: 0px;
                   8209:   padding-top: 10px;
                   8210:   padding-left: 40px;
                   8211: }
                   8212: section[class^="role-"]>h1:before {
                   8213:   position: absolute;
                   8214:   left: -5px;
                   8215:   top: 5px;
                   8216: }
                   8217: section.role-activity>h1:before {
                   8218:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8219: }
                   8220: section.role-advice>h1:before {
                   8221:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8222: }
                   8223: section.role-bibliography>h1:before {
                   8224:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8225: }
                   8226: section.role-citation>h1:before {
                   8227:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8228: }
                   8229: section.role-conclusion>h1:before {
                   8230:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8231: }
                   8232: section.role-definition>h1:before {
                   8233:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8234: }
                   8235: section.role-demonstration>h1:before {
                   8236:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8237: }
                   8238: section.role-example>h1:before {
                   8239:   content:url('/adm/daxe/images/section_icons/example.png');
                   8240: }
                   8241: section.role-explanation>h1:before {
                   8242:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8243: }
                   8244: section.role-introduction>h1:before {
                   8245:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8246: }
                   8247: section.role-method>h1:before {
                   8248:   content:url('/adm/daxe/images/section_icons/method.png');
                   8249: }
                   8250: section.role-more_information>h1:before {
                   8251:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8252: }
                   8253: section.role-objectives>h1:before {
                   8254:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8255: }
                   8256: section.role-prerequisites>h1:before {
                   8257:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8258: }
                   8259: section.role-remark>h1:before {
                   8260:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8261: }
                   8262: section.role-reminder>h1:before {
                   8263:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8264: }
                   8265: section.role-summary>h1:before {
                   8266:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8267: }
                   8268: section.role-syntax>h1:before {
                   8269:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8270: }
                   8271: section.role-warning>h1:before {
                   8272:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8273: }
                   8274: 
1.1269    raeburn  8275: #LC_minitab_header {
                   8276:   float:left;
                   8277:   width:100%;
                   8278:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8279:   font-size:93%;
                   8280:   line-height:normal;
                   8281:   margin: 0.5em 0 0.5em 0;
                   8282: }
                   8283: #LC_minitab_header ul {
                   8284:   margin:0;
                   8285:   padding:10px 10px 0;
                   8286:   list-style:none;
                   8287: }
                   8288: #LC_minitab_header li {
                   8289:   float:left;
                   8290:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8291:   margin:0;
                   8292:   padding:0 0 0 9px;
                   8293: }
                   8294: #LC_minitab_header a {
                   8295:   display:block;
                   8296:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8297:   padding:5px 15px 4px 6px;
                   8298: }
                   8299: #LC_minitab_header #LC_current_minitab {
                   8300:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8301: }
                   8302: #LC_minitab_header #LC_current_minitab a {
                   8303:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8304:   padding-bottom:5px;
                   8305: }
                   8306: 
                   8307: 
1.343     albertel 8308: END
                   8309: }
                   8310: 
1.306     albertel 8311: =pod
                   8312: 
                   8313: =item * &headtag()
                   8314: 
                   8315: Returns a uniform footer for LON-CAPA web pages.
                   8316: 
1.307     albertel 8317: Inputs: $title - optional title for the head
                   8318:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8319:         $args - optional arguments
1.319     albertel 8320:             force_register - if is true call registerurl so the remote is 
                   8321:                              informed
1.415     albertel 8322:             redirect       -> array ref of
                   8323:                                    1- seconds before redirect occurs
                   8324:                                    2- url to redirect to
                   8325:                                    3- whether the side effect should occur
1.315     albertel 8326:                            (side effect of setting 
                   8327:                                $env{'internal.head.redirect'} to the url 
                   8328:                                redirected too)
1.352     albertel 8329:             domain         -> force to color decorate a page for a specific
                   8330:                                domain
                   8331:             function       -> force usage of a specific rolish color scheme
                   8332:             bgcolor        -> override the default page bgcolor
1.460     albertel 8333:             no_auto_mt_title
                   8334:                            -> prevent &mt()ing the title arg
1.464     albertel 8335: 
1.306     albertel 8336: =cut
                   8337: 
                   8338: sub headtag {
1.313     albertel 8339:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8340:     
1.363     albertel 8341:     my $function = $args->{'function'} || &get_users_function();
                   8342:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8343:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8344:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8345:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8346: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8347: 		   #time(),
1.418     albertel 8348: 		   $env{'environment.color.timestamp'},
1.363     albertel 8349: 		   $function,$domain,$bgcolor);
                   8350: 
1.369     www      8351:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8352: 
1.308     albertel 8353:     my $result =
                   8354: 	'<head>'.
1.1160    raeburn  8355: 	&font_settings($args);
1.319     albertel 8356: 
1.1188    raeburn  8357:     my $inhibitprint;
                   8358:     if ($args->{'print_suppress'}) {
                   8359:         $inhibitprint = &print_suppression();
                   8360:     }
1.1064    raeburn  8361: 
1.461     albertel 8362:     if (!$args->{'frameset'}) {
                   8363: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8364:     }
1.962     droeschl 8365:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8366:         $result .= Apache::lonxml::display_title();
1.319     albertel 8367:     }
1.436     albertel 8368:     if (!$args->{'no_nav_bar'} 
                   8369: 	&& !$args->{'only_body'}
                   8370: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8371: 	$result .= &help_menu_js($httphost);
1.1032    www      8372:         $result.=&modal_window();
1.1038    www      8373:         $result.=&togglebox_script();
1.1034    www      8374:         $result.=&wishlist_window();
1.1041    www      8375:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8376:     } else {
                   8377:         if ($args->{'add_modal'}) {
                   8378:            $result.=&modal_window();
                   8379:         }
                   8380:         if ($args->{'add_wishlist'}) {
                   8381:            $result.=&wishlist_window();
                   8382:         }
1.1038    www      8383:         if ($args->{'add_togglebox'}) {
                   8384:            $result.=&togglebox_script();
                   8385:         }
1.1041    www      8386:         if ($args->{'add_progressbar'}) {
                   8387:            $result.=&LCprogressbarUpdate_script();
                   8388:         }
1.436     albertel 8389:     }
1.314     albertel 8390:     if (ref($args->{'redirect'})) {
1.414     albertel 8391: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8392: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8393: 	if (!$inhibit_continue) {
                   8394: 	    $env{'internal.head.redirect'} = $url;
                   8395: 	}
1.313     albertel 8396: 	$result.=<<ADDMETA
                   8397: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8398: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8399: ADDMETA
1.1210    raeburn  8400:     } else {
                   8401:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8402:             my $requrl = $env{'request.uri'};
                   8403:             if ($requrl eq '') {
                   8404:                 $requrl = $ENV{'REQUEST_URI'};
                   8405:                 $requrl =~ s/\?.+$//;
                   8406:             }
                   8407:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8408:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8409:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8410:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8411:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8412:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8413:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8414:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8415:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8416:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8417:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8418:                                 my $numsec = 5;
                   8419:                                 my $timeout = $numsec * 1000;
                   8420:                                 my ($newurl,$locknum,%locks,$msg);
                   8421:                                 if ($env{'request.role.adv'}) {
                   8422:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8423:                                 }
                   8424:                                 my $disable_submit = 0;
                   8425:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8426:                                     $disable_submit = 1;
                   8427:                                 }
                   8428:                                 if ($locknum) {
                   8429:                                     my @lockinfo = sort(values(%locks));
                   8430:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8431:                                            join(", ",sort(values(%locks)))."\\n".
                   8432:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8433:                                 } else {
                   8434:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8435:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8436:                                     }
                   8437:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8438:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8439:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8440:                                         $newurl .= '&role='.$env{'request.role'};
                   8441:                                     }
                   8442:                                     if ($env{'request.symb'}) {
                   8443:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8444:                                     } else {
                   8445:                                         $newurl .= '&origurl='.$requrl;
                   8446:                                     }
                   8447:                                 }
1.1222    damieng  8448:                                 &js_escape(\$msg);
1.1210    raeburn  8449:                                 $result.=<<OFFLOAD
                   8450: <meta http-equiv="pragma" content="no-cache" />
                   8451: <script type="text/javascript">
1.1215    raeburn  8452: // <![CDATA[
1.1210    raeburn  8453: function LC_Offload_Now() {
                   8454:     var dest = "$newurl";
                   8455:     if (dest != '') {
                   8456:         window.location.href="$newurl";
                   8457:     }
                   8458: }
1.1214    raeburn  8459: \$(document).ready(function () {
                   8460:     window.alert('$msg');
                   8461:     if ($disable_submit) {
1.1210    raeburn  8462:         \$(".LC_hwk_submit").prop("disabled", true);
                   8463:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8464:     }
                   8465:     setTimeout('LC_Offload_Now()', $timeout);
                   8466: });
1.1215    raeburn  8467: // ]]>
1.1210    raeburn  8468: </script>
                   8469: OFFLOAD
                   8470:                             }
                   8471:                         }
                   8472:                     }
                   8473:                 }
                   8474:             }
                   8475:         }
1.313     albertel 8476:     }
1.306     albertel 8477:     if (!defined($title)) {
                   8478: 	$title = 'The LearningOnline Network with CAPA';
                   8479:     }
1.460     albertel 8480:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8481:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8482: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8483:     if (!$args->{'frameset'}) {
                   8484:         $result .= ' /';
                   8485:     }
                   8486:     $result .= '>' 
1.1064    raeburn  8487:         .$inhibitprint
1.414     albertel 8488: 	.$head_extra;
1.1242    raeburn  8489:     my $clientmobile;
                   8490:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8491:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8492:     } else {
                   8493:         $clientmobile = $env{'browser.mobile'};
                   8494:     }
                   8495:     if ($clientmobile) {
1.1137    raeburn  8496:         $result .= '
                   8497: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8498: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8499:     }
1.1278    raeburn  8500:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8501:     return $result.'</head>';
1.306     albertel 8502: }
                   8503: 
                   8504: =pod
                   8505: 
1.340     albertel 8506: =item * &font_settings()
                   8507: 
                   8508: Returns neccessary <meta> to set the proper encoding
                   8509: 
1.1160    raeburn  8510: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8511: 
                   8512: =cut
                   8513: 
                   8514: sub font_settings {
1.1160    raeburn  8515:     my ($args) = @_;
1.340     albertel 8516:     my $headerstring='';
1.1160    raeburn  8517:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8518:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8519:         $headerstring.=
                   8520:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8521:         if (!$args->{'frameset'}) {
                   8522: 	    $headerstring.= ' /';
                   8523:         }
                   8524: 	$headerstring .= '>'."\n";
1.340     albertel 8525:     }
                   8526:     return $headerstring;
                   8527: }
                   8528: 
1.341     albertel 8529: =pod
                   8530: 
1.1064    raeburn  8531: =item * &print_suppression()
                   8532: 
                   8533: In course context returns css which causes the body to be blank when media="print",
                   8534: if printout generation is unavailable for the current resource.
                   8535: 
                   8536: This could be because:
                   8537: 
                   8538: (a) printstartdate is in the future
                   8539: 
                   8540: (b) printenddate is in the past
                   8541: 
                   8542: (c) there is an active exam block with "printout"
                   8543: functionality blocked
                   8544: 
                   8545: Users with pav, pfo or evb privileges are exempt.
                   8546: 
                   8547: Inputs: none
                   8548: 
                   8549: =cut
                   8550: 
                   8551: 
                   8552: sub print_suppression {
                   8553:     my $noprint;
                   8554:     if ($env{'request.course.id'}) {
                   8555:         my $scope = $env{'request.course.id'};
                   8556:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8557:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8558:             return;
                   8559:         }
                   8560:         if ($env{'request.course.sec'} ne '') {
                   8561:             $scope .= "/$env{'request.course.sec'}";
                   8562:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8563:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8564:                 return;
1.1064    raeburn  8565:             }
                   8566:         }
                   8567:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8568:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8569:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8570:         if ($blocked) {
                   8571:             my $checkrole = "cm./$cdom/$cnum";
                   8572:             if ($env{'request.course.sec'} ne '') {
                   8573:                 $checkrole .= "/$env{'request.course.sec'}";
                   8574:             }
                   8575:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8576:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8577:                 $noprint = 1;
                   8578:             }
                   8579:         }
                   8580:         unless ($noprint) {
                   8581:             my $symb = &Apache::lonnet::symbread();
                   8582:             if ($symb ne '') {
                   8583:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8584:                 if (ref($navmap)) {
                   8585:                     my $res = $navmap->getBySymb($symb);
                   8586:                     if (ref($res)) {
                   8587:                         if (!$res->resprintable()) {
                   8588:                             $noprint = 1;
                   8589:                         }
                   8590:                     }
                   8591:                 }
                   8592:             }
                   8593:         }
                   8594:         if ($noprint) {
                   8595:             return <<"ENDSTYLE";
                   8596: <style type="text/css" media="print">
                   8597:     body { display:none }
                   8598: </style>
                   8599: ENDSTYLE
                   8600:         }
                   8601:     }
                   8602:     return;
                   8603: }
                   8604: 
                   8605: =pod
                   8606: 
1.341     albertel 8607: =item * &xml_begin()
                   8608: 
                   8609: Returns the needed doctype and <html>
                   8610: 
                   8611: Inputs: none
                   8612: 
                   8613: =cut
                   8614: 
                   8615: sub xml_begin {
1.1168    raeburn  8616:     my ($is_frameset) = @_;
1.341     albertel 8617:     my $output='';
                   8618: 
                   8619:     if ($env{'browser.mathml'}) {
                   8620: 	$output='<?xml version="1.0"?>'
                   8621:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8622: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8623:             
                   8624: #	    .'<!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">] >'
                   8625: 	    .'<!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">'
                   8626:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8627: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8628:     } elsif ($is_frameset) {
                   8629:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8630:                 '<html>'."\n";
1.341     albertel 8631:     } else {
1.1168    raeburn  8632: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8633:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8634:     }
                   8635:     return $output;
                   8636: }
1.340     albertel 8637: 
                   8638: =pod
                   8639: 
1.306     albertel 8640: =item * &start_page()
                   8641: 
                   8642: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8643: 
1.648     raeburn  8644: Inputs:
                   8645: 
                   8646: =over 4
                   8647: 
                   8648: $title - optional title for the page
                   8649: 
                   8650: $head_extra - optional extra HTML to incude inside the <head>
                   8651: 
                   8652: $args - additional optional args supported are:
                   8653: 
                   8654: =over 8
                   8655: 
                   8656:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8657:                                     arg on
1.814     bisitz   8658:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8659:              add_entries    -> additional attributes to add to the  <body>
                   8660:              domain         -> force to color decorate a page for a 
1.317     albertel 8661:                                     specific domain
1.648     raeburn  8662:              function       -> force usage of a specific rolish color
1.317     albertel 8663:                                     scheme
1.648     raeburn  8664:              redirect       -> see &headtag()
                   8665:              bgcolor        -> override the default page bg color
                   8666:              js_ready       -> return a string ready for being used in 
1.317     albertel 8667:                                     a javascript writeln
1.648     raeburn  8668:              html_encode    -> return a string ready for being used in 
1.320     albertel 8669:                                     a html attribute
1.648     raeburn  8670:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8671:                                     $forcereg arg
1.648     raeburn  8672:              frameset       -> if true will start with a <frameset>
1.330     albertel 8673:                                     rather than <body>
1.648     raeburn  8674:              skip_phases    -> hash ref of 
1.338     albertel 8675:                                     head -> skip the <html><head> generation
                   8676:                                     body -> skip all <body> generation
1.648     raeburn  8677:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8678:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8679:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8680:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8681:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8682:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8683:                                specific group
                   8684:              use_absolute   -> for request for external resource or syllabus, this
                   8685:                                will contain https://<hostname> if server uses
                   8686:                                https (as per hosts.tab), but request is for http
                   8687:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8688: 
1.648     raeburn  8689: =back
1.460     albertel 8690: 
1.648     raeburn  8691: =back
1.562     albertel 8692: 
1.306     albertel 8693: =cut
                   8694: 
                   8695: sub start_page {
1.309     albertel 8696:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8697:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8698: 
1.315     albertel 8699:     $env{'internal.start_page'}++;
1.1316  ! raeburn  8700:     my ($result,@advtools,$ltiscope,$ltiuri);
1.964     droeschl 8701: 
1.338     albertel 8702:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8703:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8704:     }
1.1316  ! raeburn  8705: 
        !          8706:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
        !          8707:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
        !          8708:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
        !          8709:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
        !          8710:     }
1.338     albertel 8711:     
                   8712:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8713: 	if ($args->{'frameset'}) {
                   8714: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8715: 						$args->{'add_entries'});
                   8716: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8717:         } else {
                   8718:             $result .=
                   8719:                 &bodytag($title, 
                   8720:                          $args->{'function'},       $args->{'add_entries'},
                   8721:                          $args->{'only_body'},      $args->{'domain'},
                   8722:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8723:                          $args->{'bgcolor'},        $args,
1.1316  ! raeburn  8724:                          \@advtools,$ltiscope,$ltiuri);
1.831     bisitz   8725:         }
1.330     albertel 8726:     }
1.338     albertel 8727: 
1.315     albertel 8728:     if ($args->{'js_ready'}) {
1.713     kaisler  8729: 		$result = &js_ready($result);
1.315     albertel 8730:     }
1.320     albertel 8731:     if ($args->{'html_encode'}) {
1.713     kaisler  8732: 		$result = &html_encode($result);
                   8733:     }
                   8734: 
1.813     bisitz   8735:     # Preparation for new and consistent functionlist at top of screen
                   8736:     # if ($args->{'functionlist'}) {
                   8737:     #            $result .= &build_functionlist();
                   8738:     #}
                   8739: 
1.964     droeschl 8740:     # Don't add anything more if only_body wanted or in const space
                   8741:     return $result if    $args->{'only_body'} 
                   8742:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8743: 
                   8744:     #Breadcrumbs
1.758     kaisler  8745:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8746: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8747: 		#if any br links exists, add them to the breadcrumbs
                   8748: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8749: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8750: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8751: 			}
                   8752: 		}
1.1096    raeburn  8753:                 # if @advtools array contains items add then to the breadcrumbs
                   8754:                 if (@advtools > 0) {
                   8755:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8756:                 }
1.1272    raeburn  8757:                 my $menulink;
                   8758:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8759:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  8760:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  8761:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8762:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8763:                      (!$env{'request.role.adv'}))) {
                   8764:                     $menulink = 0;
                   8765:                 } else {
                   8766:                     undef($menulink);
                   8767:                 }
1.758     kaisler  8768: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8769: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8770: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8771:                 } else {
1.1272    raeburn  8772: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8773: 		}
1.320     albertel 8774:     }
1.315     albertel 8775:     return $result;
1.306     albertel 8776: }
                   8777: 
                   8778: sub end_page {
1.315     albertel 8779:     my ($args) = @_;
                   8780:     $env{'internal.end_page'}++;
1.330     albertel 8781:     my $result;
1.335     albertel 8782:     if ($args->{'discussion'}) {
                   8783: 	my ($target,$parser);
                   8784: 	if (ref($args->{'discussion'})) {
                   8785: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8786: 				$args->{'discussion'}{'parser'});
                   8787: 	}
                   8788: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8789:     }
1.330     albertel 8790:     if ($args->{'frameset'}) {
                   8791: 	$result .= '</frameset>';
                   8792:     } else {
1.635     raeburn  8793: 	$result .= &endbodytag($args);
1.330     albertel 8794:     }
1.1080    raeburn  8795:     unless ($args->{'notbody'}) {
                   8796:         $result .= "\n</html>";
                   8797:     }
1.330     albertel 8798: 
1.315     albertel 8799:     if ($args->{'js_ready'}) {
1.317     albertel 8800: 	$result = &js_ready($result);
1.315     albertel 8801:     }
1.335     albertel 8802: 
1.320     albertel 8803:     if ($args->{'html_encode'}) {
                   8804: 	$result = &html_encode($result);
                   8805:     }
1.335     albertel 8806: 
1.315     albertel 8807:     return $result;
                   8808: }
                   8809: 
1.1034    www      8810: sub wishlist_window {
                   8811:     return(<<'ENDWISHLIST');
1.1046    raeburn  8812: <script type="text/javascript">
1.1034    www      8813: // <![CDATA[
                   8814: // <!-- BEGIN LON-CAPA Internal
                   8815: function set_wishlistlink(title, path) {
                   8816:     if (!title) {
                   8817:         title = document.title;
                   8818:         title = title.replace(/^LON-CAPA /,'');
                   8819:     }
1.1175    raeburn  8820:     title = encodeURIComponent(title);
1.1203    raeburn  8821:     title = title.replace("'","\\\'");
1.1034    www      8822:     if (!path) {
                   8823:         path = location.pathname;
                   8824:     }
1.1175    raeburn  8825:     path = encodeURIComponent(path);
1.1203    raeburn  8826:     path = path.replace("'","\\\'");
1.1034    www      8827:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8828:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8829: }
                   8830: // END LON-CAPA Internal -->
                   8831: // ]]>
                   8832: </script>
                   8833: ENDWISHLIST
                   8834: }
                   8835: 
1.1030    www      8836: sub modal_window {
                   8837:     return(<<'ENDMODAL');
1.1046    raeburn  8838: <script type="text/javascript">
1.1030    www      8839: // <![CDATA[
                   8840: // <!-- BEGIN LON-CAPA Internal
                   8841: var modalWindow = {
                   8842: 	parent:"body",
                   8843: 	windowId:null,
                   8844: 	content:null,
                   8845: 	width:null,
                   8846: 	height:null,
                   8847: 	close:function()
                   8848: 	{
                   8849: 	        $(".LCmodal-window").remove();
                   8850: 	        $(".LCmodal-overlay").remove();
                   8851: 	},
                   8852: 	open:function()
                   8853: 	{
                   8854: 		var modal = "";
                   8855: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8856: 		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;\">";
                   8857: 		modal += this.content;
                   8858: 		modal += "</div>";	
                   8859: 
                   8860: 		$(this.parent).append(modal);
                   8861: 
                   8862: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8863: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8864: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8865: 	}
                   8866: };
1.1140    raeburn  8867: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8868: 	{
1.1266    raeburn  8869:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8870: 		modalWindow.windowId = "myModal";
                   8871: 		modalWindow.width = width;
                   8872: 		modalWindow.height = height;
1.1196    raeburn  8873: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8874: 		modalWindow.open();
1.1208    raeburn  8875: 	};
1.1030    www      8876: // END LON-CAPA Internal -->
                   8877: // ]]>
                   8878: </script>
                   8879: ENDMODAL
                   8880: }
                   8881: 
                   8882: sub modal_link {
1.1140    raeburn  8883:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8884:     unless ($width) { $width=480; }
                   8885:     unless ($height) { $height=400; }
1.1031    www      8886:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8887:     unless ($transparency) { $transparency='true'; }
                   8888: 
1.1074    raeburn  8889:     my $target_attr;
                   8890:     if (defined($target)) {
                   8891:         $target_attr = 'target="'.$target.'"';
                   8892:     }
                   8893:     return <<"ENDLINK";
1.1140    raeburn  8894: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8895:            $linktext</a>
                   8896: ENDLINK
1.1030    www      8897: }
                   8898: 
1.1032    www      8899: sub modal_adhoc_script {
                   8900:     my ($funcname,$width,$height,$content)=@_;
                   8901:     return (<<ENDADHOC);
1.1046    raeburn  8902: <script type="text/javascript">
1.1032    www      8903: // <![CDATA[
                   8904:         var $funcname = function()
                   8905:         {
                   8906:                 modalWindow.windowId = "myModal";
                   8907:                 modalWindow.width = $width;
                   8908:                 modalWindow.height = $height;
                   8909:                 modalWindow.content = '$content';
                   8910:                 modalWindow.open();
                   8911:         };  
                   8912: // ]]>
                   8913: </script>
                   8914: ENDADHOC
                   8915: }
                   8916: 
1.1041    www      8917: sub modal_adhoc_inner {
                   8918:     my ($funcname,$width,$height,$content)=@_;
                   8919:     my $innerwidth=$width-20;
                   8920:     $content=&js_ready(
1.1140    raeburn  8921:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8922:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8923:                  $content.
1.1041    www      8924:                  &end_scrollbox().
1.1140    raeburn  8925:                  &end_page()
1.1041    www      8926:              );
                   8927:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8928: }
                   8929: 
                   8930: sub modal_adhoc_window {
                   8931:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8932:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8933:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8934: }
                   8935: 
                   8936: sub modal_adhoc_launch {
                   8937:     my ($funcname,$width,$height,$content)=@_;
                   8938:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8939: <script type="text/javascript">
                   8940: // <![CDATA[
                   8941: $funcname();
                   8942: // ]]>
                   8943: </script>
                   8944: ENDLAUNCH
                   8945: }
                   8946: 
                   8947: sub modal_adhoc_close {
                   8948:     return (<<ENDCLOSE);
                   8949: <script type="text/javascript">
                   8950: // <![CDATA[
                   8951: modalWindow.close();
                   8952: // ]]>
                   8953: </script>
                   8954: ENDCLOSE
                   8955: }
                   8956: 
1.1038    www      8957: sub togglebox_script {
                   8958:    return(<<ENDTOGGLE);
                   8959: <script type="text/javascript"> 
                   8960: // <![CDATA[
                   8961: function LCtoggleDisplay(id,hidetext,showtext) {
                   8962:    link = document.getElementById(id + "link").childNodes[0];
                   8963:    with (document.getElementById(id).style) {
                   8964:       if (display == "none" ) {
                   8965:           display = "inline";
                   8966:           link.nodeValue = hidetext;
                   8967:         } else {
                   8968:           display = "none";
                   8969:           link.nodeValue = showtext;
                   8970:        }
                   8971:    }
                   8972: }
                   8973: // ]]>
                   8974: </script>
                   8975: ENDTOGGLE
                   8976: }
                   8977: 
1.1039    www      8978: sub start_togglebox {
                   8979:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8980:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8981:     unless ($showtext) { $showtext=&mt('show'); }
                   8982:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8983:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8984:     return &start_data_table().
                   8985:            &start_data_table_header_row().
                   8986:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8987:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8988:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8989:            &end_data_table_header_row().
                   8990:            '<tr id="'.$id.'" style="display:none""><td>';
                   8991: }
                   8992: 
                   8993: sub end_togglebox {
                   8994:     return '</td></tr>'.&end_data_table();
                   8995: }
                   8996: 
1.1041    www      8997: sub LCprogressbar_script {
1.1302    raeburn  8998:    my ($id,$number_to_do)=@_;
                   8999:    if ($number_to_do) {
                   9000:        return(<<ENDPROGRESS);
1.1041    www      9001: <script type="text/javascript">
                   9002: // <![CDATA[
1.1045    www      9003: \$('#progressbar$id').progressbar({
1.1041    www      9004:   value: 0,
                   9005:   change: function(event, ui) {
                   9006:     var newVal = \$(this).progressbar('option', 'value');
                   9007:     \$('.pblabel', this).text(LCprogressTxt);
                   9008:   }
                   9009: });
                   9010: // ]]>
                   9011: </script>
                   9012: ENDPROGRESS
1.1302    raeburn  9013:    } else {
                   9014:        return(<<ENDPROGRESS);
                   9015: <script type="text/javascript">
                   9016: // <![CDATA[
                   9017: \$('#progressbar$id').progressbar({
                   9018:   value: false,
                   9019:   create: function(event, ui) {
                   9020:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9021:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9022:   }
                   9023: });
                   9024: // ]]>
                   9025: </script>
                   9026: ENDPROGRESS
                   9027:    }
1.1041    www      9028: }
                   9029: 
                   9030: sub LCprogressbarUpdate_script {
                   9031:    return(<<ENDPROGRESSUPDATE);
                   9032: <style type="text/css">
                   9033: .ui-progressbar { position:relative; }
1.1302    raeburn  9034: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      9035: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9036: </style>
                   9037: <script type="text/javascript">
                   9038: // <![CDATA[
1.1045    www      9039: var LCprogressTxt='---';
                   9040: 
1.1302    raeburn  9041: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9042:    LCprogressTxt=progresstext;
1.1302    raeburn  9043:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9044:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9045:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9046:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9047:    } else {
                   9048:        \$('#progressbar'+id).progressbar('value',percent);
                   9049:    }
1.1041    www      9050: }
                   9051: // ]]>
                   9052: </script>
                   9053: ENDPROGRESSUPDATE
                   9054: }
                   9055: 
1.1042    www      9056: my $LClastpercent;
1.1045    www      9057: my $LCidcnt;
                   9058: my $LCcurrentid;
1.1042    www      9059: 
1.1041    www      9060: sub LCprogressbar {
1.1302    raeburn  9061:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9062:     $LClastpercent=0;
1.1045    www      9063:     $LCidcnt++;
                   9064:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9065:     my ($starting,$content);
                   9066:     if ($number_to_do) {
                   9067:         $starting=&mt('Starting');
                   9068:         $content=(<<ENDPROGBAR);
                   9069: $preamble
1.1045    www      9070:   <div id="progressbar$LCcurrentid">
1.1041    www      9071:     <span class="pblabel">$starting</span>
                   9072:   </div>
                   9073: ENDPROGBAR
1.1302    raeburn  9074:     } else {
                   9075:         $starting=&mt('Loading...');
                   9076:         $LClastpercent='false';
                   9077:         $content=(<<ENDPROGBAR);
                   9078: $preamble
                   9079:   <div id="progressbar$LCcurrentid">
                   9080:       <div class="progress-label">$starting</div>
                   9081:   </div>
                   9082: ENDPROGBAR
                   9083:     }
                   9084:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9085: }
                   9086: 
                   9087: sub LCprogressbarUpdate {
1.1302    raeburn  9088:     my ($r,$val,$text,$number_to_do)=@_;
                   9089:     if ($number_to_do) {
                   9090:         unless ($val) { 
                   9091:             if ($LClastpercent) {
                   9092:                 $val=$LClastpercent;
                   9093:             } else {
                   9094:                 $val=0;
                   9095:             }
                   9096:         }
                   9097:         if ($val<0) { $val=0; }
                   9098:         if ($val>100) { $val=0; }
                   9099:         $LClastpercent=$val;
                   9100:         unless ($text) { $text=$val.'%'; }
                   9101:     } else {
                   9102:         $val = 'false';
1.1042    www      9103:     }
1.1041    www      9104:     $text=&js_ready($text);
1.1044    www      9105:     &r_print($r,<<ENDUPDATE);
1.1041    www      9106: <script type="text/javascript">
                   9107: // <![CDATA[
1.1302    raeburn  9108: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9109: // ]]>
                   9110: </script>
                   9111: ENDUPDATE
1.1035    www      9112: }
                   9113: 
1.1042    www      9114: sub LCprogressbarClose {
                   9115:     my ($r)=@_;
                   9116:     $LClastpercent=0;
1.1044    www      9117:     &r_print($r,<<ENDCLOSE);
1.1042    www      9118: <script type="text/javascript">
                   9119: // <![CDATA[
1.1045    www      9120: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9121: // ]]>
                   9122: </script>
                   9123: ENDCLOSE
1.1044    www      9124: }
                   9125: 
                   9126: sub r_print {
                   9127:     my ($r,$to_print)=@_;
                   9128:     if ($r) {
                   9129:       $r->print($to_print);
                   9130:       $r->rflush();
                   9131:     } else {
                   9132:       print($to_print);
                   9133:     }
1.1042    www      9134: }
                   9135: 
1.320     albertel 9136: sub html_encode {
                   9137:     my ($result) = @_;
                   9138: 
1.322     albertel 9139:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9140:     
                   9141:     return $result;
                   9142: }
1.1044    www      9143: 
1.317     albertel 9144: sub js_ready {
                   9145:     my ($result) = @_;
                   9146: 
1.323     albertel 9147:     $result =~ s/[\n\r]/ /xmsg;
                   9148:     $result =~ s/\\/\\\\/xmsg;
                   9149:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9150:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9151:     
                   9152:     return $result;
                   9153: }
                   9154: 
1.315     albertel 9155: sub validate_page {
                   9156:     if (  exists($env{'internal.start_page'})
1.316     albertel 9157: 	  &&     $env{'internal.start_page'} > 1) {
                   9158: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9159: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9160: 				 $ENV{'request.filename'});
1.315     albertel 9161:     }
                   9162:     if (  exists($env{'internal.end_page'})
1.316     albertel 9163: 	  &&     $env{'internal.end_page'} > 1) {
                   9164: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9165: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9166: 				 $env{'request.filename'});
1.315     albertel 9167:     }
                   9168:     if (     exists($env{'internal.start_page'})
                   9169: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9170: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9171: 				 $env{'request.filename'});
1.315     albertel 9172:     }
                   9173:     if (   ! exists($env{'internal.start_page'})
                   9174: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9175: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9176: 				 $env{'request.filename'});
1.315     albertel 9177:     }
1.306     albertel 9178: }
1.315     albertel 9179: 
1.996     www      9180: 
                   9181: sub start_scrollbox {
1.1140    raeburn  9182:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9183:     unless ($outerwidth) { $outerwidth='520px'; }
                   9184:     unless ($width) { $width='500px'; }
                   9185:     unless ($height) { $height='200px'; }
1.1075    raeburn  9186:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9187:     if ($id ne '') {
1.1140    raeburn  9188:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9189:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9190:     }
1.1075    raeburn  9191:     if ($bgcolor ne '') {
                   9192:         $tdcol = "background-color: $bgcolor;";
                   9193:     }
1.1137    raeburn  9194:     my $nicescroll_js;
                   9195:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9196:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9197:     }
                   9198:     return <<"END";
                   9199: $nicescroll_js
                   9200: 
                   9201: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9202: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9203: END
                   9204: }
                   9205: 
                   9206: sub end_scrollbox {
                   9207:     return '</div></td></tr></table>';
                   9208: }
                   9209: 
                   9210: sub nicescroll_javascript {
                   9211:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9212:     my %options;
                   9213:     if (ref($cursor) eq 'HASH') {
                   9214:         %options = %{$cursor};
                   9215:     }
                   9216:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9217:         $options{'railalign'} = 'left';
                   9218:     }
                   9219:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9220:         my $function  = &get_users_function();
                   9221:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9222:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9223:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9224:         }
1.1140    raeburn  9225:     }
                   9226:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9227:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9228:             $options{'cursoropacity'}='1.0';
                   9229:         }
1.1140    raeburn  9230:     } else {
                   9231:         $options{'cursoropacity'}='1.0';
                   9232:     }
                   9233:     if ($options{'cursorfixedheight'} eq 'none') {
                   9234:         delete($options{'cursorfixedheight'});
                   9235:     } else {
                   9236:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9237:     }
                   9238:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9239:         delete($options{'railoffset'});
                   9240:     }
                   9241:     my @niceoptions;
                   9242:     while (my($key,$value) = each(%options)) {
                   9243:         if ($value =~ /^\{.+\}$/) {
                   9244:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9245:         } else {
1.1140    raeburn  9246:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9247:         }
1.1140    raeburn  9248:     }
                   9249:     my $nicescroll_js = '
1.1137    raeburn  9250: $(document).ready(
1.1140    raeburn  9251:       function() {
                   9252:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9253:       }
1.1137    raeburn  9254: );
                   9255: ';
1.1140    raeburn  9256:     if ($framecheck) {
                   9257:         $nicescroll_js .= '
                   9258: function expand_div(caller) {
                   9259:     if (top === self) {
                   9260:         document.getElementById("'.$id.'").style.width = "auto";
                   9261:         document.getElementById("'.$id.'").style.height = "auto";
                   9262:     } else {
                   9263:         try {
                   9264:             if (parent.frames) {
                   9265:                 if (parent.frames.length > 1) {
                   9266:                     var framesrc = parent.frames[1].location.href;
                   9267:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9268:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9269:                         document.getElementById("'.$id.'").style.width = "auto";
                   9270:                         document.getElementById("'.$id.'").style.height = "auto";
                   9271:                     }
                   9272:                 }
                   9273:             }
                   9274:         } catch (e) {
                   9275:             return;
                   9276:         }
1.1137    raeburn  9277:     }
1.1140    raeburn  9278:     return;
1.996     www      9279: }
1.1140    raeburn  9280: ';
                   9281:     }
                   9282:     if ($needjsready) {
                   9283:         $nicescroll_js = '
                   9284: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9285:     } else {
                   9286:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9287:     }
                   9288:     return $nicescroll_js;
1.996     www      9289: }
                   9290: 
1.318     albertel 9291: sub simple_error_page {
1.1150    bisitz   9292:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9293:     my %displayargs;
1.1151    raeburn  9294:     if (ref($args) eq 'HASH') {
                   9295:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9296:         if ($args->{'only_body'}) {
                   9297:             $displayargs{'only_body'} = 1;
                   9298:         }
                   9299:         if ($args->{'no_nav_bar'}) {
                   9300:             $displayargs{'no_nav_bar'} = 1;
                   9301:         }
1.1151    raeburn  9302:     } else {
                   9303:         $msg = &mt($msg);
                   9304:     }
1.1150    bisitz   9305: 
1.318     albertel 9306:     my $page =
1.1304    raeburn  9307: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9308: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9309: 	&Apache::loncommon::end_page();
                   9310:     if (ref($r)) {
                   9311: 	$r->print($page);
1.327     albertel 9312: 	return;
1.318     albertel 9313:     }
                   9314:     return $page;
                   9315: }
1.347     albertel 9316: 
                   9317: {
1.610     albertel 9318:     my @row_count;
1.961     onken    9319: 
                   9320:     sub start_data_table_count {
                   9321:         unshift(@row_count, 0);
                   9322:         return;
                   9323:     }
                   9324: 
                   9325:     sub end_data_table_count {
                   9326:         shift(@row_count);
                   9327:         return;
                   9328:     }
                   9329: 
1.347     albertel 9330:     sub start_data_table {
1.1018    raeburn  9331: 	my ($add_class,$id) = @_;
1.422     albertel 9332: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9333:         my $table_id;
                   9334:         if (defined($id)) {
                   9335:             $table_id = ' id="'.$id.'"';
                   9336:         }
1.961     onken    9337: 	&start_data_table_count();
1.1018    raeburn  9338: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9339:     }
                   9340: 
                   9341:     sub end_data_table {
1.961     onken    9342: 	&end_data_table_count();
1.389     albertel 9343: 	return '</table>'."\n";;
1.347     albertel 9344:     }
                   9345: 
                   9346:     sub start_data_table_row {
1.974     wenzelju 9347: 	my ($add_class, $id) = @_;
1.610     albertel 9348: 	$row_count[0]++;
                   9349: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9350: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9351:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9352:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9353:     }
1.471     banghart 9354:     
                   9355:     sub continue_data_table_row {
1.974     wenzelju 9356: 	my ($add_class, $id) = @_;
1.610     albertel 9357: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9358: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9359:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9360:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9361:     }
1.347     albertel 9362: 
                   9363:     sub end_data_table_row {
1.389     albertel 9364: 	return '</tr>'."\n";;
1.347     albertel 9365:     }
1.367     www      9366: 
1.421     albertel 9367:     sub start_data_table_empty_row {
1.707     bisitz   9368: #	$row_count[0]++;
1.421     albertel 9369: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9370:     }
                   9371: 
                   9372:     sub end_data_table_empty_row {
                   9373: 	return '</tr>'."\n";;
                   9374:     }
                   9375: 
1.367     www      9376:     sub start_data_table_header_row {
1.389     albertel 9377: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9378:     }
                   9379: 
                   9380:     sub end_data_table_header_row {
1.389     albertel 9381: 	return '</tr>'."\n";;
1.367     www      9382:     }
1.890     droeschl 9383: 
                   9384:     sub data_table_caption {
                   9385:         my $caption = shift;
                   9386:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9387:     }
1.347     albertel 9388: }
                   9389: 
1.548     albertel 9390: =pod
                   9391: 
                   9392: =item * &inhibit_menu_check($arg)
                   9393: 
                   9394: Checks for a inhibitmenu state and generates output to preserve it
                   9395: 
                   9396: Inputs:         $arg - can be any of
                   9397:                      - undef - in which case the return value is a string 
                   9398:                                to add  into arguments list of a uri
                   9399:                      - 'input' - in which case the return value is a HTML
                   9400:                                  <form> <input> field of type hidden to
                   9401:                                  preserve the value
                   9402:                      - a url - in which case the return value is the url with
                   9403:                                the neccesary cgi args added to preserve the
                   9404:                                inhibitmenu state
                   9405:                      - a ref to a url - no return value, but the string is
                   9406:                                         updated to include the neccessary cgi
                   9407:                                         args to preserve the inhibitmenu state
                   9408: 
                   9409: =cut
                   9410: 
                   9411: sub inhibit_menu_check {
                   9412:     my ($arg) = @_;
                   9413:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9414:     if ($arg eq 'input') {
                   9415: 	if ($env{'form.inhibitmenu'}) {
                   9416: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9417: 	} else {
                   9418: 	    return
                   9419: 	}
                   9420:     }
                   9421:     if ($env{'form.inhibitmenu'}) {
                   9422: 	if (ref($arg)) {
                   9423: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9424: 	} elsif ($arg eq '') {
                   9425: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9426: 	} else {
                   9427: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9428: 	}
                   9429:     }
                   9430:     if (!ref($arg)) {
                   9431: 	return $arg;
                   9432:     }
                   9433: }
                   9434: 
1.251     albertel 9435: ###############################################
1.182     matthew  9436: 
                   9437: =pod
                   9438: 
1.549     albertel 9439: =back
                   9440: 
                   9441: =head1 User Information Routines
                   9442: 
                   9443: =over 4
                   9444: 
1.405     albertel 9445: =item * &get_users_function()
1.182     matthew  9446: 
                   9447: Used by &bodytag to determine the current users primary role.
                   9448: Returns either 'student','coordinator','admin', or 'author'.
                   9449: 
                   9450: =cut
                   9451: 
                   9452: ###############################################
                   9453: sub get_users_function {
1.815     tempelho 9454:     my $function = 'norole';
1.818     tempelho 9455:     if ($env{'request.role'}=~/^(st)/) {
                   9456:         $function='student';
                   9457:     }
1.907     raeburn  9458:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9459:         $function='coordinator';
                   9460:     }
1.258     albertel 9461:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9462:         $function='admin';
                   9463:     }
1.826     bisitz   9464:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9465:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9466:         $function='author';
                   9467:     }
                   9468:     return $function;
1.54      www      9469: }
1.99      www      9470: 
                   9471: ###############################################
                   9472: 
1.233     raeburn  9473: =pod
                   9474: 
1.821     raeburn  9475: =item * &show_course()
                   9476: 
                   9477: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9478: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9479: 
                   9480: Inputs:
                   9481: None
                   9482: 
                   9483: Outputs:
                   9484: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9485: 
                   9486: =cut
                   9487: 
                   9488: ###############################################
                   9489: sub show_course {
                   9490:     my $course = !$env{'user.adv'};
                   9491:     if (!$env{'user.adv'}) {
                   9492:         foreach my $env (keys(%env)) {
                   9493:             next if ($env !~ m/^user\.priv\./);
                   9494:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9495:                 $course = 0;
                   9496:                 last;
                   9497:             }
                   9498:         }
                   9499:     }
                   9500:     return $course;
                   9501: }
                   9502: 
                   9503: ###############################################
                   9504: 
                   9505: =pod
                   9506: 
1.542     raeburn  9507: =item * &check_user_status()
1.274     raeburn  9508: 
                   9509: Determines current status of supplied role for a
                   9510: specific user. Roles can be active, previous or future.
                   9511: 
                   9512: Inputs: 
                   9513: user's domain, user's username, course's domain,
1.375     raeburn  9514: course's number, optional section ID.
1.274     raeburn  9515: 
                   9516: Outputs:
                   9517: role status: active, previous or future. 
                   9518: 
                   9519: =cut
                   9520: 
                   9521: sub check_user_status {
1.412     raeburn  9522:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9523:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9524:     my @uroles = keys(%userinfo);
1.274     raeburn  9525:     my $srchstr;
                   9526:     my $active_chk = 'none';
1.412     raeburn  9527:     my $now = time;
1.274     raeburn  9528:     if (@uroles > 0) {
1.908     raeburn  9529:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9530:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9531:         } else {
1.412     raeburn  9532:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9533:         }
                   9534:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9535:             my $role_end = 0;
                   9536:             my $role_start = 0;
                   9537:             $active_chk = 'active';
1.412     raeburn  9538:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9539:                 $role_end = $1;
                   9540:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9541:                     $role_start = $1;
1.274     raeburn  9542:                 }
                   9543:             }
                   9544:             if ($role_start > 0) {
1.412     raeburn  9545:                 if ($now < $role_start) {
1.274     raeburn  9546:                     $active_chk = 'future';
                   9547:                 }
                   9548:             }
                   9549:             if ($role_end > 0) {
1.412     raeburn  9550:                 if ($now > $role_end) {
1.274     raeburn  9551:                     $active_chk = 'previous';
                   9552:                 }
                   9553:             }
                   9554:         }
                   9555:     }
                   9556:     return $active_chk;
                   9557: }
                   9558: 
                   9559: ###############################################
                   9560: 
                   9561: =pod
                   9562: 
1.405     albertel 9563: =item * &get_sections()
1.233     raeburn  9564: 
                   9565: Determines all the sections for a course including
                   9566: sections with students and sections containing other roles.
1.419     raeburn  9567: Incoming parameters: 
                   9568: 
                   9569: 1. domain
                   9570: 2. course number 
                   9571: 3. reference to array containing roles for which sections should 
                   9572: be gathered (optional).
                   9573: 4. reference to array containing status types for which sections 
                   9574: should be gathered (optional).
                   9575: 
                   9576: If the third argument is undefined, sections are gathered for any role. 
                   9577: If the fourth argument is undefined, sections are gathered for any status.
                   9578: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9579:  
1.374     raeburn  9580: Returns section hash (keys are section IDs, values are
                   9581: number of users in each section), subject to the
1.419     raeburn  9582: optional roles filter, optional status filter 
1.233     raeburn  9583: 
                   9584: =cut
                   9585: 
                   9586: ###############################################
                   9587: sub get_sections {
1.419     raeburn  9588:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9589:     if (!defined($cdom) || !defined($cnum)) {
                   9590:         my $cid =  $env{'request.course.id'};
                   9591: 
                   9592: 	return if (!defined($cid));
                   9593: 
                   9594:         $cdom = $env{'course.'.$cid.'.domain'};
                   9595:         $cnum = $env{'course.'.$cid.'.num'};
                   9596:     }
                   9597: 
                   9598:     my %sectioncount;
1.419     raeburn  9599:     my $now = time;
1.240     albertel 9600: 
1.1118    raeburn  9601:     my $check_students = 1;
                   9602:     my $only_students = 0;
                   9603:     if (ref($possible_roles) eq 'ARRAY') {
                   9604:         if (grep(/^st$/,@{$possible_roles})) {
                   9605:             if (@{$possible_roles} == 1) {
                   9606:                 $only_students = 1;
                   9607:             }
                   9608:         } else {
                   9609:             $check_students = 0;
                   9610:         }
                   9611:     }
                   9612: 
                   9613:     if ($check_students) { 
1.276     albertel 9614: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9615: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9616: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9617:         my $start_index = &Apache::loncoursedata::CL_START();
                   9618:         my $end_index = &Apache::loncoursedata::CL_END();
                   9619:         my $status;
1.366     albertel 9620: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9621: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9622: 				                     $data->[$status_index],
                   9623:                                                      $data->[$start_index],
                   9624:                                                      $data->[$end_index]);
                   9625:             if ($stu_status eq 'Active') {
                   9626:                 $status = 'active';
                   9627:             } elsif ($end < $now) {
                   9628:                 $status = 'previous';
                   9629:             } elsif ($start > $now) {
                   9630:                 $status = 'future';
                   9631:             } 
                   9632: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9633:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9634:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9635: 		    $sectioncount{$section}++;
                   9636:                 }
1.240     albertel 9637: 	    }
                   9638: 	}
                   9639:     }
1.1118    raeburn  9640:     if ($only_students) {
                   9641:         return %sectioncount;
                   9642:     }
1.240     albertel 9643:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9644:     foreach my $user (sort(keys(%courseroles))) {
                   9645: 	if ($user !~ /^(\w{2})/) { next; }
                   9646: 	my ($role) = ($user =~ /^(\w{2})/);
                   9647: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9648: 	my ($section,$status);
1.240     albertel 9649: 	if ($role eq 'cr' &&
                   9650: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9651: 	    $section=$1;
                   9652: 	}
                   9653: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9654: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9655:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9656:         if ($end == -1 && $start == -1) {
                   9657:             next; #deleted role
                   9658:         }
                   9659:         if (!defined($possible_status)) { 
                   9660:             $sectioncount{$section}++;
                   9661:         } else {
                   9662:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9663:                 $status = 'active';
                   9664:             } elsif ($end < $now) {
                   9665:                 $status = 'future';
                   9666:             } elsif ($start > $now) {
                   9667:                 $status = 'previous';
                   9668:             }
                   9669:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9670:                 $sectioncount{$section}++;
                   9671:             }
                   9672:         }
1.233     raeburn  9673:     }
1.366     albertel 9674:     return %sectioncount;
1.233     raeburn  9675: }
                   9676: 
1.274     raeburn  9677: ###############################################
1.294     raeburn  9678: 
                   9679: =pod
1.405     albertel 9680: 
                   9681: =item * &get_course_users()
                   9682: 
1.275     raeburn  9683: Retrieves usernames:domains for users in the specified course
                   9684: with specific role(s), and access status. 
                   9685: 
                   9686: Incoming parameters:
1.277     albertel 9687: 1. course domain
                   9688: 2. course number
                   9689: 3. access status: users must have - either active, 
1.275     raeburn  9690: previous, future, or all.
1.277     albertel 9691: 4. reference to array of permissible roles
1.288     raeburn  9692: 5. reference to array of section restrictions (optional)
                   9693: 6. reference to results object (hash of hashes).
                   9694: 7. reference to optional userdata hash
1.609     raeburn  9695: 8. reference to optional statushash
1.630     raeburn  9696: 9. flag if privileged users (except those set to unhide in
                   9697:    course settings) should be excluded    
1.609     raeburn  9698: Keys of top level results hash are roles.
1.275     raeburn  9699: Keys of inner hashes are username:domain, with 
                   9700: values set to access type.
1.288     raeburn  9701: Optional userdata hash returns an array with arguments in the 
                   9702: same order as loncoursedata::get_classlist() for student data.
                   9703: 
1.609     raeburn  9704: Optional statushash returns
                   9705: 
1.288     raeburn  9706: Entries for end, start, section and status are blank because
                   9707: of the possibility of multiple values for non-student roles.
                   9708: 
1.275     raeburn  9709: =cut
1.405     albertel 9710: 
1.275     raeburn  9711: ###############################################
1.405     albertel 9712: 
1.275     raeburn  9713: sub get_course_users {
1.630     raeburn  9714:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9715:     my %idx = ();
1.419     raeburn  9716:     my %seclists;
1.288     raeburn  9717: 
                   9718:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9719:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9720:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9721:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9722:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9723:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9724:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9725:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9726: 
1.290     albertel 9727:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9728:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9729:         my $now = time;
1.277     albertel 9730:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9731:             my $match = 0;
1.412     raeburn  9732:             my $secmatch = 0;
1.419     raeburn  9733:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9734:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9735:             if ($section eq '') {
                   9736:                 $section = 'none';
                   9737:             }
1.291     albertel 9738:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9739:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9740:                     $secmatch = 1;
                   9741:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9742:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9743:                         $secmatch = 1;
                   9744:                     }
                   9745:                 } else {  
1.419     raeburn  9746: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9747: 		        $secmatch = 1;
                   9748:                     }
1.290     albertel 9749: 		}
1.412     raeburn  9750:                 if (!$secmatch) {
                   9751:                     next;
                   9752:                 }
1.419     raeburn  9753:             }
1.275     raeburn  9754:             if (defined($$types{'active'})) {
1.288     raeburn  9755:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9756:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9757:                     $match = 1;
1.275     raeburn  9758:                 }
                   9759:             }
                   9760:             if (defined($$types{'previous'})) {
1.609     raeburn  9761:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9762:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9763:                     $match = 1;
1.275     raeburn  9764:                 }
                   9765:             }
                   9766:             if (defined($$types{'future'})) {
1.609     raeburn  9767:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9768:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9769:                     $match = 1;
1.275     raeburn  9770:                 }
                   9771:             }
1.609     raeburn  9772:             if ($match) {
                   9773:                 push(@{$seclists{$student}},$section);
                   9774:                 if (ref($userdata) eq 'HASH') {
                   9775:                     $$userdata{$student} = $$classlist{$student};
                   9776:                 }
                   9777:                 if (ref($statushash) eq 'HASH') {
                   9778:                     $statushash->{$student}{'st'}{$section} = $status;
                   9779:                 }
1.288     raeburn  9780:             }
1.275     raeburn  9781:         }
                   9782:     }
1.412     raeburn  9783:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9784:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9785:         my $now = time;
1.609     raeburn  9786:         my %displaystatus = ( previous => 'Expired',
                   9787:                               active   => 'Active',
                   9788:                               future   => 'Future',
                   9789:                             );
1.1121    raeburn  9790:         my (%nothide,@possdoms);
1.630     raeburn  9791:         if ($hidepriv) {
                   9792:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9793:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9794:                 if ($user !~ /:/) {
                   9795:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9796:                 } else {
                   9797:                     $nothide{$user} = 1;
                   9798:                 }
                   9799:             }
1.1121    raeburn  9800:             my @possdoms = ($cdom);
                   9801:             if ($coursehash{'checkforpriv'}) {
                   9802:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9803:             }
1.630     raeburn  9804:         }
1.439     raeburn  9805:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9806:             my $match = 0;
1.412     raeburn  9807:             my $secmatch = 0;
1.439     raeburn  9808:             my $status;
1.412     raeburn  9809:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9810:             $user =~ s/:$//;
1.439     raeburn  9811:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9812:             if ($end == -1 || $start == -1) {
                   9813:                 next;
                   9814:             }
                   9815:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9816:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9817:                 my ($uname,$udom) = split(/:/,$user);
                   9818:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9819:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9820:                         $secmatch = 1;
                   9821:                     } elsif ($usec eq '') {
1.420     albertel 9822:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9823:                             $secmatch = 1;
                   9824:                         }
                   9825:                     } else {
                   9826:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9827:                             $secmatch = 1;
                   9828:                         }
                   9829:                     }
                   9830:                     if (!$secmatch) {
                   9831:                         next;
                   9832:                     }
1.288     raeburn  9833:                 }
1.419     raeburn  9834:                 if ($usec eq '') {
                   9835:                     $usec = 'none';
                   9836:                 }
1.275     raeburn  9837:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9838:                     if ($hidepriv) {
1.1121    raeburn  9839:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9840:                             (!$nothide{$uname.':'.$udom})) {
                   9841:                             next;
                   9842:                         }
                   9843:                     }
1.503     raeburn  9844:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9845:                         $status = 'previous';
                   9846:                     } elsif ($start > $now) {
                   9847:                         $status = 'future';
                   9848:                     } else {
                   9849:                         $status = 'active';
                   9850:                     }
1.277     albertel 9851:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9852:                         if ($status eq $type) {
1.420     albertel 9853:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9854:                                 push(@{$$users{$role}{$user}},$type);
                   9855:                             }
1.288     raeburn  9856:                             $match = 1;
                   9857:                         }
                   9858:                     }
1.419     raeburn  9859:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9860:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9861: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9862:                         }
1.420     albertel 9863:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9864:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9865:                         }
1.609     raeburn  9866:                         if (ref($statushash) eq 'HASH') {
                   9867:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9868:                         }
1.275     raeburn  9869:                     }
                   9870:                 }
                   9871:             }
                   9872:         }
1.290     albertel 9873:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9874:             if ((defined($cdom)) && (defined($cnum))) {
                   9875:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9876:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9877:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9878:                     next if ($owner eq '');
                   9879:                     my ($ownername,$ownerdom);
                   9880:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9881:                         $ownername = $1;
                   9882:                         $ownerdom = $2;
                   9883:                     } else {
                   9884:                         $ownername = $owner;
                   9885:                         $ownerdom = $cdom;
                   9886:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9887:                     }
                   9888:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9889:                     if (defined($userdata) && 
1.609     raeburn  9890: 			!exists($$userdata{$owner})) {
                   9891: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9892:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9893:                             push(@{$seclists{$owner}},'none');
                   9894:                         }
                   9895:                         if (ref($statushash) eq 'HASH') {
                   9896:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9897:                         }
1.290     albertel 9898: 		    }
1.279     raeburn  9899:                 }
                   9900:             }
                   9901:         }
1.419     raeburn  9902:         foreach my $user (keys(%seclists)) {
                   9903:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9904:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9905:         }
1.275     raeburn  9906:     }
                   9907:     return;
                   9908: }
                   9909: 
1.288     raeburn  9910: sub get_user_info {
                   9911:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9912:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9913: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9914:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9915:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9916:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9917:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9918:     return;
                   9919: }
1.275     raeburn  9920: 
1.472     raeburn  9921: ###############################################
                   9922: 
                   9923: =pod
                   9924: 
                   9925: =item * &get_user_quota()
                   9926: 
1.1134    raeburn  9927: Retrieves quota assigned for storage of user files.
                   9928: Default is to report quota for portfolio files.
1.472     raeburn  9929: 
                   9930: Incoming parameters:
                   9931: 1. user's username
                   9932: 2. user's domain
1.1134    raeburn  9933: 3. quota name - portfolio, author, or course
1.1136    raeburn  9934:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9935: 4. crstype - official, unofficial, textbook, placement or community, 
                   9936:    if quota name is course
1.472     raeburn  9937: 
                   9938: Returns:
1.1163    raeburn  9939: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9940: 2. (Optional) Type of setting: custom or default
                   9941:    (individually assigned or default for user's 
                   9942:    institutional status).
                   9943: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9944:    or student - types as defined in localenroll::inst_usertypes 
                   9945:    for user's domain, which determines default quota for user.
                   9946: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9947: 
                   9948: If a value has been stored in the user's environment, 
1.536     raeburn  9949: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9950: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9951: 
                   9952: =cut
                   9953: 
                   9954: ###############################################
                   9955: 
                   9956: 
                   9957: sub get_user_quota {
1.1136    raeburn  9958:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9959:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9960:     if (!defined($udom)) {
                   9961:         $udom = $env{'user.domain'};
                   9962:     }
                   9963:     if (!defined($uname)) {
                   9964:         $uname = $env{'user.name'};
                   9965:     }
                   9966:     if (($udom eq '' || $uname eq '') ||
                   9967:         ($udom eq 'public') && ($uname eq 'public')) {
                   9968:         $quota = 0;
1.536     raeburn  9969:         $quotatype = 'default';
                   9970:         $defquota = 0; 
1.472     raeburn  9971:     } else {
1.536     raeburn  9972:         my $inststatus;
1.1134    raeburn  9973:         if ($quotaname eq 'course') {
                   9974:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9975:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9976:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9977:             } else {
                   9978:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9979:                 $quota = $cenv{'internal.uploadquota'};
                   9980:             }
1.536     raeburn  9981:         } else {
1.1134    raeburn  9982:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9983:                 if ($quotaname eq 'author') {
                   9984:                     $quota = $env{'environment.authorquota'};
                   9985:                 } else {
                   9986:                     $quota = $env{'environment.portfolioquota'};
                   9987:                 }
                   9988:                 $inststatus = $env{'environment.inststatus'};
                   9989:             } else {
                   9990:                 my %userenv = 
                   9991:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9992:                                          'authorquota','inststatus'],$udom,$uname);
                   9993:                 my ($tmp) = keys(%userenv);
                   9994:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9995:                     if ($quotaname eq 'author') {
                   9996:                         $quota = $userenv{'authorquota'};
                   9997:                     } else {
                   9998:                         $quota = $userenv{'portfolioquota'};
                   9999:                     }
                   10000:                     $inststatus = $userenv{'inststatus'};
                   10001:                 } else {
                   10002:                     undef(%userenv);
                   10003:                 }
                   10004:             }
                   10005:         }
                   10006:         if ($quota eq '' || wantarray) {
                   10007:             if ($quotaname eq 'course') {
                   10008:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10009:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10010:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10011:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10012:                     $defquota = $domdefs{$crstype.'quota'};
                   10013:                 }
                   10014:                 if ($defquota eq '') {
                   10015:                     $defquota = 500;
                   10016:                 }
1.1134    raeburn  10017:             } else {
                   10018:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10019:             }
                   10020:             if ($quota eq '') {
                   10021:                 $quota = $defquota;
                   10022:                 $quotatype = 'default';
                   10023:             } else {
                   10024:                 $quotatype = 'custom';
                   10025:             }
1.472     raeburn  10026:         }
                   10027:     }
1.536     raeburn  10028:     if (wantarray) {
                   10029:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10030:     } else {
                   10031:         return $quota;
                   10032:     }
1.472     raeburn  10033: }
                   10034: 
                   10035: ###############################################
                   10036: 
                   10037: =pod
                   10038: 
                   10039: =item * &default_quota()
                   10040: 
1.536     raeburn  10041: Retrieves default quota assigned for storage of user portfolio files,
                   10042: given an (optional) user's institutional status.
1.472     raeburn  10043: 
                   10044: Incoming parameters:
1.1142    raeburn  10045: 
1.472     raeburn  10046: 1. domain
1.536     raeburn  10047: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10048:    status types (e.g., faculty, staff, student etc.)
                   10049:    which apply to the user for whom the default is being retrieved.
                   10050:    If the institutional status string in undefined, the domain
1.1134    raeburn  10051:    default quota will be returned.
                   10052: 3.  quota name - portfolio, author, or course
                   10053:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10054: 
                   10055: Returns:
1.1142    raeburn  10056: 
1.1163    raeburn  10057: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10058: 2. (Optional) institutional type which determined the value of the
                   10059:    default quota.
1.472     raeburn  10060: 
                   10061: If a value has been stored in the domain's configuration db,
                   10062: it will return that, otherwise it returns 20 (for backwards 
                   10063: compatibility with domains which have not set up a configuration
1.1163    raeburn  10064: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10065: 
1.536     raeburn  10066: If the user's status includes multiple types (e.g., staff and student),
                   10067: the largest default quota which applies to the user determines the
                   10068: default quota returned.
                   10069: 
1.472     raeburn  10070: =cut
                   10071: 
                   10072: ###############################################
                   10073: 
                   10074: 
                   10075: sub default_quota {
1.1134    raeburn  10076:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10077:     my ($defquota,$settingstatus);
                   10078:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10079:                                             ['quotas'],$udom);
1.1134    raeburn  10080:     my $key = 'defaultquota';
                   10081:     if ($quotaname eq 'author') {
                   10082:         $key = 'authorquota';
                   10083:     }
1.622     raeburn  10084:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10085:         if ($inststatus ne '') {
1.765     raeburn  10086:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10087:             foreach my $item (@statuses) {
1.1134    raeburn  10088:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10089:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10090:                         if ($defquota eq '') {
1.1134    raeburn  10091:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10092:                             $settingstatus = $item;
1.1134    raeburn  10093:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10094:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10095:                             $settingstatus = $item;
                   10096:                         }
                   10097:                     }
1.1134    raeburn  10098:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10099:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10100:                         if ($defquota eq '') {
                   10101:                             $defquota = $quotahash{'quotas'}{$item};
                   10102:                             $settingstatus = $item;
                   10103:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10104:                             $defquota = $quotahash{'quotas'}{$item};
                   10105:                             $settingstatus = $item;
                   10106:                         }
1.536     raeburn  10107:                     }
                   10108:                 }
                   10109:             }
                   10110:         }
                   10111:         if ($defquota eq '') {
1.1134    raeburn  10112:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10113:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10114:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10115:                 $defquota = $quotahash{'quotas'}{'default'};
                   10116:             }
1.536     raeburn  10117:             $settingstatus = 'default';
1.1139    raeburn  10118:             if ($defquota eq '') {
                   10119:                 if ($quotaname eq 'author') {
                   10120:                     $defquota = 500;
                   10121:                 }
                   10122:             }
1.536     raeburn  10123:         }
                   10124:     } else {
                   10125:         $settingstatus = 'default';
1.1134    raeburn  10126:         if ($quotaname eq 'author') {
                   10127:             $defquota = 500;
                   10128:         } else {
                   10129:             $defquota = 20;
                   10130:         }
1.536     raeburn  10131:     }
                   10132:     if (wantarray) {
                   10133:         return ($defquota,$settingstatus);
1.472     raeburn  10134:     } else {
1.536     raeburn  10135:         return $defquota;
1.472     raeburn  10136:     }
                   10137: }
                   10138: 
1.1135    raeburn  10139: ###############################################
                   10140: 
                   10141: =pod
                   10142: 
1.1136    raeburn  10143: =item * &excess_filesize_warning()
1.1135    raeburn  10144: 
                   10145: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10146: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10147: space to be exceeded.
1.1136    raeburn  10148: 
                   10149: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10150: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10151: 
1.1165    raeburn  10152: Inputs: 7 
1.1136    raeburn  10153: 1. username or coursenum
1.1135    raeburn  10154: 2. domain
1.1136    raeburn  10155: 3. context ('author' or 'course')
1.1135    raeburn  10156: 4. filename of file for which action is being requested
                   10157: 5. filesize (kB) of file
                   10158: 6. action being taken: copy or upload.
1.1237    raeburn  10159: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10160: 
                   10161: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10162:          otherwise return null.
                   10163: 
                   10164: =back
1.1135    raeburn  10165: 
                   10166: =cut
                   10167: 
1.1136    raeburn  10168: sub excess_filesize_warning {
1.1165    raeburn  10169:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10170:     my $current_disk_usage = 0;
1.1165    raeburn  10171:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10172:     if ($context eq 'author') {
                   10173:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10174:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10175:     } else {
                   10176:         foreach my $subdir ('docs','supplemental') {
                   10177:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10178:         }
                   10179:     }
1.1135    raeburn  10180:     $disk_quota = int($disk_quota * 1000);
                   10181:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10182:         return '<p class="LC_warning">'.
1.1135    raeburn  10183:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10184:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10185:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10186:                             $disk_quota,$current_disk_usage).
                   10187:                '</p>';
                   10188:     }
                   10189:     return;
                   10190: }
                   10191: 
                   10192: ###############################################
                   10193: 
                   10194: 
1.1136    raeburn  10195: 
                   10196: 
1.384     raeburn  10197: sub get_secgrprole_info {
                   10198:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10199:     my %sections_count = &get_sections($cdom,$cnum);
                   10200:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10201:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10202:     my @groups = sort(keys(%curr_groups));
                   10203:     my $allroles = [];
                   10204:     my $rolehash;
                   10205:     my $accesshash = {
                   10206:                      active => 'Currently has access',
                   10207:                      future => 'Will have future access',
                   10208:                      previous => 'Previously had access',
                   10209:                   };
                   10210:     if ($needroles) {
                   10211:         $rolehash = {'all' => 'all'};
1.385     albertel 10212:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10213: 	if (&Apache::lonnet::error(%user_roles)) {
                   10214: 	    undef(%user_roles);
                   10215: 	}
                   10216:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10217:             my ($role)=split(/\:/,$item,2);
                   10218:             if ($role eq 'cr') { next; }
                   10219:             if ($role =~ /^cr/) {
                   10220:                 $$rolehash{$role} = (split('/',$role))[3];
                   10221:             } else {
                   10222:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10223:             }
                   10224:         }
                   10225:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10226:             push(@{$allroles},$key);
                   10227:         }
                   10228:         push (@{$allroles},'st');
                   10229:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10230:     }
                   10231:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10232: }
                   10233: 
1.555     raeburn  10234: sub user_picker {
1.1279    raeburn  10235:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10236:     my $currdom = $dom;
1.1253    raeburn  10237:     my @alldoms = &Apache::lonnet::all_domains();
                   10238:     if (@alldoms == 1) {
                   10239:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10240:                                                ['directorysrch'],$alldoms[0]);
                   10241:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10242:         my $showdom = $domdesc;
                   10243:         if ($showdom eq '') {
                   10244:             $showdom = $dom;
                   10245:         }
                   10246:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10247:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10248:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10249:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10250:             }
                   10251:         }
                   10252:     }
1.555     raeburn  10253:     my %curr_selected = (
                   10254:                         srchin => 'dom',
1.580     raeburn  10255:                         srchby => 'lastname',
1.555     raeburn  10256:                       );
                   10257:     my $srchterm;
1.625     raeburn  10258:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10259:         if ($srch->{'srchby'} ne '') {
                   10260:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10261:         }
                   10262:         if ($srch->{'srchin'} ne '') {
                   10263:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10264:         }
                   10265:         if ($srch->{'srchtype'} ne '') {
                   10266:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10267:         }
                   10268:         if ($srch->{'srchdomain'} ne '') {
                   10269:             $currdom = $srch->{'srchdomain'};
                   10270:         }
                   10271:         $srchterm = $srch->{'srchterm'};
                   10272:     }
1.1222    damieng  10273:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10274:                     'usr'       => 'Search criteria',
1.563     raeburn  10275:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10276:                     'uname'     => 'username',
                   10277:                     'lastname'  => 'last name',
1.555     raeburn  10278:                     'lastfirst' => 'last name, first name',
1.558     albertel 10279:                     'crs'       => 'in this course',
1.576     raeburn  10280:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10281:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10282:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10283:                     'exact'     => 'is',
                   10284:                     'contains'  => 'contains',
1.569     raeburn  10285:                     'begins'    => 'begins with',
1.1222    damieng  10286:                                        );
                   10287:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10288:                     'youm'      => "You must include some text to search for.",
                   10289:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10290:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10291:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10292:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10293:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10294:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10295:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10296:                                        );
1.1222    damieng  10297:     &html_escape(\%html_lt);
                   10298:     &js_escape(\%js_lt);
1.1255    raeburn  10299:     my $domform;
1.1277    raeburn  10300:     my $allow_blank = 1;
1.1255    raeburn  10301:     if ($fixeddom) {
1.1277    raeburn  10302:         $allow_blank = 0;
                   10303:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10304:     } else {
1.1287    raeburn  10305:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10306:         my ($trusted,$untrusted);
1.1287    raeburn  10307:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10308:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10309:         } elsif ($context eq 'author') {
1.1288    raeburn  10310:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10311:         } elsif ($context eq 'domain') {
1.1288    raeburn  10312:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10313:         }
1.1288    raeburn  10314:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10315:     }
1.563     raeburn  10316:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10317: 
                   10318:     my @srchins = ('crs','dom','alc','instd');
                   10319: 
                   10320:     foreach my $option (@srchins) {
                   10321:         # FIXME 'alc' option unavailable until 
                   10322:         #       loncreateuser::print_user_query_page()
                   10323:         #       has been completed.
                   10324:         next if ($option eq 'alc');
1.880     raeburn  10325:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10326:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10327:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10328:         if ($curr_selected{'srchin'} eq $option) {
                   10329:             $srchinsel .= ' 
1.1222    damieng  10330:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10331:         } else {
                   10332:             $srchinsel .= '
1.1222    damieng  10333:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10334:         }
1.555     raeburn  10335:     }
1.563     raeburn  10336:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10337: 
                   10338:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10339:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10340:         if ($curr_selected{'srchby'} eq $option) {
                   10341:             $srchbysel .= '
1.1222    damieng  10342:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10343:         } else {
                   10344:             $srchbysel .= '
1.1222    damieng  10345:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10346:          }
                   10347:     }
                   10348:     $srchbysel .= "\n  </select>\n";
                   10349: 
                   10350:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10351:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10352:         if ($curr_selected{'srchtype'} eq $option) {
                   10353:             $srchtypesel .= '
1.1222    damieng  10354:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10355:         } else {
                   10356:             $srchtypesel .= '
1.1222    damieng  10357:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10358:         }
                   10359:     }
                   10360:     $srchtypesel .= "\n  </select>\n";
                   10361: 
1.558     albertel 10362:     my ($newuserscript,$new_user_create);
1.994     raeburn  10363:     my $context_dom = $env{'request.role.domain'};
                   10364:     if ($context eq 'requestcrs') {
                   10365:         if ($env{'form.coursedom'} ne '') { 
                   10366:             $context_dom = $env{'form.coursedom'};
                   10367:         }
                   10368:     }
1.556     raeburn  10369:     if ($forcenewuser) {
1.576     raeburn  10370:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10371:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10372:                 if ($cancreate) {
                   10373:                     $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>';
                   10374:                 } else {
1.799     bisitz   10375:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10376:                     my %usertypetext = (
                   10377:                         official   => 'institutional',
                   10378:                         unofficial => 'non-institutional',
                   10379:                     );
1.799     bisitz   10380:                     $new_user_create = '<p class="LC_warning">'
                   10381:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10382:                                       .' '
                   10383:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10384:                                           ,'<a href="'.$helplink.'">','</a>')
                   10385:                                       .'</p><br />';
1.627     raeburn  10386:                 }
1.576     raeburn  10387:             }
                   10388:         }
                   10389: 
1.556     raeburn  10390:         $newuserscript = <<"ENDSCRIPT";
                   10391: 
1.570     raeburn  10392: function setSearch(createnew,callingForm) {
1.556     raeburn  10393:     if (createnew == 1) {
1.570     raeburn  10394:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10395:             if (callingForm.srchby.options[i].value == 'uname') {
                   10396:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10397:             }
                   10398:         }
1.570     raeburn  10399:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10400:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10401: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10402:             }
                   10403:         }
1.570     raeburn  10404:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10405:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10406:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10407:             }
                   10408:         }
1.570     raeburn  10409:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10410:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10411:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10412:             }
                   10413:         }
                   10414:     }
                   10415: }
                   10416: ENDSCRIPT
1.558     albertel 10417: 
1.556     raeburn  10418:     }
                   10419: 
1.555     raeburn  10420:     my $output = <<"END_BLOCK";
1.556     raeburn  10421: <script type="text/javascript">
1.824     bisitz   10422: // <![CDATA[
1.570     raeburn  10423: function validateEntry(callingForm) {
1.558     albertel 10424: 
1.556     raeburn  10425:     var checkok = 1;
1.558     albertel 10426:     var srchin;
1.570     raeburn  10427:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10428: 	if ( callingForm.srchin[i].checked ) {
                   10429: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10430: 	}
                   10431:     }
                   10432: 
1.570     raeburn  10433:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10434:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10435:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10436:     var srchterm =  callingForm.srchterm.value;
                   10437:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10438:     var msg = "";
                   10439: 
                   10440:     if (srchterm == "") {
                   10441:         checkok = 0;
1.1222    damieng  10442:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10443:     }
                   10444: 
1.569     raeburn  10445:     if (srchtype== 'begins') {
                   10446:         if (srchterm.length < 2) {
                   10447:             checkok = 0;
1.1222    damieng  10448:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10449:         }
                   10450:     }
                   10451: 
1.556     raeburn  10452:     if (srchtype== 'contains') {
                   10453:         if (srchterm.length < 3) {
                   10454:             checkok = 0;
1.1222    damieng  10455:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10456:         }
                   10457:     }
                   10458:     if (srchin == 'instd') {
                   10459:         if (srchdomain == '') {
                   10460:             checkok = 0;
1.1222    damieng  10461:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10462:         }
                   10463:     }
                   10464:     if (srchin == 'dom') {
                   10465:         if (srchdomain == '') {
                   10466:             checkok = 0;
1.1222    damieng  10467:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10468:         }
                   10469:     }
                   10470:     if (srchby == 'lastfirst') {
                   10471:         if (srchterm.indexOf(",") == -1) {
                   10472:             checkok = 0;
1.1222    damieng  10473:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10474:         }
                   10475:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10476:             checkok = 0;
1.1222    damieng  10477:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10478:         }
                   10479:     }
                   10480:     if (checkok == 0) {
1.1222    damieng  10481:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10482:         return;
                   10483:     }
                   10484:     if (checkok == 1) {
1.570     raeburn  10485:         callingForm.submit();
1.556     raeburn  10486:     }
                   10487: }
                   10488: 
                   10489: $newuserscript
                   10490: 
1.824     bisitz   10491: // ]]>
1.556     raeburn  10492: </script>
1.558     albertel 10493: 
                   10494: $new_user_create
                   10495: 
1.555     raeburn  10496: END_BLOCK
1.558     albertel 10497: 
1.876     raeburn  10498:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10499:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10500:                $domform.
                   10501:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10502:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10503:                $srchbysel.
                   10504:                $srchtypesel. 
                   10505:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10506:                $srchinsel.
                   10507:                &Apache::lonhtmlcommon::row_closure(1). 
                   10508:                &Apache::lonhtmlcommon::end_pick_box().
                   10509:                '<br />';
1.1253    raeburn  10510:     return ($output,1);
1.555     raeburn  10511: }
                   10512: 
1.612     raeburn  10513: sub user_rule_check {
1.615     raeburn  10514:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10515:     my ($response,%inst_response);
1.612     raeburn  10516:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10517:         if (keys(%{$usershash}) > 1) {
                   10518:             my (%by_username,%by_id,%userdoms);
                   10519:             my $checkid; 
                   10520:             if (ref($checks) eq 'HASH') {
                   10521:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10522:                     $checkid = 1;
                   10523:                 }
                   10524:             }
                   10525:             foreach my $user (keys(%{$usershash})) {
                   10526:                 my ($uname,$udom) = split(/:/,$user);
                   10527:                 if ($checkid) {
                   10528:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10529:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10530:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10531:                             $userdoms{$udom} = 1;
1.1227    raeburn  10532:                             if (ref($inst_results) eq 'HASH') {
                   10533:                                 $inst_results->{$uname.':'.$udom} = {};
                   10534:                             }
1.1226    raeburn  10535:                         }
                   10536:                     }
                   10537:                 } else {
                   10538:                     $by_username{$udom}{$uname} = 1;
                   10539:                     $userdoms{$udom} = 1;
1.1227    raeburn  10540:                     if (ref($inst_results) eq 'HASH') {
                   10541:                         $inst_results->{$uname.':'.$udom} = {};
                   10542:                     }
1.1226    raeburn  10543:                 }
                   10544:             }
                   10545:             foreach my $udom (keys(%userdoms)) {
                   10546:                 if (!$got_rules->{$udom}) {
                   10547:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10548:                                                              ['usercreation'],$udom);
                   10549:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10550:                         foreach my $item ('username','id') {
                   10551:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10552:                                 $$curr_rules{$udom}{$item} =
                   10553:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10554:                             }
                   10555:                         }
                   10556:                     }
                   10557:                     $got_rules->{$udom} = 1;
                   10558:                 }
1.612     raeburn  10559:             }
1.1226    raeburn  10560:             if ($checkid) {
                   10561:                 foreach my $udom (keys(%by_id)) {
                   10562:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10563:                     if ($outcome eq 'ok') {
1.1227    raeburn  10564:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10565:                             my $uname = $by_id{$udom}{$id};
                   10566:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10567:                         }
1.1226    raeburn  10568:                         if (ref($results) eq 'HASH') {
                   10569:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10570:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10571:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10572:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10573:                                 }
1.1226    raeburn  10574:                             }
                   10575:                         }
                   10576:                     }
1.612     raeburn  10577:                 }
1.615     raeburn  10578:             } else {
1.1226    raeburn  10579:                 foreach my $udom (keys(%by_username)) {
                   10580:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10581:                     if ($outcome eq 'ok') {
1.1227    raeburn  10582:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10583:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10584:                         }
1.1226    raeburn  10585:                         if (ref($results) eq 'HASH') {
                   10586:                             foreach my $uname (keys(%{$results})) {
                   10587:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10588:                             }
                   10589:                         }
                   10590:                     }
                   10591:                 }
1.612     raeburn  10592:             }
1.1226    raeburn  10593:         } elsif (keys(%{$usershash}) == 1) {
                   10594:             my $user = (keys(%{$usershash}))[0];
                   10595:             my ($uname,$udom) = split(/:/,$user);
                   10596:             if (($udom ne '') && ($uname ne '')) {
                   10597:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10598:                     if (ref($checks) eq 'HASH') {
                   10599:                         if (defined($checks->{'username'})) {
                   10600:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10601:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10602:                         } elsif (defined($checks->{'id'})) {
                   10603:                             if ($usershash->{$user}->{'id'} ne '') {
                   10604:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10605:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10606:                                                                   $usershash->{$user}->{'id'});
                   10607:                             } else {
                   10608:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10609:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10610:                             }
1.585     raeburn  10611:                         }
1.1226    raeburn  10612:                     } else {
                   10613:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10614:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10615:                        return;
                   10616:                     }
                   10617:                     if (!$got_rules->{$udom}) {
                   10618:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10619:                                                                  ['usercreation'],$udom);
                   10620:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10621:                             foreach my $item ('username','id') {
                   10622:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10623:                                    $$curr_rules{$udom}{$item} = 
                   10624:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10625:                                 }
                   10626:                             }
                   10627:                         }
                   10628:                         $got_rules->{$udom} = 1;
1.585     raeburn  10629:                     }
                   10630:                 }
1.1226    raeburn  10631:             } else {
                   10632:                 return;
                   10633:             }
                   10634:         } else {
                   10635:             return;
                   10636:         }
                   10637:         foreach my $user (keys(%{$usershash})) {
                   10638:             my ($uname,$udom) = split(/:/,$user);
                   10639:             next if (($udom eq '') || ($uname eq ''));
                   10640:             my $id;
1.1227    raeburn  10641:             if (ref($inst_results) eq 'HASH') {
                   10642:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10643:                     $id = $inst_results->{$user}->{'id'};
                   10644:                 }
                   10645:             }
                   10646:             if ($id eq '') { 
                   10647:                 if (ref($usershash->{$user})) {
                   10648:                     $id = $usershash->{$user}->{'id'};
                   10649:                 }
1.585     raeburn  10650:             }
1.612     raeburn  10651:             foreach my $item (keys(%{$checks})) {
                   10652:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10653:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10654:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10655:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10656:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10657:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10658:                                 if ($rule_check{$rule}) {
                   10659:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10660:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10661:                                         if (ref($inst_results) eq 'HASH') {
                   10662:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10663:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10664:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10665:                                                 } elsif ($item eq 'id') {
                   10666:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10667:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10668:                                                     }
1.615     raeburn  10669:                                                 }
1.612     raeburn  10670:                                             }
                   10671:                                         }
1.615     raeburn  10672:                                     }
                   10673:                                     last;
1.585     raeburn  10674:                                 }
                   10675:                             }
                   10676:                         }
                   10677:                     }
                   10678:                 }
                   10679:             }
                   10680:         }
                   10681:     }
1.612     raeburn  10682:     return;
                   10683: }
                   10684: 
                   10685: sub user_rule_formats {
                   10686:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10687:     my %text = ( 
                   10688:                  'username' => 'Usernames',
                   10689:                  'id'       => 'IDs',
                   10690:                );
                   10691:     my $output;
                   10692:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10693:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10694:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10695:             $output = '<br />'.
                   10696:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10697:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10698:                       ' <ul>';
1.612     raeburn  10699:             foreach my $rule (@{$ruleorder}) {
                   10700:                 if (ref($curr_rules) eq 'ARRAY') {
                   10701:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10702:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10703:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10704:                                         $rules->{$rule}{'desc'}.'</li>';
                   10705:                         }
                   10706:                     }
                   10707:                 }
                   10708:             }
                   10709:             $output .= '</ul>';
                   10710:         }
                   10711:     }
                   10712:     return $output;
                   10713: }
                   10714: 
                   10715: sub instrule_disallow_msg {
1.615     raeburn  10716:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10717:     my $response;
                   10718:     my %text = (
                   10719:                   item   => 'username',
                   10720:                   items  => 'usernames',
                   10721:                   match  => 'matches',
                   10722:                   do     => 'does',
                   10723:                   action => 'a username',
                   10724:                   one    => 'one',
                   10725:                );
                   10726:     if ($count > 1) {
                   10727:         $text{'item'} = 'usernames';
                   10728:         $text{'match'} ='match';
                   10729:         $text{'do'} = 'do';
                   10730:         $text{'action'} = 'usernames',
                   10731:         $text{'one'} = 'ones';
                   10732:     }
                   10733:     if ($checkitem eq 'id') {
                   10734:         $text{'items'} = 'IDs';
                   10735:         $text{'item'} = 'ID';
                   10736:         $text{'action'} = 'an ID';
1.615     raeburn  10737:         if ($count > 1) {
                   10738:             $text{'item'} = 'IDs';
                   10739:             $text{'action'} = 'IDs';
                   10740:         }
1.612     raeburn  10741:     }
1.674     bisitz   10742:     $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 />';
1.615     raeburn  10743:     if ($mode eq 'upload') {
                   10744:         if ($checkitem eq 'username') {
                   10745:             $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'}.");
                   10746:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10747:             $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.");
1.615     raeburn  10748:         }
1.669     raeburn  10749:     } elsif ($mode eq 'selfcreate') {
                   10750:         if ($checkitem eq 'id') {
                   10751:             $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.");
                   10752:         }
1.615     raeburn  10753:     } else {
                   10754:         if ($checkitem eq 'username') {
                   10755:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10756:         } elsif ($checkitem eq 'id') {
                   10757:             $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.");
                   10758:         }
1.612     raeburn  10759:     }
                   10760:     return $response;
1.585     raeburn  10761: }
                   10762: 
1.624     raeburn  10763: sub personal_data_fieldtitles {
                   10764:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10765:                         id => 'Student/Employee ID',
                   10766:                         permanentemail => 'E-mail address',
                   10767:                         lastname => 'Last Name',
                   10768:                         firstname => 'First Name',
                   10769:                         middlename => 'Middle Name',
                   10770:                         generation => 'Generation',
                   10771:                         gen => 'Generation',
1.765     raeburn  10772:                         inststatus => 'Affiliation',
1.624     raeburn  10773:                    );
                   10774:     return %fieldtitles;
                   10775: }
                   10776: 
1.642     raeburn  10777: sub sorted_inst_types {
                   10778:     my ($dom) = @_;
1.1185    raeburn  10779:     my ($usertypes,$order);
                   10780:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10781:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10782:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10783:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10784:     } else {
                   10785:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10786:     }
1.642     raeburn  10787:     my $othertitle = &mt('All users');
                   10788:     if ($env{'request.course.id'}) {
1.668     raeburn  10789:         $othertitle  = &mt('Any users');
1.642     raeburn  10790:     }
                   10791:     my @types;
                   10792:     if (ref($order) eq 'ARRAY') {
                   10793:         @types = @{$order};
                   10794:     }
                   10795:     if (@types == 0) {
                   10796:         if (ref($usertypes) eq 'HASH') {
                   10797:             @types = sort(keys(%{$usertypes}));
                   10798:         }
                   10799:     }
                   10800:     if (keys(%{$usertypes}) > 0) {
                   10801:         $othertitle = &mt('Other users');
                   10802:     }
                   10803:     return ($othertitle,$usertypes,\@types);
                   10804: }
                   10805: 
1.645     raeburn  10806: sub get_institutional_codes {
                   10807:     my ($settings,$allcourses,$LC_code) = @_;
                   10808: # Get complete list of course sections to update
                   10809:     my @currsections = ();
                   10810:     my @currxlists = ();
                   10811:     my $coursecode = $$settings{'internal.coursecode'};
                   10812: 
                   10813:     if ($$settings{'internal.sectionnums'} ne '') {
                   10814:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10815:     }
                   10816: 
                   10817:     if ($$settings{'internal.crosslistings'} ne '') {
                   10818:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10819:     }
                   10820: 
                   10821:     if (@currxlists > 0) {
                   10822:         foreach (@currxlists) {
                   10823:             if (m/^([^:]+):(\w*)$/) {
                   10824:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10825:                     push(@{$allcourses},$1);
1.645     raeburn  10826:                     $$LC_code{$1} = $2;
                   10827:                 }
                   10828:             }
                   10829:         }
                   10830:     }
                   10831:  
                   10832:     if (@currsections > 0) {
                   10833:         foreach (@currsections) {
                   10834:             if (m/^(\w+):(\w*)$/) {
                   10835:                 my $sec = $coursecode.$1;
                   10836:                 my $lc_sec = $2;
                   10837:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10838:                     push(@{$allcourses},$sec);
1.645     raeburn  10839:                     $$LC_code{$sec} = $lc_sec;
                   10840:                 }
                   10841:             }
                   10842:         }
                   10843:     }
                   10844:     return;
                   10845: }
                   10846: 
1.971     raeburn  10847: sub get_standard_codeitems {
                   10848:     return ('Year','Semester','Department','Number','Section');
                   10849: }
                   10850: 
1.112     bowersj2 10851: =pod
                   10852: 
1.780     raeburn  10853: =head1 Slot Helpers
                   10854: 
                   10855: =over 4
                   10856: 
                   10857: =item * sorted_slots()
                   10858: 
1.1040    raeburn  10859: Sorts an array of slot names in order of an optional sort key,
                   10860: default sort is by slot start time (earliest first). 
1.780     raeburn  10861: 
                   10862: Inputs:
                   10863: 
                   10864: =over 4
                   10865: 
                   10866: slotsarr  - Reference to array of unsorted slot names.
                   10867: 
                   10868: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10869: 
1.1040    raeburn  10870: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10871: 
1.549     albertel 10872: =back
                   10873: 
1.780     raeburn  10874: Returns:
                   10875: 
                   10876: =over 4
                   10877: 
1.1040    raeburn  10878: sorted   - An array of slot names sorted by a specified sort key 
                   10879:            (default sort key is start time of the slot).
1.780     raeburn  10880: 
                   10881: =back
                   10882: 
                   10883: =cut
                   10884: 
                   10885: 
                   10886: sub sorted_slots {
1.1040    raeburn  10887:     my ($slotsarr,$slots,$sortkey) = @_;
                   10888:     if ($sortkey eq '') {
                   10889:         $sortkey = 'starttime';
                   10890:     }
1.780     raeburn  10891:     my @sorted;
                   10892:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10893:         @sorted =
                   10894:             sort {
                   10895:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10896:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10897:                      }
                   10898:                      if (ref($slots->{$a})) { return -1;}
                   10899:                      if (ref($slots->{$b})) { return 1;}
                   10900:                      return 0;
                   10901:                  } @{$slotsarr};
                   10902:     }
                   10903:     return @sorted;
                   10904: }
                   10905: 
1.1040    raeburn  10906: =pod
                   10907: 
                   10908: =item * get_future_slots()
                   10909: 
                   10910: Inputs:
                   10911: 
                   10912: =over 4
                   10913: 
                   10914: cnum - course number
                   10915: 
                   10916: cdom - course domain
                   10917: 
                   10918: now - current UNIX time
                   10919: 
                   10920: symb - optional symb
                   10921: 
                   10922: =back
                   10923: 
                   10924: Returns:
                   10925: 
                   10926: =over 4
                   10927: 
                   10928: sorted_reservable - ref to array of student_schedulable slots currently 
                   10929:                     reservable, ordered by end date of reservation period.
                   10930: 
                   10931: reservable_now - ref to hash of student_schedulable slots currently
                   10932:                  reservable.
                   10933: 
                   10934:     Keys in inner hash are:
                   10935:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10936:     (b) endreserve: end date of reservation period.
                   10937:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10938:         selected.
1.1040    raeburn  10939: 
                   10940: sorted_future - ref to array of student_schedulable slots reservable in
                   10941:                 the future, ordered by start date of reservation period.
                   10942: 
                   10943: future_reservable - ref to hash of student_schedulable slots reservable
                   10944:                     in the future.
                   10945: 
                   10946:     Keys in inner hash are:
                   10947:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10948:     (b) startreserve: start date of reservation period.
                   10949:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10950:         selected.
1.1040    raeburn  10951: 
                   10952: =back
                   10953: 
                   10954: =cut
                   10955: 
                   10956: sub get_future_slots {
                   10957:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10958:     my $map;
                   10959:     if ($symb) {
                   10960:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10961:     }
1.1040    raeburn  10962:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10963:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10964:     foreach my $slot (keys(%slots)) {
                   10965:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10966:         if ($symb) {
1.1229    raeburn  10967:             if ($slots{$slot}->{'symb'} ne '') {
                   10968:                 my $canuse;
                   10969:                 my %oksymbs;
                   10970:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10971:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10972:                 if ($oksymbs{$symb}) {
                   10973:                     $canuse = 1;
                   10974:                 } else {
                   10975:                     foreach my $item (@slotsymbs) {
                   10976:                         if ($item =~ /\.(page|sequence)$/) {
                   10977:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10978:                             if (($map ne '') && ($map eq $sloturl)) {
                   10979:                                 $canuse = 1;
                   10980:                                 last;
                   10981:                             }
                   10982:                         }
                   10983:                     }
                   10984:                 }
                   10985:                 next unless ($canuse);
                   10986:             }
1.1040    raeburn  10987:         }
                   10988:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10989:             ($slots{$slot}->{'endtime'} > $now)) {
                   10990:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10991:                 my $userallowed = 0;
                   10992:                 if ($slots{$slot}->{'allowedsections'}) {
                   10993:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10994:                     if (!defined($env{'request.role.sec'})
                   10995:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10996:                         $userallowed=1;
                   10997:                     } else {
                   10998:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10999:                             $userallowed=1;
                   11000:                         }
                   11001:                     }
                   11002:                     unless ($userallowed) {
                   11003:                         if (defined($env{'request.course.groups'})) {
                   11004:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11005:                             foreach my $group (@groups) {
                   11006:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11007:                                     $userallowed=1;
                   11008:                                     last;
                   11009:                                 }
                   11010:                             }
                   11011:                         }
                   11012:                     }
                   11013:                 }
                   11014:                 if ($slots{$slot}->{'allowedusers'}) {
                   11015:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11016:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11017:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11018:                         $userallowed = 1;
                   11019:                     }
                   11020:                 }
                   11021:                 next unless($userallowed);
                   11022:             }
                   11023:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11024:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11025:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11026:             my $uniqueperiod;
                   11027:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11028:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11029:             }
1.1040    raeburn  11030:             if (($startreserve < $now) &&
                   11031:                 (!$endreserve || $endreserve > $now)) {
                   11032:                 my $lastres = $endreserve;
                   11033:                 if (!$lastres) {
                   11034:                     $lastres = $slots{$slot}->{'starttime'};
                   11035:                 }
                   11036:                 $reservable_now{$slot} = {
                   11037:                                            symb       => $symb,
1.1250    raeburn  11038:                                            endreserve => $lastres,
                   11039:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11040:                                          };
                   11041:             } elsif (($startreserve > $now) &&
                   11042:                      (!$endreserve || $endreserve > $startreserve)) {
                   11043:                 $future_reservable{$slot} = {
                   11044:                                               symb         => $symb,
1.1250    raeburn  11045:                                               startreserve => $startreserve,
                   11046:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11047:                                             };
                   11048:             }
                   11049:         }
                   11050:     }
                   11051:     my @unsorted_reservable = keys(%reservable_now);
                   11052:     if (@unsorted_reservable > 0) {
                   11053:         @sorted_reservable = 
                   11054:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11055:     }
                   11056:     my @unsorted_future = keys(%future_reservable);
                   11057:     if (@unsorted_future > 0) {
                   11058:         @sorted_future =
                   11059:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11060:     }
                   11061:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11062: }
1.780     raeburn  11063: 
                   11064: =pod
                   11065: 
1.1057    foxr     11066: =back
                   11067: 
1.549     albertel 11068: =head1 HTTP Helpers
                   11069: 
                   11070: =over 4
                   11071: 
1.648     raeburn  11072: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11073: 
1.258     albertel 11074: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11075: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11076: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11077: 
                   11078: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11079: $possible_names is an ref to an array of form element names.  As an example:
                   11080: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11081: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11082: 
                   11083: =cut
1.1       albertel 11084: 
1.6       albertel 11085: sub get_unprocessed_cgi {
1.25      albertel 11086:   my ($query,$possible_names)= @_;
1.26      matthew  11087:   # $Apache::lonxml::debug=1;
1.356     albertel 11088:   foreach my $pair (split(/&/,$query)) {
                   11089:     my ($name, $value) = split(/=/,$pair);
1.369     www      11090:     $name = &unescape($name);
1.25      albertel 11091:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11092:       $value =~ tr/+/ /;
                   11093:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11094:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11095:     }
1.16      harris41 11096:   }
1.6       albertel 11097: }
                   11098: 
1.112     bowersj2 11099: =pod
                   11100: 
1.648     raeburn  11101: =item * &cacheheader() 
1.112     bowersj2 11102: 
                   11103: returns cache-controlling header code
                   11104: 
                   11105: =cut
                   11106: 
1.7       albertel 11107: sub cacheheader {
1.258     albertel 11108:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11109:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11110:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11111:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11112:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11113:     return $output;
1.7       albertel 11114: }
                   11115: 
1.112     bowersj2 11116: =pod
                   11117: 
1.648     raeburn  11118: =item * &no_cache($r) 
1.112     bowersj2 11119: 
                   11120: specifies header code to not have cache
                   11121: 
                   11122: =cut
                   11123: 
1.9       albertel 11124: sub no_cache {
1.216     albertel 11125:     my ($r) = @_;
                   11126:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11127: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11128:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11129:     $r->no_cache(1);
                   11130:     $r->header_out("Expires" => $date);
                   11131:     $r->header_out("Pragma" => "no-cache");
1.123     www      11132: }
                   11133: 
                   11134: sub content_type {
1.181     albertel 11135:     my ($r,$type,$charset) = @_;
1.299     foxr     11136:     if ($r) {
                   11137: 	#  Note that printout.pl calls this with undef for $r.
                   11138: 	&no_cache($r);
                   11139:     }
1.258     albertel 11140:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11141:     unless ($charset) {
                   11142: 	$charset=&Apache::lonlocal::current_encoding;
                   11143:     }
                   11144:     if ($charset) { $type.='; charset='.$charset; }
                   11145:     if ($r) {
                   11146: 	$r->content_type($type);
                   11147:     } else {
                   11148: 	print("Content-type: $type\n\n");
                   11149:     }
1.9       albertel 11150: }
1.25      albertel 11151: 
1.112     bowersj2 11152: =pod
                   11153: 
1.648     raeburn  11154: =item * &add_to_env($name,$value) 
1.112     bowersj2 11155: 
1.258     albertel 11156: adds $name to the %env hash with value
1.112     bowersj2 11157: $value, if $name already exists, the entry is converted to an array
                   11158: reference and $value is added to the array.
                   11159: 
                   11160: =cut
                   11161: 
1.25      albertel 11162: sub add_to_env {
                   11163:   my ($name,$value)=@_;
1.258     albertel 11164:   if (defined($env{$name})) {
                   11165:     if (ref($env{$name})) {
1.25      albertel 11166:       #already have multiple values
1.258     albertel 11167:       push(@{ $env{$name} },$value);
1.25      albertel 11168:     } else {
                   11169:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11170:       my $first=$env{$name};
                   11171:       undef($env{$name});
                   11172:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11173:     }
                   11174:   } else {
1.258     albertel 11175:     $env{$name}=$value;
1.25      albertel 11176:   }
1.31      albertel 11177: }
1.149     albertel 11178: 
                   11179: =pod
                   11180: 
1.648     raeburn  11181: =item * &get_env_multiple($name) 
1.149     albertel 11182: 
1.258     albertel 11183: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11184: values may be defined and end up as an array ref.
                   11185: 
                   11186: returns an array of values
                   11187: 
                   11188: =cut
                   11189: 
                   11190: sub get_env_multiple {
                   11191:     my ($name) = @_;
                   11192:     my @values;
1.258     albertel 11193:     if (defined($env{$name})) {
1.149     albertel 11194:         # exists is it an array
1.258     albertel 11195:         if (ref($env{$name})) {
                   11196:             @values=@{ $env{$name} };
1.149     albertel 11197:         } else {
1.258     albertel 11198:             $values[0]=$env{$name};
1.149     albertel 11199:         }
                   11200:     }
                   11201:     return(@values);
                   11202: }
                   11203: 
1.1249    damieng  11204: # Looks at given dependencies, and returns something depending on the context.
                   11205: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11206: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11207: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11208: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11209: # $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.
                   11210: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11211: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11212: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11213: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11214: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11215: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11216: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11217: # @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)
                   11218: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11219: sub ask_for_embedded_content {
1.1249    damieng  11220:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11221:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11222:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11223:         %currsubfile,%unused,$rem);
1.1071    raeburn  11224:     my $counter = 0;
                   11225:     my $numnew = 0;
1.987     raeburn  11226:     my $numremref = 0;
                   11227:     my $numinvalid = 0;
                   11228:     my $numpathchg = 0;
                   11229:     my $numexisting = 0;
1.1071    raeburn  11230:     my $numunused = 0;
                   11231:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11232:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11233:     my $heading = &mt('Upload embedded files');
                   11234:     my $buttontext = &mt('Upload');
                   11235: 
1.1249    damieng  11236:     # fills these variables based on the context:
                   11237:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11238:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11239:     if ($env{'request.course.id'}) {
1.1123    raeburn  11240:         if ($actionurl eq '/adm/dependencies') {
                   11241:             $navmap = Apache::lonnavmaps::navmap->new();
                   11242:         }
                   11243:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11244:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11245:     }
1.1123    raeburn  11246:     if (($actionurl eq '/adm/portfolio') || 
                   11247:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11248:         my $current_path='/';
                   11249:         if ($env{'form.currentpath'}) {
                   11250:             $current_path = $env{'form.currentpath'};
                   11251:         }
                   11252:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11253:             $udom = $cdom;
                   11254:             $uname = $cnum;
1.984     raeburn  11255:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11256:         } else {
                   11257:             $udom = $env{'user.domain'};
                   11258:             $uname = $env{'user.name'};
                   11259:             $url = '/userfiles/portfolio';
                   11260:         }
1.987     raeburn  11261:         $toplevel = $url.'/';
1.984     raeburn  11262:         $url .= $current_path;
                   11263:         $getpropath = 1;
1.987     raeburn  11264:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11265:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11266:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11267:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11268:         $toplevel = $url;
1.984     raeburn  11269:         if ($rest ne '') {
1.987     raeburn  11270:             $url .= $rest;
                   11271:         }
                   11272:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11273:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11274:             $url = $args->{'docs_url'};
                   11275:             $toplevel = $url;
1.1084    raeburn  11276:             if ($args->{'context'} eq 'paste') {
                   11277:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11278:                 ($path) = 
                   11279:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11280:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11281:                 $fileloc =~ s{^/}{};
                   11282:             }
1.1071    raeburn  11283:         }
1.1084    raeburn  11284:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11285:         if ($env{'request.course.id'} ne '') {
                   11286:             if (ref($args) eq 'HASH') {
                   11287:                 $url = $args->{'docs_url'};
                   11288:                 $title = $args->{'docs_title'};
1.1126    raeburn  11289:                 $toplevel = $url; 
                   11290:                 unless ($toplevel =~ m{^/}) {
                   11291:                     $toplevel = "/$url";
                   11292:                 }
1.1085    raeburn  11293:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11294:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11295:                     $path = $1;
                   11296:                 } else {
                   11297:                     ($path) =
                   11298:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11299:                 }
1.1195    raeburn  11300:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11301:                     $fileloc = $toplevel;
                   11302:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11303:                     my ($udom,$uname,$fname) =
                   11304:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11305:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11306:                 } else {
                   11307:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11308:                 }
1.1071    raeburn  11309:                 $fileloc =~ s{^/}{};
                   11310:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11311:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11312:             }
1.987     raeburn  11313:         }
1.1123    raeburn  11314:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11315:         $udom = $cdom;
                   11316:         $uname = $cnum;
                   11317:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11318:         $toplevel = $url;
                   11319:         $path = $url;
                   11320:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11321:         $fileloc =~ s{^/}{};
1.987     raeburn  11322:     }
1.1249    damieng  11323:     
                   11324:     # parses the dependency paths to get some info
                   11325:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11326:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11327:     # (will be completed later)
                   11328:     # $mapping:
                   11329:     #   for external URLs: external URL -> external URL
                   11330:     #   for relative paths: clean path -> original path
                   11331:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11332:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11333:     foreach my $file (keys(%{$allfiles})) {
                   11334:         my $embed_file;
                   11335:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11336:             $embed_file = $1;
                   11337:         } else {
                   11338:             $embed_file = $file;
                   11339:         }
1.1158    raeburn  11340:         my ($absolutepath,$cleaned_file);
                   11341:         if ($embed_file =~ m{^\w+://}) {
                   11342:             $cleaned_file = $embed_file;
1.1147    raeburn  11343:             $newfiles{$cleaned_file} = 1;
                   11344:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11345:         } else {
1.1158    raeburn  11346:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11347:             if ($embed_file =~ m{^/}) {
                   11348:                 $absolutepath = $embed_file;
                   11349:             }
1.1147    raeburn  11350:             if ($cleaned_file =~ m{/}) {
                   11351:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11352:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11353:                 my $item = $fname;
                   11354:                 if ($path ne '') {
                   11355:                     $item = $path.'/'.$fname;
                   11356:                     $subdependencies{$path}{$fname} = 1;
                   11357:                 } else {
                   11358:                     $dependencies{$item} = 1;
                   11359:                 }
                   11360:                 if ($absolutepath) {
                   11361:                     $mapping{$item} = $absolutepath;
                   11362:                 } else {
                   11363:                     $mapping{$item} = $embed_file;
                   11364:                 }
                   11365:             } else {
                   11366:                 $dependencies{$embed_file} = 1;
                   11367:                 if ($absolutepath) {
1.1147    raeburn  11368:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11369:                 } else {
1.1147    raeburn  11370:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11371:                 }
                   11372:             }
1.984     raeburn  11373:         }
                   11374:     }
1.1249    damieng  11375:     
                   11376:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11377:     # and lists
                   11378:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11379:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11380:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11381:     #                                    the path had to be cleaned up
                   11382:     # $existing: hash clean path -> 1 if the file exists
                   11383:     # $numexisting: number of keys in $existing
                   11384:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11385:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11386:     #                                      dependency subdirectories that are
                   11387:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11388:     my $dirptr = 16384;
1.984     raeburn  11389:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11390:         $currsubfile{$path} = {};
1.1123    raeburn  11391:         if (($actionurl eq '/adm/portfolio') || 
                   11392:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11393:             my ($sublistref,$listerror) =
                   11394:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11395:             if (ref($sublistref) eq 'ARRAY') {
                   11396:                 foreach my $line (@{$sublistref}) {
                   11397:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11398:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11399:                 }
1.984     raeburn  11400:             }
1.987     raeburn  11401:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11402:             if (opendir(my $dir,$url.'/'.$path)) {
                   11403:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11404:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11405:             }
1.1084    raeburn  11406:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11407:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11408:                   ($args->{'context'} eq 'paste')) ||
                   11409:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11410:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11411:                 my $dir;
                   11412:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11413:                     $dir = $fileloc;
                   11414:                 } else {
                   11415:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11416:                 }
1.1071    raeburn  11417:                 if ($dir ne '') {
                   11418:                     my ($sublistref,$listerror) =
                   11419:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11420:                     if (ref($sublistref) eq 'ARRAY') {
                   11421:                         foreach my $line (@{$sublistref}) {
                   11422:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11423:                                 undef,$mtime)=split(/\&/,$line,12);
                   11424:                             unless (($testdir&$dirptr) ||
                   11425:                                     ($file_name =~ /^\.\.?$/)) {
                   11426:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11427:                             }
                   11428:                         }
                   11429:                     }
                   11430:                 }
1.984     raeburn  11431:             }
                   11432:         }
                   11433:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11434:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11435:                 my $item = $path.'/'.$file;
                   11436:                 unless ($mapping{$item} eq $item) {
                   11437:                     $pathchanges{$item} = 1;
                   11438:                 }
                   11439:                 $existing{$item} = 1;
                   11440:                 $numexisting ++;
                   11441:             } else {
                   11442:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11443:             }
                   11444:         }
1.1071    raeburn  11445:         if ($actionurl eq '/adm/dependencies') {
                   11446:             foreach my $path (keys(%currsubfile)) {
                   11447:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11448:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11449:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11450:                              next if (($rem ne '') &&
                   11451:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11452:                                        (ref($navmap) &&
                   11453:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11454:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11455:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11456:                              $unused{$path.'/'.$file} = 1; 
                   11457:                          }
                   11458:                     }
                   11459:                 }
                   11460:             }
                   11461:         }
1.984     raeburn  11462:     }
1.1249    damieng  11463:     
                   11464:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11465:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11466:     my %currfile;
1.1123    raeburn  11467:     if (($actionurl eq '/adm/portfolio') ||
                   11468:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11469:         my ($dirlistref,$listerror) =
                   11470:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11471:         if (ref($dirlistref) eq 'ARRAY') {
                   11472:             foreach my $line (@{$dirlistref}) {
                   11473:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11474:                 $currfile{$file_name} = 1;
                   11475:             }
1.984     raeburn  11476:         }
1.987     raeburn  11477:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11478:         if (opendir(my $dir,$url)) {
1.987     raeburn  11479:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11480:             map {$currfile{$_} = 1;} @dir_list;
                   11481:         }
1.1084    raeburn  11482:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11483:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11484:               ($args->{'context'} eq 'paste')) ||
                   11485:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11486:         if ($env{'request.course.id'} ne '') {
                   11487:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11488:             if ($dir ne '') {
                   11489:                 my ($dirlistref,$listerror) =
                   11490:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11491:                 if (ref($dirlistref) eq 'ARRAY') {
                   11492:                     foreach my $line (@{$dirlistref}) {
                   11493:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11494:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11495:                         unless (($testdir&$dirptr) ||
                   11496:                                 ($file_name =~ /^\.\.?$/)) {
                   11497:                             $currfile{$file_name} = [$size,$mtime];
                   11498:                         }
                   11499:                     }
                   11500:                 }
                   11501:             }
                   11502:         }
1.984     raeburn  11503:     }
1.1249    damieng  11504:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11505:     # are not in subdirectories, using $currfile
1.984     raeburn  11506:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11507:         if (exists($currfile{$file})) {
1.987     raeburn  11508:             unless ($mapping{$file} eq $file) {
                   11509:                 $pathchanges{$file} = 1;
                   11510:             }
                   11511:             $existing{$file} = 1;
                   11512:             $numexisting ++;
                   11513:         } else {
1.984     raeburn  11514:             $newfiles{$file} = 1;
                   11515:         }
                   11516:     }
1.1071    raeburn  11517:     foreach my $file (keys(%currfile)) {
                   11518:         unless (($file eq $filename) ||
                   11519:                 ($file eq $filename.'.bak') ||
                   11520:                 ($dependencies{$file})) {
1.1085    raeburn  11521:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11522:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11523:                     next if (($rem ne '') &&
                   11524:                              (($env{"httpref.$rem".$file} ne '') ||
                   11525:                               (ref($navmap) &&
                   11526:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11527:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11528:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11529:                 }
1.1085    raeburn  11530:             }
1.1071    raeburn  11531:             $unused{$file} = 1;
                   11532:         }
                   11533:     }
1.1249    damieng  11534:     
                   11535:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11536:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11537:         ($args->{'context'} eq 'paste')) {
                   11538:         $counter = scalar(keys(%existing));
                   11539:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11540:         return ($output,$counter,$numpathchg,\%existing);
                   11541:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11542:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11543:         $counter = scalar(keys(%existing));
                   11544:         $numpathchg = scalar(keys(%pathchanges));
                   11545:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11546:     }
1.1249    damieng  11547:     
                   11548:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11549:     
                   11550:     # $upload_output: missing dependencies (with upload form)
                   11551:     # $modify_output: uploaded dependencies (in use)
                   11552:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11553:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11554:         if ($actionurl eq '/adm/dependencies') {
                   11555:             next if ($embed_file =~ m{^\w+://});
                   11556:         }
1.660     raeburn  11557:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11558:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11559:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11560:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11561:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11562:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11563:         }
1.1123    raeburn  11564:         $upload_output .= '</td>';
1.1071    raeburn  11565:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11566:             $upload_output.='<td align="right">'.
                   11567:                             '<span class="LC_info LC_fontsize_medium">'.
                   11568:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11569:             $numremref++;
1.660     raeburn  11570:         } elsif ($args->{'error_on_invalid_names'}
                   11571:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11572:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11573:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11574:             $numinvalid++;
1.660     raeburn  11575:         } else {
1.1123    raeburn  11576:             $upload_output .= '<td>'.
                   11577:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11578:                                                      $embed_file,\%mapping,
1.1071    raeburn  11579:                                                      $allfiles,$codebase,'upload');
                   11580:             $counter ++;
                   11581:             $numnew ++;
1.987     raeburn  11582:         }
                   11583:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11584:     }
                   11585:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11586:         if ($actionurl eq '/adm/dependencies') {
                   11587:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11588:             $modify_output .= &start_data_table_row().
                   11589:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11590:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11591:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11592:                               '<td>'.$size.'</td>'.
                   11593:                               '<td>'.$mtime.'</td>'.
                   11594:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11595:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11596:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11597:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11598:                               &embedded_file_element('upload_embedded',$counter,
                   11599:                                                      $embed_file,\%mapping,
                   11600:                                                      $allfiles,$codebase,'modify').
                   11601:                               '</div></td>'.
                   11602:                               &end_data_table_row()."\n";
                   11603:             $counter ++;
                   11604:         } else {
                   11605:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11606:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11607:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11608:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11609:                               &Apache::loncommon::end_data_table_row()."\n";
                   11610:         }
                   11611:     }
                   11612:     my $delidx = $counter;
                   11613:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11614:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11615:         $delete_output .= &start_data_table_row().
                   11616:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11617:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11618:                           '<td>'.$size.'</td>'.
                   11619:                           '<td>'.$mtime.'</td>'.
                   11620:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11621:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11622:                           &embedded_file_element('upload_embedded',$delidx,
                   11623:                                                  $oldfile,\%mapping,$allfiles,
                   11624:                                                  $codebase,'delete').'</td>'.
                   11625:                           &end_data_table_row()."\n"; 
                   11626:         $numunused ++;
                   11627:         $delidx ++;
1.987     raeburn  11628:     }
                   11629:     if ($upload_output) {
                   11630:         $upload_output = &start_data_table().
                   11631:                          $upload_output.
                   11632:                          &end_data_table()."\n";
                   11633:     }
1.1071    raeburn  11634:     if ($modify_output) {
                   11635:         $modify_output = &start_data_table().
                   11636:                          &start_data_table_header_row().
                   11637:                          '<th>'.&mt('File').'</th>'.
                   11638:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11639:                          '<th>'.&mt('Modified').'</th>'.
                   11640:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11641:                          &end_data_table_header_row().
                   11642:                          $modify_output.
                   11643:                          &end_data_table()."\n";
                   11644:     }
                   11645:     if ($delete_output) {
                   11646:         $delete_output = &start_data_table().
                   11647:                          &start_data_table_header_row().
                   11648:                          '<th>'.&mt('File').'</th>'.
                   11649:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11650:                          '<th>'.&mt('Modified').'</th>'.
                   11651:                          '<th>'.&mt('Delete?').'</th>'.
                   11652:                          &end_data_table_header_row().
                   11653:                          $delete_output.
                   11654:                          &end_data_table()."\n";
                   11655:     }
1.987     raeburn  11656:     my $applies = 0;
                   11657:     if ($numremref) {
                   11658:         $applies ++;
                   11659:     }
                   11660:     if ($numinvalid) {
                   11661:         $applies ++;
                   11662:     }
                   11663:     if ($numexisting) {
                   11664:         $applies ++;
                   11665:     }
1.1071    raeburn  11666:     if ($counter || $numunused) {
1.987     raeburn  11667:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11668:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11669:                   $state.'<h3>'.$heading.'</h3>'; 
                   11670:         if ($actionurl eq '/adm/dependencies') {
                   11671:             if ($numnew) {
                   11672:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11673:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11674:                            $upload_output.'<br />'."\n";
                   11675:             }
                   11676:             if ($numexisting) {
                   11677:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11678:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11679:                            $modify_output.'<br />'."\n";
                   11680:                            $buttontext = &mt('Save changes');
                   11681:             }
                   11682:             if ($numunused) {
                   11683:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11684:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11685:                            $delete_output.'<br />'."\n";
                   11686:                            $buttontext = &mt('Save changes');
                   11687:             }
                   11688:         } else {
                   11689:             $output .= $upload_output.'<br />'."\n";
                   11690:         }
                   11691:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11692:                    $counter.'" />'."\n";
                   11693:         if ($actionurl eq '/adm/dependencies') { 
                   11694:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11695:                        $numnew.'" />'."\n";
                   11696:         } elsif ($actionurl eq '') {
1.987     raeburn  11697:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11698:         }
                   11699:     } elsif ($applies) {
                   11700:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11701:         if ($applies > 1) {
                   11702:             $output .=  
1.1123    raeburn  11703:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11704:             if ($numremref) {
                   11705:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11706:             }
                   11707:             if ($numinvalid) {
                   11708:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11709:             }
                   11710:             if ($numexisting) {
                   11711:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11712:             }
                   11713:             $output .= '</ul><br />';
                   11714:         } elsif ($numremref) {
                   11715:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11716:         } elsif ($numinvalid) {
                   11717:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11718:         } elsif ($numexisting) {
                   11719:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11720:         }
                   11721:         $output .= $upload_output.'<br />';
                   11722:     }
                   11723:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11724:     $chgcount = $counter;
1.987     raeburn  11725:     if (keys(%pathchanges) > 0) {
                   11726:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11727:             if ($counter) {
1.987     raeburn  11728:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11729:                                                   $embed_file,\%mapping,
1.1071    raeburn  11730:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11731:             } else {
                   11732:                 $pathchange_output .= 
                   11733:                     &start_data_table_row().
                   11734:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11735:                     $chgcount.'" checked="checked" /></td>'.
                   11736:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11737:                     '<td>'.$embed_file.
                   11738:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11739:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11740:                     '</td>'.&end_data_table_row();
1.660     raeburn  11741:             }
1.987     raeburn  11742:             $numpathchg ++;
                   11743:             $chgcount ++;
1.660     raeburn  11744:         }
                   11745:     }
1.1127    raeburn  11746:     if (($counter) || ($numunused)) {
1.987     raeburn  11747:         if ($numpathchg) {
                   11748:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11749:                        $numpathchg.'" />'."\n";
                   11750:         }
                   11751:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11752:             ($actionurl eq '/adm/imsimport')) {
                   11753:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11754:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11755:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11756:         } elsif ($actionurl eq '/adm/dependencies') {
                   11757:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11758:         }
1.1123    raeburn  11759:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11760:     } elsif ($numpathchg) {
                   11761:         my %pathchange = ();
                   11762:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11763:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11764:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11765:         }
1.987     raeburn  11766:     }
1.1071    raeburn  11767:     return ($output,$counter,$numpathchg);
1.987     raeburn  11768: }
                   11769: 
1.1147    raeburn  11770: =pod
                   11771: 
                   11772: =item * clean_path($name)
                   11773: 
                   11774: Performs clean-up of directories, subdirectories and filename in an
                   11775: embedded object, referenced in an HTML file which is being uploaded
                   11776: to a course or portfolio, where 
                   11777: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11778: checked.
                   11779: 
                   11780: Clean-up is similar to replacements in lonnet::clean_filename()
                   11781: except each / between sub-directory and next level is preserved.
                   11782: 
                   11783: =cut
                   11784: 
                   11785: sub clean_path {
                   11786:     my ($embed_file) = @_;
                   11787:     $embed_file =~s{^/+}{};
                   11788:     my @contents;
                   11789:     if ($embed_file =~ m{/}) {
                   11790:         @contents = split(/\//,$embed_file);
                   11791:     } else {
                   11792:         @contents = ($embed_file);
                   11793:     }
                   11794:     my $lastidx = scalar(@contents)-1;
                   11795:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11796:         $contents[$i]=~s{\\}{/}g;
                   11797:         $contents[$i]=~s/\s+/\_/g;
                   11798:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11799:         if ($i == $lastidx) {
                   11800:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11801:         }
                   11802:     }
                   11803:     if ($lastidx > 0) {
                   11804:         return join('/',@contents);
                   11805:     } else {
                   11806:         return $contents[0];
                   11807:     }
                   11808: }
                   11809: 
1.987     raeburn  11810: sub embedded_file_element {
1.1071    raeburn  11811:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11812:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11813:                    (ref($codebase) eq 'HASH'));
                   11814:     my $output;
1.1071    raeburn  11815:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11816:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11817:     }
                   11818:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11819:                &escape($embed_file).'" />';
                   11820:     unless (($context eq 'upload_embedded') && 
                   11821:             ($mapping->{$embed_file} eq $embed_file)) {
                   11822:         $output .='
                   11823:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11824:     }
                   11825:     my $attrib;
                   11826:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11827:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11828:     }
                   11829:     $output .=
                   11830:         "\n\t\t".
                   11831:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11832:         $attrib.'" />';
                   11833:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11834:         $output .=
                   11835:             "\n\t\t".
                   11836:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11837:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11838:     }
1.987     raeburn  11839:     return $output;
1.660     raeburn  11840: }
                   11841: 
1.1071    raeburn  11842: sub get_dependency_details {
                   11843:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11844:     my ($size,$mtime,$showsize,$showmtime);
                   11845:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11846:         if ($embed_file =~ m{/}) {
                   11847:             my ($path,$fname) = split(/\//,$embed_file);
                   11848:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11849:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11850:             }
                   11851:         } else {
                   11852:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11853:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11854:             }
                   11855:         }
                   11856:         $showsize = $size/1024.0;
                   11857:         $showsize = sprintf("%.1f",$showsize);
                   11858:         if ($mtime > 0) {
                   11859:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11860:         }
                   11861:     }
                   11862:     return ($showsize,$showmtime);
                   11863: }
                   11864: 
                   11865: sub ask_embedded_js {
                   11866:     return <<"END";
                   11867: <script type="text/javascript"">
                   11868: // <![CDATA[
                   11869: function toggleBrowse(counter) {
                   11870:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11871:     var fileid = document.getElementById('embedded_item_'+counter);
                   11872:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11873:     if (chkboxid.checked == true) {
                   11874:         uploaddivid.style.display='block';
                   11875:     } else {
                   11876:         uploaddivid.style.display='none';
                   11877:         fileid.value = '';
                   11878:     }
                   11879: }
                   11880: // ]]>
                   11881: </script>
                   11882: 
                   11883: END
                   11884: }
                   11885: 
1.661     raeburn  11886: sub upload_embedded {
                   11887:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11888:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11889:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11890:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11891:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11892:         my $orig_uploaded_filename =
                   11893:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11894:         foreach my $type ('orig','ref','attrib','codebase') {
                   11895:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11896:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11897:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11898:             }
                   11899:         }
1.661     raeburn  11900:         my ($path,$fname) =
                   11901:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11902:         # no path, whole string is fname
                   11903:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11904:         $fname = &Apache::lonnet::clean_filename($fname);
                   11905:         # See if there is anything left
                   11906:         next if ($fname eq '');
                   11907: 
                   11908:         # Check if file already exists as a file or directory.
                   11909:         my ($state,$msg);
                   11910:         if ($context eq 'portfolio') {
                   11911:             my $port_path = $dirpath;
                   11912:             if ($group ne '') {
                   11913:                 $port_path = "groups/$group/$port_path";
                   11914:             }
1.987     raeburn  11915:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11916:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11917:                                               $dir_root,$port_path,$disk_quota,
                   11918:                                               $current_disk_usage,$uname,$udom);
                   11919:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11920:                 || $state eq 'file_locked') {
1.661     raeburn  11921:                 $output .= $msg;
                   11922:                 next;
                   11923:             }
                   11924:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11925:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11926:             if ($state eq 'exists') {
                   11927:                 $output .= $msg;
                   11928:                 next;
                   11929:             }
                   11930:         }
                   11931:         # Check if extension is valid
                   11932:         if (($fname =~ /\.(\w+)$/) &&
                   11933:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11934:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11935:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11936:             next;
                   11937:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11938:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11939:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11940:             next;
                   11941:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11942:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  11943:             next;
                   11944:         }
                   11945:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11946:         my $subdir = $path;
                   11947:         $subdir =~ s{/+$}{};
1.661     raeburn  11948:         if ($context eq 'portfolio') {
1.984     raeburn  11949:             my $result;
                   11950:             if ($state eq 'existingfile') {
                   11951:                 $result=
                   11952:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11953:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11954:             } else {
1.984     raeburn  11955:                 $result=
                   11956:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11957:                                                     $dirpath.
1.1123    raeburn  11958:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11959:                 if ($result !~ m|^/uploaded/|) {
                   11960:                     $output .= '<span class="LC_error">'
                   11961:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11962:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11963:                                .'</span><br />';
                   11964:                     next;
                   11965:                 } else {
1.987     raeburn  11966:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11967:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11968:                 }
1.661     raeburn  11969:             }
1.1123    raeburn  11970:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11971:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11972:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11973:             my $result =
1.1126    raeburn  11974:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11975:             if ($result !~ m|^/uploaded/|) {
                   11976:                 $output .= '<span class="LC_error">'
                   11977:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11978:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11979:                            .'</span><br />';
                   11980:                     next;
                   11981:             } else {
                   11982:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11983:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11984:                 if ($context eq 'syllabus') {
                   11985:                     &Apache::lonnet::make_public_indefinitely($result);
                   11986:                 }
1.987     raeburn  11987:             }
1.661     raeburn  11988:         } else {
                   11989: # Save the file
                   11990:             my $target = $env{'form.embedded_item_'.$i};
                   11991:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11992:             my $dest = $fullpath.$fname;
                   11993:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11994:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11995:             my $count;
                   11996:             my $filepath = $dir_root;
1.1027    raeburn  11997:             foreach my $subdir (@parts) {
                   11998:                 $filepath .= "/$subdir";
                   11999:                 if (!-e $filepath) {
1.661     raeburn  12000:                     mkdir($filepath,0770);
                   12001:                 }
                   12002:             }
                   12003:             my $fh;
                   12004:             if (!open($fh,'>'.$dest)) {
                   12005:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12006:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12007:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12008:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12009:                            '</span><br />';
                   12010:             } else {
                   12011:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12012:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12013:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12014:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12015:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12016:                               '</span><br />';
                   12017:                 } else {
1.987     raeburn  12018:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12019:                                $url.'</span>').'<br />';
                   12020:                     unless ($context eq 'testbank') {
                   12021:                         $footer .= &mt('View embedded file: [_1]',
                   12022:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12023:                     }
                   12024:                 }
                   12025:                 close($fh);
                   12026:             }
                   12027:         }
                   12028:         if ($env{'form.embedded_ref_'.$i}) {
                   12029:             $pathchange{$i} = 1;
                   12030:         }
                   12031:     }
                   12032:     if ($output) {
                   12033:         $output = '<p>'.$output.'</p>';
                   12034:     }
                   12035:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12036:     $returnflag = 'ok';
1.1071    raeburn  12037:     my $numpathchgs = scalar(keys(%pathchange));
                   12038:     if ($numpathchgs > 0) {
1.987     raeburn  12039:         if ($context eq 'portfolio') {
                   12040:             $output .= '<p>'.&mt('or').'</p>';
                   12041:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12042:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12043:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12044:             $returnflag = 'modify_orightml';
                   12045:         }
                   12046:     }
1.1071    raeburn  12047:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12048: }
                   12049: 
                   12050: sub modify_html_form {
                   12051:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12052:     my $end = 0;
                   12053:     my $modifyform;
                   12054:     if ($context eq 'upload_embedded') {
                   12055:         return unless (ref($pathchange) eq 'HASH');
                   12056:         if ($env{'form.number_embedded_items'}) {
                   12057:             $end += $env{'form.number_embedded_items'};
                   12058:         }
                   12059:         if ($env{'form.number_pathchange_items'}) {
                   12060:             $end += $env{'form.number_pathchange_items'};
                   12061:         }
                   12062:         if ($end) {
                   12063:             for (my $i=0; $i<$end; $i++) {
                   12064:                 if ($i < $env{'form.number_embedded_items'}) {
                   12065:                     next unless($pathchange->{$i});
                   12066:                 }
                   12067:                 $modifyform .=
                   12068:                     &start_data_table_row().
                   12069:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12070:                     'checked="checked" /></td>'.
                   12071:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12072:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12073:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12074:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12075:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12076:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12077:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12078:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12079:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12080:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12081:                     &end_data_table_row();
1.1071    raeburn  12082:             }
1.987     raeburn  12083:         }
                   12084:     } else {
                   12085:         $modifyform = $pathchgtable;
                   12086:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12087:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12088:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12089:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12090:         }
                   12091:     }
                   12092:     if ($modifyform) {
1.1071    raeburn  12093:         if ($actionurl eq '/adm/dependencies') {
                   12094:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12095:         }
1.987     raeburn  12096:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12097:                '<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".
                   12098:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12099:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12100:                '</ol></p>'."\n".'<p>'.
                   12101:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12102:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12103:                &start_data_table()."\n".
                   12104:                &start_data_table_header_row().
                   12105:                '<th>'.&mt('Change?').'</th>'.
                   12106:                '<th>'.&mt('Current reference').'</th>'.
                   12107:                '<th>'.&mt('Required reference').'</th>'.
                   12108:                &end_data_table_header_row()."\n".
                   12109:                $modifyform.
                   12110:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12111:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12112:                '</form>'."\n";
                   12113:     }
                   12114:     return;
                   12115: }
                   12116: 
                   12117: sub modify_html_refs {
1.1123    raeburn  12118:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12119:     my $container;
                   12120:     if ($context eq 'portfolio') {
                   12121:         $container = $env{'form.container'};
                   12122:     } elsif ($context eq 'coursedoc') {
                   12123:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12124:     } elsif ($context eq 'manage_dependencies') {
                   12125:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12126:         $container = "/$container";
1.1123    raeburn  12127:     } elsif ($context eq 'syllabus') {
                   12128:         $container = $url;
1.987     raeburn  12129:     } else {
1.1027    raeburn  12130:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12131:     }
                   12132:     my (%allfiles,%codebase,$output,$content);
                   12133:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12134:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12135:         if (wantarray) {
                   12136:             return ('',0,0); 
                   12137:         } else {
                   12138:             return;
                   12139:         }
                   12140:     }
                   12141:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12142:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12143:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12144:             if (wantarray) {
                   12145:                 return ('',0,0);
                   12146:             } else {
                   12147:                 return;
                   12148:             }
                   12149:         } 
1.987     raeburn  12150:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12151:         if ($content eq '-1') {
                   12152:             if (wantarray) {
                   12153:                 return ('',0,0);
                   12154:             } else {
                   12155:                 return;
                   12156:             }
                   12157:         }
1.987     raeburn  12158:     } else {
1.1071    raeburn  12159:         unless ($container =~ /^\Q$dir_root\E/) {
                   12160:             if (wantarray) {
                   12161:                 return ('',0,0);
                   12162:             } else {
                   12163:                 return;
                   12164:             }
                   12165:         } 
1.987     raeburn  12166:         if (open(my $fh,"<$container")) {
                   12167:             $content = join('', <$fh>);
                   12168:             close($fh);
                   12169:         } else {
1.1071    raeburn  12170:             if (wantarray) {
                   12171:                 return ('',0,0);
                   12172:             } else {
                   12173:                 return;
                   12174:             }
1.987     raeburn  12175:         }
                   12176:     }
                   12177:     my ($count,$codebasecount) = (0,0);
                   12178:     my $mm = new File::MMagic;
                   12179:     my $mime_type = $mm->checktype_contents($content);
                   12180:     if ($mime_type eq 'text/html') {
                   12181:         my $parse_result = 
                   12182:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12183:                                                     \%codebase,\$content);
                   12184:         if ($parse_result eq 'ok') {
                   12185:             foreach my $i (@changes) {
                   12186:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12187:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12188:                 if ($allfiles{$ref}) {
                   12189:                     my $newname =  $orig;
                   12190:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12191:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12192:                     if ($attrib_regexp =~ /:/) {
                   12193:                         $attrib_regexp =~ s/\:/|/g;
                   12194:                     }
                   12195:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12196:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12197:                         $count += $numchg;
1.1123    raeburn  12198:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12199:                         delete($allfiles{$ref});
1.987     raeburn  12200:                     }
                   12201:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12202:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12203:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12204:                         $codebasecount ++;
                   12205:                     }
                   12206:                 }
                   12207:             }
1.1123    raeburn  12208:             my $skiprewrites;
1.987     raeburn  12209:             if ($count || $codebasecount) {
                   12210:                 my $saveresult;
1.1071    raeburn  12211:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12212:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12213:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12214:                     if ($url eq $container) {
                   12215:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12216:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12217:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12218:                                             $fname.'</span>').'</p>';
1.987     raeburn  12219:                     } else {
                   12220:                          $output = '<p class="LC_error">'.
                   12221:                                    &mt('Error: update failed for: [_1].',
                   12222:                                    '<span class="LC_filename">'.
                   12223:                                    $container.'</span>').'</p>';
                   12224:                     }
1.1123    raeburn  12225:                     if ($context eq 'syllabus') {
                   12226:                         unless ($saveresult eq 'ok') {
                   12227:                             $skiprewrites = 1;
                   12228:                         }
                   12229:                     }
1.987     raeburn  12230:                 } else {
                   12231:                     if (open(my $fh,">$container")) {
                   12232:                         print $fh $content;
                   12233:                         close($fh);
                   12234:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12235:                                   $count,'<span class="LC_filename">'.
                   12236:                                   $container.'</span>').'</p>';
1.661     raeburn  12237:                     } else {
1.987     raeburn  12238:                          $output = '<p class="LC_error">'.
                   12239:                                    &mt('Error: could not update [_1].',
                   12240:                                    '<span class="LC_filename">'.
                   12241:                                    $container.'</span>').'</p>';
1.661     raeburn  12242:                     }
                   12243:                 }
                   12244:             }
1.1123    raeburn  12245:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12246:                 my ($actionurl,$state);
                   12247:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12248:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12249:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12250:                                               \%codebase,
                   12251:                                               {'context' => 'rewrites',
                   12252:                                                'ignore_remote_references' => 1,});
                   12253:                 if (ref($mapping) eq 'HASH') {
                   12254:                     my $rewrites = 0;
                   12255:                     foreach my $key (keys(%{$mapping})) {
                   12256:                         next if ($key =~ m{^https?://});
                   12257:                         my $ref = $mapping->{$key};
                   12258:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12259:                         my $attrib;
                   12260:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12261:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12262:                         }
                   12263:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12264:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12265:                             $rewrites += $numchg;
                   12266:                         }
                   12267:                     }
                   12268:                     if ($rewrites) {
                   12269:                         my $saveresult; 
                   12270:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12271:                         if ($url eq $container) {
                   12272:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12273:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12274:                                             $count,'<span class="LC_filename">'.
                   12275:                                             $fname.'</span>').'</p>';
                   12276:                         } else {
                   12277:                             $output .= '<p class="LC_error">'.
                   12278:                                        &mt('Error: could not update links in [_1].',
                   12279:                                        '<span class="LC_filename">'.
                   12280:                                        $container.'</span>').'</p>';
                   12281: 
                   12282:                         }
                   12283:                     }
                   12284:                 }
                   12285:             }
1.987     raeburn  12286:         } else {
                   12287:             &logthis('Failed to parse '.$container.
                   12288:                      ' to modify references: '.$parse_result);
1.661     raeburn  12289:         }
                   12290:     }
1.1071    raeburn  12291:     if (wantarray) {
                   12292:         return ($output,$count,$codebasecount);
                   12293:     } else {
                   12294:         return $output;
                   12295:     }
1.661     raeburn  12296: }
                   12297: 
                   12298: sub check_for_existing {
                   12299:     my ($path,$fname,$element) = @_;
                   12300:     my ($state,$msg);
                   12301:     if (-d $path.'/'.$fname) {
                   12302:         $state = 'exists';
                   12303:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12304:     } elsif (-e $path.'/'.$fname) {
                   12305:         $state = 'exists';
                   12306:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12307:     }
                   12308:     if ($state eq 'exists') {
                   12309:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12310:     }
                   12311:     return ($state,$msg);
                   12312: }
                   12313: 
                   12314: sub check_for_upload {
                   12315:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12316:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12317:     my $filesize = length($env{'form.'.$element});
                   12318:     if (!$filesize) {
                   12319:         my $msg = '<span class="LC_error">'.
                   12320:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12321:                       '<span class="LC_filename">'.$fname.'</span>',
                   12322:                       $filesize).'<br />'.
1.1007    raeburn  12323:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12324:                   '</span>';
                   12325:         return ('zero_bytes',$msg);
                   12326:     }
                   12327:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12328:     my $getpropath = 1;
1.1021    raeburn  12329:     my ($dirlistref,$listerror) =
                   12330:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12331:     my $found_file = 0;
                   12332:     my $locked_file = 0;
1.991     raeburn  12333:     my @lockers;
                   12334:     my $navmap;
                   12335:     if ($env{'request.course.id'}) {
                   12336:         $navmap = Apache::lonnavmaps::navmap->new();
                   12337:     }
1.1021    raeburn  12338:     if (ref($dirlistref) eq 'ARRAY') {
                   12339:         foreach my $line (@{$dirlistref}) {
                   12340:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12341:             if ($file_name eq $fname){
                   12342:                 $file_name = $path.$file_name;
                   12343:                 if ($group ne '') {
                   12344:                     $file_name = $group.$file_name;
                   12345:                 }
                   12346:                 $found_file = 1;
                   12347:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12348:                     foreach my $lock (@lockers) {
                   12349:                         if (ref($lock) eq 'ARRAY') {
                   12350:                             my ($symb,$crsid) = @{$lock};
                   12351:                             if ($crsid eq $env{'request.course.id'}) {
                   12352:                                 if (ref($navmap)) {
                   12353:                                     my $res = $navmap->getBySymb($symb);
                   12354:                                     foreach my $part (@{$res->parts()}) { 
                   12355:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12356:                                         unless (($slot_status == $res->RESERVED) ||
                   12357:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12358:                                             $locked_file = 1;
                   12359:                                         }
1.991     raeburn  12360:                                     }
1.1021    raeburn  12361:                                 } else {
                   12362:                                     $locked_file = 1;
1.991     raeburn  12363:                                 }
                   12364:                             } else {
                   12365:                                 $locked_file = 1;
                   12366:                             }
                   12367:                         }
1.1021    raeburn  12368:                    }
                   12369:                 } else {
                   12370:                     my @info = split(/\&/,$rest);
                   12371:                     my $currsize = $info[6]/1000;
                   12372:                     if ($currsize < $filesize) {
                   12373:                         my $extra = $filesize - $currsize;
                   12374:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12375:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12376:                                       &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.',
1.1179    bisitz   12377:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12378:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12379:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12380:                             return ('will_exceed_quota',$msg);
                   12381:                         }
1.984     raeburn  12382:                     }
                   12383:                 }
1.661     raeburn  12384:             }
                   12385:         }
                   12386:     }
                   12387:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12388:         my $msg = '<p class="LC_warning">'.
                   12389:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12390:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12391:         return ('will_exceed_quota',$msg);
                   12392:     } elsif ($found_file) {
                   12393:         if ($locked_file) {
1.1179    bisitz   12394:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12395:             $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>');
1.1179    bisitz   12396:             $msg .= '</p>';
1.661     raeburn  12397:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12398:             return ('file_locked',$msg);
                   12399:         } else {
1.1179    bisitz   12400:             my $msg = '<p class="LC_error">';
1.984     raeburn  12401:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   12402:             $msg .= '</p>';
1.984     raeburn  12403:             return ('existingfile',$msg);
1.661     raeburn  12404:         }
                   12405:     }
                   12406: }
                   12407: 
1.987     raeburn  12408: sub check_for_traversal {
                   12409:     my ($path,$url,$toplevel) = @_;
                   12410:     my @parts=split(/\//,$path);
                   12411:     my $cleanpath;
                   12412:     my $fullpath = $url;
                   12413:     for (my $i=0;$i<@parts;$i++) {
                   12414:         next if ($parts[$i] eq '.');
                   12415:         if ($parts[$i] eq '..') {
                   12416:             $fullpath =~ s{([^/]+/)$}{};
                   12417:         } else {
                   12418:             $fullpath .= $parts[$i].'/';
                   12419:         }
                   12420:     }
                   12421:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12422:         $cleanpath = $1;
                   12423:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12424:         my $curr_toprel = $1;
                   12425:         my @parts = split(/\//,$curr_toprel);
                   12426:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12427:         my @urlparts = split(/\//,$url_toprel);
                   12428:         my $doubledots;
                   12429:         my $startdiff = -1;
                   12430:         for (my $i=0; $i<@urlparts; $i++) {
                   12431:             if ($startdiff == -1) {
                   12432:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12433:                     $startdiff = $i;
                   12434:                     $doubledots .= '../';
                   12435:                 }
                   12436:             } else {
                   12437:                 $doubledots .= '../';
                   12438:             }
                   12439:         }
                   12440:         if ($startdiff > -1) {
                   12441:             $cleanpath = $doubledots;
                   12442:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12443:                 $cleanpath .= $parts[$i].'/';
                   12444:             }
                   12445:         }
                   12446:     }
                   12447:     $cleanpath =~ s{(/)$}{};
                   12448:     return $cleanpath;
                   12449: }
1.31      albertel 12450: 
1.1053    raeburn  12451: sub is_archive_file {
                   12452:     my ($mimetype) = @_;
                   12453:     if (($mimetype eq 'application/octet-stream') ||
                   12454:         ($mimetype eq 'application/x-stuffit') ||
                   12455:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12456:         return 1;
                   12457:     }
                   12458:     return;
                   12459: }
                   12460: 
                   12461: sub decompress_form {
1.1065    raeburn  12462:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12463:     my %lt = &Apache::lonlocal::texthash (
                   12464:         this => 'This file is an archive file.',
1.1067    raeburn  12465:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12466:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12467:         youm => 'You may wish to extract its contents.',
                   12468:         extr => 'Extract contents',
1.1067    raeburn  12469:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12470:         proa => 'Process automatically?',
1.1053    raeburn  12471:         yes  => 'Yes',
                   12472:         no   => 'No',
1.1067    raeburn  12473:         fold => 'Title for folder containing movie',
                   12474:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12475:     );
1.1065    raeburn  12476:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12477:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12478:     my $info = &list_archive_contents($fileloc,\@paths);
                   12479:     if (@paths) {
                   12480:         foreach my $path (@paths) {
                   12481:             $path =~ s{^/}{};
1.1067    raeburn  12482:             if ($path =~ m{^([^/]+)/$}) {
                   12483:                 $topdir = $1;
                   12484:             }
1.1065    raeburn  12485:             if ($path =~ m{^([^/]+)/}) {
                   12486:                 $toplevel{$1} = $path;
                   12487:             } else {
                   12488:                 $toplevel{$path} = $path;
                   12489:             }
                   12490:         }
                   12491:     }
1.1067    raeburn  12492:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12493:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12494:                         "$topdir/media/",
                   12495:                         "$topdir/media/$topdir.mp4",
                   12496:                         "$topdir/media/FirstFrame.png",
                   12497:                         "$topdir/media/player.swf",
                   12498:                         "$topdir/media/swfobject.js",
                   12499:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12500:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12501:                          "$topdir/$topdir.mp4",
                   12502:                          "$topdir/$topdir\_config.xml",
                   12503:                          "$topdir/$topdir\_controller.swf",
                   12504:                          "$topdir/$topdir\_embed.css",
                   12505:                          "$topdir/$topdir\_First_Frame.png",
                   12506:                          "$topdir/$topdir\_player.html",
                   12507:                          "$topdir/$topdir\_Thumbnails.png",
                   12508:                          "$topdir/playerProductInstall.swf",
                   12509:                          "$topdir/scripts/",
                   12510:                          "$topdir/scripts/config_xml.js",
                   12511:                          "$topdir/scripts/handlebars.js",
                   12512:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12513:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12514:                          "$topdir/scripts/modernizr.js",
                   12515:                          "$topdir/scripts/player-min.js",
                   12516:                          "$topdir/scripts/swfobject.js",
                   12517:                          "$topdir/skins/",
                   12518:                          "$topdir/skins/configuration_express.xml",
                   12519:                          "$topdir/skins/express_show/",
                   12520:                          "$topdir/skins/express_show/player-min.css",
                   12521:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12522:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12523:                          "$topdir/$topdir.mp4",
                   12524:                          "$topdir/$topdir\_config.xml",
                   12525:                          "$topdir/$topdir\_controller.swf",
                   12526:                          "$topdir/$topdir\_embed.css",
                   12527:                          "$topdir/$topdir\_First_Frame.png",
                   12528:                          "$topdir/$topdir\_player.html",
                   12529:                          "$topdir/$topdir\_Thumbnails.png",
                   12530:                          "$topdir/playerProductInstall.swf",
                   12531:                          "$topdir/scripts/",
                   12532:                          "$topdir/scripts/config_xml.js",
                   12533:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12534:                          "$topdir/skins/",
                   12535:                          "$topdir/skins/configuration_express.xml",
                   12536:                          "$topdir/skins/express_show/",
                   12537:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12538:                          "$topdir/skins/express_show/spritesheet.png",
                   12539:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12540:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12541:         if (@diffs == 0) {
1.1164    raeburn  12542:             $is_camtasia = 6;
                   12543:         } else {
1.1197    raeburn  12544:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12545:             if (@diffs == 0) {
                   12546:                 $is_camtasia = 8;
1.1197    raeburn  12547:             } else {
                   12548:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12549:                 if (@diffs == 0) {
                   12550:                     $is_camtasia = 8;
                   12551:                 }
1.1164    raeburn  12552:             }
1.1067    raeburn  12553:         }
                   12554:     }
                   12555:     my $output;
                   12556:     if ($is_camtasia) {
                   12557:         $output = <<"ENDCAM";
                   12558: <script type="text/javascript" language="Javascript">
                   12559: // <![CDATA[
                   12560: 
                   12561: function camtasiaToggle() {
                   12562:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12563:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12564:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12565:                 document.getElementById('camtasia_titles').style.display='block';
                   12566:             } else {
                   12567:                 document.getElementById('camtasia_titles').style.display='none';
                   12568:             }
                   12569:         }
                   12570:     }
                   12571:     return;
                   12572: }
                   12573: 
                   12574: // ]]>
                   12575: </script>
                   12576: <p>$lt{'camt'}</p>
                   12577: ENDCAM
1.1065    raeburn  12578:     } else {
1.1067    raeburn  12579:         $output = '<p>'.$lt{'this'};
                   12580:         if ($info eq '') {
                   12581:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12582:         } else {
                   12583:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12584:                        '<div><pre>'.$info.'</pre></div>';
                   12585:         }
1.1065    raeburn  12586:     }
1.1067    raeburn  12587:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12588:     my $duplicates;
                   12589:     my $num = 0;
                   12590:     if (ref($dirlist) eq 'ARRAY') {
                   12591:         foreach my $item (@{$dirlist}) {
                   12592:             if (ref($item) eq 'ARRAY') {
                   12593:                 if (exists($toplevel{$item->[0]})) {
                   12594:                     $duplicates .= 
                   12595:                         &start_data_table_row().
                   12596:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12597:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12598:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12599:                         'value="1" />'.&mt('Yes').'</label>'.
                   12600:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12601:                         '<td>'.$item->[0].'</td>';
                   12602:                     if ($item->[2]) {
                   12603:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12604:                     } else {
                   12605:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12606:                     }
                   12607:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12608:                                    '<td>'.
                   12609:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12610:                                    '</td>'.
                   12611:                                    &end_data_table_row();
                   12612:                     $num ++;
                   12613:                 }
                   12614:             }
                   12615:         }
                   12616:     }
                   12617:     my $itemcount;
                   12618:     if (@paths > 0) {
                   12619:         $itemcount = scalar(@paths);
                   12620:     } else {
                   12621:         $itemcount = 1;
                   12622:     }
1.1067    raeburn  12623:     if ($is_camtasia) {
                   12624:         $output .= $lt{'auto'}.'<br />'.
                   12625:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12626:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12627:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12628:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12629:                    $lt{'no'}.'</label></span><br />'.
                   12630:                    '<div id="camtasia_titles" style="display:block">'.
                   12631:                    &Apache::lonhtmlcommon::start_pick_box().
                   12632:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12633:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12634:                    &Apache::lonhtmlcommon::row_closure().
                   12635:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12636:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12637:                    &Apache::lonhtmlcommon::row_closure(1).
                   12638:                    &Apache::lonhtmlcommon::end_pick_box().
                   12639:                    '</div>';
                   12640:     }
1.1065    raeburn  12641:     $output .= 
                   12642:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12643:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12644:         "\n";
1.1065    raeburn  12645:     if ($duplicates ne '') {
                   12646:         $output .= '<p><span class="LC_warning">'.
                   12647:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12648:                    &start_data_table().
                   12649:                    &start_data_table_header_row().
                   12650:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12651:                    '<th>'.&mt('Name').'</th>'.
                   12652:                    '<th>'.&mt('Type').'</th>'.
                   12653:                    '<th>'.&mt('Size').'</th>'.
                   12654:                    '<th>'.&mt('Last modified').'</th>'.
                   12655:                    &end_data_table_header_row().
                   12656:                    $duplicates.
                   12657:                    &end_data_table().
                   12658:                    '</p>';
                   12659:     }
1.1067    raeburn  12660:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12661:     if (ref($hiddenelements) eq 'HASH') {
                   12662:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12663:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12664:         }
                   12665:     }
                   12666:     $output .= <<"END";
1.1067    raeburn  12667: <br />
1.1053    raeburn  12668: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12669: </form>
                   12670: $noextract
                   12671: END
                   12672:     return $output;
                   12673: }
                   12674: 
1.1065    raeburn  12675: sub decompression_utility {
                   12676:     my ($program) = @_;
                   12677:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12678:     my $location;
                   12679:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12680:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12681:                          '/usr/sbin/') {
                   12682:             if (-x $dir.$program) {
                   12683:                 $location = $dir.$program;
                   12684:                 last;
                   12685:             }
                   12686:         }
                   12687:     }
                   12688:     return $location;
                   12689: }
                   12690: 
                   12691: sub list_archive_contents {
                   12692:     my ($file,$pathsref) = @_;
                   12693:     my (@cmd,$output);
                   12694:     my $needsregexp;
                   12695:     if ($file =~ /\.zip$/) {
                   12696:         @cmd = (&decompression_utility('unzip'),"-l");
                   12697:         $needsregexp = 1;
                   12698:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12699:              ($file =~ /\.tgz$/)) {
                   12700:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12701:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12702:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12703:     } elsif ($file =~ m|\.tar$|) {
                   12704:         @cmd = (&decompression_utility('tar'),"-tf");
                   12705:     }
                   12706:     if (@cmd) {
                   12707:         undef($!);
                   12708:         undef($@);
                   12709:         if (open(my $fh,"-|", @cmd, $file)) {
                   12710:             while (my $line = <$fh>) {
                   12711:                 $output .= $line;
                   12712:                 chomp($line);
                   12713:                 my $item;
                   12714:                 if ($needsregexp) {
                   12715:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12716:                 } else {
                   12717:                     $item = $line;
                   12718:                 }
                   12719:                 if ($item ne '') {
                   12720:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12721:                         push(@{$pathsref},$item);
                   12722:                     } 
                   12723:                 }
                   12724:             }
                   12725:             close($fh);
                   12726:         }
                   12727:     }
                   12728:     return $output;
                   12729: }
                   12730: 
1.1053    raeburn  12731: sub decompress_uploaded_file {
                   12732:     my ($file,$dir) = @_;
                   12733:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12734:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12735:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12736:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12737:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12738:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12739:     my $decompressed = $env{'cgi.decompressed'};
                   12740:     &Apache::lonnet::delenv('cgi.file');
                   12741:     &Apache::lonnet::delenv('cgi.dir');
                   12742:     &Apache::lonnet::delenv('cgi.decompressed');
                   12743:     return ($decompressed,$result);
                   12744: }
                   12745: 
1.1055    raeburn  12746: sub process_decompression {
                   12747:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12748:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12749:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12750:                &mt('Unexpected file path.').'</p>'."\n";
                   12751:     }
                   12752:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12753:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12754:                &mt('Unexpected course context.').'</p>'."\n";
                   12755:     }
1.1293    raeburn  12756:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12757:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12758:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12759:     }
1.1055    raeburn  12760:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12761:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12762:         $error = &mt('Filename not a supported archive file type.').
                   12763:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12764:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12765:     } else {
                   12766:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12767:         if ($docuhome eq 'no_host') {
                   12768:             $error = &mt('Could not determine home server for course.');
                   12769:         } else {
                   12770:             my @ids=&Apache::lonnet::current_machine_ids();
                   12771:             my $currdir = "$dir_root/$destination";
                   12772:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12773:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12774:                        "$dir_root/$destination";
                   12775:             } else {
                   12776:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12777:                        "$dir_root/$docudom/$docuname/$destination";
                   12778:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12779:                     $error = &mt('Archive file not found.');
                   12780:                 }
                   12781:             }
1.1065    raeburn  12782:             my (@to_overwrite,@to_skip);
                   12783:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12784:                 my $total = $env{'form.archive_overwrite_total'};
                   12785:                 for (my $i=0; $i<$total; $i++) {
                   12786:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12787:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12788:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12789:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12790:                     }
                   12791:                 }
                   12792:             }
                   12793:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12794:             my $numoverwrite = scalar(@to_overwrite);
                   12795:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12796:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12797:             } elsif ($dir eq '') {
1.1055    raeburn  12798:                 $error = &mt('Directory containing archive file unavailable.');
                   12799:             } elsif (!$error) {
1.1065    raeburn  12800:                 my ($decompressed,$display);
1.1292    raeburn  12801:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12802:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12803:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12804:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12805:                         ($decompressed,$display) = 
                   12806:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12807:                         foreach my $item (@to_skip) {
                   12808:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12809:                                 if (-f "$dir/$tempdir/$item") { 
                   12810:                                     unlink("$dir/$tempdir/$item");
                   12811:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12812:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12813:                                 }
                   12814:                             }
                   12815:                         }
                   12816:                         foreach my $item (@to_overwrite) {
                   12817:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12818:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12819:                                     if (-f "$dir/$item") {
                   12820:                                         unlink("$dir/$item");
                   12821:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  12822:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  12823:                                     }
                   12824:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12825:                                 }
1.1065    raeburn  12826:                             }
                   12827:                         }
1.1292    raeburn  12828:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  12829:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  12830:                         }
1.1065    raeburn  12831:                     }
                   12832:                 } else {
                   12833:                     ($decompressed,$display) = 
                   12834:                         &decompress_uploaded_file($file,$dir);
                   12835:                 }
1.1055    raeburn  12836:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12837:                     $output = '<p class="LC_info">'.
                   12838:                               &mt('Files extracted successfully from archive.').
                   12839:                               '</p>'."\n";
1.1055    raeburn  12840:                     my ($warning,$result,@contents);
                   12841:                     my ($newdirlistref,$newlisterror) =
                   12842:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12843:                                                  $docuname,1);
                   12844:                     my (%is_dir,%changes,@newitems);
                   12845:                     my $dirptr = 16384;
1.1065    raeburn  12846:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12847:                         foreach my $dir_line (@{$newdirlistref}) {
                   12848:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  12849:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  12850:                                 push(@newitems,$item);
                   12851:                                 if ($dirptr&$testdir) {
                   12852:                                     $is_dir{$item} = 1;
                   12853:                                 }
                   12854:                                 $changes{$item} = 1;
                   12855:                             }
                   12856:                         }
                   12857:                     }
                   12858:                     if (keys(%changes) > 0) {
                   12859:                         foreach my $item (sort(@newitems)) {
                   12860:                             if ($changes{$item}) {
                   12861:                                 push(@contents,$item);
                   12862:                             }
                   12863:                         }
                   12864:                     }
                   12865:                     if (@contents > 0) {
1.1067    raeburn  12866:                         my $wantform;
                   12867:                         unless ($env{'form.autoextract_camtasia'}) {
                   12868:                             $wantform = 1;
                   12869:                         }
1.1056    raeburn  12870:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12871:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12872:                                                                 $currdir,\%is_dir,
                   12873:                                                                 \%children,\%parent,
1.1056    raeburn  12874:                                                                 \@contents,\%dirorder,
                   12875:                                                                 \%titles,$wantform);
1.1055    raeburn  12876:                         if ($datatable ne '') {
                   12877:                             $output .= &archive_options_form('decompressed',$datatable,
                   12878:                                                              $count,$hiddenelem);
1.1065    raeburn  12879:                             my $startcount = 6;
1.1055    raeburn  12880:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12881:                                                            \%titles,\%children);
1.1055    raeburn  12882:                         }
1.1067    raeburn  12883:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12884:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12885:                             my %displayed;
                   12886:                             my $total = 1;
                   12887:                             $env{'form.archive_directory'} = [];
                   12888:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12889:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12890:                                 $path =~ s{/$}{};
                   12891:                                 my $item;
                   12892:                                 if ($path ne '') {
                   12893:                                     $item = "$path/$titles{$i}";
                   12894:                                 } else {
                   12895:                                     $item = $titles{$i};
                   12896:                                 }
                   12897:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12898:                                 if ($item eq $contents[0]) {
                   12899:                                     push(@{$env{'form.archive_directory'}},$i);
                   12900:                                     $env{'form.archive_'.$i} = 'display';
                   12901:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12902:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12903:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12904:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12905:                                     $env{'form.archive_'.$i} = 'display';
                   12906:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12907:                                     $displayed{'web'} = $i;
                   12908:                                 } else {
1.1164    raeburn  12909:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12910:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12911:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12912:                                         push(@{$env{'form.archive_directory'}},$i);
                   12913:                                     }
                   12914:                                     $env{'form.archive_'.$i} = 'dependency';
                   12915:                                 }
                   12916:                                 $total ++;
                   12917:                             }
                   12918:                             for (my $i=1; $i<$total; $i++) {
                   12919:                                 next if ($i == $displayed{'web'});
                   12920:                                 next if ($i == $displayed{'folder'});
                   12921:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12922:                             }
                   12923:                             $env{'form.phase'} = 'decompress_cleanup';
                   12924:                             $env{'form.archivedelete'} = 1;
                   12925:                             $env{'form.archive_count'} = $total-1;
                   12926:                             $output .=
                   12927:                                 &process_extracted_files('coursedocs',$docudom,
                   12928:                                                          $docuname,$destination,
                   12929:                                                          $dir_root,$hiddenelem);
                   12930:                         }
1.1055    raeburn  12931:                     } else {
                   12932:                         $warning = &mt('No new items extracted from archive file.');
                   12933:                     }
                   12934:                 } else {
                   12935:                     $output = $display;
                   12936:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12937:                 }
                   12938:             }
                   12939:         }
                   12940:     }
                   12941:     if ($error) {
                   12942:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12943:                    $error.'</p>'."\n";
                   12944:     }
                   12945:     if ($warning) {
                   12946:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12947:     }
                   12948:     return $output;
                   12949: }
                   12950: 
                   12951: sub get_extracted {
1.1056    raeburn  12952:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12953:         $titles,$wantform) = @_;
1.1055    raeburn  12954:     my $count = 0;
                   12955:     my $depth = 0;
                   12956:     my $datatable;
1.1056    raeburn  12957:     my @hierarchy;
1.1055    raeburn  12958:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12959:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12960:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12961:     foreach my $item (@{$contents}) {
                   12962:         $count ++;
1.1056    raeburn  12963:         @{$dirorder->{$count}} = @hierarchy;
                   12964:         $titles->{$count} = $item;
1.1055    raeburn  12965:         &archive_hierarchy($depth,$count,$parent,$children);
                   12966:         if ($wantform) {
                   12967:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12968:                                        $currdir,$depth,$count);
                   12969:         }
                   12970:         if ($is_dir->{$item}) {
                   12971:             $depth ++;
1.1056    raeburn  12972:             push(@hierarchy,$count);
                   12973:             $parent->{$depth} = $count;
1.1055    raeburn  12974:             $datatable .=
                   12975:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12976:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12977:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12978:             $depth --;
1.1056    raeburn  12979:             pop(@hierarchy);
1.1055    raeburn  12980:         }
                   12981:     }
                   12982:     return ($count,$datatable);
                   12983: }
                   12984: 
                   12985: sub recurse_extracted_archive {
1.1056    raeburn  12986:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12987:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12988:     my $result='';
1.1056    raeburn  12989:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12990:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12991:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12992:         return $result;
                   12993:     }
                   12994:     my $dirptr = 16384;
                   12995:     my ($newdirlistref,$newlisterror) =
                   12996:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12997:     if (ref($newdirlistref) eq 'ARRAY') {
                   12998:         foreach my $dir_line (@{$newdirlistref}) {
                   12999:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13000:             unless ($item =~ /^\.+$/) {
                   13001:                 $$count ++;
1.1056    raeburn  13002:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13003:                 $titles->{$$count} = $item;
1.1055    raeburn  13004:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13005: 
1.1055    raeburn  13006:                 my $is_dir;
                   13007:                 if ($dirptr&$testdir) {
                   13008:                     $is_dir = 1;
                   13009:                 }
                   13010:                 if ($wantform) {
                   13011:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13012:                 }
                   13013:                 if ($is_dir) {
                   13014:                     $$depth ++;
1.1056    raeburn  13015:                     push(@{$hierarchy},$$count);
                   13016:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13017:                     $result .=
                   13018:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13019:                                                    $docuname,$depth,$count,
1.1056    raeburn  13020:                                                    $hierarchy,$dirorder,$children,
                   13021:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13022:                     $$depth --;
1.1056    raeburn  13023:                     pop(@{$hierarchy});
1.1055    raeburn  13024:                 }
                   13025:             }
                   13026:         }
                   13027:     }
                   13028:     return $result;
                   13029: }
                   13030: 
                   13031: sub archive_hierarchy {
                   13032:     my ($depth,$count,$parent,$children) =@_;
                   13033:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13034:         if (exists($parent->{$depth})) {
                   13035:              $children->{$parent->{$depth}} .= $count.':';
                   13036:         }
                   13037:     }
                   13038:     return;
                   13039: }
                   13040: 
                   13041: sub archive_row {
                   13042:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13043:     my ($name) = ($item =~ m{([^/]+)$});
                   13044:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13045:                                        'display'    => 'Add as file',
1.1055    raeburn  13046:                                        'dependency' => 'Include as dependency',
                   13047:                                        'discard'    => 'Discard',
                   13048:                                       );
                   13049:     if ($is_dir) {
1.1059    raeburn  13050:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13051:     }
1.1056    raeburn  13052:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13053:     my $offset = 0;
1.1055    raeburn  13054:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13055:         $offset ++;
1.1065    raeburn  13056:         if ($action ne 'display') {
                   13057:             $offset ++;
                   13058:         }  
1.1055    raeburn  13059:         $output .= '<td><span class="LC_nobreak">'.
                   13060:                    '<label><input type="radio" name="archive_'.$count.
                   13061:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13062:         my $text = $choices{$action};
                   13063:         if ($is_dir) {
                   13064:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13065:             if ($action eq 'display') {
1.1059    raeburn  13066:                 $text = &mt('Add as folder');
1.1055    raeburn  13067:             }
1.1056    raeburn  13068:         } else {
                   13069:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13070: 
                   13071:         }
                   13072:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13073:         if ($action eq 'dependency') {
                   13074:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13075:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13076:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13077:                        '<option value=""></option>'."\n".
                   13078:                        '</select>'."\n".
                   13079:                        '</div>';
1.1059    raeburn  13080:         } elsif ($action eq 'display') {
                   13081:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13082:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13083:                        '</div>';
1.1055    raeburn  13084:         }
1.1056    raeburn  13085:         $output .= '</td>';
1.1055    raeburn  13086:     }
                   13087:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13088:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13089:     for (my $i=0; $i<$depth; $i++) {
                   13090:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13091:     }
                   13092:     if ($is_dir) {
                   13093:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13094:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13095:     } else {
                   13096:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13097:     }
                   13098:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13099:                &end_data_table_row();
                   13100:     return $output;
                   13101: }
                   13102: 
                   13103: sub archive_options_form {
1.1065    raeburn  13104:     my ($form,$display,$count,$hiddenelem) = @_;
                   13105:     my %lt = &Apache::lonlocal::texthash(
                   13106:                perm => 'Permanently remove archive file?',
                   13107:                hows => 'How should each extracted item be incorporated in the course?',
                   13108:                cont => 'Content actions for all',
                   13109:                addf => 'Add as folder/file',
                   13110:                incd => 'Include as dependency for a displayed file',
                   13111:                disc => 'Discard',
                   13112:                no   => 'No',
                   13113:                yes  => 'Yes',
                   13114:                save => 'Save',
                   13115:     );
                   13116:     my $output = <<"END";
                   13117: <form name="$form" method="post" action="">
                   13118: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13119: <label>
                   13120:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13121: </label>
                   13122: &nbsp;
                   13123: <label>
                   13124:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13125: </span>
                   13126: </p>
                   13127: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13128: <br />$lt{'hows'}
                   13129: <div class="LC_columnSection">
                   13130:   <fieldset>
                   13131:     <legend>$lt{'cont'}</legend>
                   13132:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13133:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13134:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13135:   </fieldset>
                   13136: </div>
                   13137: END
                   13138:     return $output.
1.1055    raeburn  13139:            &start_data_table()."\n".
1.1065    raeburn  13140:            $display."\n".
1.1055    raeburn  13141:            &end_data_table()."\n".
                   13142:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13143:            $hiddenelem.
1.1065    raeburn  13144:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13145:            '</form>';
                   13146: }
                   13147: 
                   13148: sub archive_javascript {
1.1056    raeburn  13149:     my ($startcount,$numitems,$titles,$children) = @_;
                   13150:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13151:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13152:     my $scripttag = <<START;
                   13153: <script type="text/javascript">
                   13154: // <![CDATA[
                   13155: 
                   13156: function checkAll(form,prefix) {
                   13157:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13158:     for (var i=0; i < form.elements.length; i++) {
                   13159:         var id = form.elements[i].id;
                   13160:         if ((id != '') && (id != undefined)) {
                   13161:             if (idstr.test(id)) {
                   13162:                 if (form.elements[i].type == 'radio') {
                   13163:                     form.elements[i].checked = true;
1.1056    raeburn  13164:                     var nostart = i-$startcount;
1.1059    raeburn  13165:                     var offset = nostart%7;
                   13166:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13167:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13168:                 }
                   13169:             }
                   13170:         }
                   13171:     }
                   13172: }
                   13173: 
                   13174: function propagateCheck(form,count) {
                   13175:     if (count > 0) {
1.1059    raeburn  13176:         var startelement = $startcount + ((count-1) * 7);
                   13177:         for (var j=1; j<6; j++) {
                   13178:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13179:                 var item = startelement + j; 
                   13180:                 if (form.elements[item].type == 'radio') {
                   13181:                     if (form.elements[item].checked) {
                   13182:                         containerCheck(form,count,j);
                   13183:                         break;
                   13184:                     }
1.1055    raeburn  13185:                 }
                   13186:             }
                   13187:         }
                   13188:     }
                   13189: }
                   13190: 
                   13191: numitems = $numitems
1.1056    raeburn  13192: var titles = new Array(numitems);
                   13193: var parents = new Array(numitems);
1.1055    raeburn  13194: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13195:     parents[i] = new Array;
1.1055    raeburn  13196: }
1.1059    raeburn  13197: var maintitle = '$maintitle';
1.1055    raeburn  13198: 
                   13199: START
                   13200: 
1.1056    raeburn  13201:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13202:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13203:         for (my $i=0; $i<@contents; $i ++) {
                   13204:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13205:         }
                   13206:     }
                   13207: 
1.1056    raeburn  13208:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13209:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13210:     }
                   13211: 
1.1055    raeburn  13212:     $scripttag .= <<END;
                   13213: 
                   13214: function containerCheck(form,count,offset) {
                   13215:     if (count > 0) {
1.1056    raeburn  13216:         dependencyCheck(form,count,offset);
1.1059    raeburn  13217:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13218:         form.elements[item].checked = true;
                   13219:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13220:             if (parents[count].length > 0) {
                   13221:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13222:                     containerCheck(form,parents[count][j],offset);
                   13223:                 }
                   13224:             }
                   13225:         }
                   13226:     }
                   13227: }
                   13228: 
                   13229: function dependencyCheck(form,count,offset) {
                   13230:     if (count > 0) {
1.1059    raeburn  13231:         var chosen = (offset+$startcount)+7*(count-1);
                   13232:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13233:         var currtype = form.elements[depitem].type;
                   13234:         if (form.elements[chosen].value == 'dependency') {
                   13235:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13236:             form.elements[depitem].options.length = 0;
                   13237:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13238:             for (var i=1; i<=numitems; i++) {
                   13239:                 if (i == count) {
                   13240:                     continue;
                   13241:                 }
1.1059    raeburn  13242:                 var startelement = $startcount + (i-1) * 7;
                   13243:                 for (var j=1; j<6; j++) {
                   13244:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13245:                         var item = startelement + j;
                   13246:                         if (form.elements[item].type == 'radio') {
                   13247:                             if (form.elements[item].checked) {
                   13248:                                 if (form.elements[item].value == 'display') {
                   13249:                                     var n = form.elements[depitem].options.length;
                   13250:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13251:                                 }
                   13252:                             }
                   13253:                         }
                   13254:                     }
                   13255:                 }
                   13256:             }
                   13257:         } else {
                   13258:             document.getElementById('arc_depon_'+count).style.display='none';
                   13259:             form.elements[depitem].options.length = 0;
                   13260:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13261:         }
1.1059    raeburn  13262:         titleCheck(form,count,offset);
1.1056    raeburn  13263:     }
                   13264: }
                   13265: 
                   13266: function propagateSelect(form,count,offset) {
                   13267:     if (count > 0) {
1.1065    raeburn  13268:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13269:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13270:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13271:             if (parents[count].length > 0) {
                   13272:                 for (var j=0; j<parents[count].length; j++) {
                   13273:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13274:                 }
                   13275:             }
                   13276:         }
                   13277:     }
                   13278: }
1.1056    raeburn  13279: 
                   13280: function containerSelect(form,count,offset,picked) {
                   13281:     if (count > 0) {
1.1065    raeburn  13282:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13283:         if (form.elements[item].type == 'radio') {
                   13284:             if (form.elements[item].value == 'dependency') {
                   13285:                 if (form.elements[item+1].type == 'select-one') {
                   13286:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13287:                         if (form.elements[item+1].options[i].value == picked) {
                   13288:                             form.elements[item+1].selectedIndex = i;
                   13289:                             break;
                   13290:                         }
                   13291:                     }
                   13292:                 }
                   13293:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13294:                     if (parents[count].length > 0) {
                   13295:                         for (var j=0; j<parents[count].length; j++) {
                   13296:                             containerSelect(form,parents[count][j],offset,picked);
                   13297:                         }
                   13298:                     }
                   13299:                 }
                   13300:             }
                   13301:         }
                   13302:     }
                   13303: }
                   13304: 
1.1059    raeburn  13305: function titleCheck(form,count,offset) {
                   13306:     if (count > 0) {
                   13307:         var chosen = (offset+$startcount)+7*(count-1);
                   13308:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13309:         var currtype = form.elements[depitem].type;
                   13310:         if (form.elements[chosen].value == 'display') {
                   13311:             document.getElementById('arc_title_'+count).style.display='block';
                   13312:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13313:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13314:             }
                   13315:         } else {
                   13316:             document.getElementById('arc_title_'+count).style.display='none';
                   13317:             if (currtype == 'text') { 
                   13318:                 document.getElementById('archive_title_'+count).value='';
                   13319:             }
                   13320:         }
                   13321:     }
                   13322:     return;
                   13323: }
                   13324: 
1.1055    raeburn  13325: // ]]>
                   13326: </script>
                   13327: END
                   13328:     return $scripttag;
                   13329: }
                   13330: 
                   13331: sub process_extracted_files {
1.1067    raeburn  13332:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13333:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13334:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13335:     my @ids=&Apache::lonnet::current_machine_ids();
                   13336:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13337:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13338:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13339:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13340:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13341:         $pathtocheck = "$dir_root/$destination";
                   13342:         $dir = $dir_root;
                   13343:         $ishome = 1;
                   13344:     } else {
                   13345:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13346:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13347:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13348:     }
                   13349:     my $currdir = "$dir_root/$destination";
                   13350:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13351:     if ($env{'form.folderpath'}) {
                   13352:         my @items = split('&',$env{'form.folderpath'});
                   13353:         $folders{'0'} = $items[-2];
1.1099    raeburn  13354:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13355:             $containers{'0'}='page';
                   13356:         } else {  
                   13357:             $containers{'0'}='sequence';
                   13358:         }
1.1055    raeburn  13359:     }
                   13360:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13361:     if ($numitems) {
                   13362:         for (my $i=1; $i<=$numitems; $i++) {
                   13363:             my $path = $env{'form.archive_content_'.$i};
                   13364:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13365:                 my $item = $1;
                   13366:                 $toplevelitems{$item} = $i;
                   13367:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13368:                     $is_dir{$item} = 1;
                   13369:                 }
                   13370:             }
                   13371:         }
                   13372:     }
1.1067    raeburn  13373:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13374:     if (keys(%toplevelitems) > 0) {
                   13375:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13376:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13377:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13378:     }
1.1066    raeburn  13379:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13380:     if ($numitems) {
                   13381:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13382:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13383:             my $path = $env{'form.archive_content_'.$i};
                   13384:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13385:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13386:                     if ($prefix ne '' && $path ne '') {
                   13387:                         if (-e $prefix.$path) {
1.1066    raeburn  13388:                             if ((@archdirs > 0) && 
                   13389:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13390:                                 $todeletedir{$prefix.$path} = 1;
                   13391:                             } else {
                   13392:                                 $todelete{$prefix.$path} = 1;
                   13393:                             }
1.1055    raeburn  13394:                         }
                   13395:                     }
                   13396:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13397:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13398:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13399:                     $docstitle = $env{'form.archive_title_'.$i};
                   13400:                     if ($docstitle eq '') {
                   13401:                         $docstitle = $title;
                   13402:                     }
1.1055    raeburn  13403:                     $outer = 0;
1.1056    raeburn  13404:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13405:                         if (@{$dirorder{$i}} > 0) {
                   13406:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13407:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13408:                                     $outer = $item;
                   13409:                                     last;
                   13410:                                 }
                   13411:                             }
                   13412:                         }
                   13413:                     }
                   13414:                     my ($errtext,$fatal) = 
                   13415:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13416:                                                '/'.$folders{$outer}.'.'.
                   13417:                                                $containers{$outer});
                   13418:                     next if ($fatal);
                   13419:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13420:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13421:                             $mapinner{$i} = time;
1.1055    raeburn  13422:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13423:                             $containers{$i} = 'sequence';
                   13424:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13425:                                       $folders{$i}.'.'.$containers{$i};
                   13426:                             my $newidx = &LONCAPA::map::getresidx();
                   13427:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13428:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13429:                             push(@LONCAPA::map::order,$newidx);
                   13430:                             my ($outtext,$errtext) =
                   13431:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13432:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13433:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13434:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13435:                             unless ($errtext) {
1.1294    raeburn  13436:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13437:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13438:                                             '</li>'."\n";
1.1067    raeburn  13439:                             }
1.1055    raeburn  13440:                         }
                   13441:                     } else {
                   13442:                         if ($context eq 'coursedocs') {
                   13443:                             my $newidx=&LONCAPA::map::getresidx();
                   13444:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13445:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13446:                                       $title;
1.1294    raeburn  13447:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13448:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13449:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13450:                                 }
                   13451:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13452:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13453:                                 }
                   13454:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13455:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13456:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13457:                                         unless ($ishome) {
                   13458:                                             my $fetch = "$newdest{$i}/$title";
                   13459:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13460:                                             $prompttofetch{$fetch} = 1;
                   13461:                                         }
1.1292    raeburn  13462:                                     }
1.1067    raeburn  13463:                                 }
1.1294    raeburn  13464:                                 $LONCAPA::map::resources[$newidx]=
                   13465:                                     $docstitle.':'.$url.':false:normal:res';
                   13466:                                 push(@LONCAPA::map::order, $newidx);
                   13467:                                 my ($outtext,$errtext)=
                   13468:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13469:                                                             $docuname.'/'.$folders{$outer}.
                   13470:                                                             '.'.$containers{$outer},1,1);
                   13471:                                 unless ($errtext) {
                   13472:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13473:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13474:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13475:                                                    '</li>'."\n";
                   13476:                                     }
1.1067    raeburn  13477:                                 }
1.1294    raeburn  13478:                             } else {
                   13479:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13480:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13481:                             }
1.1055    raeburn  13482:                         }
                   13483:                     }
1.1086    raeburn  13484:                 }
                   13485:             } else {
1.1294    raeburn  13486:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13487:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13488:             }
                   13489:         }
                   13490:         for (my $i=1; $i<=$numitems; $i++) {
                   13491:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13492:             my $path = $env{'form.archive_content_'.$i};
                   13493:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13494:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13495:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13496:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13497:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13498:                         my ($itemidx,$fullpath,$relpath);
                   13499:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13500:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13501:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13502:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13503:                                     $itemidx = $j;
1.1056    raeburn  13504:                                 }
                   13505:                             }
1.1086    raeburn  13506:                         }
                   13507:                         if ($itemidx eq '') {
                   13508:                             $itemidx =  0;
                   13509:                         } 
                   13510:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13511:                             if ($mapinner{$referrer{$i}}) {
                   13512:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13513:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13514:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13515:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13516:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13517:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13518:                                             if (!-e $fullpath) {
                   13519:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13520:                                             }
                   13521:                                         }
1.1086    raeburn  13522:                                     } else {
                   13523:                                         last;
1.1056    raeburn  13524:                                     }
1.1086    raeburn  13525:                                 }
                   13526:                             }
                   13527:                         } elsif ($newdest{$referrer{$i}}) {
                   13528:                             $fullpath = $newdest{$referrer{$i}};
                   13529:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13530:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13531:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13532:                                     last;
                   13533:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13534:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13535:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13536:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13537:                                         if (!-e $fullpath) {
                   13538:                                             mkdir($fullpath,0755);
1.1056    raeburn  13539:                                         }
                   13540:                                     }
1.1086    raeburn  13541:                                 } else {
                   13542:                                     last;
1.1056    raeburn  13543:                                 }
1.1055    raeburn  13544:                             }
                   13545:                         }
1.1086    raeburn  13546:                         if ($fullpath ne '') {
                   13547:                             if (-e "$prefix$path") {
1.1292    raeburn  13548:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13549:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13550:                                 }
1.1086    raeburn  13551:                             }
                   13552:                             if (-e "$fullpath/$title") {
                   13553:                                 my $showpath;
                   13554:                                 if ($relpath ne '') {
                   13555:                                     $showpath = "$relpath/$title";
                   13556:                                 } else {
                   13557:                                     $showpath = "/$title";
                   13558:                                 } 
1.1294    raeburn  13559:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13560:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13561:                                            '</li>'."\n";
1.1292    raeburn  13562:                                 unless ($ishome) {
                   13563:                                     my $fetch = "$fullpath/$title";
                   13564:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13565:                                     $prompttofetch{$fetch} = 1;
                   13566:                                 }
1.1086    raeburn  13567:                             }
                   13568:                         }
1.1055    raeburn  13569:                     }
1.1086    raeburn  13570:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13571:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13572:                                     &HTML::Entities::encode($path,'<>&"'),
                   13573:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13574:                                 '<br />';
1.1055    raeburn  13575:                 }
                   13576:             } else {
1.1294    raeburn  13577:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13578:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13579:             }
                   13580:         }
                   13581:         if (keys(%todelete)) {
                   13582:             foreach my $key (keys(%todelete)) {
                   13583:                 unlink($key);
1.1066    raeburn  13584:             }
                   13585:         }
                   13586:         if (keys(%todeletedir)) {
                   13587:             foreach my $key (keys(%todeletedir)) {
                   13588:                 rmdir($key);
                   13589:             }
                   13590:         }
                   13591:         foreach my $dir (sort(keys(%is_dir))) {
                   13592:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13593:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13594:             }
                   13595:         }
1.1067    raeburn  13596:         if ($result ne '') {
                   13597:             $output .= '<ul>'."\n".
                   13598:                        $result."\n".
                   13599:                        '</ul>';
                   13600:         }
                   13601:         unless ($ishome) {
                   13602:             my $replicationfail;
                   13603:             foreach my $item (keys(%prompttofetch)) {
                   13604:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13605:                 unless ($fetchresult eq 'ok') {
                   13606:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13607:                 }
                   13608:             }
                   13609:             if ($replicationfail) {
                   13610:                 $output .= '<p class="LC_error">'.
                   13611:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13612:                            $replicationfail.
                   13613:                            '</ul></p>';
                   13614:             }
                   13615:         }
1.1055    raeburn  13616:     } else {
                   13617:         $warning = &mt('No items found in archive.');
                   13618:     }
                   13619:     if ($error) {
                   13620:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13621:                    $error.'</p>'."\n";
                   13622:     }
                   13623:     if ($warning) {
                   13624:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13625:     }
                   13626:     return $output;
                   13627: }
                   13628: 
1.1066    raeburn  13629: sub cleanup_empty_dirs {
                   13630:     my ($path) = @_;
                   13631:     if (($path ne '') && (-d $path)) {
                   13632:         if (opendir(my $dirh,$path)) {
                   13633:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13634:             my $numitems = 0;
                   13635:             foreach my $item (@dircontents) {
                   13636:                 if (-d "$path/$item") {
1.1111    raeburn  13637:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13638:                     if (-e "$path/$item") {
                   13639:                         $numitems ++;
                   13640:                     }
                   13641:                 } else {
                   13642:                     $numitems ++;
                   13643:                 }
                   13644:             }
                   13645:             if ($numitems == 0) {
                   13646:                 rmdir($path);
                   13647:             }
                   13648:             closedir($dirh);
                   13649:         }
                   13650:     }
                   13651:     return;
                   13652: }
                   13653: 
1.41      ng       13654: =pod
1.45      matthew  13655: 
1.1162    raeburn  13656: =item * &get_folder_hierarchy()
1.1068    raeburn  13657: 
                   13658: Provides hierarchy of names of folders/sub-folders containing the current
                   13659: item,
                   13660: 
                   13661: Inputs: 3
                   13662:      - $navmap - navmaps object
                   13663: 
                   13664:      - $map - url for map (either the trigger itself, or map containing
                   13665:                            the resource, which is the trigger).
                   13666: 
                   13667:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13668: 
                   13669: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13670: 
                   13671: =cut
                   13672: 
                   13673: sub get_folder_hierarchy {
                   13674:     my ($navmap,$map,$showitem) = @_;
                   13675:     my @pathitems;
                   13676:     if (ref($navmap)) {
                   13677:         my $mapres = $navmap->getResourceByUrl($map);
                   13678:         if (ref($mapres)) {
                   13679:             my $pcslist = $mapres->map_hierarchy();
                   13680:             if ($pcslist ne '') {
                   13681:                 my @pcs = split(/,/,$pcslist);
                   13682:                 foreach my $pc (@pcs) {
                   13683:                     if ($pc == 1) {
1.1129    raeburn  13684:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13685:                     } else {
                   13686:                         my $res = $navmap->getByMapPc($pc);
                   13687:                         if (ref($res)) {
                   13688:                             my $title = $res->compTitle();
                   13689:                             $title =~ s/\W+/_/g;
                   13690:                             if ($title ne '') {
                   13691:                                 push(@pathitems,$title);
                   13692:                             }
                   13693:                         }
                   13694:                     }
                   13695:                 }
                   13696:             }
1.1071    raeburn  13697:             if ($showitem) {
                   13698:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13699:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13700:                 } else {
                   13701:                     my $maptitle = $mapres->compTitle();
                   13702:                     $maptitle =~ s/\W+/_/g;
                   13703:                     if ($maptitle ne '') {
                   13704:                         push(@pathitems,$maptitle);
                   13705:                     }
1.1068    raeburn  13706:                 }
                   13707:             }
                   13708:         }
                   13709:     }
                   13710:     return @pathitems;
                   13711: }
                   13712: 
                   13713: =pod
                   13714: 
1.1015    raeburn  13715: =item * &get_turnedin_filepath()
                   13716: 
                   13717: Determines path in a user's portfolio file for storage of files uploaded
                   13718: to a specific essayresponse or dropbox item.
                   13719: 
                   13720: Inputs: 3 required + 1 optional.
                   13721: $symb is symb for resource, $uname and $udom are for current user (required).
                   13722: $caller is optional (can be "submission", if routine is called when storing
                   13723: an upoaded file when "Submit Answer" button was pressed).
                   13724: 
                   13725: Returns array containing $path and $multiresp. 
                   13726: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13727: than one file upload item.  Callers of routine should append partid as a 
                   13728: subdirectory to $path in cases where $multiresp is 1.
                   13729: 
                   13730: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13731: 
                   13732: =cut
                   13733: 
                   13734: sub get_turnedin_filepath {
                   13735:     my ($symb,$uname,$udom,$caller) = @_;
                   13736:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13737:     my $turnindir;
                   13738:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13739:     $turnindir = $userhash{'turnindir'};
                   13740:     my ($path,$multiresp);
                   13741:     if ($turnindir eq '') {
                   13742:         if ($caller eq 'submission') {
                   13743:             $turnindir = &mt('turned in');
                   13744:             $turnindir =~ s/\W+/_/g;
                   13745:             my %newhash = (
                   13746:                             'turnindir' => $turnindir,
                   13747:                           );
                   13748:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13749:         }
                   13750:     }
                   13751:     if ($turnindir ne '') {
                   13752:         $path = '/'.$turnindir.'/';
                   13753:         my ($multipart,$turnin,@pathitems);
                   13754:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13755:         if (defined($navmap)) {
                   13756:             my $mapres = $navmap->getResourceByUrl($map);
                   13757:             if (ref($mapres)) {
                   13758:                 my $pcslist = $mapres->map_hierarchy();
                   13759:                 if ($pcslist ne '') {
                   13760:                     foreach my $pc (split(/,/,$pcslist)) {
                   13761:                         my $res = $navmap->getByMapPc($pc);
                   13762:                         if (ref($res)) {
                   13763:                             my $title = $res->compTitle();
                   13764:                             $title =~ s/\W+/_/g;
                   13765:                             if ($title ne '') {
1.1149    raeburn  13766:                                 if (($pc > 1) && (length($title) > 12)) {
                   13767:                                     $title = substr($title,0,12);
                   13768:                                 }
1.1015    raeburn  13769:                                 push(@pathitems,$title);
                   13770:                             }
                   13771:                         }
                   13772:                     }
                   13773:                 }
                   13774:                 my $maptitle = $mapres->compTitle();
                   13775:                 $maptitle =~ s/\W+/_/g;
                   13776:                 if ($maptitle ne '') {
1.1149    raeburn  13777:                     if (length($maptitle) > 12) {
                   13778:                         $maptitle = substr($maptitle,0,12);
                   13779:                     }
1.1015    raeburn  13780:                     push(@pathitems,$maptitle);
                   13781:                 }
                   13782:                 unless ($env{'request.state'} eq 'construct') {
                   13783:                     my $res = $navmap->getBySymb($symb);
                   13784:                     if (ref($res)) {
                   13785:                         my $partlist = $res->parts();
                   13786:                         my $totaluploads = 0;
                   13787:                         if (ref($partlist) eq 'ARRAY') {
                   13788:                             foreach my $part (@{$partlist}) {
                   13789:                                 my @types = $res->responseType($part);
                   13790:                                 my @ids = $res->responseIds($part);
                   13791:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13792:                                     if ($types[$i] eq 'essay') {
                   13793:                                         my $partid = $part.'_'.$ids[$i];
                   13794:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13795:                                             $totaluploads ++;
                   13796:                                         }
                   13797:                                     }
                   13798:                                 }
                   13799:                             }
                   13800:                             if ($totaluploads > 1) {
                   13801:                                 $multiresp = 1;
                   13802:                             }
                   13803:                         }
                   13804:                     }
                   13805:                 }
                   13806:             } else {
                   13807:                 return;
                   13808:             }
                   13809:         } else {
                   13810:             return;
                   13811:         }
                   13812:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13813:         $restitle =~ s/\W+/_/g;
                   13814:         if ($restitle eq '') {
                   13815:             $restitle = ($resurl =~ m{/[^/]+$});
                   13816:             if ($restitle eq '') {
                   13817:                 $restitle = time;
                   13818:             }
                   13819:         }
1.1149    raeburn  13820:         if (length($restitle) > 12) {
                   13821:             $restitle = substr($restitle,0,12);
                   13822:         }
1.1015    raeburn  13823:         push(@pathitems,$restitle);
                   13824:         $path .= join('/',@pathitems);
                   13825:     }
                   13826:     return ($path,$multiresp);
                   13827: }
                   13828: 
                   13829: =pod
                   13830: 
1.464     albertel 13831: =back
1.41      ng       13832: 
1.112     bowersj2 13833: =head1 CSV Upload/Handling functions
1.38      albertel 13834: 
1.41      ng       13835: =over 4
                   13836: 
1.648     raeburn  13837: =item * &upfile_store($r)
1.41      ng       13838: 
                   13839: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13840: needs $env{'form.upfile'}
1.41      ng       13841: returns $datatoken to be put into hidden field
                   13842: 
                   13843: =cut
1.31      albertel 13844: 
                   13845: sub upfile_store {
                   13846:     my $r=shift;
1.258     albertel 13847:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13848:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13849:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13850:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13851: 
1.1299    raeburn  13852:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13853:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13854:                                      time.'_'.$$);
                   13855:     return if ($datatoken eq '');
                   13856: 
1.31      albertel 13857:     {
1.158     raeburn  13858:         my $datafile = $r->dir_config('lonDaemons').
                   13859:                            '/tmp/'.$datatoken.'.tmp';
                   13860:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13861:             print $fh $env{'form.upfile'};
1.158     raeburn  13862:             close($fh);
                   13863:         }
1.31      albertel 13864:     }
                   13865:     return $datatoken;
                   13866: }
                   13867: 
1.56      matthew  13868: =pod
                   13869: 
1.1290    raeburn  13870: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13871: 
                   13872: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  13873: $datatoken is the name to assign to the temporary file.
1.258     albertel 13874: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13875: 
                   13876: =cut
1.31      albertel 13877: 
                   13878: sub load_tmp_file {
1.1290    raeburn  13879:     my ($r,$datatoken) = @_;
                   13880:     return if ($datatoken eq '');
1.31      albertel 13881:     my @studentdata=();
                   13882:     {
1.158     raeburn  13883:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  13884:                               '/tmp/'.$datatoken.'.tmp';
1.158     raeburn  13885:         if ( open(my $fh,"<$studentfile") ) {
                   13886:             @studentdata=<$fh>;
                   13887:             close($fh);
                   13888:         }
1.31      albertel 13889:     }
1.258     albertel 13890:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13891: }
                   13892: 
1.1290    raeburn  13893: sub valid_datatoken {
                   13894:     my ($datatoken) = @_;
1.1291    raeburn  13895:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
1.1290    raeburn  13896:         return $datatoken;
                   13897:     }
                   13898:     return;
                   13899: }
                   13900: 
1.56      matthew  13901: =pod
                   13902: 
1.648     raeburn  13903: =item * &upfile_record_sep()
1.41      ng       13904: 
                   13905: Separate uploaded file into records
                   13906: returns array of records,
1.258     albertel 13907: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13908: 
                   13909: =cut
1.31      albertel 13910: 
                   13911: sub upfile_record_sep {
1.258     albertel 13912:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13913:     } else {
1.248     albertel 13914: 	my @records;
1.258     albertel 13915: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13916: 	    if ($line=~/^\s*$/) { next; }
                   13917: 	    push(@records,$line);
                   13918: 	}
                   13919: 	return @records;
1.31      albertel 13920:     }
                   13921: }
                   13922: 
1.56      matthew  13923: =pod
                   13924: 
1.648     raeburn  13925: =item * &record_sep($record)
1.41      ng       13926: 
1.258     albertel 13927: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13928: 
                   13929: =cut
                   13930: 
1.263     www      13931: sub takeleft {
                   13932:     my $index=shift;
                   13933:     return substr('0000'.$index,-4,4);
                   13934: }
                   13935: 
1.31      albertel 13936: sub record_sep {
                   13937:     my $record=shift;
                   13938:     my %components=();
1.258     albertel 13939:     if ($env{'form.upfiletype'} eq 'xml') {
                   13940:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13941:         my $i=0;
1.356     albertel 13942:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13943:             $field=~s/^(\"|\')//;
                   13944:             $field=~s/(\"|\')$//;
1.263     www      13945:             $components{&takeleft($i)}=$field;
1.31      albertel 13946:             $i++;
                   13947:         }
1.258     albertel 13948:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13949:         my $i=0;
1.356     albertel 13950:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13951:             $field=~s/^(\"|\')//;
                   13952:             $field=~s/(\"|\')$//;
1.263     www      13953:             $components{&takeleft($i)}=$field;
1.31      albertel 13954:             $i++;
                   13955:         }
                   13956:     } else {
1.561     www      13957:         my $separator=',';
1.480     banghart 13958:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13959:             $separator=';';
1.480     banghart 13960:         }
1.31      albertel 13961:         my $i=0;
1.561     www      13962: # the character we are looking for to indicate the end of a quote or a record 
                   13963:         my $looking_for=$separator;
                   13964: # do not add the characters to the fields
                   13965:         my $ignore=0;
                   13966: # we just encountered a separator (or the beginning of the record)
                   13967:         my $just_found_separator=1;
                   13968: # store the field we are working on here
                   13969:         my $field='';
                   13970: # work our way through all characters in record
                   13971:         foreach my $character ($record=~/(.)/g) {
                   13972:             if ($character eq $looking_for) {
                   13973:                if ($character ne $separator) {
                   13974: # Found the end of a quote, again looking for separator
                   13975:                   $looking_for=$separator;
                   13976:                   $ignore=1;
                   13977:                } else {
                   13978: # Found a separator, store away what we got
                   13979:                   $components{&takeleft($i)}=$field;
                   13980: 	          $i++;
                   13981:                   $just_found_separator=1;
                   13982:                   $ignore=0;
                   13983:                   $field='';
                   13984:                }
                   13985:                next;
                   13986:             }
                   13987: # single or double quotation marks after a separator indicate beginning of a quote
                   13988: # we are now looking for the end of the quote and need to ignore separators
                   13989:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13990:                $looking_for=$character;
                   13991:                next;
                   13992:             }
                   13993: # ignore would be true after we reached the end of a quote
                   13994:             if ($ignore) { next; }
                   13995:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13996:             $field.=$character;
                   13997:             $just_found_separator=0; 
1.31      albertel 13998:         }
1.561     www      13999: # catch the very last entry, since we never encountered the separator
                   14000:         $components{&takeleft($i)}=$field;
1.31      albertel 14001:     }
                   14002:     return %components;
                   14003: }
                   14004: 
1.144     matthew  14005: ######################################################
                   14006: ######################################################
                   14007: 
1.56      matthew  14008: =pod
                   14009: 
1.648     raeburn  14010: =item * &upfile_select_html()
1.41      ng       14011: 
1.144     matthew  14012: Return HTML code to select a file from the users machine and specify 
                   14013: the file type.
1.41      ng       14014: 
                   14015: =cut
                   14016: 
1.144     matthew  14017: ######################################################
                   14018: ######################################################
1.31      albertel 14019: sub upfile_select_html {
1.144     matthew  14020:     my %Types = (
                   14021:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14022:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14023:                  space => &mt('Space separated'),
                   14024:                  tab   => &mt('Tabulator separated'),
                   14025: #                 xml   => &mt('HTML/XML'),
                   14026:                  );
                   14027:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14028:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14029:     foreach my $type (sort(keys(%Types))) {
                   14030:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14031:     }
                   14032:     $Str .= "</select>\n";
                   14033:     return $Str;
1.31      albertel 14034: }
                   14035: 
1.301     albertel 14036: sub get_samples {
                   14037:     my ($records,$toget) = @_;
                   14038:     my @samples=({});
                   14039:     my $got=0;
                   14040:     foreach my $rec (@$records) {
                   14041: 	my %temp = &record_sep($rec);
                   14042: 	if (! grep(/\S/, values(%temp))) { next; }
                   14043: 	if (%temp) {
                   14044: 	    $samples[$got]=\%temp;
                   14045: 	    $got++;
                   14046: 	    if ($got == $toget) { last; }
                   14047: 	}
                   14048:     }
                   14049:     return \@samples;
                   14050: }
                   14051: 
1.144     matthew  14052: ######################################################
                   14053: ######################################################
                   14054: 
1.56      matthew  14055: =pod
                   14056: 
1.648     raeburn  14057: =item * &csv_print_samples($r,$records)
1.41      ng       14058: 
                   14059: Prints a table of sample values from each column uploaded $r is an
                   14060: Apache Request ref, $records is an arrayref from
                   14061: &Apache::loncommon::upfile_record_sep
                   14062: 
                   14063: =cut
                   14064: 
1.144     matthew  14065: ######################################################
                   14066: ######################################################
1.31      albertel 14067: sub csv_print_samples {
                   14068:     my ($r,$records) = @_;
1.662     bisitz   14069:     my $samples = &get_samples($records,5);
1.301     albertel 14070: 
1.594     raeburn  14071:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14072:               &start_data_table_header_row());
1.356     albertel 14073:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14074:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14075:     $r->print(&end_data_table_header_row());
1.301     albertel 14076:     foreach my $hash (@$samples) {
1.594     raeburn  14077: 	$r->print(&start_data_table_row());
1.356     albertel 14078: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14079: 	    $r->print('<td>');
1.356     albertel 14080: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14081: 	    $r->print('</td>');
                   14082: 	}
1.594     raeburn  14083: 	$r->print(&end_data_table_row());
1.31      albertel 14084:     }
1.594     raeburn  14085:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14086: }
                   14087: 
1.144     matthew  14088: ######################################################
                   14089: ######################################################
                   14090: 
1.56      matthew  14091: =pod
                   14092: 
1.648     raeburn  14093: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14094: 
                   14095: Prints a table to create associations between values and table columns.
1.144     matthew  14096: 
1.41      ng       14097: $r is an Apache Request ref,
                   14098: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14099: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14100: 
                   14101: =cut
                   14102: 
1.144     matthew  14103: ######################################################
                   14104: ######################################################
1.31      albertel 14105: sub csv_print_select_table {
                   14106:     my ($r,$records,$d) = @_;
1.301     albertel 14107:     my $i=0;
                   14108:     my $samples = &get_samples($records,1);
1.144     matthew  14109:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14110: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14111:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14112:               '<th>'.&mt('Column').'</th>'.
                   14113:               &end_data_table_header_row()."\n");
1.356     albertel 14114:     foreach my $array_ref (@$d) {
                   14115: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14116: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14117: 
1.875     bisitz   14118: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14119: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14120: 	$r->print('<option value="none"></option>');
1.356     albertel 14121: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14122: 	    $r->print('<option value="'.$sample.'"'.
                   14123:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14124:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14125: 	}
1.594     raeburn  14126: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14127: 	$i++;
                   14128:     }
1.594     raeburn  14129:     $r->print(&end_data_table());
1.31      albertel 14130:     $i--;
                   14131:     return $i;
                   14132: }
1.56      matthew  14133: 
1.144     matthew  14134: ######################################################
                   14135: ######################################################
                   14136: 
1.56      matthew  14137: =pod
1.31      albertel 14138: 
1.648     raeburn  14139: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14140: 
                   14141: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14142: 
                   14143: $r is an Apache Request ref,
                   14144: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14145: $d is an array of 2 element arrays (internal name, displayed name)
                   14146: 
                   14147: =cut
                   14148: 
1.144     matthew  14149: ######################################################
                   14150: ######################################################
1.31      albertel 14151: sub csv_samples_select_table {
                   14152:     my ($r,$records,$d) = @_;
                   14153:     my $i=0;
1.144     matthew  14154:     #
1.662     bisitz   14155:     my $max_samples = 5;
                   14156:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14157:     $r->print(&start_data_table().
                   14158:               &start_data_table_header_row().'<th>'.
                   14159:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14160:               &end_data_table_header_row());
1.301     albertel 14161: 
                   14162:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14163: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14164: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14165: 	foreach my $option (@$d) {
                   14166: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14167: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14168:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14169:                       $display.'</option>');
1.31      albertel 14170: 	}
                   14171: 	$r->print('</select></td><td>');
1.662     bisitz   14172: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14173: 	    if (defined($samples->[$line]{$key})) { 
                   14174: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14175: 	    }
                   14176: 	}
1.594     raeburn  14177: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14178: 	$i++;
                   14179:     }
1.594     raeburn  14180:     $r->print(&end_data_table());
1.31      albertel 14181:     $i--;
                   14182:     return($i);
1.115     matthew  14183: }
                   14184: 
1.144     matthew  14185: ######################################################
                   14186: ######################################################
                   14187: 
1.115     matthew  14188: =pod
                   14189: 
1.648     raeburn  14190: =item * &clean_excel_name($name)
1.115     matthew  14191: 
                   14192: Returns a replacement for $name which does not contain any illegal characters.
                   14193: 
                   14194: =cut
                   14195: 
1.144     matthew  14196: ######################################################
                   14197: ######################################################
1.115     matthew  14198: sub clean_excel_name {
                   14199:     my ($name) = @_;
                   14200:     $name =~ s/[:\*\?\/\\]//g;
                   14201:     if (length($name) > 31) {
                   14202:         $name = substr($name,0,31);
                   14203:     }
                   14204:     return $name;
1.25      albertel 14205: }
1.84      albertel 14206: 
1.85      albertel 14207: =pod
                   14208: 
1.648     raeburn  14209: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14210: 
                   14211: Returns either 1 or undef
                   14212: 
                   14213: 1 if the part is to be hidden, undef if it is to be shown
                   14214: 
                   14215: Arguments are:
                   14216: 
                   14217: $id the id of the part to be checked
                   14218: $symb, optional the symb of the resource to check
                   14219: $udom, optional the domain of the user to check for
                   14220: $uname, optional the username of the user to check for
                   14221: 
                   14222: =cut
1.84      albertel 14223: 
                   14224: sub check_if_partid_hidden {
                   14225:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14226:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14227: 					 $symb,$udom,$uname);
1.141     albertel 14228:     my $truth=1;
                   14229:     #if the string starts with !, then the list is the list to show not hide
                   14230:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14231:     my @hiddenlist=split(/,/,$hiddenparts);
                   14232:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14233: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14234:     }
1.141     albertel 14235:     return !$truth;
1.84      albertel 14236: }
1.127     matthew  14237: 
1.138     matthew  14238: 
                   14239: ############################################################
                   14240: ############################################################
                   14241: 
                   14242: =pod
                   14243: 
1.157     matthew  14244: =back 
                   14245: 
1.138     matthew  14246: =head1 cgi-bin script and graphing routines
                   14247: 
1.157     matthew  14248: =over 4
                   14249: 
1.648     raeburn  14250: =item * &get_cgi_id()
1.138     matthew  14251: 
                   14252: Inputs: none
                   14253: 
                   14254: Returns an id which can be used to pass environment variables
                   14255: to various cgi-bin scripts.  These environment variables will
                   14256: be removed from the users environment after a given time by
                   14257: the routine &Apache::lonnet::transfer_profile_to_env.
                   14258: 
                   14259: =cut
                   14260: 
                   14261: ############################################################
                   14262: ############################################################
1.152     albertel 14263: my $uniq=0;
1.136     matthew  14264: sub get_cgi_id {
1.154     albertel 14265:     $uniq=($uniq+1)%100000;
1.280     albertel 14266:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14267: }
                   14268: 
1.127     matthew  14269: ############################################################
                   14270: ############################################################
                   14271: 
                   14272: =pod
                   14273: 
1.648     raeburn  14274: =item * &DrawBarGraph()
1.127     matthew  14275: 
1.138     matthew  14276: Facilitates the plotting of data in a (stacked) bar graph.
                   14277: Puts plot definition data into the users environment in order for 
                   14278: graph.png to plot it.  Returns an <img> tag for the plot.
                   14279: The bars on the plot are labeled '1','2',...,'n'.
                   14280: 
                   14281: Inputs:
                   14282: 
                   14283: =over 4
                   14284: 
                   14285: =item $Title: string, the title of the plot
                   14286: 
                   14287: =item $xlabel: string, text describing the X-axis of the plot
                   14288: 
                   14289: =item $ylabel: string, text describing the Y-axis of the plot
                   14290: 
                   14291: =item $Max: scalar, the maximum Y value to use in the plot
                   14292: If $Max is < any data point, the graph will not be rendered.
                   14293: 
1.140     matthew  14294: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14295: they are plotted.  If undefined, default values will be used.
                   14296: 
1.178     matthew  14297: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14298: 
1.138     matthew  14299: =item @Values: An array of array references.  Each array reference holds data
                   14300: to be plotted in a stacked bar chart.
                   14301: 
1.239     matthew  14302: =item If the final element of @Values is a hash reference the key/value
                   14303: pairs will be added to the graph definition.
                   14304: 
1.138     matthew  14305: =back
                   14306: 
                   14307: Returns:
                   14308: 
                   14309: An <img> tag which references graph.png and the appropriate identifying
                   14310: information for the plot.
                   14311: 
1.127     matthew  14312: =cut
                   14313: 
                   14314: ############################################################
                   14315: ############################################################
1.134     matthew  14316: sub DrawBarGraph {
1.178     matthew  14317:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14318:     #
                   14319:     if (! defined($colors)) {
                   14320:         $colors = ['#33ff00', 
                   14321:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14322:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14323:                   ]; 
                   14324:     }
1.228     matthew  14325:     my $extra_settings = {};
                   14326:     if (ref($Values[-1]) eq 'HASH') {
                   14327:         $extra_settings = pop(@Values);
                   14328:     }
1.127     matthew  14329:     #
1.136     matthew  14330:     my $identifier = &get_cgi_id();
                   14331:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14332:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14333:         return '';
                   14334:     }
1.225     matthew  14335:     #
                   14336:     my @Labels;
                   14337:     if (defined($labels)) {
                   14338:         @Labels = @$labels;
                   14339:     } else {
                   14340:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14341:             push(@Labels,$i+1);
1.225     matthew  14342:         }
                   14343:     }
                   14344:     #
1.129     matthew  14345:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14346:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14347:     my %ValuesHash;
                   14348:     my $NumSets=1;
                   14349:     foreach my $array (@Values) {
                   14350:         next if (! ref($array));
1.136     matthew  14351:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14352:             join(',',@$array);
1.129     matthew  14353:     }
1.127     matthew  14354:     #
1.136     matthew  14355:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14356:     if ($NumBars < 3) {
                   14357:         $width = 120+$NumBars*32;
1.220     matthew  14358:         $xskip = 1;
1.225     matthew  14359:         $bar_width = 30;
                   14360:     } elsif ($NumBars < 5) {
                   14361:         $width = 120+$NumBars*20;
                   14362:         $xskip = 1;
                   14363:         $bar_width = 20;
1.220     matthew  14364:     } elsif ($NumBars < 10) {
1.136     matthew  14365:         $width = 120+$NumBars*15;
                   14366:         $xskip = 1;
                   14367:         $bar_width = 15;
                   14368:     } elsif ($NumBars <= 25) {
                   14369:         $width = 120+$NumBars*11;
                   14370:         $xskip = 5;
                   14371:         $bar_width = 8;
                   14372:     } elsif ($NumBars <= 50) {
                   14373:         $width = 120+$NumBars*8;
                   14374:         $xskip = 5;
                   14375:         $bar_width = 4;
                   14376:     } else {
                   14377:         $width = 120+$NumBars*8;
                   14378:         $xskip = 5;
                   14379:         $bar_width = 4;
                   14380:     }
                   14381:     #
1.137     matthew  14382:     $Max = 1 if ($Max < 1);
                   14383:     if ( int($Max) < $Max ) {
                   14384:         $Max++;
                   14385:         $Max = int($Max);
                   14386:     }
1.127     matthew  14387:     $Title  = '' if (! defined($Title));
                   14388:     $xlabel = '' if (! defined($xlabel));
                   14389:     $ylabel = '' if (! defined($ylabel));
1.369     www      14390:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14391:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14392:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14393:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14394:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14395:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14396:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14397:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14398:     $ValuesHash{$id.'.height'}   = $height;
                   14399:     $ValuesHash{$id.'.width'}    = $width;
                   14400:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14401:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14402:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14403:     #
1.228     matthew  14404:     # Deal with other parameters
                   14405:     while (my ($key,$value) = each(%$extra_settings)) {
                   14406:         $ValuesHash{$id.'.'.$key} = $value;
                   14407:     }
                   14408:     #
1.646     raeburn  14409:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14410:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14411: }
                   14412: 
                   14413: ############################################################
                   14414: ############################################################
                   14415: 
                   14416: =pod
                   14417: 
1.648     raeburn  14418: =item * &DrawXYGraph()
1.137     matthew  14419: 
1.138     matthew  14420: Facilitates the plotting of data in an XY graph.
                   14421: Puts plot definition data into the users environment in order for 
                   14422: graph.png to plot it.  Returns an <img> tag for the plot.
                   14423: 
                   14424: Inputs:
                   14425: 
                   14426: =over 4
                   14427: 
                   14428: =item $Title: string, the title of the plot
                   14429: 
                   14430: =item $xlabel: string, text describing the X-axis of the plot
                   14431: 
                   14432: =item $ylabel: string, text describing the Y-axis of the plot
                   14433: 
                   14434: =item $Max: scalar, the maximum Y value to use in the plot
                   14435: If $Max is < any data point, the graph will not be rendered.
                   14436: 
                   14437: =item $colors: Array ref containing the hex color codes for the data to be 
                   14438: plotted in.  If undefined, default values will be used.
                   14439: 
                   14440: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14441: 
                   14442: =item $Ydata: Array ref containing Array refs.  
1.185     www      14443: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14444: 
                   14445: =item %Values: hash indicating or overriding any default values which are 
                   14446: passed to graph.png.  
                   14447: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14448: 
                   14449: =back
                   14450: 
                   14451: Returns:
                   14452: 
                   14453: An <img> tag which references graph.png and the appropriate identifying
                   14454: information for the plot.
                   14455: 
1.137     matthew  14456: =cut
                   14457: 
                   14458: ############################################################
                   14459: ############################################################
                   14460: sub DrawXYGraph {
                   14461:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14462:     #
                   14463:     # Create the identifier for the graph
                   14464:     my $identifier = &get_cgi_id();
                   14465:     my $id = 'cgi.'.$identifier;
                   14466:     #
                   14467:     $Title  = '' if (! defined($Title));
                   14468:     $xlabel = '' if (! defined($xlabel));
                   14469:     $ylabel = '' if (! defined($ylabel));
                   14470:     my %ValuesHash = 
                   14471:         (
1.369     www      14472:          $id.'.title'  => &escape($Title),
                   14473:          $id.'.xlabel' => &escape($xlabel),
                   14474:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14475:          $id.'.y_max_value'=> $Max,
                   14476:          $id.'.labels'     => join(',',@$Xlabels),
                   14477:          $id.'.PlotType'   => 'XY',
                   14478:          );
                   14479:     #
                   14480:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14481:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14482:     }
                   14483:     #
                   14484:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14485:         return '';
                   14486:     }
                   14487:     my $NumSets=1;
1.138     matthew  14488:     foreach my $array (@{$Ydata}){
1.137     matthew  14489:         next if (! ref($array));
                   14490:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14491:     }
1.138     matthew  14492:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14493:     #
                   14494:     # Deal with other parameters
                   14495:     while (my ($key,$value) = each(%Values)) {
                   14496:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14497:     }
                   14498:     #
1.646     raeburn  14499:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14500:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14501: }
                   14502: 
                   14503: ############################################################
                   14504: ############################################################
                   14505: 
                   14506: =pod
                   14507: 
1.648     raeburn  14508: =item * &DrawXYYGraph()
1.138     matthew  14509: 
                   14510: Facilitates the plotting of data in an XY graph with two Y axes.
                   14511: Puts plot definition data into the users environment in order for 
                   14512: graph.png to plot it.  Returns an <img> tag for the plot.
                   14513: 
                   14514: Inputs:
                   14515: 
                   14516: =over 4
                   14517: 
                   14518: =item $Title: string, the title of the plot
                   14519: 
                   14520: =item $xlabel: string, text describing the X-axis of the plot
                   14521: 
                   14522: =item $ylabel: string, text describing the Y-axis of the plot
                   14523: 
                   14524: =item $colors: Array ref containing the hex color codes for the data to be 
                   14525: plotted in.  If undefined, default values will be used.
                   14526: 
                   14527: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14528: 
                   14529: =item $Ydata1: The first data set
                   14530: 
                   14531: =item $Min1: The minimum value of the left Y-axis
                   14532: 
                   14533: =item $Max1: The maximum value of the left Y-axis
                   14534: 
                   14535: =item $Ydata2: The second data set
                   14536: 
                   14537: =item $Min2: The minimum value of the right Y-axis
                   14538: 
                   14539: =item $Max2: The maximum value of the left Y-axis
                   14540: 
                   14541: =item %Values: hash indicating or overriding any default values which are 
                   14542: passed to graph.png.  
                   14543: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14544: 
                   14545: =back
                   14546: 
                   14547: Returns:
                   14548: 
                   14549: An <img> tag which references graph.png and the appropriate identifying
                   14550: information for the plot.
1.136     matthew  14551: 
                   14552: =cut
                   14553: 
                   14554: ############################################################
                   14555: ############################################################
1.137     matthew  14556: sub DrawXYYGraph {
                   14557:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14558:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14559:     #
                   14560:     # Create the identifier for the graph
                   14561:     my $identifier = &get_cgi_id();
                   14562:     my $id = 'cgi.'.$identifier;
                   14563:     #
                   14564:     $Title  = '' if (! defined($Title));
                   14565:     $xlabel = '' if (! defined($xlabel));
                   14566:     $ylabel = '' if (! defined($ylabel));
                   14567:     my %ValuesHash = 
                   14568:         (
1.369     www      14569:          $id.'.title'  => &escape($Title),
                   14570:          $id.'.xlabel' => &escape($xlabel),
                   14571:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14572:          $id.'.labels' => join(',',@$Xlabels),
                   14573:          $id.'.PlotType' => 'XY',
                   14574:          $id.'.NumSets' => 2,
1.137     matthew  14575:          $id.'.two_axes' => 1,
                   14576:          $id.'.y1_max_value' => $Max1,
                   14577:          $id.'.y1_min_value' => $Min1,
                   14578:          $id.'.y2_max_value' => $Max2,
                   14579:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14580:          );
                   14581:     #
1.137     matthew  14582:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14583:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14584:     }
                   14585:     #
                   14586:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14587:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14588:         return '';
                   14589:     }
                   14590:     my $NumSets=1;
1.137     matthew  14591:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14592:         next if (! ref($array));
                   14593:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14594:     }
                   14595:     #
                   14596:     # Deal with other parameters
                   14597:     while (my ($key,$value) = each(%Values)) {
                   14598:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14599:     }
                   14600:     #
1.646     raeburn  14601:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14602:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14603: }
                   14604: 
                   14605: ############################################################
                   14606: ############################################################
                   14607: 
                   14608: =pod
                   14609: 
1.157     matthew  14610: =back 
                   14611: 
1.139     matthew  14612: =head1 Statistics helper routines?  
                   14613: 
                   14614: Bad place for them but what the hell.
                   14615: 
1.157     matthew  14616: =over 4
                   14617: 
1.648     raeburn  14618: =item * &chartlink()
1.139     matthew  14619: 
                   14620: Returns a link to the chart for a specific student.  
                   14621: 
                   14622: Inputs:
                   14623: 
                   14624: =over 4
                   14625: 
                   14626: =item $linktext: The text of the link
                   14627: 
                   14628: =item $sname: The students username
                   14629: 
                   14630: =item $sdomain: The students domain
                   14631: 
                   14632: =back
                   14633: 
1.157     matthew  14634: =back
                   14635: 
1.139     matthew  14636: =cut
                   14637: 
                   14638: ############################################################
                   14639: ############################################################
                   14640: sub chartlink {
                   14641:     my ($linktext, $sname, $sdomain) = @_;
                   14642:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14643:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14644:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14645:        '">'.$linktext.'</a>';
1.153     matthew  14646: }
                   14647: 
                   14648: #######################################################
                   14649: #######################################################
                   14650: 
                   14651: =pod
                   14652: 
                   14653: =head1 Course Environment Routines
1.157     matthew  14654: 
                   14655: =over 4
1.153     matthew  14656: 
1.648     raeburn  14657: =item * &restore_course_settings()
1.153     matthew  14658: 
1.648     raeburn  14659: =item * &store_course_settings()
1.153     matthew  14660: 
                   14661: Restores/Store indicated form parameters from the course environment.
                   14662: Will not overwrite existing values of the form parameters.
                   14663: 
                   14664: Inputs: 
                   14665: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14666: 
                   14667: a hash ref describing the data to be stored.  For example:
                   14668:    
                   14669: %Save_Parameters = ('Status' => 'scalar',
                   14670:     'chartoutputmode' => 'scalar',
                   14671:     'chartoutputdata' => 'scalar',
                   14672:     'Section' => 'array',
1.373     raeburn  14673:     'Group' => 'array',
1.153     matthew  14674:     'StudentData' => 'array',
                   14675:     'Maps' => 'array');
                   14676: 
                   14677: Returns: both routines return nothing
                   14678: 
1.631     raeburn  14679: =back
                   14680: 
1.153     matthew  14681: =cut
                   14682: 
                   14683: #######################################################
                   14684: #######################################################
                   14685: sub store_course_settings {
1.496     albertel 14686:     return &store_settings($env{'request.course.id'},@_);
                   14687: }
                   14688: 
                   14689: sub store_settings {
1.153     matthew  14690:     # save to the environment
                   14691:     # appenv the same items, just to be safe
1.300     albertel 14692:     my $udom  = $env{'user.domain'};
                   14693:     my $uname = $env{'user.name'};
1.496     albertel 14694:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14695:     my %SaveHash;
                   14696:     my %AppHash;
                   14697:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14698:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14699:         my $envname = 'environment.'.$basename;
1.258     albertel 14700:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14701:             # Save this value away
                   14702:             if ($type eq 'scalar' &&
1.258     albertel 14703:                 (! exists($env{$envname}) || 
                   14704:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14705:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14706:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14707:             } elsif ($type eq 'array') {
                   14708:                 my $stored_form;
1.258     albertel 14709:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14710:                     $stored_form = join(',',
                   14711:                                         map {
1.369     www      14712:                                             &escape($_);
1.258     albertel 14713:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14714:                 } else {
                   14715:                     $stored_form = 
1.369     www      14716:                         &escape($env{'form.'.$setting});
1.153     matthew  14717:                 }
                   14718:                 # Determine if the array contents are the same.
1.258     albertel 14719:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14720:                     $SaveHash{$basename} = $stored_form;
                   14721:                     $AppHash{$envname}   = $stored_form;
                   14722:                 }
                   14723:             }
                   14724:         }
                   14725:     }
                   14726:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14727:                                           $udom,$uname);
1.153     matthew  14728:     if ($put_result !~ /^(ok|delayed)/) {
                   14729:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14730:                                  'got error:'.$put_result);
                   14731:     }
                   14732:     # Make sure these settings stick around in this session, too
1.646     raeburn  14733:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14734:     return;
                   14735: }
                   14736: 
                   14737: sub restore_course_settings {
1.499     albertel 14738:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14739: }
                   14740: 
                   14741: sub restore_settings {
                   14742:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14743:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14744:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14745:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14746:             '.'.$setting;
1.258     albertel 14747:         if (exists($env{$envname})) {
1.153     matthew  14748:             if ($type eq 'scalar') {
1.258     albertel 14749:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14750:             } elsif ($type eq 'array') {
1.258     albertel 14751:                 $env{'form.'.$setting} = [ 
1.153     matthew  14752:                                            map { 
1.369     www      14753:                                                &unescape($_); 
1.258     albertel 14754:                                            } split(',',$env{$envname})
1.153     matthew  14755:                                            ];
                   14756:             }
                   14757:         }
                   14758:     }
1.127     matthew  14759: }
                   14760: 
1.618     raeburn  14761: #######################################################
                   14762: #######################################################
                   14763: 
                   14764: =pod
                   14765: 
                   14766: =head1 Domain E-mail Routines  
                   14767: 
                   14768: =over 4
                   14769: 
1.648     raeburn  14770: =item * &build_recipient_list()
1.618     raeburn  14771: 
1.1144    raeburn  14772: Build recipient lists for following types of e-mail:
1.766     raeburn  14773: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14774: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14775: module change checking, student/employee ID conflict checks, as
                   14776: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14777: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14778: 
                   14779: Inputs:
1.619     raeburn  14780: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14781: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14782: requestsmail, updatesmail, or idconflictsmail).
                   14783: 
1.619     raeburn  14784: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14785: 
1.619     raeburn  14786: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14787: i.e., predates configuration by DC via domainprefs.pm
                   14788: 
                   14789: $requname username of requester (if mailing type is helpdeskmail)
                   14790: 
                   14791: $requdom domain of requester (if mailing type is helpdeskmail)
                   14792: 
                   14793: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14794: 
1.618     raeburn  14795: 
1.655     raeburn  14796: Returns: comma separated list of addresses to which to send e-mail.
                   14797: 
                   14798: =back
1.618     raeburn  14799: 
                   14800: =cut
                   14801: 
                   14802: ############################################################
                   14803: ############################################################
                   14804: sub build_recipient_list {
1.1297    raeburn  14805:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14806:     my @recipients;
1.1270    raeburn  14807:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14808:     my %domconfig =
1.1270    raeburn  14809:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14810:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14811:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14812:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14813:                 my @contacts = ('adminemail','supportemail');
                   14814:                 foreach my $item (@contacts) {
                   14815:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14816:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14817:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14818:                             push(@recipients,$addr);
                   14819:                         }
1.619     raeburn  14820:                     }
1.1270    raeburn  14821:                 }
                   14822:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14823:                 if ($mailing eq 'helpdeskmail') {
                   14824:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14825:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14826:                         my @ok_bccs;
                   14827:                         foreach my $bcc (@bccs) {
                   14828:                             $bcc =~ s/^\s+//g;
                   14829:                             $bcc =~ s/\s+$//g;
                   14830:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14831:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14832:                                     push(@ok_bccs,$bcc);
                   14833:                                 }
                   14834:                             }
                   14835:                         }
                   14836:                         if (@ok_bccs > 0) {
                   14837:                             $allbcc = join(', ',@ok_bccs);
                   14838:                         }
                   14839:                     }
                   14840:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14841:                 }
                   14842:             }
1.766     raeburn  14843:         } elsif ($origmail ne '') {
1.1270    raeburn  14844:             $lastresort = $origmail;
1.618     raeburn  14845:         }
1.1297    raeburn  14846:         if ($mailing eq 'helpdeskmail') {
                   14847:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14848:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14849:                 my ($inststatus,$inststatus_checked);
                   14850:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14851:                     ($env{'user.domain'} ne 'public')) {
                   14852:                     $inststatus_checked = 1;
                   14853:                     $inststatus = $env{'environment.inststatus'};
                   14854:                 }
                   14855:                 unless ($inststatus_checked) {
                   14856:                     if (($requname ne '') && ($requdom ne '')) {
                   14857:                         if (($requname =~ /^$match_username$/) &&
                   14858:                             ($requdom =~ /^$match_domain$/) &&
                   14859:                             (&Apache::lonnet::domain($requdom))) {
                   14860:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14861:                                                                       $requdom);
                   14862:                             unless ($requhome eq 'no_host') {
                   14863:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14864:                                 $inststatus = $userenv{'inststatus'};
                   14865:                                 $inststatus_checked = 1;
                   14866:                             }
                   14867:                         }
                   14868:                     }
                   14869:                 }
                   14870:                 unless ($inststatus_checked) {
                   14871:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14872:                         my %srch = (srchby     => 'email',
                   14873:                                     srchdomain => $defdom,
                   14874:                                     srchterm   => $reqemail,
                   14875:                                     srchtype   => 'exact');
                   14876:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14877:                         foreach my $uname (keys(%srch_results)) {
                   14878:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14879:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14880:                                 $inststatus_checked = 1;
                   14881:                                 last;
                   14882:                             }
                   14883:                         }
                   14884:                         unless ($inststatus_checked) {
                   14885:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14886:                             if ($dirsrchres eq 'ok') {
                   14887:                                 foreach my $uname (keys(%srch_results)) {
                   14888:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14889:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14890:                                         $inststatus_checked = 1;
                   14891:                                         last;
                   14892:                                     }
                   14893:                                 }
                   14894:                             }
                   14895:                         }
                   14896:                     }
                   14897:                 }
                   14898:                 if ($inststatus ne '') {
                   14899:                     foreach my $status (split(/\:/,$inststatus)) {
                   14900:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14901:                             my @contacts = ('adminemail','supportemail');
                   14902:                             foreach my $item (@contacts) {
                   14903:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14904:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14905:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14906:                                         push(@recipients,$addr);
                   14907:                                     }
                   14908:                                 }
                   14909:                             }
                   14910:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14911:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14912:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14913:                                 my @ok_bccs;
                   14914:                                 foreach my $bcc (@bccs) {
                   14915:                                     $bcc =~ s/^\s+//g;
                   14916:                                     $bcc =~ s/\s+$//g;
                   14917:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14918:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14919:                                             push(@ok_bccs,$bcc);
                   14920:                                         }
                   14921:                                     }
                   14922:                                 }
                   14923:                                 if (@ok_bccs > 0) {
                   14924:                                     $allbcc = join(', ',@ok_bccs);
                   14925:                                 }
                   14926:                             }
                   14927:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14928:                             last;
                   14929:                         }
                   14930:                     }
                   14931:                 }
                   14932:             }
                   14933:         }
1.619     raeburn  14934:     } elsif ($origmail ne '') {
1.1270    raeburn  14935:         $lastresort = $origmail;
                   14936:     }
1.1297    raeburn  14937:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  14938:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14939:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14940:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14941:             my %what = (
                   14942:                           perlvar => 1,
                   14943:                        );
                   14944:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14945:             if ($primary) {
                   14946:                 my $gotaddr;
                   14947:                 my ($result,$returnhash) =
                   14948:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14949:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14950:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14951:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14952:                         $gotaddr = 1;
                   14953:                     }
                   14954:                 }
                   14955:                 unless ($gotaddr) {
                   14956:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14957:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14958:                     unless ($uintdom eq $intdom) {
                   14959:                         my %domconfig =
                   14960:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14961:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14962:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14963:                                 my @contacts = ('adminemail','supportemail');
                   14964:                                 foreach my $item (@contacts) {
                   14965:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14966:                                         my $addr = $domconfig{'contacts'}{$item};
                   14967:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14968:                                             push(@recipients,$addr);
                   14969:                                         }
                   14970:                                     }
                   14971:                                 }
                   14972:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14973:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14974:                                 }
                   14975:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14976:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14977:                                     my @ok_bccs;
                   14978:                                     foreach my $bcc (@bccs) {
                   14979:                                         $bcc =~ s/^\s+//g;
                   14980:                                         $bcc =~ s/\s+$//g;
                   14981:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14982:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14983:                                                 push(@ok_bccs,$bcc);
                   14984:                                             }
                   14985:                                         }
                   14986:                                     }
                   14987:                                     if (@ok_bccs > 0) {
                   14988:                                         $allbcc = join(', ',@ok_bccs);
                   14989:                                     }
                   14990:                                 }
                   14991:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14992:                             }
                   14993:                         }
                   14994:                     }
                   14995:                 }
                   14996:             }
                   14997:         }
1.618     raeburn  14998:     }
1.688     raeburn  14999:     if (defined($defmail)) {
                   15000:         if ($defmail ne '') {
                   15001:             push(@recipients,$defmail);
                   15002:         }
1.618     raeburn  15003:     }
                   15004:     if ($otheremails) {
1.619     raeburn  15005:         my @others;
                   15006:         if ($otheremails =~ /,/) {
                   15007:             @others = split(/,/,$otheremails);
1.618     raeburn  15008:         } else {
1.619     raeburn  15009:             push(@others,$otheremails);
                   15010:         }
                   15011:         foreach my $addr (@others) {
                   15012:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15013:                 push(@recipients,$addr);
                   15014:             }
1.618     raeburn  15015:         }
                   15016:     }
1.1298    raeburn  15017:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15018:         if ((!@recipients) && ($lastresort ne '')) {
                   15019:             push(@recipients,$lastresort);
                   15020:         }
                   15021:     } elsif ($lastresort ne '') {
                   15022:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15023:             push(@recipients,$lastresort);
                   15024:         }
                   15025:     }
1.1271    raeburn  15026:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15027:     if (wantarray) {
                   15028:         return ($recipientlist,$allbcc,$addtext);
                   15029:     } else {
                   15030:         return $recipientlist;
                   15031:     }
1.618     raeburn  15032: }
                   15033: 
1.127     matthew  15034: ############################################################
                   15035: ############################################################
1.154     albertel 15036: 
1.655     raeburn  15037: =pod
                   15038: 
1.1224    musolffc 15039: =over 4
                   15040: 
1.1223    musolffc 15041: =item * &mime_email()
                   15042: 
                   15043: Sends an email with a possible attachment
                   15044: 
                   15045: Inputs:
                   15046: 
                   15047: =over 4
                   15048: 
                   15049: from -              Sender's email address
                   15050: 
                   15051: to -                Email address of recipient
                   15052: 
                   15053: subject -           Subject of email
                   15054: 
                   15055: body -              Body of email
                   15056: 
                   15057: cc_string -         Carbon copy email address
                   15058: 
                   15059: bcc -               Blind carbon copy email address
                   15060: 
                   15061: type -              File type of attachment
                   15062: 
                   15063: attachment_path -   Path of file to be attached
                   15064: 
                   15065: file_name -         Name of file to be attached
                   15066: 
                   15067: attachment_text -   The body of an attachment of type "TEXT"
                   15068: 
                   15069: =back
                   15070: 
                   15071: =back
                   15072: 
                   15073: =cut
                   15074: 
                   15075: ############################################################
                   15076: ############################################################
                   15077: 
                   15078: sub mime_email {
                   15079:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   15080:         $file_name, $attachment_text) = @_;
                   15081:     my $msg = MIME::Lite->new(
                   15082:              From    => $from,
                   15083:              To      => $to,
                   15084:              Subject => $subject,
                   15085:              Type    =>'TEXT',
                   15086:              Data    => $body,
                   15087:              );
                   15088:     if ($cc_string ne '') {
                   15089:         $msg->add("Cc" => $cc_string);
                   15090:     }
                   15091:     if ($bcc ne '') {
                   15092:         $msg->add("Bcc" => $bcc);
                   15093:     }
                   15094:     $msg->attr("content-type"         => "text/plain");
                   15095:     $msg->attr("content-type.charset" => "UTF-8");
                   15096:     # Attach file if given
                   15097:     if ($attachment_path) {
                   15098:         unless ($file_name) {
                   15099:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15100:         }
                   15101:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15102:         $msg->attach(Type     => $type,
                   15103:                      Path     => $attachment_path,
                   15104:                      Filename => $file_name
                   15105:                      );
                   15106:     # Otherwise attach text if given
                   15107:     } elsif ($attachment_text) {
                   15108:         $msg->attach(Type => 'TEXT',
                   15109:                      Data => $attachment_text);
                   15110:     }
                   15111:     # Send it
                   15112:     $msg->send('sendmail');
                   15113: }
                   15114: 
                   15115: ############################################################
                   15116: ############################################################
                   15117: 
                   15118: =pod
                   15119: 
1.655     raeburn  15120: =head1 Course Catalog Routines
                   15121: 
                   15122: =over 4
                   15123: 
                   15124: =item * &gather_categories()
                   15125: 
                   15126: Converts category definitions - keys of categories hash stored in  
                   15127: coursecategories in configuration.db on the primary library server in a 
                   15128: domain - to an array.  Also generates javascript and idx hash used to 
                   15129: generate Domain Coordinator interface for editing Course Categories.
                   15130: 
                   15131: Inputs:
1.663     raeburn  15132: 
1.655     raeburn  15133: categories (reference to hash of category definitions).
1.663     raeburn  15134: 
1.655     raeburn  15135: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15136:       categories and subcategories).
1.663     raeburn  15137: 
1.655     raeburn  15138: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15139:       editing Course Categories).
1.663     raeburn  15140: 
1.655     raeburn  15141: jsarray (reference to array of categories used to create Javascript arrays for
                   15142:          Domain Coordinator interface for editing Course Categories).
                   15143: 
                   15144: Returns: nothing
                   15145: 
                   15146: Side effects: populates cats, idx and jsarray. 
                   15147: 
                   15148: =cut
                   15149: 
                   15150: sub gather_categories {
                   15151:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15152:     my %counters;
                   15153:     my $num = 0;
                   15154:     foreach my $item (keys(%{$categories})) {
                   15155:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15156:         if ($container eq '' && $depth == 0) {
                   15157:             $cats->[$depth][$categories->{$item}] = $cat;
                   15158:         } else {
                   15159:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15160:         }
                   15161:         my ($escitem,$tail) = split(/:/,$item,2);
                   15162:         if ($counters{$tail} eq '') {
                   15163:             $counters{$tail} = $num;
                   15164:             $num ++;
                   15165:         }
                   15166:         if (ref($idx) eq 'HASH') {
                   15167:             $idx->{$item} = $counters{$tail};
                   15168:         }
                   15169:         if (ref($jsarray) eq 'ARRAY') {
                   15170:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15171:         }
                   15172:     }
                   15173:     return;
                   15174: }
                   15175: 
                   15176: =pod
                   15177: 
                   15178: =item * &extract_categories()
                   15179: 
                   15180: Used to generate breadcrumb trails for course categories.
                   15181: 
                   15182: Inputs:
1.663     raeburn  15183: 
1.655     raeburn  15184: categories (reference to hash of category definitions).
1.663     raeburn  15185: 
1.655     raeburn  15186: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15187:       categories and subcategories).
1.663     raeburn  15188: 
1.655     raeburn  15189: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15190: 
1.655     raeburn  15191: allitems (reference to hash - key is category key 
                   15192:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15193: 
1.655     raeburn  15194: idx (reference to hash of counters used in Domain Coordinator interface for
                   15195:       editing Course Categories).
1.663     raeburn  15196: 
1.655     raeburn  15197: jsarray (reference to array of categories used to create Javascript arrays for
                   15198:          Domain Coordinator interface for editing Course Categories).
                   15199: 
1.665     raeburn  15200: subcats (reference to hash of arrays containing all subcategories within each 
                   15201:          category, -recursive)
                   15202: 
1.655     raeburn  15203: Returns: nothing
                   15204: 
                   15205: Side effects: populates trails and allitems hash references.
                   15206: 
                   15207: =cut
                   15208: 
                   15209: sub extract_categories {
1.665     raeburn  15210:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  15211:     if (ref($categories) eq 'HASH') {
                   15212:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15213:         if (ref($cats->[0]) eq 'ARRAY') {
                   15214:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15215:                 my $name = $cats->[0][$i];
                   15216:                 my $item = &escape($name).'::0';
                   15217:                 my $trailstr;
                   15218:                 if ($name eq 'instcode') {
                   15219:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15220:                 } elsif ($name eq 'communities') {
                   15221:                     $trailstr = &mt('Communities');
1.1239    raeburn  15222:                 } elsif ($name eq 'placement') {
                   15223:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15224:                 } else {
                   15225:                     $trailstr = $name;
                   15226:                 }
                   15227:                 if ($allitems->{$item} eq '') {
                   15228:                     push(@{$trails},$trailstr);
                   15229:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15230:                 }
                   15231:                 my @parents = ($name);
                   15232:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15233:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15234:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15235:                         if (ref($subcats) eq 'HASH') {
                   15236:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15237:                         }
                   15238:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   15239:                     }
                   15240:                 } else {
                   15241:                     if (ref($subcats) eq 'HASH') {
                   15242:                         $subcats->{$item} = [];
1.655     raeburn  15243:                     }
                   15244:                 }
                   15245:             }
                   15246:         }
                   15247:     }
                   15248:     return;
                   15249: }
                   15250: 
                   15251: =pod
                   15252: 
1.1162    raeburn  15253: =item * &recurse_categories()
1.655     raeburn  15254: 
                   15255: Recursively used to generate breadcrumb trails for course categories.
                   15256: 
                   15257: Inputs:
1.663     raeburn  15258: 
1.655     raeburn  15259: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15260:       categories and subcategories).
1.663     raeburn  15261: 
1.655     raeburn  15262: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15263: 
                   15264: category (current course category, for which breadcrumb trail is being generated).
                   15265: 
                   15266: trails (reference to array of breadcrumb trails for each category).
                   15267: 
1.655     raeburn  15268: allitems (reference to hash - key is category key
                   15269:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15270: 
1.655     raeburn  15271: parents (array containing containers directories for current category, 
                   15272:          back to top level). 
                   15273: 
                   15274: Returns: nothing
                   15275: 
                   15276: Side effects: populates trails and allitems hash references
                   15277: 
                   15278: =cut
                   15279: 
                   15280: sub recurse_categories {
1.665     raeburn  15281:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  15282:     my $shallower = $depth - 1;
                   15283:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15284:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15285:             my $name = $cats->[$depth]{$category}[$k];
                   15286:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15287:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15288:             if ($allitems->{$item} eq '') {
                   15289:                 push(@{$trails},$trailstr);
                   15290:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15291:             }
                   15292:             my $deeper = $depth+1;
                   15293:             push(@{$parents},$category);
1.665     raeburn  15294:             if (ref($subcats) eq 'HASH') {
                   15295:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15296:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15297:                     my $higher;
                   15298:                     if ($j > 0) {
                   15299:                         $higher = &escape($parents->[$j]).':'.
                   15300:                                   &escape($parents->[$j-1]).':'.$j;
                   15301:                     } else {
                   15302:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15303:                     }
                   15304:                     push(@{$subcats->{$higher}},$subcat);
                   15305:                 }
                   15306:             }
                   15307:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   15308:                                 $subcats);
1.655     raeburn  15309:             pop(@{$parents});
                   15310:         }
                   15311:     } else {
                   15312:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   15313:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15314:         if ($allitems->{$item} eq '') {
                   15315:             push(@{$trails},$trailstr);
                   15316:             $allitems->{$item} = scalar(@{$trails})-1;
                   15317:         }
                   15318:     }
                   15319:     return;
                   15320: }
                   15321: 
1.663     raeburn  15322: =pod
                   15323: 
1.1162    raeburn  15324: =item * &assign_categories_table()
1.663     raeburn  15325: 
                   15326: Create a datatable for display of hierarchical categories in a domain,
                   15327: with checkboxes to allow a course to be categorized. 
                   15328: 
                   15329: Inputs:
                   15330: 
                   15331: cathash - reference to hash of categories defined for the domain (from
                   15332:           configuration.db)
                   15333: 
                   15334: currcat - scalar with an & separated list of categories assigned to a course. 
                   15335: 
1.919     raeburn  15336: type    - scalar contains course type (Course or Community).
                   15337: 
1.1260    raeburn  15338: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15339:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15340: 
1.663     raeburn  15341: Returns: $output (markup to be displayed) 
                   15342: 
                   15343: =cut
                   15344: 
                   15345: sub assign_categories_table {
1.1259    raeburn  15346:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15347:     my $output;
                   15348:     if (ref($cathash) eq 'HASH') {
                   15349:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   15350:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   15351:         $maxdepth = scalar(@cats);
                   15352:         if (@cats > 0) {
                   15353:             my $itemcount = 0;
                   15354:             if (ref($cats[0]) eq 'ARRAY') {
                   15355:                 my @currcategories;
                   15356:                 if ($currcat ne '') {
                   15357:                     @currcategories = split('&',$currcat);
                   15358:                 }
1.919     raeburn  15359:                 my $table;
1.663     raeburn  15360:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15361:                     my $parent = $cats[0][$i];
1.919     raeburn  15362:                     next if ($parent eq 'instcode');
                   15363:                     if ($type eq 'Community') {
                   15364:                         next unless ($parent eq 'communities');
1.1239    raeburn  15365:                     } elsif ($type eq 'Placement') {
                   15366:                         next unless ($parent eq 'placement');
1.919     raeburn  15367:                     } else {
1.1239    raeburn  15368:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15369:                     }
1.663     raeburn  15370:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15371:                     my $item = &escape($parent).'::0';
                   15372:                     my $checked = '';
                   15373:                     if (@currcategories > 0) {
                   15374:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15375:                             $checked = ' checked="checked"';
1.663     raeburn  15376:                         }
                   15377:                     }
1.919     raeburn  15378:                     my $parent_title = $parent;
                   15379:                     if ($parent eq 'communities') {
                   15380:                         $parent_title = &mt('Communities');
1.1239    raeburn  15381:                     } elsif ($parent eq 'placement') {
                   15382:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15383:                     }
                   15384:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15385:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15386:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15387:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15388:                     my $depth = 1;
                   15389:                     push(@path,$parent);
1.1259    raeburn  15390:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15391:                     pop(@path);
1.919     raeburn  15392:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15393:                     $itemcount ++;
                   15394:                 }
1.919     raeburn  15395:                 if ($itemcount) {
                   15396:                     $output = &Apache::loncommon::start_data_table().
                   15397:                               $table.
                   15398:                               &Apache::loncommon::end_data_table();
                   15399:                 }
1.663     raeburn  15400:             }
                   15401:         }
                   15402:     }
                   15403:     return $output;
                   15404: }
                   15405: 
                   15406: =pod
                   15407: 
1.1162    raeburn  15408: =item * &assign_category_rows()
1.663     raeburn  15409: 
                   15410: Create a datatable row for display of nested categories in a domain,
                   15411: with checkboxes to allow a course to be categorized,called recursively.
                   15412: 
                   15413: Inputs:
                   15414: 
                   15415: itemcount - track row number for alternating colors
                   15416: 
                   15417: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15418:       categories and subcategories.
                   15419: 
                   15420: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15421: 
                   15422: parent - parent of current category item
                   15423: 
                   15424: path - Array containing all categories back up through the hierarchy from the
                   15425:        current category to the top level.
                   15426: 
                   15427: currcategories - reference to array of current categories assigned to the course
                   15428: 
1.1260    raeburn  15429: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15430:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15431: 
1.663     raeburn  15432: Returns: $output (markup to be displayed).
                   15433: 
                   15434: =cut
                   15435: 
                   15436: sub assign_category_rows {
1.1259    raeburn  15437:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15438:     my ($text,$name,$item,$chgstr);
                   15439:     if (ref($cats) eq 'ARRAY') {
                   15440:         my $maxdepth = scalar(@{$cats});
                   15441:         if (ref($cats->[$depth]) eq 'HASH') {
                   15442:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15443:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15444:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15445:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15446:                 for (my $j=0; $j<$numchildren; $j++) {
                   15447:                     $name = $cats->[$depth]{$parent}[$j];
                   15448:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15449:                     my $deeper = $depth+1;
                   15450:                     my $checked = '';
                   15451:                     if (ref($currcategories) eq 'ARRAY') {
                   15452:                         if (@{$currcategories} > 0) {
                   15453:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15454:                                 $checked = ' checked="checked"';
1.663     raeburn  15455:                             }
                   15456:                         }
                   15457:                     }
1.664     raeburn  15458:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15459:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15460:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15461:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15462:                              '</td><td>';
1.663     raeburn  15463:                     if (ref($path) eq 'ARRAY') {
                   15464:                         push(@{$path},$name);
1.1259    raeburn  15465:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15466:                         pop(@{$path});
                   15467:                     }
                   15468:                     $text .= '</td></tr>';
                   15469:                 }
                   15470:                 $text .= '</table></td>';
                   15471:             }
                   15472:         }
                   15473:     }
                   15474:     return $text;
                   15475: }
                   15476: 
1.1181    raeburn  15477: =pod
                   15478: 
                   15479: =back
                   15480: 
                   15481: =cut
                   15482: 
1.655     raeburn  15483: ############################################################
                   15484: ############################################################
                   15485: 
                   15486: 
1.443     albertel 15487: sub commit_customrole {
1.664     raeburn  15488:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15489:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15490:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15491:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15492:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15493:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15494:                  '</b><br />';
                   15495:     return $output;
                   15496: }
                   15497: 
                   15498: sub commit_standardrole {
1.1116    raeburn  15499:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15500:     my ($output,$logmsg,$linefeed);
                   15501:     if ($context eq 'auto') {
                   15502:         $linefeed = "\n";
                   15503:     } else {
                   15504:         $linefeed = "<br />\n";
                   15505:     }  
1.443     albertel 15506:     if ($three eq 'st') {
1.541     raeburn  15507:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15508:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15509:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15510:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15511:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15512:         } else {
1.541     raeburn  15513:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15514:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15515:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15516:             if ($context eq 'auto') {
                   15517:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15518:             } else {
                   15519:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15520:                &mt('Add to classlist').': <b>ok</b>';
                   15521:             }
                   15522:             $output .= $linefeed;
1.443     albertel 15523:         }
                   15524:     } else {
                   15525:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15526:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15527:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15528:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15529:         if ($context eq 'auto') {
                   15530:             $output .= $result.$linefeed;
                   15531:         } else {
                   15532:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15533:         }
1.443     albertel 15534:     }
                   15535:     return $output;
                   15536: }
                   15537: 
                   15538: sub commit_studentrole {
1.1116    raeburn  15539:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15540:         $credits) = @_;
1.626     raeburn  15541:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15542:     if ($context eq 'auto') {
                   15543:         $linefeed = "\n";
                   15544:     } else {
                   15545:         $linefeed = '<br />'."\n";
                   15546:     }
1.443     albertel 15547:     if (defined($one) && defined($two)) {
                   15548:         my $cid=$one.'_'.$two;
                   15549:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15550:         my $secchange = 0;
                   15551:         my $expire_role_result;
                   15552:         my $modify_section_result;
1.628     raeburn  15553:         if ($oldsec ne '-1') { 
                   15554:             if ($oldsec ne $sec) {
1.443     albertel 15555:                 $secchange = 1;
1.628     raeburn  15556:                 my $now = time;
1.443     albertel 15557:                 my $uurl='/'.$cid;
                   15558:                 $uurl=~s/\_/\//g;
                   15559:                 if ($oldsec) {
                   15560:                     $uurl.='/'.$oldsec;
                   15561:                 }
1.626     raeburn  15562:                 $oldsecurl = $uurl;
1.628     raeburn  15563:                 $expire_role_result = 
1.652     raeburn  15564:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15565:                 if ($env{'request.course.sec'} ne '') { 
                   15566:                     if ($expire_role_result eq 'refused') {
                   15567:                         my @roles = ('st');
                   15568:                         my @statuses = ('previous');
                   15569:                         my @roledoms = ($one);
                   15570:                         my $withsec = 1;
                   15571:                         my %roleshash = 
                   15572:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15573:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15574:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15575:                             my ($oldstart,$oldend) = 
                   15576:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15577:                             if ($oldend > 0 && $oldend <= $now) {
                   15578:                                 $expire_role_result = 'ok';
                   15579:                             }
                   15580:                         }
                   15581:                     }
                   15582:                 }
1.443     albertel 15583:                 $result = $expire_role_result;
                   15584:             }
                   15585:         }
                   15586:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15587:             $modify_section_result = 
                   15588:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15589:                                                            undef,undef,undef,$sec,
                   15590:                                                            $end,$start,'','',$cid,
                   15591:                                                            '',$context,$credits);
1.443     albertel 15592:             if ($modify_section_result =~ /^ok/) {
                   15593:                 if ($secchange == 1) {
1.628     raeburn  15594:                     if ($sec eq '') {
                   15595:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15596:                     } else {
                   15597:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15598:                     }
1.443     albertel 15599:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15600:                     if ($sec eq '') {
                   15601:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15602:                     } else {
                   15603:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15604:                     }
1.443     albertel 15605:                 } else {
1.628     raeburn  15606:                     if ($sec eq '') {
                   15607:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15608:                     } else {
                   15609:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15610:                     }
1.443     albertel 15611:                 }
                   15612:             } else {
1.1115    raeburn  15613:                 if ($secchange) { 
1.628     raeburn  15614:                     $$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;
                   15615:                 } else {
                   15616:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15617:                 }
1.443     albertel 15618:             }
                   15619:             $result = $modify_section_result;
                   15620:         } elsif ($secchange == 1) {
1.628     raeburn  15621:             if ($oldsec eq '') {
1.1103    raeburn  15622:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  15623:             } else {
                   15624:                 $$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;
                   15625:             }
1.626     raeburn  15626:             if ($expire_role_result eq 'refused') {
                   15627:                 my $newsecurl = '/'.$cid;
                   15628:                 $newsecurl =~ s/\_/\//g;
                   15629:                 if ($sec ne '') {
                   15630:                     $newsecurl.='/'.$sec;
                   15631:                 }
                   15632:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15633:                     if ($sec eq '') {
                   15634:                         $$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;
                   15635:                     } else {
                   15636:                         $$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;
                   15637:                     }
                   15638:                 }
                   15639:             }
1.443     albertel 15640:         }
                   15641:     } else {
1.626     raeburn  15642:         $$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;
1.443     albertel 15643:         $result = "error: incomplete course id\n";
                   15644:     }
                   15645:     return $result;
                   15646: }
                   15647: 
1.1108    raeburn  15648: sub show_role_extent {
                   15649:     my ($scope,$context,$role) = @_;
                   15650:     $scope =~ s{^/}{};
                   15651:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15652:     push(@courseroles,'co');
                   15653:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15654:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15655:         $scope =~ s{/}{_};
                   15656:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15657:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15658:         my ($audom,$auname) = split(/\//,$scope);
                   15659:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15660:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15661:     } else {
                   15662:         $scope =~ s{/$}{};
                   15663:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15664:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15665:     }
                   15666: }
                   15667: 
1.443     albertel 15668: ############################################################
                   15669: ############################################################
                   15670: 
1.566     albertel 15671: sub check_clone {
1.578     raeburn  15672:     my ($args,$linefeed) = @_;
1.566     albertel 15673:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15674:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15675:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15676:     my $clonemsg;
                   15677:     my $can_clone = 0;
1.944     raeburn  15678:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15679:     if ($lctype ne 'community') {
                   15680:         $lctype = 'course';
                   15681:     }
1.566     albertel 15682:     if ($clonehome eq 'no_host') {
1.944     raeburn  15683:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15684:             $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'});
                   15685:         } else {
                   15686:             $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'});
                   15687:         }     
1.566     albertel 15688:     } else {
                   15689: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15690:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15691:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15692:                 $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'});
1.908     raeburn  15693:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15694:             }
                   15695:         }
1.1262    raeburn  15696: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15697:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15698: 	    $can_clone = 1;
                   15699: 	} else {
1.1221    raeburn  15700: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15701: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15702:             if ($clonehash{'cloners'} eq '') {
                   15703:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15704:                 if ($domdefs{'canclone'}) {
                   15705:                     unless ($domdefs{'canclone'} eq 'none') {
                   15706:                         if ($domdefs{'canclone'} eq 'domain') {
                   15707:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15708:                                 $can_clone = 1;
                   15709:                             }
                   15710:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15711:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15712:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15713:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15714:                                 $can_clone = 1;
                   15715:                             }
                   15716:                         }
                   15717:                     }
                   15718:                 }
1.578     raeburn  15719:             } else {
1.1221    raeburn  15720: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15721:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15722:                     $can_clone = 1;
1.1221    raeburn  15723:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15724:                     $can_clone = 1;
1.1225    raeburn  15725:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15726:                     $can_clone = 1;
1.1221    raeburn  15727:                 }
                   15728:                 unless ($can_clone) {
1.1225    raeburn  15729:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15730:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15731:                         my (%gotdomdefaults,%gotcodedefaults);
                   15732:                         foreach my $cloner (@cloners) {
                   15733:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15734:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15735:                                 my (%codedefaults,@code_order);
                   15736:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15737:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15738:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15739:                                     }
                   15740:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15741:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15742:                                     }
                   15743:                                 } else {
                   15744:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15745:                                                                             \%codedefaults,
                   15746:                                                                             \@code_order);
                   15747:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15748:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15749:                                 }
                   15750:                                 if (@code_order > 0) {
                   15751:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15752:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15753:                                                                                 $args->{'crscode'})) {
                   15754:                                         $can_clone = 1;
                   15755:                                         last;
                   15756:                                     }
                   15757:                                 }
                   15758:                             }
                   15759:                         }
                   15760:                     }
1.1225    raeburn  15761:                 }
                   15762:             }
                   15763:             unless ($can_clone) {
                   15764:                 my $ccrole = 'cc';
                   15765:                 if ($args->{'crstype'} eq 'Community') {
                   15766:                     $ccrole = 'co';
                   15767:                 }
                   15768: 	        my %roleshash =
                   15769: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15770: 					          $args->{'ccdomain'},
                   15771:                                                   'userroles',['active'],[$ccrole],
                   15772: 					          [$args->{'clonedomain'}]);
                   15773: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15774:                     $can_clone = 1;
                   15775:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15776:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15777:                     $can_clone = 1;
1.1221    raeburn  15778:                 }
                   15779:             }
                   15780:             unless ($can_clone) {
                   15781:                 if ($args->{'crstype'} eq 'Community') {
                   15782:                     $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'});
1.942     raeburn  15783:                 } else {
1.1221    raeburn  15784:                     $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'});
                   15785:                 }
1.566     albertel 15786: 	    }
1.578     raeburn  15787:         }
1.566     albertel 15788:     }
                   15789:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15790: }
                   15791: 
1.444     albertel 15792: sub construct_course {
1.1262    raeburn  15793:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15794:         $cnum,$category,$coderef) = @_;
1.444     albertel 15795:     my $outcome;
1.541     raeburn  15796:     my $linefeed =  '<br />'."\n";
                   15797:     if ($context eq 'auto') {
                   15798:         $linefeed = "\n";
                   15799:     }
1.566     albertel 15800: 
                   15801: #
                   15802: # Are we cloning?
                   15803: #
                   15804:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15805:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15806: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15807: 	if ($context ne 'auto') {
1.578     raeburn  15808:             if ($clonemsg ne '') {
                   15809: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15810:             }
1.566     albertel 15811: 	}
                   15812: 	$outcome .= $clonemsg.$linefeed;
                   15813: 
                   15814:         if (!$can_clone) {
                   15815: 	    return (0,$outcome);
                   15816: 	}
                   15817:     }
                   15818: 
1.444     albertel 15819: #
                   15820: # Open course
                   15821: #
1.1239    raeburn  15822:     my $showncrstype;
                   15823:     if ($args->{'crstype'} eq 'Placement') {
                   15824:         $showncrstype = 'placement test'; 
                   15825:     } else {  
                   15826:         $showncrstype = lc($args->{'crstype'});
                   15827:     }
1.444     albertel 15828:     my %cenv=();
                   15829:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15830:                                              $args->{'cdescr'},
                   15831:                                              $args->{'curl'},
                   15832:                                              $args->{'course_home'},
                   15833:                                              $args->{'nonstandard'},
                   15834:                                              $args->{'crscode'},
                   15835:                                              $args->{'ccuname'}.':'.
                   15836:                                              $args->{'ccdomain'},
1.882     raeburn  15837:                                              $args->{'crstype'},
1.885     raeburn  15838:                                              $cnum,$context,$category);
1.444     albertel 15839: 
                   15840:     # Note: The testing routines depend on this being output; see 
                   15841:     # Utils::Course. This needs to at least be output as a comment
                   15842:     # if anyone ever decides to not show this, and Utils::Course::new
                   15843:     # will need to be suitably modified.
1.1239    raeburn  15844:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15845:     if ($$courseid =~ /^error:/) {
                   15846:         return (0,$outcome);
                   15847:     }
                   15848: 
1.444     albertel 15849: #
                   15850: # Check if created correctly
                   15851: #
1.479     albertel 15852:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15853:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15854:     if ($crsuhome eq 'no_host') {
                   15855:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15856:         return (0,$outcome);
                   15857:     }
1.541     raeburn  15858:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15859: 
1.444     albertel 15860: #
1.566     albertel 15861: # Do the cloning
                   15862: #   
                   15863:     if ($can_clone && $cloneid) {
1.1239    raeburn  15864: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15865: 	if ($context ne 'auto') {
                   15866: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15867: 	}
                   15868: 	$outcome .= $clonemsg.$linefeed;
                   15869: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15870: # Copy all files
1.637     www      15871: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15872: # Restore URL
1.566     albertel 15873: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15874: # Restore title
1.566     albertel 15875: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15876: # Restore creation date, creator and creation context.
                   15877:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15878:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15879:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15880: # Mark as cloned
1.566     albertel 15881: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15882: # Need to clone grading mode
                   15883:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15884:         $cenv{'grading'}=$newenv{'grading'};
                   15885: # Do not clone these environment entries
                   15886:         &Apache::lonnet::del('environment',
                   15887:                   ['default_enrollment_start_date',
                   15888:                    'default_enrollment_end_date',
                   15889:                    'question.email',
                   15890:                    'policy.email',
                   15891:                    'comment.email',
                   15892:                    'pch.users.denied',
1.725     raeburn  15893:                    'plc.users.denied',
                   15894:                    'hidefromcat',
1.1121    raeburn  15895:                    'checkforpriv',
1.1166    raeburn  15896:                    'categories',
                   15897:                    'internal.uniquecode'],
1.638     www      15898:                    $$crsudom,$$crsunum);
1.1170    raeburn  15899:         if ($args->{'textbook'}) {
                   15900:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15901:         }
1.444     albertel 15902:     }
1.566     albertel 15903: 
1.444     albertel 15904: #
                   15905: # Set environment (will override cloned, if existing)
                   15906: #
                   15907:     my @sections = ();
                   15908:     my @xlists = ();
                   15909:     if ($args->{'crstype'}) {
                   15910:         $cenv{'type'}=$args->{'crstype'};
                   15911:     }
                   15912:     if ($args->{'crsid'}) {
                   15913:         $cenv{'courseid'}=$args->{'crsid'};
                   15914:     }
                   15915:     if ($args->{'crscode'}) {
                   15916:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15917:     }
                   15918:     if ($args->{'crsquota'} ne '') {
                   15919:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15920:     } else {
                   15921:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15922:     }
                   15923:     if ($args->{'ccuname'}) {
                   15924:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15925:                                         ':'.$args->{'ccdomain'};
                   15926:     } else {
                   15927:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15928:     }
1.1116    raeburn  15929:     if ($args->{'defaultcredits'}) {
                   15930:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15931:     }
1.444     albertel 15932:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15933:     if ($args->{'crssections'}) {
                   15934:         $cenv{'internal.sectionnums'} = '';
                   15935:         if ($args->{'crssections'} =~ m/,/) {
                   15936:             @sections = split/,/,$args->{'crssections'};
                   15937:         } else {
                   15938:             $sections[0] = $args->{'crssections'};
                   15939:         }
                   15940:         if (@sections > 0) {
                   15941:             foreach my $item (@sections) {
                   15942:                 my ($sec,$gp) = split/:/,$item;
                   15943:                 my $class = $args->{'crscode'}.$sec;
                   15944:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15945:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15946:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15947:                     push(@badclasses,$class);
1.444     albertel 15948:                 }
                   15949:             }
                   15950:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15951:         }
                   15952:     }
                   15953: # do not hide course coordinator from staff listing, 
                   15954: # even if privileged
                   15955:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15956: # add course coordinator's domain to domains to check for privileged users
                   15957: # if different to course domain
                   15958:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15959:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15960:     }
1.444     albertel 15961: # add crosslistings
                   15962:     if ($args->{'crsxlist'}) {
                   15963:         $cenv{'internal.crosslistings'}='';
                   15964:         if ($args->{'crsxlist'} =~ m/,/) {
                   15965:             @xlists = split/,/,$args->{'crsxlist'};
                   15966:         } else {
                   15967:             $xlists[0] = $args->{'crsxlist'};
                   15968:         }
                   15969:         if (@xlists > 0) {
                   15970:             foreach my $item (@xlists) {
                   15971:                 my ($xl,$gp) = split/:/,$item;
                   15972:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15973:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15974:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15975:                     push(@badclasses,$xl);
1.444     albertel 15976:                 }
                   15977:             }
                   15978:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15979:         }
                   15980:     }
                   15981:     if ($args->{'autoadds'}) {
                   15982:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15983:     }
                   15984:     if ($args->{'autodrops'}) {
                   15985:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15986:     }
                   15987: # check for notification of enrollment changes
                   15988:     my @notified = ();
                   15989:     if ($args->{'notify_owner'}) {
                   15990:         if ($args->{'ccuname'} ne '') {
                   15991:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15992:         }
                   15993:     }
                   15994:     if ($args->{'notify_dc'}) {
                   15995:         if ($uname ne '') { 
1.630     raeburn  15996:             push(@notified,$uname.':'.$udom);
1.444     albertel 15997:         }
                   15998:     }
                   15999:     if (@notified > 0) {
                   16000:         my $notifylist;
                   16001:         if (@notified > 1) {
                   16002:             $notifylist = join(',',@notified);
                   16003:         } else {
                   16004:             $notifylist = $notified[0];
                   16005:         }
                   16006:         $cenv{'internal.notifylist'} = $notifylist;
                   16007:     }
                   16008:     if (@badclasses > 0) {
                   16009:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16010:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16011:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16012:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16013:         );
1.1264    raeburn  16014:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16015:                            &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'};
1.541     raeburn  16016:         if ($context eq 'auto') {
                   16017:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16018:         } else {
1.566     albertel 16019:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16020:         }
                   16021:         foreach my $item (@badclasses) {
1.541     raeburn  16022:             if ($context eq 'auto') {
1.1261    raeburn  16023:                 $outcome .= " - $item\n";
1.541     raeburn  16024:             } else {
1.1261    raeburn  16025:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16026:             }
1.1261    raeburn  16027:         }
                   16028:         if ($context eq 'auto') {
                   16029:             $outcome .= $linefeed;
                   16030:         } else {
                   16031:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16032:         } 
1.444     albertel 16033:     }
                   16034:     if ($args->{'no_end_date'}) {
                   16035:         $args->{'endaccess'} = 0;
                   16036:     }
                   16037:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16038:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16039:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16040:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16041:     if ($args->{'showphotos'}) {
                   16042:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16043:     }
                   16044:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16045:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16046:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16047:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16048:             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'); 
                   16049:             if ($context eq 'auto') {
                   16050:                 $outcome .= $krb_msg;
                   16051:             } else {
1.566     albertel 16052:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16053:             }
                   16054:             $outcome .= $linefeed;
1.444     albertel 16055:         }
                   16056:     }
                   16057:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16058:        if ($args->{'setpolicy'}) {
                   16059:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16060:        }
                   16061:        if ($args->{'setcontent'}) {
                   16062:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16063:        }
1.1251    raeburn  16064:        if ($args->{'setcomment'}) {
                   16065:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16066:        }
1.444     albertel 16067:     }
                   16068:     if ($args->{'reshome'}) {
                   16069: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16070: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16071:     }
                   16072: #
                   16073: # course has keyed access
                   16074: #
                   16075:     if ($args->{'setkeys'}) {
                   16076:        $cenv{'keyaccess'}='yes';
                   16077:     }
                   16078: # if specified, key authority is not course, but user
                   16079: # only active if keyaccess is yes
                   16080:     if ($args->{'keyauth'}) {
1.487     albertel 16081: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16082: 	$user = &LONCAPA::clean_username($user);
                   16083: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16084: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16085: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16086: 	}
                   16087:     }
                   16088: 
1.1166    raeburn  16089: #
1.1167    raeburn  16090: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16091: #
                   16092:     if ($args->{'uniquecode'}) {
                   16093:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16094:         if ($code) {
                   16095:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16096:             my %crsinfo =
                   16097:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16098:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16099:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16100:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16101:             } 
1.1166    raeburn  16102:             if (ref($coderef)) {
                   16103:                 $$coderef = $code;
                   16104:             }
                   16105:         }
                   16106:     }
                   16107: 
1.444     albertel 16108:     if ($args->{'disresdis'}) {
                   16109:         $cenv{'pch.roles.denied'}='st';
                   16110:     }
                   16111:     if ($args->{'disablechat'}) {
                   16112:         $cenv{'plc.roles.denied'}='st';
                   16113:     }
                   16114: 
                   16115:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16116:     # course
                   16117:     $cenv{'course.helper.not.run'} = 1;
                   16118:     #
                   16119:     # Use new Randomseed
                   16120:     #
                   16121:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16122:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16123:     #
                   16124:     # The encryption code and receipt prefix for this course
                   16125:     #
                   16126:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16127:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16128:     #
                   16129:     # By default, use standard grading
                   16130:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16131: 
1.541     raeburn  16132:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16133:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16134: #
                   16135: # Open all assignments
                   16136: #
                   16137:     if ($args->{'openall'}) {
                   16138:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   16139:        my %storecontent = ($storeunder         => time,
                   16140:                            $storeunder.'.type' => 'date_start');
                   16141:        
                   16142:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  16143:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16144:    }
                   16145: #
                   16146: # Set first page
                   16147: #
                   16148:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16149: 	    || ($cloneid)) {
1.445     albertel 16150: 	use LONCAPA::map;
1.444     albertel 16151: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16152: 
                   16153: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16154:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16155: 
1.444     albertel 16156:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16157:         my $title; my $url;
                   16158:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16159: 	    $title=&mt('Syllabus');
1.444     albertel 16160:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16161:         } else {
1.963     raeburn  16162:             $title=&mt('Table of Contents');
1.444     albertel 16163:             $url='/adm/navmaps';
                   16164:         }
1.445     albertel 16165: 
                   16166:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16167: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16168: 
                   16169: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16170:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16171:     }
1.566     albertel 16172: 
1.1237    raeburn  16173: # 
                   16174: # Set params for Placement Tests
                   16175: #
1.1239    raeburn  16176:     if ($args->{'crstype'} eq 'Placement') {
                   16177:        my %storecontent; 
                   16178:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16179:        my %defaults = (
                   16180:                         buttonshide   => { value => 'yes',
                   16181:                                            type => 'string_yesno',},
                   16182:                         type          => { value => 'randomizetry',
                   16183:                                            type  => 'string_questiontype',},
                   16184:                         maxtries      => { value => 1,
                   16185:                                            type => 'int_pos',},
                   16186:                         problemstatus => { value => 'no',
                   16187:                                            type  => 'string_problemstatus',},
                   16188:                       );
                   16189:        foreach my $key (keys(%defaults)) {
                   16190:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16191:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16192:        }
1.1237    raeburn  16193:        &Apache::lonnet::cput
                   16194:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16195:     }
                   16196: 
1.566     albertel 16197:     return (1,$outcome);
1.444     albertel 16198: }
                   16199: 
1.1166    raeburn  16200: sub make_unique_code {
                   16201:     my ($cdom,$cnum) = @_;
                   16202:     # get lock on uniquecodes db
                   16203:     my $lockhash = {
                   16204:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16205:                                                   ':'.$env{'user.domain'},
                   16206:                    };
                   16207:     my $tries = 0;
                   16208:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16209:     my ($code,$error);
                   16210:   
                   16211:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16212:         $tries ++;
                   16213:         sleep 1;
                   16214:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16215:     }
                   16216:     if ($gotlock eq 'ok') {
                   16217:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16218:         my $gotcode;
                   16219:         my $attempts = 0;
                   16220:         while ((!$gotcode) && ($attempts < 100)) {
                   16221:             $code = &generate_code();
                   16222:             if (!exists($currcodes{$code})) {
                   16223:                 $gotcode = 1;
                   16224:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16225:                     $error = 'nostore';
                   16226:                 }
                   16227:             }
                   16228:             $attempts ++;
                   16229:         }
                   16230:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16231:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16232:     } else {
                   16233:         $error = 'nolock';
                   16234:     }
                   16235:     return ($code,$error);
                   16236: }
                   16237: 
                   16238: sub generate_code {
                   16239:     my $code;
                   16240:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16241:     for (my $i=0; $i<6; $i++) {
                   16242:         my $lettnum = int (rand 2);
                   16243:         my $item = '';
                   16244:         if ($lettnum) {
                   16245:             $item = $letts[int( rand(18) )];
                   16246:         } else {
                   16247:             $item = 1+int( rand(8) );
                   16248:         }
                   16249:         $code .= $item;
                   16250:     }
                   16251:     return $code;
                   16252: }
                   16253: 
1.444     albertel 16254: ############################################################
                   16255: ############################################################
                   16256: 
1.1237    raeburn  16257: # Community, Course and Placement Test
1.378     raeburn  16258: sub course_type {
                   16259:     my ($cid) = @_;
                   16260:     if (!defined($cid)) {
                   16261:         $cid = $env{'request.course.id'};
                   16262:     }
1.404     albertel 16263:     if (defined($env{'course.'.$cid.'.type'})) {
                   16264:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16265:     } else {
                   16266:         return 'Course';
1.377     raeburn  16267:     }
                   16268: }
1.156     albertel 16269: 
1.406     raeburn  16270: sub group_term {
                   16271:     my $crstype = &course_type();
                   16272:     my %names = (
                   16273:                   'Course' => 'group',
1.865     raeburn  16274:                   'Community' => 'group',
1.1237    raeburn  16275:                   'Placement' => 'group',
1.406     raeburn  16276:                 );
                   16277:     return $names{$crstype};
                   16278: }
                   16279: 
1.902     raeburn  16280: sub course_types {
1.1310    raeburn  16281:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16282:     my %typename = (
                   16283:                          official   => 'Official course',
                   16284:                          unofficial => 'Unofficial course',
                   16285:                          community  => 'Community',
1.1165    raeburn  16286:                          textbook   => 'Textbook course',
1.1237    raeburn  16287:                          placement  => 'Placement test',
1.1310    raeburn  16288:                          lti        => 'LTI provider',
1.902     raeburn  16289:                    );
                   16290:     return (\@types,\%typename);
                   16291: }
                   16292: 
1.156     albertel 16293: sub icon {
                   16294:     my ($file)=@_;
1.505     albertel 16295:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16296:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16297:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16298:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16299: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16300: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16301: 	            $curfext.".gif") {
                   16302: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16303: 		$curfext.".gif";
                   16304: 	}
                   16305:     }
1.249     albertel 16306:     return &lonhttpdurl($iconname);
1.154     albertel 16307: } 
1.84      albertel 16308: 
1.575     albertel 16309: sub lonhttpdurl {
1.692     www      16310: #
                   16311: # Had been used for "small fry" static images on separate port 8080.
                   16312: # Modify here if lightweight http functionality desired again.
                   16313: # Currently eliminated due to increasing firewall issues.
                   16314: #
1.575     albertel 16315:     my ($url)=@_;
1.692     www      16316:     return $url;
1.215     albertel 16317: }
                   16318: 
1.213     albertel 16319: sub connection_aborted {
                   16320:     my ($r)=@_;
                   16321:     $r->print(" ");$r->rflush();
                   16322:     my $c = $r->connection;
                   16323:     return $c->aborted();
                   16324: }
                   16325: 
1.221     foxr     16326: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16327: #    strings as 'strings'.
                   16328: sub escape_single {
1.221     foxr     16329:     my ($input) = @_;
1.223     albertel 16330:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16331:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16332:     return $input;
                   16333: }
1.223     albertel 16334: 
1.222     foxr     16335: #  Same as escape_single, but escape's "'s  This 
                   16336: #  can be used for  "strings"
                   16337: sub escape_double {
                   16338:     my ($input) = @_;
                   16339:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16340:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16341:     return $input;
                   16342: }
1.223     albertel 16343:  
1.222     foxr     16344: #   Escapes the last element of a full URL.
                   16345: sub escape_url {
                   16346:     my ($url)   = @_;
1.238     raeburn  16347:     my @urlslices = split(/\//, $url,-1);
1.369     www      16348:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16349:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16350: }
1.462     albertel 16351: 
1.820     raeburn  16352: sub compare_arrays {
                   16353:     my ($arrayref1,$arrayref2) = @_;
                   16354:     my (@difference,%count);
                   16355:     @difference = ();
                   16356:     %count = ();
                   16357:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16358:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16359:         foreach my $element (keys(%count)) {
                   16360:             if ($count{$element} == 1) {
                   16361:                 push(@difference,$element);
                   16362:             }
                   16363:         }
                   16364:     }
                   16365:     return @difference;
                   16366: }
                   16367: 
1.817     bisitz   16368: # -------------------------------------------------------- Initialize user login
1.462     albertel 16369: sub init_user_environment {
1.463     albertel 16370:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16371:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16372: 
                   16373:     my $public=($username eq 'public' && $domain eq 'public');
                   16374: 
1.1062    raeburn  16375:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16376:     my $now=time;
                   16377: 
                   16378:     if ($public) {
                   16379: 	my $max_public=100;
                   16380: 	my $oldest;
                   16381: 	my $oldest_time=0;
                   16382: 	for(my $next=1;$next<=$max_public;$next++) {
                   16383: 	    if (-e $lonids."/publicuser_$next.id") {
                   16384: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16385: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16386: 		    $oldest_time=$mtime;
                   16387: 		    $oldest=$next;
                   16388: 		}
                   16389: 	    } else {
                   16390: 		$cookie="publicuser_$next";
                   16391: 		last;
                   16392: 	    }
                   16393: 	}
                   16394: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16395:     } else {
1.1275    raeburn  16396: 	# See if old ID present, if so, remove if this isn't a robot,
                   16397: 	# killing any existing non-robot sessions
1.463     albertel 16398: 	if (!$args->{'robot'}) {
                   16399: 	    opendir(DIR,$lonids);
                   16400: 	    while ($filename=readdir(DIR)) {
                   16401: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1295    raeburn  16402:                     if ($ENV{'SERVER_PORT'} == 443) {
                   16403:                         my $linkedfile;
                   16404:                         if (tie(my %oldenv,'GDBM_File',"$lonids/$cookie.id",
                   16405:                                 &GDBM_READER(),0640)) {
                   16406:                             if (exists($oldenv{'user.linkedenv'})) {
                   16407:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   16408:                             }
                   16409:                             untie(%oldenv);
                   16410:                         }
                   16411:                         if (unlink($lonids.'/'.$filename)) {
                   16412:                             if ($linkedfile =~ /^[a-f0-9]+_linked\.id$/) {
                   16413:                                 unlink($lonids.'/'.$linkedfile);
                   16414:                             }
                   16415:                         }
                   16416:                     } else {
                   16417:                         unlink($lonids.'/'.$filename);
                   16418:                     }
1.463     albertel 16419: 		}
1.462     albertel 16420: 	    }
1.463     albertel 16421: 	    closedir(DIR);
1.1204    raeburn  16422: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16423:             my $namespace = 'nohist_courseeditor';
                   16424:             my $lockingkey = 'paste'."\0".'locked_num';
                   16425:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16426:                                                 $domain,$username);
                   16427:             if (exists($lockhash{$lockingkey})) {
                   16428:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16429:                 unless ($delresult eq 'ok') {
                   16430:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16431:                 }
                   16432:             }
1.462     albertel 16433: 	}
                   16434: # Give them a new cookie
1.463     albertel 16435: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16436: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16437: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16438:     
                   16439: # Initialize roles
                   16440: 
1.1062    raeburn  16441: 	($userroles,$firstaccenv,$timerintenv) = 
                   16442:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16443:     }
                   16444: # ------------------------------------ Check browser type and MathML capability
                   16445: 
1.1194    raeburn  16446:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16447:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16448: 
                   16449: # ------------------------------------------------------------- Get environment
                   16450: 
                   16451:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16452:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16453:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16454: 	undef(%userenv);
                   16455:     }
                   16456:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16457: 	$form->{'interface'}=$userenv{'interface'};
                   16458:     }
                   16459:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16460: 
                   16461: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16462:     foreach my $option ('interface','localpath','localres') {
                   16463:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16464:     }
                   16465: # --------------------------------------------------------- Write first profile
                   16466: 
                   16467:     {
                   16468: 	my %initial_env = 
                   16469: 	    ("user.name"          => $username,
                   16470: 	     "user.domain"        => $domain,
                   16471: 	     "user.home"          => $authhost,
                   16472: 	     "browser.type"       => $clientbrowser,
                   16473: 	     "browser.version"    => $clientversion,
                   16474: 	     "browser.mathml"     => $clientmathml,
                   16475: 	     "browser.unicode"    => $clientunicode,
                   16476: 	     "browser.os"         => $clientos,
1.1137    raeburn  16477:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16478:              "browser.info"       => $clientinfo,
1.1194    raeburn  16479:              "browser.osversion"  => $clientosversion,
1.462     albertel 16480: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16481: 	     "request.course.fn"  => '',
                   16482: 	     "request.course.uri" => '',
                   16483: 	     "request.course.sec" => '',
                   16484: 	     "request.role"       => 'cm',
                   16485: 	     "request.role.adv"   => $env{'user.adv'},
                   16486: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16487: 
                   16488:         if ($form->{'localpath'}) {
                   16489: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16490: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16491:         }
                   16492: 	
                   16493: 	if ($form->{'interface'}) {
                   16494: 	    $form->{'interface'}=~s/\W//gs;
                   16495: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16496: 	    $env{'browser.interface'}=$form->{'interface'};
                   16497: 	}
                   16498: 
1.1157    raeburn  16499:         if ($form->{'iptoken'}) {
                   16500:             my $lonhost = $r->dir_config('lonHostID');
                   16501:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16502:             $env{'user.noloadbalance'} = $lonhost;
                   16503:         }
                   16504: 
1.1268    raeburn  16505:         if ($form->{'noloadbalance'}) {
                   16506:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16507:             my $hosthere = $form->{'noloadbalance'};
                   16508:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16509:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16510:                 $env{'user.noloadbalance'} = $hosthere;
                   16511:             }
                   16512:         }
                   16513: 
1.1016    raeburn  16514:         unless ($domain eq 'public') {
1.1273    raeburn  16515:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16516:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16517: 
                   16518:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16519:                 $userenv{'availabletools.'.$tool} = 
                   16520:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16521:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16522:             }
1.980     raeburn  16523: 
1.1311    raeburn  16524:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  16525:                 $userenv{'canrequest.'.$crstype} =
                   16526:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16527:                                                       'reload','requestcourses',
                   16528:                                                       \%userenv,\%domdef,\%is_adv);
                   16529:             }
1.724     raeburn  16530: 
1.1273    raeburn  16531:             $userenv{'canrequest.author'} =
                   16532:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16533:                                                   'reload','requestauthor',
1.980     raeburn  16534:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16535:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16536:                                                  $domain,$username);
                   16537:             my $reqstatus = $reqauthor{'author_status'};
                   16538:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16539:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16540:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16541:                                                       $reqauthor{'author'}{'timestamp'};
                   16542:                 }
1.1092    raeburn  16543:             }
1.1287    raeburn  16544:             my ($types,$typename) = &course_types();
                   16545:             if (ref($types) eq 'ARRAY') {
                   16546:                 my @options = ('approval','validate','autolimit');
                   16547:                 my $optregex = join('|',@options);
                   16548:                 my (%willtrust,%trustchecked);
                   16549:                 foreach my $type (@{$types}) {
                   16550:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16551:                     if ($dom_str ne '') {
                   16552:                         my $updatedstr = '';
                   16553:                         my @possdomains = split(',',$dom_str);
                   16554:                         foreach my $entry (@possdomains) {
                   16555:                             my ($extdom,$extopt) = split(':',$entry);
                   16556:                             unless ($trustchecked{$extdom}) {
                   16557:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16558:                                 $trustchecked{$extdom} = 1;
                   16559:                             }
                   16560:                             if ($willtrust{$extdom}) {
                   16561:                                 $updatedstr .= $entry.',';
                   16562:                             }
                   16563:                         }
                   16564:                         $updatedstr =~ s/,$//;
                   16565:                         if ($updatedstr) {
                   16566:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16567:                         } else {
                   16568:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16569:                         }
                   16570:                     }
                   16571:                 }
                   16572:             }
1.1092    raeburn  16573:         }
1.462     albertel 16574: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16575: 
1.462     albertel 16576: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16577: 		 &GDBM_WRCREAT(),0640)) {
                   16578: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16579: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16580: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16581:             if (ref($firstaccenv) eq 'HASH') {
                   16582:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16583:             }
                   16584:             if (ref($timerintenv) eq 'HASH') {
                   16585:                 &_add_to_env(\%disk_env,$timerintenv);
                   16586:             }
1.463     albertel 16587: 	    if (ref($args->{'extra_env'})) {
                   16588: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16589: 	    }
1.462     albertel 16590: 	    untie(%disk_env);
                   16591: 	} else {
1.705     tempelho 16592: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16593: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16594: 	    return 'error: '.$!;
                   16595: 	}
                   16596:     }
                   16597:     $env{'request.role'}='cm';
                   16598:     $env{'request.role.adv'}=$env{'user.adv'};
                   16599:     $env{'browser.type'}=$clientbrowser;
                   16600: 
                   16601:     return $cookie;
                   16602: 
                   16603: }
                   16604: 
                   16605: sub _add_to_env {
                   16606:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16607:     if (ref($env_data) eq 'HASH') {
                   16608:         while (my ($key,$value) = each(%$env_data)) {
                   16609: 	    $idf->{$prefix.$key} = $value;
                   16610: 	    $env{$prefix.$key}   = $value;
                   16611:         }
1.462     albertel 16612:     }
                   16613: }
                   16614: 
1.685     tempelho 16615: # --- Get the symbolic name of a problem and the url
                   16616: sub get_symb {
                   16617:     my ($request,$silent) = @_;
1.726     raeburn  16618:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16619:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16620:     if ($symb eq '') {
                   16621:         if (!$silent) {
1.1071    raeburn  16622:             if (ref($request)) { 
                   16623:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16624:             }
1.685     tempelho 16625:             return ();
                   16626:         }
                   16627:     }
                   16628:     &Apache::lonenc::check_decrypt(\$symb);
                   16629:     return ($symb);
                   16630: }
                   16631: 
                   16632: # --------------------------------------------------------------Get annotation
                   16633: 
                   16634: sub get_annotation {
                   16635:     my ($symb,$enc) = @_;
                   16636: 
                   16637:     my $key = $symb;
                   16638:     if (!$enc) {
                   16639:         $key =
                   16640:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16641:     }
                   16642:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16643:     return $annotation{$key};
                   16644: }
                   16645: 
                   16646: sub clean_symb {
1.731     raeburn  16647:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16648: 
                   16649:     &Apache::lonenc::check_decrypt(\$symb);
                   16650:     my $enc = $env{'request.enc'};
1.731     raeburn  16651:     if ($delete_enc) {
1.730     raeburn  16652:         delete($env{'request.enc'});
                   16653:     }
1.685     tempelho 16654: 
                   16655:     return ($symb,$enc);
                   16656: }
1.462     albertel 16657: 
1.1181    raeburn  16658: ############################################################
                   16659: ############################################################
                   16660: 
                   16661: =pod
                   16662: 
                   16663: =head1 Routines for building display used to search for courses
                   16664: 
                   16665: 
                   16666: =over 4
                   16667: 
                   16668: =item * &build_filters()
                   16669: 
                   16670: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16671: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16672: and quotacheck.pl
                   16673: 
1.1181    raeburn  16674: 
                   16675: Inputs:
                   16676: 
                   16677: filterlist - anonymous array of fields to include as potential filters 
                   16678: 
                   16679: crstype - course type
                   16680: 
                   16681: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16682:               to pop-open a course selector (will contain "extra element"). 
                   16683: 
                   16684: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16685: 
                   16686: filter - anonymous hash of criteria and their values
                   16687: 
                   16688: action - form action
                   16689: 
                   16690: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16691: 
1.1182    raeburn  16692: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16693: 
                   16694: cloneruname - username of owner of new course who wants to clone
                   16695: 
                   16696: clonerudom - domain of owner of new course who wants to clone
                   16697: 
                   16698: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16699: 
                   16700: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16701: 
                   16702: codedom - domain
                   16703: 
                   16704: formname - value of form element named "form". 
                   16705: 
                   16706: fixeddom - domain, if fixed.
                   16707: 
                   16708: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16709: 
                   16710: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16711: 
                   16712: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16713: 
                   16714: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16715: 
                   16716: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16717: 
                   16718: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16719: 
                   16720: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16721: 
1.1182    raeburn  16722: 
1.1181    raeburn  16723: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16724: 
1.1182    raeburn  16725: 
1.1181    raeburn  16726: Side Effects: None
                   16727: 
                   16728: =cut
                   16729: 
                   16730: # ---------------------------------------------- search for courses based on last activity etc.
                   16731: 
                   16732: sub build_filters {
                   16733:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16734:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16735:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16736:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16737:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16738:     my ($list,$jscript);
1.1181    raeburn  16739:     my $onchange = 'javascript:updateFilters(this)';
                   16740:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16741:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16742:         $typeselectform,$instcodetitle);
                   16743:     if ($formname eq '') {
                   16744:         $formname = $caller;
                   16745:     }
                   16746:     foreach my $item (@{$filterlist}) {
                   16747:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16748:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16749:             if ($item eq 'domainfilter') {
                   16750:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16751:             } elsif ($item eq 'coursefilter') {
                   16752:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16753:             } elsif ($item eq 'ownerfilter') {
                   16754:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16755:             } elsif ($item eq 'ownerdomfilter') {
                   16756:                 $filter->{'ownerdomfilter'} =
                   16757:                     &LONCAPA::clean_domain($filter->{$item});
                   16758:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16759:                                                        'ownerdomfilter',1);
                   16760:             } elsif ($item eq 'personfilter') {
                   16761:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16762:             } elsif ($item eq 'persondomfilter') {
                   16763:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16764:                                                         'persondomfilter',1);
                   16765:             } else {
                   16766:                 $filter->{$item} =~ s/\W//g;
                   16767:             }
                   16768:             if (!$filter->{$item}) {
                   16769:                 $filter->{$item} = '';
                   16770:             }
                   16771:         }
                   16772:         if ($item eq 'domainfilter') {
                   16773:             my $allow_blank = 1;
                   16774:             if ($formname eq 'portform') {
                   16775:                 $allow_blank=0;
                   16776:             } elsif ($formname eq 'studentform') {
                   16777:                 $allow_blank=0;
                   16778:             }
                   16779:             if ($fixeddom) {
                   16780:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16781:                                     ' value="'.$codedom.'" />'.
                   16782:                                     &Apache::lonnet::domain($codedom,'description');
                   16783:             } else {
                   16784:                 $domainselectform = &select_dom_form($filter->{$item},
                   16785:                                                      'domainfilter',
                   16786:                                                       $allow_blank,'',$onchange);
                   16787:             }
                   16788:         } else {
                   16789:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16790:         }
                   16791:     }
                   16792: 
                   16793:     # last course activity filter and selection
                   16794:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16795: 
                   16796:     # course created filter and selection
                   16797:     if (exists($filter->{'createdfilter'})) {
                   16798:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16799:     }
                   16800: 
1.1239    raeburn  16801:     my $prefix = $crstype;
                   16802:     if ($crstype eq 'Placement') {
                   16803:         $prefix = 'Placement Test'
                   16804:     }
1.1181    raeburn  16805:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16806:                 'cac' => "$prefix Activity",
                   16807:                 'ccr' => "$prefix Created",
                   16808:                 'cde' => "$prefix Title",
                   16809:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16810:                 'ins' => 'Institutional Code',
                   16811:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16812:                 'cow' => "$prefix Owner/Co-owner",
                   16813:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16814:                 'cog' => 'Type',
                   16815:              );
                   16816: 
                   16817:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16818:         my $typeval = 'Course';
                   16819:         if ($crstype eq 'Community') {
                   16820:             $typeval = 'Community';
1.1239    raeburn  16821:         } elsif ($crstype eq 'Placement') {
                   16822:             $typeval = 'Placement';
1.1181    raeburn  16823:         }
                   16824:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16825:     } else {
                   16826:         $typeselectform =  '<select name="type" size="1"';
                   16827:         if ($onchange) {
                   16828:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16829:         }
                   16830:         $typeselectform .= '>'."\n";
1.1237    raeburn  16831:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16832:             my $shown;
                   16833:             if ($posstype eq 'Placement') {
                   16834:                 $shown = &mt('Placement Test');
                   16835:             } else {
                   16836:                 $shown = &mt($posstype);
                   16837:             }
1.1181    raeburn  16838:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16839:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16840:         }
                   16841:         $typeselectform.="</select>";
                   16842:     }
                   16843: 
                   16844:     my ($cloneableonlyform,$cloneabletitle);
                   16845:     if (exists($filter->{'cloneableonly'})) {
                   16846:         my $cloneableon = '';
                   16847:         my $cloneableoff = ' checked="checked"';
                   16848:         if ($filter->{'cloneableonly'}) {
                   16849:             $cloneableon = $cloneableoff;
                   16850:             $cloneableoff = '';
                   16851:         }
                   16852:         $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>';
                   16853:         if ($formname eq 'ccrs') {
1.1187    bisitz   16854:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16855:         } else {
                   16856:             $cloneabletitle = &mt('Cloneable by you');
                   16857:         }
                   16858:     }
                   16859:     my $officialjs;
                   16860:     if ($crstype eq 'Course') {
                   16861:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16862: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16863: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16864:             if ($codedom) { 
1.1181    raeburn  16865:                 $officialjs = 1;
                   16866:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16867:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16868:                                                                   $officialjs,$codetitlesref);
                   16869:                 if ($jscript) {
1.1182    raeburn  16870:                     $jscript = '<script type="text/javascript">'."\n".
                   16871:                                '// <![CDATA['."\n".
                   16872:                                $jscript."\n".
                   16873:                                '// ]]>'."\n".
                   16874:                                '</script>'."\n";
1.1181    raeburn  16875:                 }
                   16876:             }
                   16877:             if ($instcodeform eq '') {
                   16878:                 $instcodeform =
                   16879:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16880:                     $list->{'instcodefilter'}.'" />';
                   16881:                 $instcodetitle = $lt{'ins'};
                   16882:             } else {
                   16883:                 $instcodetitle = $lt{'inc'};
                   16884:             }
                   16885:             if ($fixeddom) {
                   16886:                 $instcodetitle .= '<br />('.$codedom.')';
                   16887:             }
                   16888:         }
                   16889:     }
                   16890:     my $output = qq|
                   16891: <form method="post" name="filterpicker" action="$action">
                   16892: <input type="hidden" name="form" value="$formname" />
                   16893: |;
                   16894:     if ($formname eq 'modifycourse') {
                   16895:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16896:                    '<input type="hidden" name="prevphase" value="'.
                   16897:                    $prevphase.'" />'."\n";
1.1198    musolffc 16898:     } elsif ($formname eq 'quotacheck') {
                   16899:         $output .= qq|
                   16900: <input type="hidden" name="sortby" value="" />
                   16901: <input type="hidden" name="sortorder" value="" />
                   16902: |;
                   16903:     } else {
1.1181    raeburn  16904:         my $name_input;
                   16905:         if ($cnameelement ne '') {
                   16906:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16907:                           $cnameelement.'" />';
                   16908:         }
                   16909:         $output .= qq|
1.1182    raeburn  16910: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16911: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16912: $name_input
                   16913: $roleelement
                   16914: $multelement
                   16915: $typeelement
                   16916: |;
                   16917:         if ($formname eq 'portform') {
                   16918:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16919:         }
                   16920:     }
                   16921:     if ($fixeddom) {
                   16922:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16923:     }
                   16924:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16925:     if ($sincefilterform) {
                   16926:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16927:                   .$sincefilterform
                   16928:                   .&Apache::lonhtmlcommon::row_closure();
                   16929:     }
                   16930:     if ($createdfilterform) {
                   16931:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16932:                   .$createdfilterform
                   16933:                   .&Apache::lonhtmlcommon::row_closure();
                   16934:     }
                   16935:     if ($domainselectform) {
                   16936:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16937:                   .$domainselectform
                   16938:                   .&Apache::lonhtmlcommon::row_closure();
                   16939:     }
                   16940:     if ($typeselectform) {
                   16941:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16942:             $output .= $typeselectform;
                   16943:         } else {
                   16944:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16945:                       .$typeselectform
                   16946:                       .&Apache::lonhtmlcommon::row_closure();
                   16947:         }
                   16948:     }
                   16949:     if ($instcodeform) {
                   16950:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16951:                   .$instcodeform
                   16952:                   .&Apache::lonhtmlcommon::row_closure();
                   16953:     }
                   16954:     if (exists($filter->{'ownerfilter'})) {
                   16955:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16956:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16957:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16958:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16959:                    $ownerdomselectform.'</td></tr></table>'.
                   16960:                    &Apache::lonhtmlcommon::row_closure();
                   16961:     }
                   16962:     if (exists($filter->{'personfilter'})) {
                   16963:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16964:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16965:                    '<input type="text" name="personfilter" size="20" value="'.
                   16966:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16967:                    $persondomselectform.'</td></tr></table>'.
                   16968:                    &Apache::lonhtmlcommon::row_closure();
                   16969:     }
                   16970:     if (exists($filter->{'coursefilter'})) {
                   16971:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16972:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16973:                   .$list->{'coursefilter'}.'" />'
                   16974:                   .&Apache::lonhtmlcommon::row_closure();
                   16975:     }
                   16976:     if ($cloneableonlyform) {
                   16977:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16978:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16979:     }
                   16980:     if (exists($filter->{'descriptfilter'})) {
                   16981:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16982:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16983:                   .$list->{'descriptfilter'}.'" />'
                   16984:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16985:     }
                   16986:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16987:                '<input type="hidden" name="updater" value="" />'."\n".
                   16988:                '<input type="submit" name="gosearch" value="'.
                   16989:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16990:     return $jscript.$clonewarning.$output;
                   16991: }
                   16992: 
                   16993: =pod 
                   16994: 
                   16995: =item * &timebased_select_form()
                   16996: 
1.1182    raeburn  16997: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16998: filter e.g., Course Activity, Course Created, when searching for courses
                   16999: or communities
                   17000: 
                   17001: Inputs:
                   17002: 
                   17003: item - name of form element (sincefilter or createdfilter)
                   17004: 
                   17005: filter - anonymous hash of criteria and their values
                   17006: 
                   17007: Returns: HTML for a select box contained a blank, then six time selections,
                   17008:          with value set in incoming form variables currently selected. 
                   17009: 
                   17010: Side Effects: None
                   17011: 
                   17012: =cut
                   17013: 
                   17014: sub timebased_select_form {
                   17015:     my ($item,$filter) = @_;
                   17016:     if (ref($filter) eq 'HASH') {
                   17017:         $filter->{$item} =~ s/[^\d-]//g;
                   17018:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17019:         return &select_form(
                   17020:                             $filter->{$item},
                   17021:                             $item,
                   17022:                             {      '-1' => '',
                   17023:                                 '86400' => &mt('today'),
                   17024:                                '604800' => &mt('last week'),
                   17025:                               '2592000' => &mt('last month'),
                   17026:                               '7776000' => &mt('last three months'),
                   17027:                              '15552000' => &mt('last six months'),
                   17028:                              '31104000' => &mt('last year'),
                   17029:                     'select_form_order' =>
                   17030:                            ['-1','86400','604800','2592000','7776000',
                   17031:                             '15552000','31104000']});
                   17032:     }
                   17033: }
                   17034: 
                   17035: =pod
                   17036: 
                   17037: =item * &js_changer()
                   17038: 
                   17039: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17040: when course type or domain is changed, and also to hide 'Searching ...' on
                   17041: page load completion for page showing search result.
1.1181    raeburn  17042: 
                   17043: Inputs: None
                   17044: 
1.1183    raeburn  17045: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17046: 
                   17047: Side Effects: None
                   17048: 
                   17049: =cut
                   17050: 
                   17051: sub js_changer {
                   17052:     return <<ENDJS;
                   17053: <script type="text/javascript">
                   17054: // <![CDATA[
                   17055: function updateFilters(caller) {
                   17056:     if (typeof(caller) != "undefined") {
                   17057:         document.filterpicker.updater.value = caller.name;
                   17058:     }
                   17059:     document.filterpicker.submit();
                   17060: }
1.1183    raeburn  17061: 
                   17062: function hideSearching() {
                   17063:     if (document.getElementById('searching')) {
                   17064:         document.getElementById('searching').style.display = 'none';
                   17065:     }
                   17066:     return;
                   17067: }
                   17068: 
1.1181    raeburn  17069: // ]]>
                   17070: </script>
                   17071: 
                   17072: ENDJS
                   17073: }
                   17074: 
                   17075: =pod
                   17076: 
1.1182    raeburn  17077: =item * &search_courses()
                   17078: 
                   17079: Process selected filters form course search form and pass to lonnet::courseiddump
                   17080: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17081: 
                   17082: Inputs:
                   17083: 
                   17084: dom - domain being searched 
                   17085: 
                   17086: type - course type ('Course' or 'Community' or '.' if any).
                   17087: 
                   17088: filter - anonymous hash of criteria and their values
                   17089: 
                   17090: numtitles - for institutional codes - number of categories
                   17091: 
                   17092: cloneruname - optional username of new course owner
                   17093: 
                   17094: clonerudom - optional domain of new course owner
                   17095: 
1.1221    raeburn  17096: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17097:             (used when DC is using course creation form)
                   17098: 
                   17099: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17100: 
1.1221    raeburn  17101: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17102:            (and so can clone automatically)
                   17103: 
                   17104: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17105: 
                   17106: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17107:               courses to clone 
1.1182    raeburn  17108: 
                   17109: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17110: 
                   17111: 
                   17112: Side Effects: None
                   17113: 
                   17114: =cut
                   17115: 
                   17116: 
                   17117: sub search_courses {
1.1221    raeburn  17118:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17119:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17120:     my (%courses,%showcourses,$cloner);
                   17121:     if (($filter->{'ownerfilter'} ne '') ||
                   17122:         ($filter->{'ownerdomfilter'} ne '')) {
                   17123:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17124:                                        $filter->{'ownerdomfilter'};
                   17125:     }
                   17126:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17127:         if (!$filter->{$item}) {
                   17128:             $filter->{$item}='.';
                   17129:         }
                   17130:     }
                   17131:     my $now = time;
                   17132:     my $timefilter =
                   17133:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17134:     my ($createdbefore,$createdafter);
                   17135:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17136:         $createdbefore = $now;
                   17137:         $createdafter = $now-$filter->{'createdfilter'};
                   17138:     }
                   17139:     my ($instcodefilter,$regexpok);
                   17140:     if ($numtitles) {
                   17141:         if ($env{'form.official'} eq 'on') {
                   17142:             $instcodefilter =
                   17143:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17144:             $regexpok = 1;
                   17145:         } elsif ($env{'form.official'} eq 'off') {
                   17146:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17147:             unless ($instcodefilter eq '') {
                   17148:                 $regexpok = -1;
                   17149:             }
                   17150:         }
                   17151:     } else {
                   17152:         $instcodefilter = $filter->{'instcodefilter'};
                   17153:     }
                   17154:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17155:     if ($type eq '') { $type = '.'; }
                   17156: 
                   17157:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17158:         $cloner = $cloneruname.':'.$clonerudom;
                   17159:     }
                   17160:     %courses = &Apache::lonnet::courseiddump($dom,
                   17161:                                              $filter->{'descriptfilter'},
                   17162:                                              $timefilter,
                   17163:                                              $instcodefilter,
                   17164:                                              $filter->{'combownerfilter'},
                   17165:                                              $filter->{'coursefilter'},
                   17166:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17167:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17168:                                              $filter->{'cloneableonly'},
                   17169:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17170:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17171:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17172:         my $ccrole;
                   17173:         if ($type eq 'Community') {
                   17174:             $ccrole = 'co';
                   17175:         } else {
                   17176:             $ccrole = 'cc';
                   17177:         }
                   17178:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17179:                                                      $filter->{'persondomfilter'},
                   17180:                                                      'userroles',undef,
                   17181:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17182:                                                      $dom);
                   17183:         foreach my $role (keys(%rolehash)) {
                   17184:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17185:             my $cid = $cdom.'_'.$cnum;
                   17186:             if (exists($courses{$cid})) {
                   17187:                 if (ref($courses{$cid}) eq 'HASH') {
                   17188:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17189:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17190:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17191:                         }
                   17192:                     } else {
                   17193:                         $courses{$cid}{roles} = [$courserole];
                   17194:                     }
                   17195:                     $showcourses{$cid} = $courses{$cid};
                   17196:                 }
                   17197:             }
                   17198:         }
                   17199:         %courses = %showcourses;
                   17200:     }
                   17201:     return %courses;
                   17202: }
                   17203: 
                   17204: =pod
                   17205: 
1.1181    raeburn  17206: =back
                   17207: 
1.1207    raeburn  17208: =head1 Routines for version requirements for current course.
                   17209: 
                   17210: =over 4
                   17211: 
                   17212: =item * &check_release_required()
                   17213: 
                   17214: Compares required LON-CAPA version with version on server, and
                   17215: if required version is newer looks for a server with the required version.
                   17216: 
                   17217: Looks first at servers in user's owen domain; if none suitable, looks at
                   17218: servers in course's domain are permitted to host sessions for user's domain.
                   17219: 
                   17220: Inputs:
                   17221: 
                   17222: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17223: 
                   17224: $courseid - Course ID of current course
                   17225: 
                   17226: $rolecode - User's current role in course (for switchserver query string).
                   17227: 
                   17228: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17229: 
                   17230: 
                   17231: Returns:
                   17232: 
                   17233: $switchserver - query string tp append to /adm/switchserver call (if 
                   17234:                 current server's LON-CAPA version is too old. 
                   17235: 
                   17236: $warning - Message is displayed if no suitable server could be found.
                   17237: 
                   17238: =cut
                   17239: 
                   17240: sub check_release_required {
                   17241:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17242:     my ($switchserver,$warning);
                   17243:     if ($required ne '') {
                   17244:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17245:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17246:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17247:             my $otherserver;
                   17248:             if (($major eq '' && $minor eq '') ||
                   17249:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17250:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17251:                 my $switchlcrev =
                   17252:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17253:                                                            $userdomserver);
                   17254:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17255:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17256:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17257:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17258:                     if ($cdom ne $env{'user.domain'}) {
                   17259:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17260:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17261:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17262:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17263:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17264:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17265:                         my $canhost =
                   17266:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17267:                                                               $coursedomserver,
                   17268:                                                               $remoterev,
                   17269:                                                               $udomdefaults{'remotesessions'},
                   17270:                                                               $defdomdefaults{'hostedsessions'});
                   17271: 
                   17272:                         if ($canhost) {
                   17273:                             $otherserver = $coursedomserver;
                   17274:                         } else {
                   17275:                             $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.");
                   17276:                         }
                   17277:                     } else {
                   17278:                         $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).");
                   17279:                     }
                   17280:                 } else {
                   17281:                     $otherserver = $userdomserver;
                   17282:                 }
                   17283:             }
                   17284:             if ($otherserver ne '') {
                   17285:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17286:             }
                   17287:         }
                   17288:     }
                   17289:     return ($switchserver,$warning);
                   17290: }
                   17291: 
                   17292: =pod
                   17293: 
                   17294: =item * &check_release_result()
                   17295: 
                   17296: Inputs:
                   17297: 
                   17298: $switchwarning - Warning message if no suitable server found to host session.
                   17299: 
                   17300: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17301:                 and current role.
                   17302: 
                   17303: Returns: HTML to display with information about requirement to switch server.
                   17304:          Either displaying warning with link to Roles/Courses screen or
                   17305:          display link to switchserver.
                   17306: 
1.1181    raeburn  17307: =cut
                   17308: 
1.1207    raeburn  17309: sub check_release_result {
                   17310:     my ($switchwarning,$switchserver) = @_;
                   17311:     my $output = &start_page('Selected course unavailable on this server').
                   17312:                  '<p class="LC_warning">';
                   17313:     if ($switchwarning) {
                   17314:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17315:         if (&show_course()) {
                   17316:             $output .= &mt('Display courses');
                   17317:         } else {
                   17318:             $output .= &mt('Display roles');
                   17319:         }
                   17320:         $output .= '</a>';
                   17321:     } elsif ($switchserver) {
                   17322:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17323:                    '<br />'.
                   17324:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17325:                    &mt('Switch Server').
                   17326:                    '</a>';
                   17327:     }
                   17328:     $output .= '</p>'.&end_page();
                   17329:     return $output;
                   17330: }
                   17331: 
                   17332: =pod
                   17333: 
                   17334: =item * &needs_coursereinit()
                   17335: 
                   17336: Determine if course contents stored for user's session needs to be
                   17337: refreshed, because content has changed since "Big Hash" last tied.
                   17338: 
                   17339: Check for change is made if time last checked is more than 10 minutes ago
                   17340: (by default).
                   17341: 
                   17342: Inputs:
                   17343: 
                   17344: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17345: 
                   17346: $interval (optional) - Time which may elapse (in s) between last check for content
                   17347:                        change in current course. (default: 600 s).  
                   17348: 
                   17349: Returns: an array; first element is:
                   17350: 
                   17351: =over 4
                   17352: 
                   17353: 'switch' - if content updates mean user's session
                   17354:            needs to be switched to a server running a newer LON-CAPA version
                   17355:  
                   17356: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17357:            on current server hosting user's session                
                   17358: 
                   17359: ''       - if no action required.
                   17360: 
                   17361: =back
                   17362: 
                   17363: If first item element is 'switch':
                   17364: 
                   17365: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17366: 
                   17367: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17368:                               and current role. 
                   17369: 
                   17370: otherwise: no other elements returned.
                   17371: 
                   17372: =back
                   17373: 
                   17374: =cut
                   17375: 
                   17376: sub needs_coursereinit {
                   17377:     my ($loncaparev,$interval) = @_;
                   17378:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17379:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17380:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17381:     my $now = time;
                   17382:     if ($interval eq '') {
                   17383:         $interval = 600;
                   17384:     }
                   17385:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17386:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17387:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17388:         if ($blocked) {
                   17389:             return ();
                   17390:         }
1.1207    raeburn  17391:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17392:         if ($lastchange > $env{'request.course.tied'}) {
                   17393:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17394:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17395:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17396:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17397:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17398:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17399:                     my ($switchserver,$switchwarning) =
                   17400:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17401:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17402:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17403:                         return ('switch',$switchwarning,$switchserver);
                   17404:                     }
                   17405:                 }
                   17406:             }
                   17407:             return ('update');
                   17408:         }
                   17409:     }
                   17410:     return ();
                   17411: }
1.1181    raeburn  17412: 
1.1083    raeburn  17413: sub update_content_constraints {
                   17414:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17415:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17416:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17417:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17418:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17419:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17420:         if ($item eq 'resourcetag') {
                   17421:             if ($name eq 'responsetype') {
                   17422:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17423:             }
1.1307    raeburn  17424:         } elsif ($item eq 'course') {
                   17425:             if ($name eq 'courserestype') {
                   17426:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17427:             }
1.1083    raeburn  17428:         }
                   17429:     }
                   17430:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17431:     if (defined($navmap)) {
1.1307    raeburn  17432:         my (%allresponses,%allcrsrestypes);
                   17433:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17434:             if ($res->is_tool()) {
                   17435:                 if ($allcrsrestypes{'exttool'}) {
                   17436:                     $allcrsrestypes{'exttool'} ++;
                   17437:                 } else {
                   17438:                     $allcrsrestypes{'exttool'} = 1;
                   17439:                 }
                   17440:                 next;
                   17441:             }
1.1083    raeburn  17442:             my %responses = $res->responseTypes();
                   17443:             foreach my $key (keys(%responses)) {
                   17444:                 next unless(exists($checkresponsetypes{$key}));
                   17445:                 $allresponses{$key} += $responses{$key};
                   17446:             }
                   17447:         }
                   17448:         foreach my $key (keys(%allresponses)) {
                   17449:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17450:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17451:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17452:             }
                   17453:         }
1.1307    raeburn  17454:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17455:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17456:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17457:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17458:             }
                   17459:         }
1.1083    raeburn  17460:         undef($navmap);
                   17461:     }
1.1308    raeburn  17462:     my $suppmap = 'supplemental.sequence';
                   17463:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   17464:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   17465:                                                             $suppcount,$supptools,$errors);
                   17466:     if ($supptools) {
                   17467:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   17468:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17469:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   17470:         }
                   17471:     }
1.1083    raeburn  17472:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17473:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17474:     }
                   17475:     return;
                   17476: }
                   17477: 
1.1110    raeburn  17478: sub allmaps_incourse {
                   17479:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17480:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17481:         $cid = $env{'request.course.id'};
                   17482:         $cdom = $env{'course.'.$cid.'.domain'};
                   17483:         $cnum = $env{'course.'.$cid.'.num'};
                   17484:         $chome = $env{'course.'.$cid.'.home'};
                   17485:     }
                   17486:     my %allmaps = ();
                   17487:     my $lastchange =
                   17488:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17489:     if ($lastchange > $env{'request.course.tied'}) {
                   17490:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17491:         unless ($ferr) {
                   17492:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17493:         }
                   17494:     }
                   17495:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17496:     if (defined($navmap)) {
                   17497:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17498:             $allmaps{$res->src()} = 1;
                   17499:         }
                   17500:     }
                   17501:     return \%allmaps;
                   17502: }
                   17503: 
1.1083    raeburn  17504: sub parse_supplemental_title {
                   17505:     my ($title) = @_;
                   17506: 
                   17507:     my ($foldertitle,$renametitle);
                   17508:     if ($title =~ /&amp;&amp;&amp;/) {
                   17509:         $title = &HTML::Entites::decode($title);
                   17510:     }
                   17511:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17512:         $renametitle=$4;
                   17513:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17514:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17515:         my $name =  &plainname($uname,$udom);
                   17516:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17517:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17518:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17519:             $name.': <br />'.$foldertitle;
                   17520:     }
                   17521:     if (wantarray) {
                   17522:         return ($title,$foldertitle,$renametitle);
                   17523:     }
                   17524:     return $title;
                   17525: }
                   17526: 
1.1143    raeburn  17527: sub recurse_supplemental {
1.1308    raeburn  17528:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  17529:     if ($suppmap) {
                   17530:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17531:         if ($fatal) {
                   17532:             $errors ++;
                   17533:         } else {
                   17534:             if ($#LONCAPA::map::resources > 0) {
                   17535:                 foreach my $res (@LONCAPA::map::resources) {
                   17536:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17537:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17538:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  17539:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   17540:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  17541:                         } else {
1.1308    raeburn  17542:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   17543:                                 $numexttools ++;
                   17544:                             }
1.1143    raeburn  17545:                             $numfiles ++;
                   17546:                         }
                   17547:                     }
                   17548:                 }
                   17549:             }
                   17550:         }
                   17551:     }
1.1308    raeburn  17552:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  17553: }
                   17554: 
1.1101    raeburn  17555: sub symb_to_docspath {
1.1267    raeburn  17556:     my ($symb,$navmapref) = @_;
                   17557:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17558:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17559:     if ($resurl=~/\.(sequence|page)$/) {
                   17560:         $mapurl=$resurl;
                   17561:     } elsif ($resurl eq 'adm/navmaps') {
                   17562:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17563:     }
                   17564:     my $mapresobj;
1.1267    raeburn  17565:     unless (ref($$navmapref)) {
                   17566:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17567:     }
                   17568:     if (ref($$navmapref)) {
                   17569:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17570:     }
                   17571:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17572:     my $type=$2;
                   17573:     my $path;
                   17574:     if (ref($mapresobj)) {
                   17575:         my $pcslist = $mapresobj->map_hierarchy();
                   17576:         if ($pcslist ne '') {
                   17577:             foreach my $pc (split(/,/,$pcslist)) {
                   17578:                 next if ($pc <= 1);
1.1267    raeburn  17579:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17580:                 if (ref($res)) {
                   17581:                     my $thisurl = $res->src();
                   17582:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17583:                     my $thistitle = $res->title();
                   17584:                     $path .= '&'.
                   17585:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17586:                              &escape($thistitle).
1.1101    raeburn  17587:                              ':'.$res->randompick().
                   17588:                              ':'.$res->randomout().
                   17589:                              ':'.$res->encrypted().
                   17590:                              ':'.$res->randomorder().
                   17591:                              ':'.$res->is_page();
                   17592:                 }
                   17593:             }
                   17594:         }
                   17595:         $path =~ s/^\&//;
                   17596:         my $maptitle = $mapresobj->title();
                   17597:         if ($mapurl eq 'default') {
1.1129    raeburn  17598:             $maptitle = 'Main Content';
1.1101    raeburn  17599:         }
                   17600:         $path .= (($path ne '')? '&' : '').
                   17601:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17602:                  &escape($maptitle).
1.1101    raeburn  17603:                  ':'.$mapresobj->randompick().
                   17604:                  ':'.$mapresobj->randomout().
                   17605:                  ':'.$mapresobj->encrypted().
                   17606:                  ':'.$mapresobj->randomorder().
                   17607:                  ':'.$mapresobj->is_page();
                   17608:     } else {
                   17609:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17610:         my $ispage = (($type eq 'page')? 1 : '');
                   17611:         if ($mapurl eq 'default') {
1.1129    raeburn  17612:             $maptitle = 'Main Content';
1.1101    raeburn  17613:         }
                   17614:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17615:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17616:     }
                   17617:     unless ($mapurl eq 'default') {
                   17618:         $path = 'default&'.
1.1146    raeburn  17619:                 &escape('Main Content').
1.1101    raeburn  17620:                 ':::::&'.$path;
                   17621:     }
                   17622:     return $path;
                   17623: }
                   17624: 
1.1094    raeburn  17625: sub captcha_display {
                   17626:     my ($context,$lonhost) = @_;
                   17627:     my ($output,$error);
1.1234    raeburn  17628:     my ($captcha,$pubkey,$privkey,$version) = 
                   17629:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17630:     if ($captcha eq 'original') {
1.1094    raeburn  17631:         $output = &create_captcha();
                   17632:         unless ($output) {
1.1172    raeburn  17633:             $error = 'captcha';
1.1094    raeburn  17634:         }
                   17635:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17636:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17637:         unless ($output) {
1.1172    raeburn  17638:             $error = 'recaptcha';
1.1094    raeburn  17639:         }
                   17640:     }
1.1234    raeburn  17641:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17642: }
                   17643: 
                   17644: sub captcha_response {
                   17645:     my ($context,$lonhost) = @_;
                   17646:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17647:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17648:     if ($captcha eq 'original') {
1.1094    raeburn  17649:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17650:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17651:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17652:     } else {
                   17653:         $captcha_chk = 1;
                   17654:     }
                   17655:     return ($captcha_chk,$captcha_error);
                   17656: }
                   17657: 
                   17658: sub get_captcha_config {
                   17659:     my ($context,$lonhost) = @_;
1.1234    raeburn  17660:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17661:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17662:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17663:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17664:     if ($context eq 'usercreation') {
                   17665:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17666:         if (ref($domconfig{$context}) eq 'HASH') {
                   17667:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17668:             if (ref($hashtocheck) eq 'HASH') {
                   17669:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17670:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17671:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17672:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17673:                     }
                   17674:                     if ($privkey && $pubkey) {
                   17675:                         $captcha = 'recaptcha';
1.1234    raeburn  17676:                         $version = $hashtocheck->{'recaptchaversion'};
                   17677:                         if ($version ne '2') {
                   17678:                             $version = 1;
                   17679:                         }
1.1095    raeburn  17680:                     } else {
                   17681:                         $captcha = 'original';
                   17682:                     }
                   17683:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17684:                     $captcha = 'original';
                   17685:                 }
1.1094    raeburn  17686:             }
1.1095    raeburn  17687:         } else {
                   17688:             $captcha = 'captcha';
                   17689:         }
                   17690:     } elsif ($context eq 'login') {
                   17691:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17692:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17693:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17694:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17695:             if ($privkey && $pubkey) {
                   17696:                 $captcha = 'recaptcha';
1.1234    raeburn  17697:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17698:                 if ($version ne '2') {
                   17699:                     $version = 1; 
                   17700:                 }
1.1095    raeburn  17701:             } else {
                   17702:                 $captcha = 'original';
1.1094    raeburn  17703:             }
1.1095    raeburn  17704:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17705:             $captcha = 'original';
1.1094    raeburn  17706:         }
                   17707:     }
1.1234    raeburn  17708:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17709: }
                   17710: 
                   17711: sub create_captcha {
                   17712:     my %captcha_params = &captcha_settings();
                   17713:     my ($output,$maxtries,$tries) = ('',10,0);
                   17714:     while ($tries < $maxtries) {
                   17715:         $tries ++;
                   17716:         my $captcha = Authen::Captcha->new (
                   17717:                                            output_folder => $captcha_params{'output_dir'},
                   17718:                                            data_folder   => $captcha_params{'db_dir'},
                   17719:                                           );
                   17720:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17721: 
                   17722:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17723:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17724:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17725:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17726:                       '<br />'.
                   17727:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17728:             last;
                   17729:         }
                   17730:     }
                   17731:     return $output;
                   17732: }
                   17733: 
                   17734: sub captcha_settings {
                   17735:     my %captcha_params = (
                   17736:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17737:                            www_output_dir => "/captchaspool",
                   17738:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17739:                            numchars       => '5',
                   17740:                          );
                   17741:     return %captcha_params;
                   17742: }
                   17743: 
                   17744: sub check_captcha {
                   17745:     my ($captcha_chk,$captcha_error);
                   17746:     my $code = $env{'form.code'};
                   17747:     my $md5sum = $env{'form.crypt'};
                   17748:     my %captcha_params = &captcha_settings();
                   17749:     my $captcha = Authen::Captcha->new(
                   17750:                       output_folder => $captcha_params{'output_dir'},
                   17751:                       data_folder   => $captcha_params{'db_dir'},
                   17752:                   );
1.1109    raeburn  17753:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17754:     my %captcha_hash = (
                   17755:                         0       => 'Code not checked (file error)',
                   17756:                        -1      => 'Failed: code expired',
                   17757:                        -2      => 'Failed: invalid code (not in database)',
                   17758:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17759:     );
                   17760:     if ($captcha_chk != 1) {
                   17761:         $captcha_error = $captcha_hash{$captcha_chk}
                   17762:     }
                   17763:     return ($captcha_chk,$captcha_error);
                   17764: }
                   17765: 
                   17766: sub create_recaptcha {
1.1234    raeburn  17767:     my ($pubkey,$version) = @_;
                   17768:     if ($version >= 2) {
                   17769:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17770:     } else {
                   17771:         my $use_ssl;
                   17772:         if ($ENV{'SERVER_PORT'} == 443) {
                   17773:             $use_ssl = 1;
                   17774:         }
                   17775:         my $captcha = Captcha::reCAPTCHA->new;
                   17776:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17777:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17778:                &mt('If the text is hard to read, [_1] will replace them.',
                   17779:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17780:                '<br /><br />';
                   17781:     }
1.1094    raeburn  17782: }
                   17783: 
                   17784: sub check_recaptcha {
1.1234    raeburn  17785:     my ($privkey,$version) = @_;
1.1094    raeburn  17786:     my $captcha_chk;
1.1234    raeburn  17787:     if ($version >= 2) {
                   17788:         my %info = (
                   17789:                      secret   => $privkey, 
                   17790:                      response => $env{'form.g-recaptcha-response'},
                   17791:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17792:                    );
1.1280    raeburn  17793:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17794:         $request->content(join('&',map {
                   17795:                          my $name = escape($_);
                   17796:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17797:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17798:                          : &escape($info{$_}) );
                   17799:         } keys(%info)));
                   17800:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17801:         if ($response->is_success)  {
                   17802:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17803:             if (ref($data) eq 'HASH') {
                   17804:                 if ($data->{'success'}) {
                   17805:                     $captcha_chk = 1;
                   17806:                 }
                   17807:             }
                   17808:         }
                   17809:     } else {
                   17810:         my $captcha = Captcha::reCAPTCHA->new;
                   17811:         my $captcha_result =
                   17812:             $captcha->check_answer(
                   17813:                                     $privkey,
                   17814:                                     $ENV{'REMOTE_ADDR'},
                   17815:                                     $env{'form.recaptcha_challenge_field'},
                   17816:                                     $env{'form.recaptcha_response_field'},
                   17817:                                   );
                   17818:         if ($captcha_result->{is_valid}) {
                   17819:             $captcha_chk = 1;
                   17820:         }
1.1094    raeburn  17821:     }
                   17822:     return $captcha_chk;
                   17823: }
                   17824: 
1.1174    raeburn  17825: sub emailusername_info {
1.1244    raeburn  17826:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17827:     my %titles = &Apache::lonlocal::texthash (
                   17828:                      lastname      => 'Last Name',
                   17829:                      firstname     => 'First Name',
                   17830:                      institution   => 'School/college/university',
                   17831:                      location      => "School's city, state/province, country",
                   17832:                      web           => "School's web address",
                   17833:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17834:                      id            => 'Student/Employee ID',
1.1174    raeburn  17835:                  );
                   17836:     return (\@fields,\%titles);
                   17837: }
                   17838: 
1.1161    raeburn  17839: sub cleanup_html {
                   17840:     my ($incoming) = @_;
                   17841:     my $outgoing;
                   17842:     if ($incoming ne '') {
                   17843:         $outgoing = $incoming;
                   17844:         $outgoing =~ s/;/&#059;/g;
                   17845:         $outgoing =~ s/\#/&#035;/g;
                   17846:         $outgoing =~ s/\&/&#038;/g;
                   17847:         $outgoing =~ s/</&#060;/g;
                   17848:         $outgoing =~ s/>/&#062;/g;
                   17849:         $outgoing =~ s/\(/&#040/g;
                   17850:         $outgoing =~ s/\)/&#041;/g;
                   17851:         $outgoing =~ s/"/&#034;/g;
                   17852:         $outgoing =~ s/'/&#039;/g;
                   17853:         $outgoing =~ s/\$/&#036;/g;
                   17854:         $outgoing =~ s{/}{&#047;}g;
                   17855:         $outgoing =~ s/=/&#061;/g;
                   17856:         $outgoing =~ s/\\/&#092;/g
                   17857:     }
                   17858:     return $outgoing;
                   17859: }
                   17860: 
1.1190    musolffc 17861: # Checks for critical messages and returns a redirect url if one exists.
                   17862: # $interval indicates how often to check for messages.
1.1282    raeburn  17863: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 17864: sub critical_redirect {
1.1282    raeburn  17865:     my ($interval,$context) = @_;
1.1190    musolffc 17866:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  17867:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17870:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17871:             if ($blocked) {
                   17872:                 my $checkrole = "cm./$cdom/$cnum";
                   17873:                 if ($env{'request.course.sec'} ne '') {
                   17874:                     $checkrole .= "/$env{'request.course.sec'}";
                   17875:                 }
                   17876:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17877:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17878:                     return;
                   17879:                 }
                   17880:             }
                   17881:         }
1.1190    musolffc 17882:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17883:                                         $env{'user.name'});
                   17884:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17885:         my $redirecturl;
1.1190    musolffc 17886:         if ($what[0]) {
                   17887: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17888: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17889: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17890:                 return (1, $url);
1.1190    musolffc 17891:             }
1.1191    raeburn  17892:         }
                   17893:     } 
                   17894:     return ();
1.1190    musolffc 17895: }
                   17896: 
1.1174    raeburn  17897: # Use:
                   17898: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17899: #
                   17900: ##################################################
                   17901: #          password associated functions         #
                   17902: ##################################################
                   17903: sub des_keys {
                   17904:     # Make a new key for DES encryption.
                   17905:     # Each key has two parts which are returned separately.
                   17906:     # Please note:  Each key must be passed through the &hex function
                   17907:     # before it is output to the web browser.  The hex versions cannot
                   17908:     # be used to decrypt.
                   17909:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17910:                 '8','9','a','b','c','d','e','f');
                   17911:     my $lkey='';
                   17912:     for (0..7) {
                   17913:         $lkey.=$hexstr[rand(15)];
                   17914:     }
                   17915:     my $ukey='';
                   17916:     for (0..7) {
                   17917:         $ukey.=$hexstr[rand(15)];
                   17918:     }
                   17919:     return ($lkey,$ukey);
                   17920: }
                   17921: 
                   17922: sub des_decrypt {
                   17923:     my ($key,$cyphertext) = @_;
                   17924:     my $keybin=pack("H16",$key);
                   17925:     my $cypher;
                   17926:     if ($Crypt::DES::VERSION>=2.03) {
                   17927:         $cypher=new Crypt::DES $keybin;
                   17928:     } else {
                   17929:         $cypher=new DES $keybin;
                   17930:     }
1.1233    raeburn  17931:     my $plaintext='';
                   17932:     my $cypherlength = length($cyphertext);
                   17933:     my $numchunks = int($cypherlength/32);
                   17934:     for (my $j=0; $j<$numchunks; $j++) {
                   17935:         my $start = $j*32;
                   17936:         my $cypherblock = substr($cyphertext,$start,32);
                   17937:         my $chunk =
                   17938:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17939:         $chunk .=
                   17940:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17941:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17942:         $plaintext .= $chunk;
                   17943:     }
1.1174    raeburn  17944:     return $plaintext;
                   17945: }
                   17946: 
1.1309    raeburn  17947: sub make_short_symbs {
                   17948:     my ($cdom,$cnum,$navmap) = @_;
                   17949:     return unless (ref($navmap));
                   17950:     my ($numnew,@errors);
                   17951:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17952:     if (@toshorten) {
                   17953:         my (%maps,%resources,%titles);
                   17954:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17955:                                                                'shorturls',$cdom,$cnum);
                   17956:         my %tocreate;
                   17957:         if (keys(%resources)) {
                   17958:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17959:                 my $symb = $resources{$item};
                   17960:                 if ($symb) {
                   17961:                     $tocreate{$cnum.'&'.$symb} = 1;
                   17962:                 }
                   17963:             }
                   17964:         }
                   17965:         if (keys(%tocreate)) {
                   17966:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17967:             my $su = Short::URL->new(no_vowels => 1);
                   17968:             my $init = '';
                   17969:             my (%newunique,%addcourse,%courseonly,%failed);
                   17970:             # get lock on tiny db
                   17971:             my $now = time;
                   17972:             my $lockhash = {
                   17973:                                 "lock\0$now" => $env{'user.name'}.
                   17974:                                                 ':'.$env{'user.domain'},
                   17975:                             };
                   17976:             my $tries = 0;
                   17977:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17978:             my ($code,$error);
                   17979:             while (($gotlock ne 'ok') && ($tries<3)) {
                   17980:                 $tries ++;
                   17981:                 sleep 1;
                   17982:                 $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17983:             }
                   17984:             if ($gotlock eq 'ok') {
                   17985:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17986:                                        \%addcourse,\%courseonly,\%failed);
                   17987:                 if (keys(%failed)) {
                   17988:                     my $numfailed = scalar(keys(%failed));
                   17989:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17990:                 }
                   17991:                 if (keys(%newunique)) {
                   17992:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17993:                     if ($putres eq 'ok') {
                   17994:                         $numnew = scalar(keys(%newunique));
                   17995:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17996:                         unless ($newputres eq 'ok') {
                   17997:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17998:                         }
                   17999:                     } else {
                   18000:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18001:                     }
                   18002:                 }
                   18003:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18004:                 unless ($dellockres eq 'ok') {
                   18005:                     push(@errors,&mt('error: could not release lockfile'));
                   18006:                 }
                   18007:             } else {
                   18008:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18009:             }
                   18010:             if (keys(%courseonly)) {
                   18011:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18012:                 if ($result ne 'ok') {
                   18013:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18014:                 }
                   18015:             }
                   18016:         }
                   18017:     }
                   18018:     return ($numnew,\@errors);
                   18019: }
                   18020: 
                   18021: sub shorten_symbs {
                   18022:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18023:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18024:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18025:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18026:     my (%possibles,%collisions);
                   18027:     foreach my $key (keys(%{$tocreate})) {
                   18028:         my $num = String::CRC32::crc32($key);
                   18029:         my $tiny = $su->encode($num,$init);
                   18030:         if ($tiny) {
                   18031:             $possibles{$tiny} = $key;
                   18032:         }
                   18033:     }
                   18034:     if (!$init) {
                   18035:         $init = 1;
                   18036:     } else {
                   18037:         $init ++;
                   18038:     }
                   18039:     if (keys(%possibles)) {
                   18040:         my @posstiny = keys(%possibles);
                   18041:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18042:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18043:         if (keys(%currtiny)) {
                   18044:             foreach my $key (keys(%currtiny)) {
                   18045:                 next if ($currtiny{$key} eq '');
                   18046:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18047:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18048:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18049:                         $courseonly->{$tsymb} = $key;
                   18050:                     }
                   18051:                 } else {
                   18052:                     $collisions{$possibles{$key}} = 1;
                   18053:                 }
                   18054:                 delete($possibles{$key});
                   18055:             }
                   18056:         }
                   18057:         foreach my $key (keys(%possibles)) {
                   18058:             $newunique->{$key} = $possibles{$key};
                   18059:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18060:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18061:                 $addcourse->{$tsymb} = $key;
                   18062:             }
                   18063:         }
                   18064:     }
                   18065:     if (keys(%collisions)) {
                   18066:         if ($init <5) {
                   18067:             if (!$init) {
                   18068:                 $init = 1;
                   18069:             } else {
                   18070:                 $init ++;
                   18071:             }
                   18072:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18073:                                    $newunique,$addcourse,$courseonly,$failed);
                   18074:         } else {
                   18075:             foreach my $key (keys(%collisions)) {
                   18076:                 $failed->{$key} = 1;
                   18077:             }
                   18078:         }
                   18079:     }
                   18080:     return $init;
                   18081: }
                   18082: 
1.112     bowersj2 18083: 1;
                   18084: __END__;
1.41      ng       18085: 

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